Documentation
¶
Overview ¶
Package terminal — observability declarations (BS-08 Terminal).
Package terminal — proc_cwd.go: 「这个进程此刻在哪个目录」的唯一实现。
Package terminal — protocol.go: T5 §5 WebSocket 终端消息协议定义 (r2) BS-08 v2 消息类型:input/output/resize/ping/pong/closed
Package terminal implements the BS-08 Terminal subsystem. It provides PTY management, WebSocket-based terminal I/O, and session lifecycle for browser-based terminal access. All state is held in memory (IR-03).
Index ¶
- Constants
- func BuildVersion(injected string) string
- func ClipboardBufferPath(dataDir, target string) string
- func DialTestWS(t *testing.T, server *httptest.Server, sessionID string, token string) *websocket.Conn
- func IsNewerRelease(current, latest string) bool
- func LoadUploadLimit(dataDir string) error
- func LocalUploadLimitBytes() int64
- func NewTestCLIServer(t *testing.T) (*httptest.Server, *SessionManager, *SafeWriteEnds)
- func NewTestCLIServerWithAuth(t *testing.T, authCode string) (*httptest.Server, *SessionManager, *SafeWriteEnds)
- func SessionCWD(meta []byte) string
- func SessionLabel(meta []byte, id string) string
- func SetUploadLimitMB(mb int) (int, error)
- func UploadLimitBytes() int64
- func WaitForBinaryContaining(t *testing.T, ws *websocket.Conn, substr string, timeout time.Duration) []byte
- func WaitForPTYReady(t *testing.T, sm *SessionManager, sessionID string, timeout time.Duration)
- type AgentDetectFunc
- type AgentSignalEntry
- type AgentSignalPayload
- type AgentStatePushFunc
- type Config
- type CreateOptions
- type DaemonHealth
- type ErrorPayload
- type Hooks
- type HudLogRequest
- type InProcessService
- func (s *InProcessService) Close() error
- func (s *InProcessService) Create(_ context.Context, opts CreateOptions) (*SessionInfo, error)
- func (s *InProcessService) Delete(_ context.Context, id string) error
- func (s *InProcessService) Get(_ context.Context, id string) (*SessionInfo, error)
- func (s *InProcessService) Input(_ context.Context, id string, data []byte) error
- func (s *InProcessService) List(_ context.Context) ([]SessionInfo, error)
- func (s *InProcessService) PasteUpload(_ context.Context, id string, filename string, content io.Reader, ...) (string, error)
- func (s *InProcessService) Resize(_ context.Context, id string, cols, rows int) error
- func (s *InProcessService) TailOutput(_ context.Context, id string, lines int) ([]string, error)
- type InputPayload
- type Option
- type PTYFactory
- type PreemptedPayload
- type ReleaseInfo
- type ReleaseState
- type ResizePayload
- type ResizedPayload
- type RingBuffer
- type SafeWriteEnds
- type Server
- type Session
- func (s *Session) ClearSignal()
- func (s *Session) Done() <-chan struct{}
- func (s *Session) ForceKillForeground() error
- func (s *Session) GetExitCode() int
- func (s *Session) GetLastActive() time.Time
- func (s *Session) GetStatus() SessionStatus
- func (s *Session) GetTmuxDetected() bool
- func (s *Session) History(req muxd.HistoryReq) (muxd.HistoryAck, error)
- func (s *Session) PTYSize() muxd.Grid
- func (s *Session) PasteMode() (enabled, known bool)
- func (s *Session) PendingSignal() (sig ansisignal.Signal, at time.Time, seq uint64, ok bool)
- func (s *Session) RecordSignal(sig ansisignal.Signal, at time.Time) uint64
- func (s *Session) ReleaseViewerOwner(subID string)
- func (s *Session) ReplayTail(max int) (data []byte, currentGrid int)
- func (s *Session) RequestPTYSize(cols, rows int) error
- func (s *Session) SearchHistory(req muxd.HistorySearchReq) (muxd.HistorySearchAck, error)
- func (s *Session) SetName(name string)
- func (s *Session) SetViewerOwner(subID string, epoch uint64)
- func (s *Session) SetViewerSize(subID string, cols, rows int) error
- func (s *Session) ShellPID() int
- func (s *Session) TailOutput(n int) []string
- func (s *Session) Viewport() muxd.Grid
- func (s *Session) WorkingDir() string
- func (s *Session) WriteInput(data []byte) error
- type SessionInfo
- type SessionManager
- func (m *SessionManager) ClearActiveConn(sessionID string, conn *websocket.Conn)
- func (m *SessionManager) CloseAll() error
- func (m *SessionManager) Create(name string) (*Session, error)
- func (m *SessionManager) CreateWithOptions(opts CreateOptions) (*Session, error)
- func (m *SessionManager) DaemonHealth() DaemonHealth
- func (m *SessionManager) Destroy(id string) error
- func (m *SessionManager) DestroyAll()
- func (m *SessionManager) Get(id string) (*Session, error)
- func (m *SessionManager) List() []*Session
- func (m *SessionManager) Restore() error
- func (m *SessionManager) SetActiveConn(sessionID string, conn *websocket.Conn, cancel context.CancelFunc) uint64
- func (m *SessionManager) SetOrigin(origin string)
- func (m *SessionManager) Subscribe(sess *Session, subID string) (<-chan viewerFrame, int, int, func())
- func (m *SessionManager) WatchDaemon(ctx context.Context)
- type SessionMeta
- type SessionMetaPayload
- type SessionOverviewEntry
- type SessionSnapshot
- type SessionStatus
- type SessionStore
- type SessionSummary
- type ShellExitPayload
- type TermMsg
- type TerminalSessionService
- type TmuxCopyMotioner
- type TmuxNavPayload
- type TmuxOverviewToggler
- type TmuxRefresher
- type TmuxSessionMaker
- type TmuxStateProvider
- type TmuxWindowSelector
- type WSControlMessage
Constants ¶
const ( // MsgInput 键盘输入 / 控制序列 (客户端→服务端) MsgInput = "input" // MsgResize 窗口大小变化 (客户端→服务端) MsgResize = "resize" // MsgPing 心跳 (客户端→服务端) MsgPing = "ping" )
const ( // MsgOutput PTY 输出 ANSI 透传 (服务端→客户端) MsgOutput = "output" // MsgClosed 终端关闭通知 (服务端→客户端) MsgClosed = "closed" // MsgPong 心跳响应 (服务端→客户端) MsgPong = "pong" )
const ( ClosedReasonNormal = "normal" ClosedReasonCrashed = "crashed" ClosedReasonStopCalled = "stop_called" )
const ( MsgTypeResize = "resize" MsgTypePresentation = "presentation" // client → server: visible tab and overview subscription MsgTypeHeartbeat = "heartbeat" MsgTypeHeartbeatAck = "heartbeat_ack" MsgTypePing = "ping" MsgTypePong = "pong" MsgTypeAuthRefresh = "auth_refresh" MsgTypeShellExit = "shell_exit" MsgTypeError = "error" MsgTypePreempted = "preempted" MsgTypeInput = "input" // client → server: terminal input as text frame (WKWebView binary frame fix) MsgTypeSessionMeta = "session_meta" // server → client: pushed once after WS handshake MsgTypeAgentState = "agent_state" // server → client: agent state push (replaces SSE) MsgTypeTmuxState = "tmux_state" // server → client: tmux topology/prefix/agent-status push (terminal-owned) // server → client: every session's status + live tail, for the NON-tmux Agent Overview. // Structural twin of tmux_state — one frame describing all units, pushed on the active // session's existing WS by the same 1s diff-suppressed ticker. See sessions_overview.go. MsgTypeSessionsOverview = "sessions_overview" // server → client: the sessions whose program EXPLICITLY asked for the user (BEL / OSC // notification). Same one-frame-describes-everything shape as sessions_overview, and for // the same reason: a bell can ring in a background session that has no WebSocket of its // own. See session_signal.go. MsgTypeAgentSignal = "agent_signal" // server → client: the session's grid is now this big. NOT an echo of the client's own // resize — it is the size the session actually entered after fitting every window // watching it, which is a different number whenever a smaller window is also attached. // Sent once before the replay (so the replay lands on the right grid) and then whenever // the size changes, in stream order with the output it applies to. MsgTypeResized = "resized" // MsgTypeReplayReset tells a client to clear its terminal because what follows is a // REPLAY — the session's screen from the beginning of the current grid epoch — not a // continuation of what it is already showing. // // Without it a browser that switches away and back writes a second copy of the screen // underneath the first, and the two copies are what a user reports as "duplicated bottom // line". The frames are indistinguishable once they arrive (replay and live output are // both binary), so the boundary has to be stated, not inferred. // // A client that does not know this type ignores it and keeps the old behaviour, which is // why it is a separate frame rather than a field on "resized": an old page must not have // its resize silently changed shape underneath it. MsgTypeReplayReset = "replay_reset" )
Control message type constants.
const ( // ClipboardMaxUploadSize is the compile-time DEFAULT for the SESSION file-upload cap // (paste/attach → agent working dir). Exported because deepwork-pro's parallel session // upload route imports it instead of re-declaring the number — one source, so the two // deployments can never drift (they did: pro's wsSessionUploadMaxBytes was a hand-"aligned" // copy). Distinct from chat-image attachments (a different bounded context, its own smaller // cap) — do NOT fold that in here. // // This is no longer the sole authority at runtime: upload_limit.go layers a // runtime-configurable, persisted override on top (UploadLimitBytes / SetUploadLimitMB), // initialized to this const. Both enforcement points (below, and service_inproc.go's // LimitReader) call UploadLimitBytes(), not this const directly. Keep this const's // value as the shipped default — pro and any caller that never touches upload_limit.go // must keep seeing exactly this number. // // 10 → 100 MB: the old number was set when an upload was read whole into memory, so the // cap was really a memory budget wearing a network argument's clothes. The upload path // now streams (stageClipboardUpload) and paces itself against terminal traffic // (uploadPacer), so what is left to bound is genuinely the network: 100 MB is roughly a // minute on a decent uplink, still short enough that a stuck transfer is noticed rather // than endured. Same-machine clients are not subject to this at all — see // uploadLimitBytesFor. ClipboardMaxUploadSize = 100 << 20 // 100 MB )
const DefaultBufferCapacity = muxd.DefaultBufferCapacity
DefaultBufferCapacity is the default ring size (1 MB).
Variables ¶
This section is empty.
Functions ¶
func BuildVersion ¶ added in v0.7.15
BuildVersion resolves the identity string a running binary reports as its build version — the value behind `GET /version`, the `--version` output, and the badge in the top-right of the UI.
Why this lives in the shared package ¶
TWO binaries surface a build version: the standalone `dw-terminal` and deepwork-pro's `dw-host` (which embeds this package and, until now, never set Config.Version at all — so pro's badge had no source and simply never rendered). "What does a build's identity look like" is one rule, so it gets one implementation here rather than one per binary.
The rule ¶
- A stamped build wins. Releases inject a clean tag via `-ldflags "-X main.version=v0.7.14"` (goreleaser) and build.sh injects a `git describe` (e.g. "v0.7.14-3-gb2535a0"). Either is already the truth; pass it through untouched.
- An UNSTAMPED build (`go build` / `go install`, and pro's run_cli.sh, none of which pass -ldflags) would otherwise report the bare sentinel "dev" — which cannot answer the ONE question a version badge exists to answer: *is this the code I just built?* Go stamps every module build with VCS metadata automatically (debug.ReadBuildInfo), so we enrich it into "dev-<shorthash>" (+"-dirty" when the tree had uncommitted changes) for free, with no build-script changes required in either repo.
The string returned here is the FULL, honest identity — deliberately not the abbreviated form the UI badge shows. Shortening is a presentation decision and belongs to the frontend (see frontend/src/composables/cli/buildVersion.ts), which keeps the full string in the badge's tooltip. A server that shortened its own answer would be throwing away the detail `--version` and bug reports need.
`injected` is the link-time variable of the calling binary ("dev" or "" when unstamped).
func ClipboardBufferPath ¶ added in v0.12.0
ClipboardBufferPath is shared with the local CLI. The path contains no user supplied path components, and buffers are private to this server's data directory.
func DialTestWS ¶
func DialTestWS(t *testing.T, server *httptest.Server, sessionID string, token string) *websocket.Conn
DialTestWS opens a WebSocket connection to the test server for the given session.
func IsNewerRelease ¶ added in v0.7.15
IsNewerRelease 报告 latest 是否严格新于 current。两者都必须是干净的发布版,否则一律返回 false —— 比不了就不比,绝不猜。
func LoadUploadLimit ¶ added in v0.7.11
LoadUploadLimit reads <dataDir>/upload-limit.json (written by a prior SetUploadLimitMB) and applies it as the effective upload cap. Call once at server startup with Config.DataDir (see NewServer) — a missing file is NOT an error, it just means the limit was never overridden, so the compile-time ClipboardMaxUploadSize default (already the package-init value) stands. Also remembers dataDir so a later SetUploadLimitMB call knows where to persist.
func LocalUploadLimitBytes ¶ added in v0.9.0
func LocalUploadLimitBytes() int64
LocalUploadLimitBytes is the cap for an upload that never crosses a network — the HTTP loopback case above, and the in-process (Wails desktop) path in service_inproc.go, which is same-machine by construction and has no request to inspect.
func NewTestCLIServer ¶
func NewTestCLIServer(t *testing.T) (*httptest.Server, *SessionManager, *SafeWriteEnds)
NewTestCLIServer creates a test HTTP server with terminal routes. Returns the server, SessionManager, and write-end pipes for data injection.
func NewTestCLIServerWithAuth ¶
func NewTestCLIServerWithAuth(t *testing.T, authCode string) (*httptest.Server, *SessionManager, *SafeWriteEnds)
NewTestCLIServerWithAuth creates a test server with a specific auth code.
func SessionCWD ¶ added in v0.12.0
SessionCWD reports the working directory recorded in a session's metadata blob, for the same reason as SessionLabel: the CLI has to show what the web UI shows.
func SessionLabel ¶ added in v0.12.0
SessionLabel renders a human name for a session from the daemon's opaque metadata blob, falling back to a short id when the blob says nothing useful.
It is exported for ONE reason: there is now a second client. The CLI (`dw-terminal ls`, `dw-terminal attach work`) has to resolve the same human names the web UI shows, and the only honest way to do that is to decode the blob with the same decoder rather than re-implementing its schema in the command package. The daemon still never interprets the blob — the split it protects is daemon-vs-server, not server-vs-CLI.
func SetUploadLimitMB ¶ added in v0.7.11
SetUploadLimitMB clamps mb to [1, 1024] MB, applies it as the new effective upload cap (visible to UploadLimitBytes immediately), persists it to <DataDir>/upload-limit.json (the DataDir last supplied to LoadUploadLimit), and returns the actually-applied MB value. If no DataDir has ever been loaded (Set called before LoadUploadLimit, e.g. in a caller that skips startup wiring), the in-memory value still applies — persistence is best-effort, never a precondition for the limit taking effect. A write failure is returned but the in-memory value is NOT rolled back: the running server keeps honoring the new limit; only a future restart would miss it.
func UploadLimitBytes ¶ added in v0.7.11
func UploadLimitBytes() int64
UploadLimitBytes returns the current effective upload cap in bytes. Exported so deepwork-pro — which imports ClipboardMaxUploadSize today as its own default — can switch to this runtime-configurable SSOT later without duplicating the clamp/ persist/load logic; terminal-only callers (clipboard_paste.go, service_inproc.go) use it directly in place of the const.
func WaitForBinaryContaining ¶
func WaitForBinaryContaining(t *testing.T, ws *websocket.Conn, substr string, timeout time.Duration) []byte
WaitForBinaryContaining reads binary WS messages until one contains substr.
func WaitForPTYReady ¶
WaitForPTYReady waits for the session to appear in the SessionManager.
Types ¶
type AgentDetectFunc ¶
AgentDetectFunc detects an AI agent running under the given shell PID. Returns (tool, status) strings; empty tool means no agent detected.
type AgentSignalEntry ¶ added in v0.7.13
type AgentSignalEntry struct {
SessionID string `json:"sessionId"`
Kind string `json:"kind"` // "bell" | "notify"
Title string `json:"title,omitempty"` // OSC notifications only
Body string `json:"body,omitempty"` // OSC notifications only
At string `json:"at"` // RFC3339 (ms precision) when it arrived
Seq uint64 `json:"seq"` // per-session counter; a new value = a NEW signal
}
AgentSignalEntry is one session's currently-unanswered explicit signal.
type AgentSignalPayload ¶ added in v0.7.13
type AgentSignalPayload struct {
Signals []AgentSignalEntry `json:"signals"`
}
AgentSignalPayload is the payload of an "agent_signal" control message. Signals is the COMPLETE current set (never a delta), so an empty array is the explicit "nothing pending anymore" that clears the client's state.
type AgentStatePushFunc ¶
type AgentStatePushFunc func(ctx context.Context, sessionID string) (<-chan json.RawMessage, func(), error)
AgentStatePushFunc subscribes to agent state changes for a session. Returns a channel of JSON-encoded AgentIntelResponse and a cleanup function. Injected by the webui layer to avoid terminal → agent_intel import cycle.
type Config ¶
type Config struct {
Addr string // listen address, e.g. ":8022" (always 0.0.0.0)
DefaultShell string // e.g. "/bin/bash --login"
BufferSize int // ring buffer size in bytes, default 1MB
MaxSessions int // max concurrent sessions, default 100
AuthCode string // auto-generated auth code, printed to console on start
DataDir string // data directory for persistence
Version string // build version (e.g. "v0.4.0"), surfaced to the UI via GET /version; "dev" for source builds
// ReleaseRepo is the GitHub "owner/name" whose published releases this build's Version
// should be compared against ("有新版本吗"). EMPTY DISABLES THE CHECK, and empty is the
// default on purpose: only the binary knows which product it is. deepwork-pro embeds this
// package as a subsystem and stamps Version with ITS OWN tag — comparing that against
// deepwork-terminal's releases would either claim "已是最新发布版" about a repo it does not
// come from, or point the user at another product's download page. A library must not
// assume its embedder's identity; the binary opts in (see cmd/dw-terminal/main.go).
ReleaseRepo string
// Tunnel, when true, opens a Cloudflare quick tunnel at startup so the server is
// reachable over the public internet (a temporary *.trycloudflare.com URL, no
// Cloudflare account needed) — the same thing the UI's tunnel toggle does, wired to
// a launch flag so an agent can bring up public access in one command. The URL is
// printed in the startup banner. Named/persistent tunnels stay UI-driven (they need
// an interactive `cloudflared login`).
Tunnel bool
}
Config for the terminal session server.
type CreateOptions ¶
CreateOptions describes the product-level terminal session metadata and runtime options supplied by the WebUI.
type DaemonHealth ¶ added in v0.12.0
type DaemonHealth struct {
Socket string `json:"socket"`
Connected bool `json:"connected"`
PID int `json:"pid,omitempty"`
Proto int `json:"proto,omitempty"`
Sessions int `json:"sessions,omitempty"`
StartedAt *time.Time `json:"startedAt,omitempty"`
// Missing names the capabilities this build needs and the running daemon does not
// advertise. Carried separately from Problem because it is the machine-readable half:
// prose is for the user, this is for anything that wants to decide something.
Missing []string `json:"missing,omitempty"`
Problem string `json:"problem,omitempty"`
Remedy string `json:"remedy,omitempty"`
}
DaemonHealth is what the product can SAY about the daemon: is it reachable, who is it, how much of the user's work is inside it, and — when something is wrong — what the user should do about it.
Problem and Remedy are separate fields on purpose. A UI that only receives prose can print it; a UI that receives a remedy can offer a button. The remedy is the half that is usually missing, and its absence is what turns a recoverable situation ("your daemon is from the previous build; restarting it ends 7 sessions") into an unrecoverable-looking one ("failed to connect to session daemon"). StartedAt is a POINTER because `omitempty` does not omit a zero time.Time — it renders "0001-01-01T00:00:00Z", which reads to a consumer as a real timestamp from the year 1. A daemon too old to report when it started must be indistinguishable from one that was never asked: absent, not epoch-zero. (The wire protocol dodges this by carrying unix seconds; this DTO is the same hazard one layer up, and it shipped once before this was caught in the live /api/system response.)
type ErrorPayload ¶
ErrorPayload is the payload for an "error" control message.
type Hooks ¶
type Hooks struct {
OnSessionStart func(ctx context.Context, id string, meta SessionMeta) error
OnSessionEnd func(ctx context.Context, id string, exitCode int) error
OnOutput func(ctx context.Context, id string, data []byte) error
OnCommand func(ctx context.Context, id string, cmd string) (handled bool, err error)
Store SessionStore
// AgentDetect is a DEPRECATED override for agent detection, consulted only when the built-in
// detector finds no agent in a session. Detection now lives in this package (session_agent.go)
// because hosting it outside produced two shells with different behavior and a transcript
// binding that mixed up same-directory sessions. Kept for embedders with a runtime the
// built-in detector doesn't know; new code should not set it.
AgentDetect AgentDetectFunc
// AgentStatePush optionally subscribes to agent state changes for WS push.
// Injected by the host to avoid import cycles.
AgentStatePush AgentStatePushFunc
}
Hooks defines optional integration points for a host application. All fields are optional — nil means standalone behavior.
type HudLogRequest ¶
type HudLogRequest struct {
SessionID string `json:"sessionId"`
Timestamp string `json:"timestamp"`
UserAgent string `json:"userAgent"`
Screen json.RawMessage `json:"screen"`
Events json.RawMessage `json:"events"`
Snapshot json.RawMessage `json:"snapshot"`
}
HudLogRequest is the request body for POST /api/cli/debug/logs. [Ref: CAP-hud-diagnostics S4]
type InProcessService ¶
type InProcessService struct {
// contains filtered or unexported fields
}
InProcessService wraps SessionManager and implements TerminalSessionService. All calls are in-process; no network hop occurs. SessionManager is already thread-safe via sync.Map, so InProcessService inherits that guarantee.
func NewInProcessService ¶
func NewInProcessService(manager *SessionManager) *InProcessService
NewInProcessService creates an InProcessService backed by the given manager.
func (*InProcessService) Close ¶
func (s *InProcessService) Close() error
Close implements TerminalSessionService.
func (*InProcessService) Create ¶
func (s *InProcessService) Create(_ context.Context, opts CreateOptions) (*SessionInfo, error)
Create implements TerminalSessionService.
func (*InProcessService) Delete ¶
func (s *InProcessService) Delete(_ context.Context, id string) error
Delete implements TerminalSessionService.
func (*InProcessService) Get ¶
func (s *InProcessService) Get(_ context.Context, id string) (*SessionInfo, error)
Get implements TerminalSessionService.
func (*InProcessService) Input ¶
Input implements TerminalSessionService. Writes raw bytes directly to the session's PTY file descriptor.
func (*InProcessService) List ¶
func (s *InProcessService) List(_ context.Context) ([]SessionInfo, error)
List implements TerminalSessionService.
func (*InProcessService) PasteUpload ¶
func (s *InProcessService) PasteUpload(_ context.Context, id string, filename string, content io.Reader, sessionCWD string) (string, error)
PasteUpload implements TerminalSessionService. Saves content to a temp directory under the resolved session cwd and returns the absolute path of the saved file. The logic mirrors clipboard_paste.go but operates on io.Reader rather than gin.Context so that it can be called without an HTTP layer.
func (*InProcessService) TailOutput ¶
TailOutput implements TerminalSessionService.
type InputPayload ¶
type InputPayload struct {
Data []byte `json:"data"` // raw terminal bytes (JSON base64-encoded)
}
InputPayload carries terminal input bytes as a JSON text frame. [TH-0501-m9j] WKWebView drops rapid binary WS frames; text frames are reliable.
type Option ¶
type Option func(*Server)
Option configures a Server.
func WithAuthCode ¶
WithAuthCode sets the auth code. When left empty, NewServer generates one.
func WithTmuxProvider ¶ added in v0.2.0
func WithTmuxProvider(p TmuxStateProvider) Option
WithTmuxProvider overrides the default in-process tmux provider. Hosts use this to supply a richer snapshot; standalone needs nothing.
func WithTunnel ¶ added in v0.7.11
WithTunnel opens a Cloudflare quick tunnel at startup when true (see Config.Tunnel).
type PTYFactory ¶
type PTYFactory = muxd.PTYFactory
PTYFactory is the daemon's PTY constructor, re-exported so test fixtures can inject a pipe-backed one without importing muxd directly.
The implementation moved to muxd because the daemon is now the ONLY thing that creates PTYs. There is deliberately no second construction path left in this package: two PTY paths is exactly the shape this repo has been burned by before ("两条 PTY 路径只修一条, 等于没修" — shell_cmd.go), and here it would be worse, because only one of the two would survive a restart.
type PreemptedPayload ¶
type PreemptedPayload struct {
Message string `json:"message"`
}
PreemptedPayload is the payload for a "preempted" control message.
type ReleaseInfo ¶ added in v0.7.15
ReleaseInfo 是"最新发布版"的全部事实。两个字段要么都有、要么都没有。
type ReleaseState ¶ added in v0.7.15
type ReleaseState string
ReleaseState 是给 UI 的**唯一权威答案**,四态互斥。
为什么由服务端定态、而不是把 latest 丢给前端自己比:语义化版本的比较规则属于"发布"这个领域, 它只该有一份实现。更要紧的是 —— **"查过了,你是最新的" 和 "根本没查到" 必须是两个态**。 早先的设计只在"有更新"时下发 latest 字段,于是这两种情况在前端长得一模一样,UI 只能二选一地 猜,而猜错的那一半会变成一句自信的假话(对着一次失败的查询显示 ✓ 已是最新)。
const ( // ReleaseLocal 本地构建(非干净 tag):从不查询,也不该对它说任何关于发布版的话。 ReleaseLocal ReleaseState = "local" // ReleaseCurrent 查到了,且当前就是最新发布版。 ReleaseCurrent ReleaseState = "current" // ReleaseOutdated 查到了,且有更新的发布版(此时 ReleaseInfo 一定非空)。 ReleaseOutdated ReleaseState = "outdated" // ReleaseUnknown 是发布版,但还没有可用结果(首次加载 / 离线 / GitHub 不可达)。 // **它不是 current**,UI 必须如实说"没查到"。 ReleaseUnknown ReleaseState = "unknown" )
type ResizePayload ¶
ResizePayload is the payload for a "resize" control message. [Ref: T5-B3]
type ResizedPayload ¶ added in v0.12.0
ResizedPayload is the payload of a "resized" control message.
type RingBuffer ¶
type RingBuffer = muxd.RingBuffer
Things that moved into the muxd package, kept reachable under their old names.
Why they moved: the daemon is what owns PTYs now, so everything about *making* a PTY — the scrollback ring it fills, the environment scrubbing that decides what the child inherits, the shell-words tokenizer that turns a configured command into argv — belongs on that side of the boundary. The dependency runs one way (terminal imports muxd, never the reverse), which is what keeps a single implementation possible.
These aliases are transitional: they exist so the move did not have to rewrite every call site at once. They disappear together with the in-process PTY path.
func NewRingBuffer ¶
func NewRingBuffer(capacity int) *RingBuffer
NewRingBuffer creates a RingBuffer with the given capacity.
type SafeWriteEnds ¶
type SafeWriteEnds struct {
// contains filtered or unexported fields
}
SafeWriteEnds provides thread-safe access to pipe write ends.
func (*SafeWriteEnds) CloseAt ¶
func (s *SafeWriteEnds) CloseAt(index int)
CloseAt closes the write end at the given index.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a complete terminal session HTTP service. Standalone: ListenAndServe() runs API + SPA. Embedded: Handler() returns API routes for a host to mount.
func (*Server) Handler ¶
Handler returns the API routes (no SPA) for embedding into a host server. Routes are relative: GET /sessions, POST /sessions, GET /sessions/{id}/ws, etc. The host uses http.StripPrefix to mount at any path prefix.
func (*Server) ListenAndServe ¶
ListenAndServe starts the standalone server (API + SPA). The SPA is the embedded Vue frontend (built by build.sh).
func (*Server) Service ¶ added in v0.2.0
func (s *Server) Service() TerminalSessionService
Service returns the in-process terminal session service owned by this server. Hosts should depend on this interface for product integrations such as agent state enrichment instead of reaching into SessionManager internals.
func (*Server) SetAuthCode ¶ added in v0.6.0
SetAuthCode replaces the current auth code under lock. Exported so an embedding host (deepwork-pro) can keep this embedded terminal's gate in sync when it rotates its own auth code — the code pro injects via withTerminalHostAuth must match what this terminal compares against, or every forwarded request 401s.
type Session ¶
type Session struct {
ID string `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
Engine string `json:"engine"`
CWD string `json:"cwd"`
ShellPath string `json:"-"`
Buffer *RingBuffer `json:"-"`
// Origin is which deployment's tab list owns this session — see sessionMeta.Origin for
// why one daemon serves two tab lists. Carried on the struct (not just in the meta blob)
// because SetName rewrites the whole meta from these fields: a rename would otherwise
// quietly blank it, and a session with no origin is a session orphan adoption has to guess
// about.
Origin string `json:"origin,omitempty"`
Status SessionStatus `json:"status"`
CreatedAt time.Time `json:"createdAt"`
LastActive time.Time `json:"lastActive"`
// TmuxDetected indicates whether the shell is running inside tmux.
// Set after session creation by checking /proc/{pid}/environ.
// [Ref: BUG-6, DDC-13]
TmuxDetected bool `json:"tmuxDetected"`
// contains filtered or unexported fields
}
Session represents a single terminal session backed by a PTY. [Ref: T5-B3]
func (*Session) ClearSignal ¶ added in v0.7.13
func (s *Session) ClearSignal()
ClearSignal drops the pending signal — the user answered. The sequence number is NOT reset, so the next signal still reads as new to a client that saw the previous one.
func (*Session) Done ¶
func (s *Session) Done() <-chan struct{}
Done returns a channel that is closed when the PTY read loop exits.
func (*Session) ForceKillForeground ¶ added in v0.12.0
meaningful to do, and pretending to succeed while leaving the user still stuck would be worse.
Not offered for tmux-attached sessions: the PTY's foreground pgid there belongs to tmux's own server/client plumbing, not a fact the web UI can act on — tmux has its own recovery tools (kill-pane etc.) for that case. Callers should already hide the affordance for those sessions; this is the defense-in-depth backend half of that guard.
func (*Session) GetExitCode ¶
GetExitCode returns the shell exit code (thread-safe).
func (*Session) GetLastActive ¶
GetLastActive returns when the session last received PTY output (thread-safe).
func (*Session) GetStatus ¶
func (s *Session) GetStatus() SessionStatus
GetStatus returns the session status (thread-safe).
func (*Session) GetTmuxDetected ¶
GetTmuxDetected returns whether tmux was detected (thread-safe).
func (*Session) History ¶ added in v0.12.0
func (s *Session) History(req muxd.HistoryReq) (muxd.HistoryAck, error)
ForceKillForeground sends SIGKILL to the PTY's current foreground process group — a harder-than-Ctrl+C recovery path for when the foreground program ignores SIGINT (the signal Ctrl+C sends through the PTY). TIOCGPGRP on the PTY master reads exactly the fact the kernel itself consults to route Ctrl+C; this just sends a stronger signal on demand instead of waiting for a program that has decided to ignore the polite one.
When the foreground process IS the shell itself (no interactive child running), the shell's own process group gets killed too — the tab disconnects rather than no-op'ing. A "kill whatever's in front" command with no foreground child left to kill has nothing else History reads a page of this session's scrollback from the daemon that owns it.
The server does NOT cache the result. It already keeps a duplicate of every session's byte stream (see Session.Buffer); adding a third copy of the same content in a different shape would give the same bug three places to disagree, and the daemon can answer a page in microseconds from memory it already has.
func (*Session) PTYSize ¶ added in v0.10.0
PTYSize returns the PTY's current window size. Falls back to the spawn size when a session predates any resize — never zero, because the replay grid must always have dimensions.
func (*Session) PasteMode ¶ added in v0.14.0
PasteMode reports whether the program in this session last negotiated bracketed paste, and whether that is known at all. Callers must not read known=false as enabled=false.
func (*Session) PendingSignal ¶ added in v0.7.13
PendingSignal returns the unanswered signal, when the session has one (thread-safe).
func (*Session) RecordSignal ¶ added in v0.7.13
RecordSignal stores an explicit out-of-band signal as this session's pending "needs-you" state and returns its sequence number (thread-safe).
func (*Session) ReleaseViewerOwner ¶ added in v0.12.0
ReleaseViewerOwner drops ownership if subID still holds it, and re-declares.
Conditional because a departing viewer is routinely NOT the owner any more: preemption hands ownership to the new connection first, and the old one's teardown runs afterwards. An unconditional clear there would take the grid away from the browser that just won it.
func (*Session) ReplayTail ¶ added in v0.12.0
ReplayTail returns up to max bytes of scrollback and says how many of them at the END were drawn for the CURRENT grid — everything a replay may send without mixing two geometries.
The bytes and the boundary are computed together on purpose. Reading the ring's contents, its byte counter, and the grid mark in three separate calls lets a write or a resize land between them, and the arithmetic then mixes a length from one moment with a counter from another — producing a cut that is off by exactly the bytes that arrived in the gap. The ring hands back its data and its counter under one lock (ReadTailAt); the grid mark is read AFTER, so the two possible orderings both have an honest answer:
- mark ≤ seq: the mark is inside what we just read; keep everything after it.
- mark > seq: the resize happened after our read, so every byte we hold predates the current grid. Keep none of it, and let the program's own repaint fill the screen.
A session that has never resized has no boundary to respect: its whole ring is one epoch.
func (*Session) RequestPTYSize ¶ added in v0.12.0
RequestPTYSize asks for a session size on behalf of a caller that is NOT a window — the REST endpoint and InProcessService, neither of which has a viewer behind it.
It goes to the daemon's control plane, which treats it as the FALLBACK size: the one used while nothing attached has declared a size of its own. That is the honest place for it. A caller that is not displaying the session cannot know what will fit in the windows that are, so letting it overrule them would re-open the exact bug per-attachment geometry closes — one client reflowing another's terminal. When a browser IS watching, this request is therefore ignored, deliberately and silently, in the same way `tmux resize-window` is clamped by the clients actually attached.
Note what it does NOT do: write the size onto the session. The daemon decides the session's size and reports it back (AttachAck / MsgResized); recording our request as if it were the answer is what used to make the overview's replay grid disagree with the real terminal.
func (*Session) SearchHistory ¶ added in v0.12.0
func (s *Session) SearchHistory(req muxd.HistorySearchReq) (muxd.HistorySearchAck, error)
SearchHistory finds text in this session's scrollback, IN THE DAEMON.
func (*Session) SetName ¶ added in v0.12.0
SetName renames the session (thread-safe). Clears Title too: sessionTitle() prefers Title over Name, so an explicit user rename must win over whatever static Title the session was created with, or the old value would keep winning forever no matter what the user renames it to — the exact bug this method exists to close (a renamed tab's notifications kept the pre-rename name because nothing ever wrote a new value back to the session at all).
func (*Session) SetViewerOwner ¶ added in v0.12.0
SetViewerOwner makes one viewer the session's sole owner of the grid, or clears ownership when subID is empty, and re-declares the resulting size.
Called where preemption already happens, so that "who receives the output" and "whose window sizes the session" cannot answer differently — they are the same question asked twice, and the whole failure this replaces came from letting them drift.
func (*Session) SetViewerSize ¶ added in v0.12.0
SetViewerSize records the size of ONE viewer's window and re-declares this server's aggregate to the daemon.
0×0 is a legitimate, meaningful argument: "I am still here, still receiving output, but I am not displaying this session any more — do not size the PTY for me." A backgrounded browser tab says exactly that. Rejecting it as out-of-bounds (the obvious reading of a zero size) would make withdrawal impossible and turn the minimum into a ratchet.
A viewer that has already disconnected is not an error: the socket closing and the last resize crossing on the wire is an ordinary race, and the registry has already forgotten the constraint that resize was about to change.
func (*Session) TailOutput ¶
TailOutput returns the last n lines of terminal output from the RingBuffer. Used by agent intel for output analysis in direct (non-tmux) mode.
func (*Session) Viewport ¶ added in v0.12.0
Viewport returns the size this server declares on its attachment: the window of the viewer that OWNS the session, or 0,0 when no browser owns it.
## Why ownership rather than the minimum
This used to min over every viewer, on tmux's rule and tmux's reason. It does not any more, because this server is not tmux: a browser attaching here already PREEMPTS whoever held the session (SetActiveConn, and the "Session 已被其他设备接管" banner that goes with it). Only one browser can be receiving output at a time, so minimising across the others gave the vote to windows that were no longer being drawn into — and worse, the preemption is asynchronous: the losing connection unsubscribes from its own defer, so for the length of one handler teardown BOTH viewers were in the map and the session took the smaller.
The result was a grid that oscillated on every tab switch. Each oscillation makes the program inside repaint at the new size, appending a screen's worth of bytes to the ring at a width the next replay will not be using — see gridSeq for what that does to the picture. A phone opening the same session reflowed the desktop watching it, then handed it back on disconnect, and neither window ever settled.
So: exclusive. The owner's window is the session's size, and a viewer that has been preempted has no vote — it is not displaying the session any more, which is exactly the condition SetViewerSize's 0×0 already describes. The daemon still mins across its own clients (another host's server, a `dw-terminal attach` CLI): those genuinely ARE simultaneous, and smallest-wins remains right where windows really do coexist.
func (*Session) WorkingDir ¶
WorkingDir returns the working directory of the session.
func (*Session) WriteInput ¶ added in v0.12.0
WriteInput sends bytes to the session's PTY, which lives in the daemon.
It replaces every `sess.PTY.Write(...)` call site. Those used to reach a file descriptor this process owned; now the bytes travel over the protocol. Keeping it as one method means there is a single place where "type into this session" is defined, rather than four callers each holding an fd.
The attached stream is preferred when there is one — it is the hot path and carries raw frames — with the control connection as the fallback for callers that never attached (the HTTP input endpoint).
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Title string `json:"title,omitempty"`
Engine string `json:"engine"`
CWD string `json:"cwd"`
Status SessionStatus `json:"status"`
CreatedAt string `json:"created_at"`
LastActive string `json:"last_active"`
ShellPID int `json:"shell_pid,omitempty"`
TmuxDetected bool `json:"tmux_detected,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
}
SessionInfo is the service-layer representation of a terminal session. It avoids exposing the internal Session struct (with PTY, Cmd, etc.) to callers outside the package.
type SessionManager ¶
type SessionManager struct {
// OnSignal is called from the PTY read goroutine for every EXPLICIT out-of-band signal
// the program emitted (BEL / OSC notification — see ansisignal). It is a pure tap: the
// bytes are already on their way to the browser by the time it runs, and nothing it does
// can alter them.
//
// Must be set BEFORE the first session is created (NewServer does): read loops run
// concurrently, so assigning it later is a data race. It runs on the output hot path, so
// the implementation must not block — see onSessionSignal for how that is honoured.
OnSignal func(*Session, ansisignal.Signal)
// Set before Restore/Create; observes bounded clipboard writes without browser ownership.
OnClipboard func(*Session, string, int64, bool)
// EnvSource answers "what environment should the NEXT shell start with". Called per create,
// never cached, because the whole point of the overlay behind it is that editing it takes
// effect on the next terminal WITHOUT restarting this process (see env_overlay.go).
//
// A hook rather than a direct call so this file keeps knowing nothing about where the
// overlay lives; nil falls back to this process's own environment, which is what every
// session got before the overlay existed.
EnvSource func() []string
// contains filtered or unexported fields
}
SessionManager manages terminal sessions with PTY processes. All state is held in memory (IR-03: no DB, no persistence). [Ref: T5-B3, CAP-session-lifecycle S2, DDC-11]
func NewSessionManager ¶
func NewSessionManager(bufferSize int, defaultShell string) *SessionManager
NewSessionManager creates a new SessionManager.
func NewSessionManagerWithFactory ¶
func NewSessionManagerWithFactory(bufferSize int, defaultShell string, factory PTYFactory) *SessionManager
NewSessionManagerWithFactory creates a SessionManager backed by an IN-PROCESS daemon using the given PTY factory. Test fixtures use it to drive terminal output through a pipe.
It is a fixture, not a second deployment mode: the sessions still live in a muxd Daemon, reached over a real unix socket with the real protocol. What differs is only where that daemon is hosted. (A "run the daemon in-process for production too" option was considered and rejected — persistence would hold in one mode and not the other, which is two products wearing one name.)
func (*SessionManager) ClearActiveConn ¶
func (m *SessionManager) ClearActiveConn(sessionID string, conn *websocket.Conn)
ClearActiveConn removes the active connection entry for a session if it matches the given conn.
func (*SessionManager) CloseAll ¶
func (m *SessionManager) CloseAll() error
CloseAll DETACHES from the daemon. Called during server shutdown.
It used to destroy every session, and that was the bug: shutting down the HTTP server is not a request to end the user's work. Restarting after a recompile took every tab with it — the exact symptom dw-muxd exists to remove. The sessions keep running in the daemon and are picked back up by Restore on the next start.
Deliberate destruction still exists and is still reachable — it is DestroyAll, and the two must never be collapsed back into one.
func (*SessionManager) Create ¶
func (m *SessionManager) Create(name string) (*Session, error)
Create creates a new terminal session with a PTY process. [Ref: T5-B3, T5-B4.M1, CAP-session-lifecycle S2]
func (*SessionManager) CreateWithOptions ¶
func (m *SessionManager) CreateWithOptions(opts CreateOptions) (*Session, error)
CreateWithOptions creates a new terminal session with product metadata.
func (*SessionManager) DaemonHealth ¶ added in v0.12.0
func (m *SessionManager) DaemonHealth() DaemonHealth
DaemonHealth probes the daemon WITHOUT starting one.
That restraint is the entire point: a health check that spawns the thing it is measuring always reports health. "No daemon is running" is a true and useful answer, and here it is a benign one — the next session created will start one.
func (*SessionManager) Destroy ¶
func (m *SessionManager) Destroy(id string) error
Destroy terminates a session's PTY process and removes it from the manager. [Ref: CAP-session-lifecycle S2]
func (*SessionManager) DestroyAll ¶
func (m *SessionManager) DestroyAll()
DestroyAll terminates every session for real.
This is the EXPLICIT teardown: tests cleaning up after themselves, and any deliberate "end everything" action. It is intentionally NOT what shutdown calls — see CloseAll.
func (*SessionManager) Get ¶
func (m *SessionManager) Get(id string) (*Session, error)
Get returns a session by ID or an error if not found.
func (*SessionManager) List ¶
func (m *SessionManager) List() []*Session
List returns all sessions. List returns every live session in STABLE CREATION ORDER (oldest first).
The sort is load-bearing, not cosmetic. sync.Map.Range visits in an unspecified order that varies between calls, and pro's CLI derives its whole tab strip straight from this list — so an unsorted List() meant:
- a newly created terminal could appear anywhere in the strip, including first, where the position-based label renders it as "终端1" while an older tab is also showing "终端1";
- the numbers reshuffled on every poll, which silently breaks the two things built on top of them — `prefix+N` jump-to-tab and the overview card numbering (both promise "the number you see is the number you press").
Creation order is also simply what a user means by "the new tab goes on the end". Ties (two sessions created inside the same clock tick) fall back to ID so the order is total and never flickers between two equally-old sessions.
func (*SessionManager) Restore ¶ added in v0.12.0
func (m *SessionManager) Restore() error
Restore rebuilds the session view from what the daemon holds. It is what makes a restart invisible: the tabs, their names, their scrollback and their running processes were never in this process to begin with, so coming back is a matter of asking.
Sessions the daemon reports but this process has never seen are adopted, which is the whole point — they were created by a previous run of the server (or by another host entirely, since the daemon is per-user rather than per-server).
It also RECONCILES in the other direction: sessions in the local view that the daemon no longer holds are removed. That is what makes cross-host visibility eventual rather than best-effort. Events can be missed — a subscriber that falls behind drops them, and a server that was disconnected while something happened never sees them at all — and without this pass a tab deleted elsewhere, or one whose daemon died while we were not looking, stayed on screen forever, swallowing keystrokes.
It never spawns. A daemon that is not running holds no sessions, so there is nothing to restore and saying so is the correct answer; the next create will start one.
func (*SessionManager) SetActiveConn ¶
func (m *SessionManager) SetActiveConn(sessionID string, conn *websocket.Conn, cancel context.CancelFunc) uint64
SetActiveConn registers a new active WS connection for a session, preempting any existing one. BUG-3: Only one WS connection per session is allowed at a time.
func (*SessionManager) SetOrigin ¶ added in v0.12.0
func (m *SessionManager) SetOrigin(origin string)
SetOrigin names the deployment this manager belongs to, so sessions it creates can be told apart from those of another deployment sharing the same per-user daemon (see sessionMeta.Origin). Must be called before the first Create.
func (*SessionManager) Subscribe ¶
func (m *SessionManager) Subscribe(sess *Session, subID string) (<-chan viewerFrame, int, int, func())
Subscribe registers one viewer — a WebSocket connection — and returns its frame channel plus the function that removes it.
The new viewer starts as an OBSERVER: it receives output but declares no size until the browser measures its own terminal and calls SetViewerSize. Seeding it with a guess would let a tab that has not even rendered yet shrink the session for everyone already watching.
Unsubscribing withdraws its size as part of removing it — the two cannot be separated because they are one entry. That is what stops a closed window from constraining the session forever, and it is why the size lives in this registry rather than beside it.
It also returns the grid the session is running at AS OF the moment this viewer joined. That is not a convenience — it is the only value the caller may announce. Reading it separately afterwards races applyGrid: a resize landing in between would leave the caller announcing the NEW size to a browser whose queue still holds bytes drawn at the old one, and old-grid bytes painted onto a new grid is a scrambled screen, not a slightly-off one. The daemon's own Subscribe hands back replay and geometry together for the same reason.
func (*SessionManager) WatchDaemon ¶ added in v0.12.0
func (m *SessionManager) WatchDaemon(ctx context.Context)
WatchDaemon keeps this server's view in step with the daemon for as long as ctx lives.
It exists because the daemon is per-USER, not per-server: the same daemon backs the standalone build and the embedded one, so a tab created in one is a real session the other should see. Polling would make that "eventually, on the next refresh"; subscribing makes it immediate.
Events are treated as a TRIGGER to re-read, never as the new state themselves. The daemon stays the single source of truth — an event only says "something changed", and the answer to "changed to what" is fetched. That keeps one authority rather than two that can disagree, which is the failure this whole design is organised against.
type SessionMeta ¶
SessionMeta is passed to OnSessionStart.
type SessionMetaPayload ¶
type SessionMetaPayload struct {
TmuxDetected bool `json:"tmux_detected"`
}
SessionMetaPayload is pushed to the client once after the WS replay buffer is sent. The client uses TmuxDetected to decide whether to show tmux gesture hints.
type SessionOverviewEntry ¶ added in v0.7.13
type SessionOverviewEntry struct {
ID string `json:"id"`
Title string `json:"title"`
CWD string `json:"cwd,omitempty"`
Engine string `json:"engine,omitempty"`
// Exited marks a dead PTY. Kept explicit rather than inferred from an empty tail: a live shell
// that has simply printed nothing is NOT the same as one whose process is gone.
Exited bool `json:"exited,omitempty"`
// TmuxDetected mirrors Session.TmuxDetected — the tab strip's right-click menu needs it to
// decide whether "结束卡死进程" (force-kill the foreground process) applies to THIS tab, for
// every tab, not just the currently-active one. Single-session GET already exposed the same
// fact (handleGetSession); this is that fact reaching the ALL-sessions feed the menu is built
// from, so a background tab doesn't have to become active before its menu can be trusted.
TmuxDetected bool `json:"tmuxDetected,omitempty"`
// Embedded, not listed: the CARD — its agent facts and its tail, the same declaration the tmux
// window carries (agentintel/surface_card.go). AgentTool / AgentStatus still come from the same
// detector the session list uses — literally the same snapshot (handleListSessions reads this
// struct), so a card and its tab dot cannot disagree even for one tick.
//
// This card has exactly ONE unit and that unit is the session itself, so its facts and the
// unit's are the same values — which is not a shortcut taken here but the general rule applied
// to N=1 (RollUp is used below rather than assigning around it, and TestRollUp_OneUnitIsIdentity
// is what makes that safe to rely on).
agentintel.SurfaceCard
}
SessionOverviewEntry is one card in the non-tmux Agent Overview.
The agent facts are NOT declared here: they are the embedded SurfaceUnit, the single declaration this payload shares with the tmux pane (agentintel/tmux_state.go). This comment used to say "field names mirror the tmux pane/window payload … so the frontend can normalize both sources into ONE card model" — an accurate description of the intent and a request the compiler could not enforce. It is now enforced: there is one field list, so a card and a pane cannot describe the same fact under different names, and neither can grow a fact the other lacks.
type SessionSnapshot ¶
SessionSnapshot is a point-in-time session state for persistence.
type SessionStatus ¶
type SessionStatus string
SessionStatus represents the lifecycle state of a terminal session. [Ref: T5-B3, CAP-session-lifecycle S2]
const ( StatusRunning SessionStatus = "running" StatusExited SessionStatus = "exited" )
type SessionStore ¶
type SessionStore interface {
SaveSession(ctx context.Context, s *SessionSnapshot) error
ListSessions(ctx context.Context) ([]SessionSummary, error)
}
SessionStore is optional persistence. nil = in-memory only (data lost on restart).
type SessionSummary ¶
SessionSummary is a brief session descriptor.
type ShellExitPayload ¶
type ShellExitPayload struct {
ExitCode int `json:"exitCode"`
}
ShellExitPayload is the payload for a "shell_exit" control message.
type TermMsg ¶
type TermMsg struct {
Type string `json:"type"`
Data string `json:"data,omitempty"` // input / output
Cols int `json:"cols,omitempty"` // resize
Rows int `json:"rows,omitempty"` // resize
Reason string `json:"reason,omitempty"` // closed
ExitCode int `json:"exit_code,omitempty"` // closed
}
TermMsg 是 WebSocket 文本帧的统一 JSON 格式 [T5 §5.2 §5.3]
type TerminalSessionService ¶
type TerminalSessionService interface {
// List returns all active sessions.
List(ctx context.Context) ([]SessionInfo, error)
// Create starts a new PTY-backed session with the given options.
Create(ctx context.Context, opts CreateOptions) (*SessionInfo, error)
// Get returns the session info for the given ID.
// Returns an error wrapping "not found" when the session does not exist.
Get(ctx context.Context, id string) (*SessionInfo, error)
// Delete destroys the session identified by id, killing the PTY process.
Delete(ctx context.Context, id string) error
// Resize sets the terminal window size for the session.
Resize(ctx context.Context, id string, cols, rows int) error
// Input writes raw terminal bytes to the session PTY.
// Used by the HTTP fallback path (WKWebView POST /sessions/:id/input).
Input(ctx context.Context, id string, data []byte) error
// PasteUpload saves clipboard content to a temp file under the session CWD
// and returns the absolute path. filename is the original filename hint;
// content is the raw file body; sessionCWD is the working directory to use
// (pass empty string to use the session's own CWD).
PasteUpload(ctx context.Context, id string, filename string, content io.Reader, sessionCWD string) (string, error)
// TailOutput returns the last n lines of terminal output for agent intel.
TailOutput(ctx context.Context, id string, lines int) ([]string, error)
// Close shuts down the service and destroys all sessions.
Close() error
}
TerminalSessionService is the service-layer interface for terminal session management. Implementations: InProcessService (delegates to SessionManager directly) or a future RemoteService (proxies to a TerminalMuxHost over HTTP). The webui layer and tests depend only on this interface, enabling the underlying transport to be swapped without touching callers.
type TmuxCopyMotioner ¶ added in v0.2.0
TmuxCopyMotioner is an OPTIONAL provider capability: drive a copy-mode scroll motion directly against the tmux server (bypassing the PTY keystroke stream, which silently no-ops for these motions). The default provider implements it; a host-injected provider may omit it, in which case the endpoint 501s gracefully.
type TmuxNavPayload ¶
type TmuxNavPayload struct {
}
TmuxNavPayload is the payload for a "tmux_nav" control message. The backend silently ignores the action when TmuxDetected=false.
type TmuxOverviewToggler ¶ added in v0.7.0
type TmuxOverviewToggler interface {
SetOverviewActive(v bool)
}
TmuxOverviewToggler is an OPTIONAL provider capability: gate per-window live-tail capture on whether a client has the Agent Overview open — so tail costs nothing when nobody's viewing it.
type TmuxRefresher ¶ added in v0.6.0
TmuxRefresher is an OPTIONAL provider capability: force a full server-side redraw to the caller's tmux client. Used by the UI to resync xterm.js when its buffer has diverged from tmux's model (ghosting under fullscreen TUIs). Default provider implements it.
type TmuxSessionMaker ¶ added in v0.2.0
TmuxSessionMaker is an OPTIONAL provider capability: create a new tmux session and switch the requesting client onto it (server-side, since keystroke-driven new-session is unreliable and refuses to nest inside a client). Default provider implements it.
type TmuxStateProvider ¶ added in v0.2.0
type TmuxStateProvider interface {
TmuxState(ctx context.Context, shellPID int) (json.RawMessage, error)
}
TmuxStateProvider yields a JSON-encoded tmux topology snapshot for the host.
The terminal ships a default, in-process provider (defaultTmuxProvider) so the standalone build gets tmux topology/prefix/agent-status without any host wiring. A host (e.g. the pro repo) may inject a richer provider via WithTmuxProvider; this is purely additive and never required.
shellPID is the calling session's shell PID (0 when unknown); it lets the provider compute whether that specific shell is attached inside tmux.
type TmuxWindowSelector ¶ added in v0.7.6
TmuxWindowSelector is an OPTIONAL provider capability: switch the requesting client onto a window by index, server-side. The keystroke route leaks a `select-window -t N` burst into the focused pane for index ≥10 (tmux binds prefix+digit only up to 9), so this drives it against the socket instead. The default provider implements it; a host-injected provider may omit it, in which case the endpoint 501s gracefully.
type WSControlMessage ¶
type WSControlMessage struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload,omitempty"`
}
WSControlMessage represents a JSON control message on the WebSocket. Binary frames carry raw terminal I/O; Text/JSON frames carry control messages. [Ref: T5-B3, CAP-terminal-io S3, DDC-02]
func WaitForControlMessage ¶
func WaitForControlMessage(t *testing.T, ws *websocket.Conn, msgType string, timeout time.Duration) WSControlMessage
WaitForControlMessage reads WS messages until a control message of the given type is found.
Source Files
¶
- agent_index_store.go
- agent_notifier.go
- agent_outcomes.go
- agent_report.go
- agent_state_provider.go
- archive_preview.go
- authcode.go
- claude_tui.go
- clipboard_handlers.go
- clipboard_native.go
- clipboard_native_other.go
- clipboard_paste.go
- clipboard_store.go
- clipboard_stream.go
- config.go
- convert_office.go
- env_overlay.go
- files.go
- files_chunk.go
- files_crud.go
- files_cwd_probe.go
- files_search_index.go
- git.go
- handlers.go
- history_api.go
- history_tail.go
- hooks.go
- http_inflight.go
- ilink.go
- input_observe.go
- inputs.go
- localclient.go
- metrics.go
- muxd_alias.go
- notify_providers.go
- notify_stats.go
- observe.go
- overview.go
- paste_infer.go
- paste_mode.go
- paste_replay.go
- proc_cwd.go
- proc_cwd_linux.go
- protocol.go
- reconnect_pack.go
- release_check.go
- replay_strip.go
- screen.go
- server.go
- service.go
- service_inproc.go
- session_agent.go
- session_manager.go
- session_mux.go
- session_screen.go
- session_seed.go
- session_signal.go
- session_viewport.go
- sessions_overview.go
- sessions_overview_tmux.go
- settings.go
- stream_boundary.go
- testutil.go
- testutil_mux.go
- tmux_handlers.go
- tmux_provider.go
- types.go
- upload_limit.go
- upload_pacing.go
- uploads.go
- uploads_index.go
- usage.go
- usage_codex_declaration.go
- usage_credentials.go
- version.go
- websocket_compat.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ansisignal extracts the out-of-band signals a terminal program emits when it wants the human back: the ASCII BEL (0x07) and the OSC desktop-notification sequences (iTerm2 OSC 9, the OSC 777 "notify" extension, kitty's OSC 99).
|
Package ansisignal extracts the out-of-band signals a terminal program emits when it wants the human back: the ASCII BEL (0x07) and the OSC desktop-notification sequences (iTerm2 OSC 9, the OSC 777 "notify" extension, kitty's OSC 99). |
|
cmd
|
|
|
dw-terminal
command
|
|
|
internal
|
|
|
Package muxd implements dw-muxd: the resident daemon that owns every PTY, and the client half that dw-terminal uses to reach it.
|
Package muxd implements dw-muxd: the resident daemon that owns every PTY, and the client half that dw-terminal uses to reach it. |
|
Package notify is the host-agnostic notification provider abstraction shared by deepwork-terminal and deepwork-pro (imported like agentintel).
|
Package notify is the host-agnostic notification provider abstraction shared by deepwork-terminal and deepwork-pro (imported like agentintel). |
|
scripts
|
|
|
diag/pricecov
command
Command pricecov reports WHY usage facts go unpriced.
|
Command pricecov reports WHY usage facts go unpriced. |
|
diag/switchlat
command
switchlat — how long does ONE tmux window switch take, and where does the time go?
|
switchlat — how long does ONE tmux window switch take, and where does the time go? |
|
diag/tmuxprobe
command
tmuxprobe — what does ONE status probe cost, and what happens when N connections each want one?
|
tmuxprobe — what does ONE status probe cost, and what happens when N connections each want one? |
|
diag/uploadlat
command
uploadlat — does a big upload steal the terminal?
|
uploadlat — does a big upload steal the terminal? |
|
diag/wsprobe
command
wsprobe — attach a session's WebSocket exactly like the browser does, and measure what the SERVER pushes at an IDLE terminal.
|
wsprobe — attach a session's WebSocket exactly like the browser does, and measure what the SERVER pushes at an IDLE terminal. |















