terminal

package module
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 60 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

deepwork-terminal

English | 简体中文

A mobile-first web terminal for watching and steering your AI coding agents (Claude Code / Codex) — reach the machine where the agent actually runs from anywhere: your phone on the go, or a browser tab in place of an SSH session on a remote box. Sessions live in tmux, so they survive disconnects. With auth, one-flag public access via Cloudflare tunnel, WeChat / Feishu / Web Push notifications, and an embedded Vue frontend. Drop it into any Go application via a single HTTP handler.

Why deepwork-terminal

You kick off a long refactor in Claude Code and close your laptop. On the way out it stalls on a Proceed? [Y/n] — and the rest of the run is wasted. Agents run async on one machine; you don't stay at that machine.

deepwork-terminal unpins the terminal: it puts the agent's status, its output files, and that [Y/n] prompt in any browser, keeps the session alive across disconnects, and pings you (WeChat / Feishu / Web Push) the moment an agent needs you or finishes.

Who it's for

Three situations where it earns its place:

1 · You step away — the agent shouldn't stall. You're running Claude Code / Codex on your desktop, then you're off to a meeting or out the door. When the agent hits a [Y/n] or finishes, a push — WeChat / Feishu / browser Web Push — finds you; tap it to deep-link straight to that session and reply in one line. The input box is a normal field, so multi-line text and your phone's voice input go right to the agent. Async agent, mobile you.

2 · Remote development that survives the network. Your session lives in tmux on the dev box, so the process persists — lock the phone, switch apps, drop off wifi, hop networks; reconnect and you're exactly where you left off. A two-hour agent run never dies to a flaky link. It's tmux/screen's "detach and survive," but with a web/mobile UI you'll actually want to use — reach it over HTTPS from anywhere via the built-in Cloudflare tunnel or your own Tailscale.

3 · Heavy tmux user, many panes. Several agents open at once. deepwork-terminal gives tmux the best touch/web control layer there is: a one-row quick-key bar (copy / split / switch pane / new session, live prefix shown — nothing to memorize), a pane overview, and one-tap window switching. Flipping between agents gets smooth enough that you stop reaching for the raw terminal.

Across all three — SSH-grade file transfer, no scp. Copy, upload, download, and browse files in the agent's working tree, all in the browser: Ctrl/Cmd+V a screenshot straight into the cwd (relative path auto-injected), upload from your phone's camera roll, chunked resumable upload for big files over a flaky link or a tunnel, one-tap download, and a VS-Code-style directory tree (create / rename / delete, fuzzy search, in-browser preview). The moves that are clumsy over SSH become one step.

Not for someone who only codes in one window on one machine and never goes remote — you genuinely don't need this.

Features

Watch & steer AI coding agents

  • Live agent status (running / waiting / idle) for Claude Code & Codex, with per-session token & cost overview
  • Notify on Web Push (PWA) and WeChat (iLink official channel) when an agent needs you — tap to deep-link back to the exact session
  • Multi-device session takeover — switch between phone and PC mid-task

Mobile-first terminal

  • Full PTY terminal over WebSocket, with reconnect
  • Quick-keyboard bar for tmux (copy-mode, split / zoom / switch pane, new / list / detach session) — no shortcuts to memorize, dynamic prefix
  • Paste a screenshot with Ctrl/Cmd+V → lands in the active pane's cwd, path injected into the terminal; mobile upload and one-tap download too
  • Remote clipboard: automatic foreground tmux / SSH text copying, searchable history, and explicit text transfer to a selected terminal or pane (guide)
  • Resource drawer: cross-session upload index, input-history reuse, fuzzy file search, and in-browser preview of agent output — markdown, code, text/logs, and HTML reports (source ⇄ rendered toggle)

Deploy anywhere

  • Embedded Vue SPA — zero static file serving; ships as a single binary
  • One-flag public access — --tunnel opens a Cloudflare quick tunnel at launch (auto-downloads cloudflared, no account needed); persistent named tunnels via the UI
  • Hook points for auth, session lifecycle, and shell customization

Install

AI-native — just ask your coding agent. You already have Claude Code or Codex open; hand it the whole job in one sentence:

"Install deepwork-terminal from github.com/brightman-ai/deepwork-terminal — grab a prebuilt binary for my platform, or build from source if there isn't one. Run it on port 8222, then ask me whether to expose it on the public internet with --tunnel."

The agent downloads (or builds), launches, and reads the access URL + login code back to you from the startup output. Because public access is a single --tunnel flag, "now make it reachable from my phone" is one more sentence — no dashboard, no config file.

Prefer to do it by hand? A prebuilt binary, no Go or Node required:

curl -fsSL https://raw.githubusercontent.com/brightman-ai/deepwork-terminal/main/install.sh | sh

Installs dw-terminal to ~/.local/bin for Linux (amd64/arm64) and macOS (universal). On WSL, this is the right path — it just works. Pin a version or change the directory:

curl -fsSL https://raw.githubusercontent.com/brightman-ai/deepwork-terminal/main/install.sh | sh -s -- --version=v0.5.1 --dir=/usr/local/bin
Homebrew (macOS / Linux)
brew install brightman-ai/tap/dw-terminal
Go (developers, Go ≥ 1.26)
go install github.com/brightman-ai/deepwork-terminal/cmd/dw-terminal@latest

Slow or blocked network? Set a proxy so module + Go-toolchain downloads succeed (./build.sh and install.sh --from-source already default to this):

GOPROXY=https://goproxy.cn,direct go install github.com/brightman-ai/deepwork-terminal/cmd/dw-terminal@latest
Frontend checks

The frontend tests use Bun. From the repository root, install the locked dependencies and run the suite and type-check. Type-check/build also need the brightman-ai/deepwork checkout beside this repository because the frontend shares its CE components:

cd frontend
bun install --frozen-lockfile
bun run test
bun run type-check
bun run build

No Go installed but want a source build? The installer can bootstrap the latest stable Go:

curl -fsSL https://raw.githubusercontent.com/brightman-ai/deepwork-terminal/main/install.sh | sh -s -- --from-source --install-go
Manual download

Grab a tarball from the Releases page and put dw-terminal on your PATH.

Verify & run
dw-terminal --version
dw-terminal --addr :8222              # serve on port 8222 (reachable on your LAN)
dw-terminal --addr :8222 --tunnel     # ... and expose it on the public internet

On startup dw-terminal prints — to stdout, so an agent driving it can read them straight back — the reachable URLs (local + network, plus the public *.trycloudflare.com URL when --tunnel is set) and the login code. Run dw-terminal --help for all flags.

Platform notes

  • Linux / WSL — one Linux binary covers both. On WSL2 a Windows browser reaches the server at http://localhost:<port>.
  • macOS — release binaries are signed with a Developer ID and notarized, so Gatekeeper allows them. (Homebrew and the install script also clear the quarantine flag as a fallback.)

Screenshots

Standard view — tmux panes + quick-key toolbar


Paste, type, or speak to the agent

Ctrl/Cmd+V a screenshot and the relative path is injected. The input box is also a normal field, so multi-line text and your phone's voice input go straight in.

Multi-line text input

Voice input via the system keyboard


Watch agents from your phone — multi-channel notify

Push "an agent is waiting" to wherever you already look — WeChat / Feishu / WeCom / DingTalk.

Multi-channel notifications

WeChat (iLink) quota: each message you send buys ~10 pushes; reply anything to refresh.

WeChat notify

WeChat notify

A status strip up top shows each session's state plus connection latency.

Health / latency strip


tmux without the shortcuts

Two toolbars — one for tmux (panes / sessions), one general — with your live prefix shown. No tmux? Multiple terminals still work.

Multiple terminals without tmux


Cross-session continuity — uploads, history, file drawer

Past uploads and the prompts you actually typed are reusable from any new session; the file drawer browses the tree and previews files in the browser.


More

Per-session token & cost overview; phone and PC share one session with takeover.

Session cost overview

Multi-device takeover

🔔 Notifications setup

When an agent needs you (waiting on [Y/n], or done), deepwork-terminal pushes to any enabled channel:

Channel Default Credential
WeChat (iLink) on scan-to-login
Browser Web Push (PWA) on grant permission
Feishu / Lark off webhook URL + secret (sign)
DingTalk off webhook URL + secret (sign)
WeCom (企业微信) off webhook URL (key in URL)
Slack off webhook URL

Everything is configured in Settings → Notifications. Each channel has an enable toggle, a 配置 Webhook form (URL + optional secret), and a 测试 (Test) button that fires a real message and echoes the honest backend result. URLs/secrets are encrypted at rest and redacted in the UI (secret is write-only).

To get each webhook URL:

Feishu / Lark
  1. In a group: Settings → Group Bots → Add Bot → Custom Bot.
  2. Security: choose 签名校验 (Signature verification) and copy the secret.
  3. Copy the Webhook URL (https://open.feishu.cn/open-apis/bot/v2/hook/…).
  4. App → 配置 Webhook → paste URL + Secret → 保存 → enable → 测试.
    • Sign mismatch returns 19021 — recheck the secret. (If you picked "keyword" mode instead, the message must contain that keyword — signature mode is recommended.)
🔔 DingTalk
  1. Group → Settings → Group Assistant → Add Bot → Custom.
  2. Security: choose 加签 (Additional signature) and copy the secret (starts with SEC).
  3. Copy the Webhook URL (https://oapi.dingtalk.com/robot/send?access_token=…).
  4. App → paste URL + Secret (加签) → 保存 → enable → 测试.
    • Sign error → 310000 sign not match. Avoid "keyword" mode (messages may be rejected).
WeCom (企业微信)
  1. Group → … → Group Bots → Add → Create.
  2. Copy the Webhook URL (https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…). The key in the URL is the credential — no secret needed.
  3. App → paste URL (leave Secret blank) → 保存 → enable → 测试.
    • 93000 → the URL/key is wrong, or the bot was removed from the group.
Slack
  1. Create an incoming webhook: api.slack.com/apps → Create New App → Incoming Webhooks → Activate → Add New Webhook to Workspace, then pick a channel.
  2. Copy the Webhook URL (https://hooks.slack.com/services/…). The URL is the credential — no secret needed.
  3. App → paste URL (leave Secret blank) → 保存 → enable → 测试.
    • Success returns ok; a malformed request returns invalid_payload. The server must be able to reach hooks.slack.com (may need a proxy in some regions).

Limitations (honest)

A project that only sells itself isn't worth trusting — a few boundaries up front:

  • No native app — it's web-first (PWA), not an App Store application; iOS Web Push has platform caveats.
  • Early-stage — few stars yet; ecosystem, docs, and community are all early.
  • Local-only — it's a remote control for the machine the agent runs on, not a cloud agent-scheduler. You can still reach it over HTTPS from anywhere via the built-in Cloudflare Tunnel.

Quick Start (as a library)

go get github.com/brightman-ai/deepwork-terminal
import terminal "github.com/brightman-ai/deepwork-terminal"

srv := terminal.New(terminal.DefaultConfig())
http.Handle("/terminal/", srv.Handler())
http.ListenAndServe(":8080", nil)

Or run the CLI directly:

go run ./cmd/dw-terminal

See guide/ for full documentation.

Build from source

git clone https://github.com/brightman-ai/deepwork-terminal
cd deepwork-terminal
./build.sh

build.sh handles everything in one step:

  1. Clones (or pulls to latest) the CE App Shell (brightman-ai/deepwork) into a sibling directory
  2. Runs npm install to pick up any new frontend dependencies
  3. Builds the Vue frontend and embeds it into internal/spa/dist/
  4. Downloads any new Go module dependencies (go mod download)
  5. Compiles the Go binary → ./dw-terminal

To update to the latest version after an initial clone:

git pull
./build.sh

Requires: Go 1.26+, Node.js 18+, npm.

Headless servers: npm install browser-download hooks (Playwright/Puppeteer) are suppressed automatically via PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1.

Go binary only (no frontend changes)

The frontend is pre-built and committed to internal/spa/dist/. If you only need to recompile the Go binary:

./build.sh --skip-frontend

Or manually:

go build -o dw-terminal ./cmd/dw-terminal/

Contributing

Open source under MIT. If you run Claude Code / Codex heavily and often work away from your desk, give it a try — a ⭐ or an issue is always welcome.

License

MIT

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

View Source
const (
	// MsgInput 键盘输入 / 控制序列 (客户端→服务端)
	MsgInput = "input"
	// MsgResize 窗口大小变化 (客户端→服务端)
	MsgResize = "resize"
	// MsgPing 心跳 (客户端→服务端)
	MsgPing = "ping"
)
View Source
const (
	// MsgOutput PTY 输出 ANSI 透传 (服务端→客户端)
	MsgOutput = "output"
	// MsgClosed 终端关闭通知 (服务端→客户端)
	MsgClosed = "closed"
	// MsgPong 心跳响应 (服务端→客户端)
	MsgPong = "pong"
)
View Source
const (
	ClosedReasonNormal     = "normal"
	ClosedReasonCrashed    = "crashed"
	ClosedReasonStopCalled = "stop_called"
)
View Source
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)
	MsgTypeTmuxNav      = "tmux_nav"     // client → server: navigate tmux windows/sessions
	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.

View Source
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

)
View Source
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

func BuildVersion(injected string) string

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

  1. 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.
  2. 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

func ClipboardBufferPath(dataDir, target string) string

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

func IsNewerRelease(current, latest string) bool

IsNewerRelease 报告 latest 是否严格新于 current。两者都必须是干净的发布版,否则一律返回 false —— 比不了就不比,绝不猜。

func LoadUploadLimit added in v0.7.11

func LoadUploadLimit(dataDir string) error

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

func SessionCWD(meta []byte) string

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

func SessionLabel(meta []byte, id string) string

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

func SetUploadLimitMB(mb int) (int, error)

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

func WaitForPTYReady(t *testing.T, sm *SessionManager, sessionID string, timeout time.Duration)

WaitForPTYReady waits for the session to appear in the SessionManager.

Types

type AgentDetectFunc

type AgentDetectFunc func(ctx context.Context, shellPID int, cwd string) (tool, status string)

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.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults.

type CreateOptions

type CreateOptions struct {
	Name   string
	Title  string
	Engine string
	Shell  string
	CWD    string
}

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

type ErrorPayload struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

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

Create implements TerminalSessionService.

func (*InProcessService) Delete

func (s *InProcessService) Delete(_ context.Context, id string) error

Delete implements TerminalSessionService.

func (*InProcessService) Get

Get implements TerminalSessionService.

func (*InProcessService) Input

func (s *InProcessService) Input(_ context.Context, id string, data []byte) error

Input implements TerminalSessionService. Writes raw bytes directly to the session's PTY file descriptor.

func (*InProcessService) List

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) Resize

func (s *InProcessService) Resize(_ context.Context, id string, cols, rows int) error

Resize implements TerminalSessionService.

func (*InProcessService) TailOutput

func (s *InProcessService) TailOutput(_ context.Context, id string, lines int) ([]string, error)

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 WithAddr

func WithAddr(addr string) Option

WithAddr sets the listen address.

func WithAuthCode

func WithAuthCode(code string) Option

WithAuthCode sets the auth code. When left empty, NewServer generates one.

func WithConfig

func WithConfig(c Config) Option

WithConfig replaces the entire config.

func WithHooks

func WithHooks(h Hooks) Option

WithHooks sets integration hooks.

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

func WithTunnel(enabled bool) Option

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

type ReleaseInfo struct {
	Tag string `json:"tag"`
	URL string `json:"url"`
}

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

type ResizePayload struct {
	Cols int `json:"cols"`
	Rows int `json:"rows"`
}

ResizePayload is the payload for a "resize" control message. [Ref: T5-B3]

type ResizedPayload added in v0.12.0

type ResizedPayload struct {
	Cols int `json:"cols"`
	Rows int `json:"rows"`
}

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.

func (*SafeWriteEnds) Get

func (s *SafeWriteEnds) Get(index int) *os.File

Get returns the write end at the given index (thread-safe).

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 NewServer

func NewServer(opts ...Option) (*Server, error)

NewServer creates a terminal session server.

func (*Server) Close

func (s *Server) Close() error

Close shuts down all sessions and stops the background agent notifier.

func (*Server) Handler

func (s *Server) Handler() http.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

func (s *Server) ListenAndServe(ctx context.Context) error

ListenAndServe starts the standalone server (API + SPA). The SPA is the embedded Vue frontend (built by build.sh).

func (*Server) Port

func (s *Server) Port() int

Port returns the actual listening port (useful when Addr is ":0").

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

func (s *Server) SetAuthCode(code string)

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

func (s *Session) ForceKillForeground() error

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

func (s *Session) GetExitCode() int

GetExitCode returns the shell exit code (thread-safe).

func (*Session) GetLastActive

func (s *Session) GetLastActive() time.Time

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

func (s *Session) GetTmuxDetected() bool

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

func (s *Session) PTYSize() muxd.Grid

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

func (s *Session) PasteMode() (enabled, known bool)

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

func (s *Session) PendingSignal() (sig ansisignal.Signal, at time.Time, seq uint64, ok bool)

PendingSignal returns the unanswered signal, when the session has one (thread-safe).

func (*Session) RecordSignal added in v0.7.13

func (s *Session) RecordSignal(sig ansisignal.Signal, at time.Time) uint64

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

func (s *Session) ReleaseViewerOwner(subID string)

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

func (s *Session) ReplayTail(max int) (data []byte, currentGrid int)

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

func (s *Session) RequestPTYSize(cols, rows int) error

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

func (s *Session) SetName(name string)

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

func (s *Session) SetViewerOwner(subID string, epoch uint64)

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

func (s *Session) SetViewerSize(subID string, cols, rows int) error

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) ShellPID

func (s *Session) ShellPID() int

ShellPID returns the PID of the shell process running in the PTY.

func (*Session) TailOutput

func (s *Session) TailOutput(n int) []string

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

func (s *Session) Viewport() muxd.Grid

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

func (s *Session) WorkingDir() string

WorkingDir returns the working directory of the session.

func (*Session) WriteInput added in v0.12.0

func (s *Session) WriteInput(data []byte) error

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

type SessionMeta struct {
	Shell string
	CWD   string
}

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

type SessionSnapshot struct {
	ID     string
	Name   string
	Shell  string
	CWD    string
	Status string
}

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

type SessionSummary struct {
	ID     string
	Name   string
	Status string
}

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

type TmuxCopyMotioner interface {
	CopyMotion(ctx context.Context, session, motion string) error
}

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 {
	Action string `json:"action"` // "window_next"|"window_prev"|"session_next"|"session_prev"
}

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

type TmuxRefresher interface {
	RefreshClient(ctx context.Context, shellPID int) error
}

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

type TmuxSessionMaker interface {
	NewSession(ctx context.Context, shellPID int) (string, error)
}

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

type TmuxWindowSelector interface {
	SelectWindow(ctx context.Context, shellPID, index int) error
}

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.

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
spa
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址