Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat: add terminal tab support (#285)

Myriad-Dreamin3847eb282378
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e993b52b..de193430 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,7 +1,7 @@
# CI: build -> style (Prettier) -> typecheck (tsc) -> unit tests (vitest) -> live e2e (DeepSeek).
# Build first: core's exports point at dist/, and cli's type resolution and runtime imports both need core's build output.
# e2e needs the repo secret DEEPSEEK_API_KEY; when absent (e.g. forks) that step self-skips and the other checks run as usual.
-# A second job repeats build/typecheck/test on windows-latest (see ci-windows below).
+# Two more jobs repeat build/typecheck/test on macos-latest and windows-latest (ci-macos / ci-windows below).
name: CI
# Limit triggers to avoid duplicate runs: push runs only on main/dev; PRs always run once (no target-branch filter --
@@ -60,6 +60,41 @@ jobs:
fi
pnpm test:e2e
+ # macOS: the same build/typecheck/test gates on macos-latest (arm64). This is the only job
+ # where the terminal's pty suites run on darwin — node-pty compiles against the runner's
+ # toolchain and its darwin-only spawn-helper actually executes — and the standalone
+ # terminal smoke script then re-runs node-pty under Electron's own Node
+ # (ELECTRON_RUN_AS_NODE), the runtime the packaged app's server really uses. A macOS
+ # terminal regression that once shipped as a silently empty panel fails here instead.
+ # No format:check (same files as ubuntu) and no live-LLM e2e (ubuntu-only budget).
+ ci-macos:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v5
+
+ # pnpm version comes from package.json's packageManager field.
+ - uses: pnpm/action-setup@v6
+
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 24
+ cache: pnpm
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Build (tsup)
+ run: pnpm build
+
+ - name: Typecheck (tsc)
+ run: pnpm typecheck
+
+ - name: Unit tests (vitest)
+ run: pnpm test
+
+ - name: Terminal smoke (node-pty under Electron's Node)
+ run: node packages/desktop/scripts/terminal-smoke.mjs
+
# Windows: the same build/typecheck/test gates on windows-latest (the ubuntu job above stays the
# required one). The runner ships Git-Bash on PATH, so core's exec_command tests run through the
# shell resolver's bash pick; genuinely POSIX-only tests skip themselves via process.platform
diff --git a/changelog/unreleased/2026-08-14-terminal.md b/changelog/unreleased/2026-08-14-terminal.md
new file mode 100644
index 00000000..341102b8
--- /dev/null
+++ b/changelog/unreleased/2026-08-14-terminal.md
@@ -0,0 +1,91 @@
+# Server-side terminals: an integrated dock and a standalone page
+
+- **Date:** 2026-08-14
+- **Type:** feature
+- **Scope:** `server`, `web`, `desktop`
+- **PR:** [#285](https://github.com/Prism-Shadow/penguin-harness/pull/285)
+
+[中文版](2026-08-14-terminal.zh.md)
+
+Shells now run in the server, not in the browser tab that shows them: every pty byte
+feeds a headless xterm in the daemon, so views are disposable. A reload, a moved panel or a
+second device repaints the exact screen — scrollback, colours, cursor, input modes — while
+the shell keeps running.
+
+## Server: `/api/terminals`
+
+- Control plane over JSON: list / create (`cwd`, `name`, `cols`/`rows`, `shell`) / get /
+ kill, plus plain-text `capture` (line ranges) and `keys` (literal text or `Enter` /
+ `C-c`-style tokens) so non-rendering clients can drive a shell too. Unnamed terminals
+ auto-increment per user (`tmp`, `tmp 2`, …) and carry a stable display number that never
+ shifts under reorders.
+- Data plane: binary WebSocket at `/api/terminals/:id/stream`, output coalesced (~5 ms
+ window, immediate leading flush). Attach resizes the pty to the client's geometry, then
+ one Restore frame repaints the whole screen; output produced meanwhile is buffered in.
+- Size has a single claimant (focus/attach claims, others' updates are ignored), sessions
+ outlive connections, exited ones stay readable for a grace period, 12 live shells per
+ user, and shutdown escalates SIGHUP to SIGKILL (`nohup` servers inherit ignored HUP).
+- A viewer lagging past 1 MiB stops receiving live output and is resynced with a fresh
+ Restore once its socket drains — never disconnected.
+- The shell is the user's own, started so their profile is in effect: `$SHELL` with `-l`
+ on POSIX, and on Windows PowerShell (`pwsh`, else `powershell`) rather than `%ComSpec%`,
+ which reads no profile at all. `PENGUIN_SHELL` overrides it everywhere. This is not the
+ agent's command shell, which stays POSIX-first and `-NoProfile` for determinism.
+- Security: a terminal is a shell as the server's OS account and is per-user, not
+ Project-scoped (foreign ids answer 404); the upgrade checks the session cookie plus a
+ strict `Origin` (exact `host:port`, `http(s)` only), since WebSocket handshakes bypass
+ CORS. Don't enable terminals for accounts you wouldn't give SSH.
+
+## Web App
+
+- **Dock** (`` Ctrl+` ``): a multi-pane terminal panel, at most one pane per edge of the
+ content area. Tabs are labelled `N: title` (stable number + live OSC title, `user@host`
+ stripped), drag sideways to reorder, squeeze browser-style when crowded, and wheel-scroll.
+ Dragging a tab out of the strip — or a pane's header — brings up the edge overlay (edge
+ bands, drop targets, a preview of the exact landing region) and moves the terminal/pane to
+ the chosen edge, creating a pane there on demand. The pane/main boundary drags to resize
+ (ratio-persisted per edge, double-click resets). Layout changes never reconnect: xterm
+ views are pooled by terminal id and handed between panes as DOM.
+- The dock belongs to the conversation it was opened in: switching Sessions switches
+ panes, tabs and visibility with it, and switching back restores them. A terminal opened
+ while drafting moves into the Session that draft becomes — every draft shares one scope,
+ having no id of its own, so otherwise it would sit there waiting to reappear in the next
+ new conversation. The shells keep
+ running either way — the toolbar's terminal menu lists every live one, and picking one
+ brings it into the conversation on screen.
+- A left or right pane and the chat's Agents/Workspace panel share the same horizontal half
+ of the content area, so only one of them is on screen: whichever the user asked for last.
+ Opening a panel displaces the side pane; opening or focusing a terminal retracts the
+ panel. They also share the *width* — one dragged on any of the three is the width the next
+ one opens at — and the same 200ms slide, the displaced side collapsing rather than
+ popping, with its shell and screen untouched behind it. Top and bottom panes cost height
+ rather than width and keep their own ratio.
+- Opening lands on the last-shown live shell, else the newest live one, else a fresh one;
+ panes, sizes, tab order, assignments and each pane's shown terminal persist. Being OPEN
+ does not: a fresh load starts with the panel closed, and reopening comes back to exactly
+ the arrangement that was there. The count on the toolbar is this conversation's, so
+ closing its last terminal takes it to zero rather than leaving it parked on a shell
+ running somewhere else. A tab's `×`
+ kills that shell; killing the last one closes the pane. Detach hands one terminal to its
+ own `/terminal?id=…` window while the dock keeps its remaining tabs.
+- **`/terminal` page**: full-window and deep-linkable — `?id=` attaches an existing terminal
+ (the detach handoff), `?cwd=`/`?name=` parameterize a new one; the attached id is written
+ back into the URL so a reload or a copied link reattaches.
+- **Chat toolbar**: icon-only panel switcher — pinned triggers plus a hover-opened Create
+ menu listing Agents panel / Terminal / Workspace with per-row pin toggles (agents +
+ workspace pinned by default). The terminal shows a live shell count (updated the moment
+ the user creates or closes one) and its pinned icon lists live terminals on hover for
+ one-click focus.
+- Light and dark, as the terminal's **own** setting (user menu → Terminal theme): light,
+ dark, or follow the app, defaulting to **dark** whatever the app is doing — a terminal is
+ where prompts and TUIs are tuned for a dark screen. Switching repaints in place; the
+ shell, its scrollback and its connection all survive. Surfaces are the app's own tones
+ rather than a terminal's charcoal, so a docked pane no longer reads as a foreign window;
+ the sixteen ANSI colours stay recognisable and get their own light-mode set, legible on
+ white.
+- Clipboard: copy via `Ctrl+Shift+C` / `Ctrl+Insert` / `Ctrl+C`-with-selection (otherwise
+ still SIGINT); paste via `Ctrl+V` / `Ctrl+Shift+V` / `Shift+Insert` riding the native
+ paste event (no clipboard permission). Right-click copies the selection or pastes, never
+ the page menu; middle-click pastes; both defer to apps owning the mouse (vim, htop).
+ Clicking anywhere in the view focuses the shell; hover-revealed controls also show on
+ keyboard focus.
diff --git a/changelog/unreleased/2026-08-14-terminal.zh.md b/changelog/unreleased/2026-08-14-terminal.zh.md
new file mode 100644
index 00000000..d231a7aa
--- /dev/null
+++ b/changelog/unreleased/2026-08-14-terminal.zh.md
@@ -0,0 +1,30 @@
+# 服务端终端:内置终端面板与独立页面
+
+- **Date:** 2026-08-14
+- **Type:** feature
+- **Scope:** `server`, `web`, `desktop`
+- **PR:** [#285](https://github.com/Prism-Shadow/penguin-harness/pull/285)
+
+[English](2026-08-14-terminal.md)
+
+Shell 现在跑在服务端,而不是跑在展示它的那个浏览器标签页里:每一个 pty 字节都会喂给守护进程里的一个无头 xterm,因此视图是可丢弃的。刷新页面、移动面板或换一台设备,重绘出的都是那一块完全相同的屏幕——回滚缓冲、颜色、光标、输入模式——而 shell 始终在运行。
+
+## 服务端:`/api/terminals`
+
+- 控制面走 JSON:列出 / 创建(`cwd`、`name`、`cols`/`rows`、`shell`)/ 获取 / 结束,另有纯文本的 `capture`(按行范围)与 `keys`(字面文本,或 `Enter`、`C-c` 这类按键记号),因此不做渲染的客户端同样能驱动一个 shell。未命名的终端按用户各自递增(`tmp`、`tmp 2`、……),并带一个稳定的显示编号,重排也不会让它移位。
+- 数据面是 `/api/terminals/:id/stream` 上的二进制 WebSocket,输出会做合并(约 5 ms 窗口,首字节立即冲刷)。接入时会把 pty 尺寸调整为客户端的几何尺寸,随后用一帧 Restore 重绘整块屏幕;这期间产生的输出会被缓冲进来。
+- 尺寸只有一个主张者(获得焦点或接入即主张,其他人的更新会被忽略);会话的寿命长于连接,已退出的会话在一段宽限期内仍可读;每用户 12 个存活 shell;关闭时从 SIGHUP 升级到 SIGKILL(`nohup` 启动的服务端会继承被忽略的 HUP)。
+- 落后超过 1 MiB 的观察者会停止接收实时输出,并在其套接字排空后用一帧新的 Restore 重新同步——而不是被断开。
+- 起的是用户自己的 shell,并且让他们的 profile 生效:POSIX 上取 `$SHELL` 并加 `-l`,Windows 上取 PowerShell(`pwsh`,否则 `powershell`)而不是 `%ComSpec%`——后者根本不读任何 profile。`PENGUIN_SHELL` 在所有平台上都可覆盖它。这与 agent 执行命令用的那个 shell 不是一回事:那一个为了确定性,仍然优先 POSIX 并带 `-NoProfile`。
+- 安全性:一个终端就是一个以服务端 OS 账户身份运行的 shell,它按用户隔离而不按 Project 隔离(他人的 id 一律回 404);升级握手会校验会话 cookie 以及严格的 `Origin`(精确到 `host:port`,仅 `http(s)`),因为 WebSocket 握手绕过 CORS。不要为你不愿意给 SSH 的账户开启终端。
+
+## Web App
+
+- **终端面板**(`` Ctrl+` ``):一个多窗格的终端面板,内容区每条边最多一个窗格。标签页标注为 `N: 标题`(稳定编号 + 实时 OSC 标题,`user@host` 会被剥掉),横向拖动可重排,拥挤时会像浏览器那样压缩,并支持滚轮滚动。把一个标签页拖出标签条——或拖动某个窗格的头部——会唤出边缘浮层(边缘感应带、投放靶标、最终落点区域的预览),并把该终端/窗格移到选中的边,必要时在那里新建一个窗格。窗格与主区的边界可拖动调整大小(按边各自记住比例,双击复位)。布局变化从不导致重连:xterm 视图按终端 id 池化,在窗格之间以 DOM 形式交接。
+- 终端面板归属于它被打开时所在的那个对话:切换 Session 时,窗格、标签页与显示与否都随之切换,切回来则原样恢复。在草稿里打开的终端会跟着这份草稿变成的那个 Session 走——草稿没有自己的 id,所有草稿共用一个 scope,否则它会滞留在那里,等着在下一个新对话里再冒出来。两种情况下 shell 都继续运行——工具条的终端菜单列出全部存活的终端,选中其中一个即可把它带到当前对话里。
+- 左侧或右侧窗格与聊天的 Agents / 工作区面板争的是内容区里同一块横向空间,因此同时只有一个在屏幕上:用户最后要的那个。打开面板会挤开侧边窗格;打开或聚焦终端则会收起面板。三者还共用同一个**宽度**——在其中任何一个上拖出来的宽度,就是下一个打开时的宽度——以及同样的 200ms 滑动:被挤开的一侧是收拢而不是啪地消失,它背后的 shell 与屏幕内容原封不动。上下窗格占的是高度而不是宽度,仍用它们自己的比例。
+- 打开时落在上次展示过的存活 shell 上,其次是最新的存活 shell,再次才新建一个;窗格、尺寸、标签顺序、归属关系以及每个窗格当前展示的终端都会被持久化。但**是否打开**不持久化:新载入时面板是关着的,重新打开则原样回到此前的布局。工具条上的计数是当前对话的,因此关掉它最后一个终端就会归零,而不会停在别处仍在运行的 shell 上。标签页上的 `×` 会结束那个 shell;结束最后一个会关掉该窗格。分离会把单个终端交给它自己的 `/terminal?id=…` 窗口,而面板保留其余标签页。
+- **`/terminal` 页面**:占满窗口且可深链——`?id=` 接入一个已存在的终端(分离时的交接),`?cwd=`/`?name=` 用于参数化新建的终端;接入的 id 会写回 URL,因此刷新或复制链接都能重新接入。
+- **聊天工具条**:纯图标的面板切换器——固定的触发按钮,外加悬停展开的「创建」菜单,其中列出 Agents 面板 / 终端 / 工作区,每行带一个固定开关(agents 与工作区默认固定)。终端项显示实时的 shell 数量(用户创建或关闭的那一刻就更新),其固定图标悬停时会列出存活的终端,一次点击即可聚焦。
+- 亮色与暗色,作为终端**自己的**设置(用户菜单 → 终端主题):亮色、暗色,或跟随 App 主题,且默认**暗色**——无论 App 是什么外观,因为终端正是提示符与 TUI 按深色屏调好的地方。切换时就地重绘,shell、回滚缓冲与连接都能挺过去。底色用的是 App 自己的色调而不是终端惯有的炭灰,因此停靠的窗格不再像一扇外来的窗;16 个 ANSI 颜色则保持可辨识,并为亮色模式单独配了一套,在白底上依然清晰。
+- 剪贴板:复制用 `Ctrl+Shift+C` / `Ctrl+Insert` / 有选区时的 `Ctrl+C`(无选区仍是 SIGINT);粘贴用 `Ctrl+V` / `Ctrl+Shift+V` / `Shift+Insert`,走原生 paste 事件(不需要剪贴板权限)。右键复制选区或粘贴,绝不弹出网页菜单;中键粘贴;两者都会让位于自行接管鼠标的程序(vim、htop)。点击视图内任意位置即可聚焦 shell;悬停才显现的控件在键盘聚焦时同样会显现。
diff --git a/packages/desktop/scripts/terminal-smoke.mjs b/packages/desktop/scripts/terminal-smoke.mjs
new file mode 100644
index 00000000..d971d940
--- /dev/null
+++ b/packages/desktop/scripts/terminal-smoke.mjs
@@ -0,0 +1,45 @@
+/**
+ * Terminal smoke test on the runtime that actually runs it: the desktop shell executes
+ * the server as an Electron utilityProcess, so node-pty's native binding — and, on macOS,
+ * its `spawn-helper` side binary — must work under Electron's Node, not the Node that
+ * compiled the tree. ELECTRON_RUN_AS_NODE is that same runtime, so this loads node-pty
+ * the way the server resolves it, spawns a real shell and waits for one byte of output.
+ *
+ * A platform where the pty cannot load or spawn fails here with the real error, instead
+ * of shipping a desktop app whose terminal panel silently stays empty (the macOS bug
+ * this guards against). Run standalone (CI's ci-macos job) after `pnpm install`; it needs
+ * no build outputs and does not touch the staging tree.
+ */
+import { execFileSync } from "node:child_process";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const repoRoot = path.resolve(pkgDir, "..", "..");
+
+// Resolve node-pty exactly the way the server package does.
+const serverRequire = createRequire(path.join(repoRoot, "packages", "server", "package.json"));
+const ptyPath = path.dirname(serverRequire.resolve("node-pty/package.json"));
+
+const smoke = `
+ const pty = require(${JSON.stringify(ptyPath)});
+ const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh";
+ const term = pty.spawn(shell, [], { name: "xterm-256color", cols: 40, rows: 10, cwd: process.cwd(), env: process.env });
+ const timer = setTimeout(() => { console.error("no pty output within 15s"); process.exit(1); }, 15000);
+ term.onData(() => { clearTimeout(timer); term.kill(); console.log("[terminal-smoke] node-pty spawn OK (Electron Node " + process.versions.node + ", ABI " + process.versions.modules + ")"); process.exit(0); });
+ term.write("echo ready\\r");
+`;
+
+const isWindows = process.platform === "win32";
+const electronBin = path.join(
+ pkgDir,
+ "node_modules",
+ ".bin",
+ isWindows ? "electron.cmd" : "electron",
+);
+execFileSync(electronBin, ["-e", smoke], {
+ stdio: "inherit",
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
+ shell: isWindows,
+});
diff --git a/packages/server/README.md b/packages/server/README.md
index b0f1736a..c2e9314c 100644
--- a/packages/server/README.md
+++ b/packages/server/README.md
@@ -9,6 +9,7 @@ The PenguinHarness Web backend — the Web implementation of the SDK's Human bou
- **Runtime**: a session manager keeps active Sessions (get-or-resume-or-heal, per-Session mutex, run/compact driving); approvals surface over SSE as `approval_request` and decisions re-read the stored approval mode each time; interrupts converge pending approvals to deny before aborting; a scheduler fires `agent_state/schedule/*.toml` tasks while the service runs.
- **SSE**: per-channel monotonic event ids with a bounded replay buffer (1000 events / 2MB); reconnects replay from `Last-Event-ID` or receive `resync_required`; heartbeat comment every 20s.
- **Usage**: `token_usage` events are persisted row by row; costs are computed at query time from current per-model pricing.
+- **Terminals**: `src/terminal/` runs pty sessions server-side (node-pty) and feeds every byte into a headless xterm, so the daemon — not the browser — owns the screen. Control is JSON over HTTP (`/api/terminals`: list / create / capture / keys / kill; create accepts `cwd`, `name`, `cols`/`rows` and a `shell` override); the byte stream is a binary WebSocket at `/api/terminals/:id/stream` (`[opcode, slot, payload]`, output coalesced into ~5ms windows with an immediate leading flush). On attach the server renders the current grid back into an ANSI restore stream, so a reload or a second device rebuilds the exact screen — scrollback, colours, cursor and DEC input modes — while the shell keeps running the whole time. The web app surfaces this twice: an in-app dock (Ctrl+` , Codex-style) and the standalone `/terminal` page (`?id=` attaches an existing terminal — the dock's detach handoff — `?cwd=`/`?name=` parameterize a new one). Sessions run in-process (no forked terminal worker); this module is the only thing touching node-pty, which is where that split would go if load ever demands it.
The full route tables and the SSE protocol are documented in the [Server API reference](https://penguin.ooo/docs/server-api). DTO types are exported for type-only import via `@prismshadow/penguin-server/api`.
@@ -41,6 +42,7 @@ pnpm --filter @prismshadow/penguin-server start # node dist/index.js
- **Built-in admin `admin` starts with a random initial password** of the form `penguin-1234`, printed once to the server console at seed time (`PENGUIN_SEED_ADMIN_PASSWORD` pins it for tests/e2e): change it immediately (a banner keeps reminding until you do).
- Passwords use `node:crypto` scrypt (`scrypt$N$r$p$salt$hash`, timingSafeEqual); login sessions renew on a 7-day sliding window; the DB stores only the token's sha256.
- Model credentials live in the Project's hidden 0600 config file; the API always masks them.
+- **Terminals are a shell as the OS account running the server**, i.e. the most privileged thing the API hands out — they are not Project-scoped. A terminal is only visible to the account that created it (someone else's id answers 404, not 403), and the stream WebSocket checks `Origin` on top of the session cookie because a WebSocket handshake is not subject to CORS. Do not expose a deployment with terminals enabled to accounts you would not give SSH.
- Behind a reverse proxy, disable response buffering for SSE paths (the server already sends `X-Accel-Buffering: no`) and forward `x-forwarded-proto` to enable Secure cookies.
Part of [PenguinHarness](https://github.com/Prism-Shadow/penguin-harness) · Apache-2.0
diff --git a/packages/server/package.json b/packages/server/package.json
index e811c012..f6fa1516 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -51,16 +51,20 @@
"@hono/node-server": "^2.0.5",
"@prismshadow/penguin-core": "workspace:*",
"@prismshadow/penguin-skills": "workspace:*",
+ "@xterm/headless": "^5.5.0",
"dotenv": "^17.0.0",
"fflate": "^0.8.3",
"hono": "^4.12.34",
+ "node-pty": "^1.1.0",
"smol-toml": "^1.3.0",
"tar": "^7.5.21",
"undici": "^7.29.0",
+ "ws": "^8.18.3",
"yaml": "^2.5.0"
},
"devDependencies": {
"@types/node": "^24.0.0",
+ "@types/ws": "^8.18.1",
"tsup": "^8.3.0",
"tsx": "^4.20.0",
"typescript": "^5.6.0",
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index a423fa99..62003a5d 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -31,7 +31,8 @@ import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
import { UsageRepo } from "./db/repos/usage.js";
import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
-import { authMiddleware, jsonOnlyWrites } from "./auth/middleware.js";
+import { authMiddleware, jsonOnlyWrites, SESSION_COOKIE } from "./auth/middleware.js";
+import { IDENTITY_RESOURCE_ID } from "./platform/terminal/identity.js";
import type { AppEnv } from "./auth/middleware.js";
import { ADMIN_USER_ID, AuthService } from "./auth/service.js";
import { clearInitialAdminPassword } from "./initial-password.js";
@@ -332,6 +333,19 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
});
+ // Hoisted out of the returned literal so its registry can be populated before anything
+ // boots against it.
+ const hmr = new HmrHost(config.root);
+ // The seam runs before the auth middleware, so a platform serving an API of its own has
+ // no `c.var.user`. Authenticating is the runtime's job, not something a bundle should
+ // re-implement against cookie names and session TTLs — so it is published as a
+ // capability the booting platform claims (see platform/terminal/identity.ts).
+ hmr.resources.register(IDENTITY_RESOURCE_ID, async (request: Request) => {
+ const token = readSessionCookie(request.headers.get("cookie"));
+ const authed = token === null ? null : authService.authenticateWithMeta(token);
+ return authed === null ? null : { userId: authed.user.userId };
+ });
+
return {
config,
db,
@@ -363,7 +377,7 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
sessionSources,
errors,
desktop: config.desktopToken !== null ? new DesktopService(config.desktopToken) : null,
- hmr: new HmrHost(config.root),
+ hmr,
log,
};
}
@@ -646,3 +660,15 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<We
});
});
}
+
+/** The session cookie out of a raw Cookie header (the seam hands over a plain Request). */
+function readSessionCookie(header: string | null): string | null {
+ if (header === null) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
+ return decodeURIComponent(part.slice(eq + 1).trim());
+ }
+ return null;
+}
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index db150326..b3ae9864 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -103,13 +103,44 @@ export interface GitSource {
* manifest. All three travel in the SAME request — there is no partial-target
* upgrade.
*/
+/**
+ * Files a push needs on DISK rather than in memory. The web dist is only ever served as
+ * bytes, so it stays in RAM; an asset is something the platform hands to the OS — a
+ * native `.node` whose loader resolves it by path, a helper binary it execs — and a
+ * bundle cannot carry those: it is imported from the data root, where neither a relative
+ * `build/Release/pty.node` nor a bare specifier resolves (verified: node-pty's binding
+ * fails to load from a bundle placed outside the server's own module graph).
+ */
+export interface UpgradeAssets {
+ /** relPath → base64 content. */
+ files: Record<string, string>;
+ /** relPaths that must land executable (a helper binary the platform spawns). */
+ exec?: string[];
+}
+
export interface UpgradeAllTarget {
platform: string;
cli: string;
web: Record<string, string>;
+ assets?: UpgradeAssets;
source?: GitSource;
}
+/**
+ * Where the runtime publishes the unpacked assets directory for the booting platform.
+ * The resource registry is the only runtime→platform channel the kernel offers (ctx
+ * carries `resources`, nothing else), and it is kind-agnostic by design — see
+ * ./resources.ts.
+ */
+export const ASSETS_RESOURCE_ID = "runtime:assets-dir";
+
+/**
+ * Written into an assets directory once every file in it is on disk. Its absence marks a
+ * directory whose materialization was interrupted; no asset path can collide with it
+ * (assets arrive as `node_modules/...` paths).
+ */
+const MATERIALIZED = ".materialized";
+
export type UpgradeOutcome =
| {
status: "ok";
@@ -251,6 +282,15 @@ export class HmrHost {
if (!fs.existsSync(cliPath)) {
throw new Error(`cli bundle '${manifest.cli.bundle}' does not exist`);
}
+ // Republished before boot, same ordering as an upgrade: a resumed platform loads its
+ // native modules out of the assets the version was committed with.
+ if (manifest.assets !== undefined) {
+ const assetsDir = path.join(this.hmrDir, manifest.assets.dir);
+ if (!fs.existsSync(assetsDir)) {
+ throw new Error(`assets dir '${manifest.assets.dir}' does not exist`);
+ }
+ this.publishAssets(assetsDir);
+ }
const bundle = await this.importBundleFile(path.join(this.hmrDir, manifest.platform.bundle));
const gz = await fsp.readFile(path.join(this.hmrDir, manifest.web.manifest));
const webMem = filesMapFromGzip(gz);
@@ -300,13 +340,27 @@ export class HmrHost {
const bundle = await this.importBundleFile(platformPath);
const source = target.source ?? null;
- const result = await upgrade({
- current,
- impl: bundle.impl,
- iface: bundle.iface,
- resources: this.resources,
- });
+ // Assets land BEFORE the boot: the platform's create() may load a native module out of
+ // them. A failed boot puts the pointer back, so the surviving old platform keeps
+ // claiming the assets it booted with.
+ const previousAssets = this.resources.claim<string>(ASSETS_RESOURCE_ID) ?? null;
+ const assetsDir = target.assets ? await this.materializeAssets(target.assets) : null;
+ if (assetsDir !== null) this.publishAssets(assetsDir);
+
+ let result;
+ try {
+ result = await upgrade({
+ current,
+ impl: bundle.impl,
+ iface: bundle.iface,
+ resources: this.resources,
+ });
+ } catch (err) {
+ this.publishAssets(previousAssets);
+ throw err;
+ }
if (result.status === "blocked") {
+ this.publishAssets(previousAssets);
// Old instance + web untouched; the doc + path lists are the input for the
// upper upgrade-ladder rungs (auto-upgrader / agent / human).
return {
@@ -332,6 +386,7 @@ export class HmrHost {
target.cli,
gz,
digest.slice(0, 16),
+ assetsDir,
);
return {
@@ -412,11 +467,54 @@ export class HmrHost {
* (`persisted` in UpgradeOutcome) so a live swap that could not be written to disk
* is visibly at risk of reverting on the next restart, rather than silently ok.
*/
+ /**
+ * Unpacks a push's assets under store/assets/<sha>/, content-addressed like every other
+ * artifact so an unchanged set reuses its directory. Modes are restored from the push's
+ * `exec` list: an asset arrives as base64 with no mode of its own, and a helper binary
+ * without its exec bit is exactly the failure this whole path exists to avoid.
+ *
+ * An identical set is NOT re-written. That is a correctness requirement, not a saving:
+ * these assets are native modules, and on Windows the copies from the last push are
+ * mapped into this very process — reopening one for writing fails with EBUSY and takes
+ * the whole upgrade down with it. The directory name already proves the content
+ * matches; MATERIALIZED, written last, is what proves the directory is complete, so a
+ * push interrupted halfway is repaired rather than trusted.
+ */
+ private async materializeAssets(assets: UpgradeAssets): Promise<string> {
+ const sha = filesDigest(assets.files).slice(0, 16);
+ const dir = path.join(this.storeDir, "assets", sha);
+ const marker = path.join(dir, MATERIALIZED);
+ if (fs.existsSync(marker)) return dir;
+
+ const exec = new Set(assets.exec ?? []);
+ for (const [rel, b64] of Object.entries(assets.files)) {
+ if (!isSafeRelPath(rel)) throw new Error(`unsafe path in assets manifest: ${rel}`);
+ const file = path.join(dir, rel);
+ const content = Buffer.from(b64, "base64");
+ await fsp.mkdir(path.dirname(file), { recursive: true });
+ // Repairing an incomplete directory: whatever already matches is left alone, for the
+ // same reason the whole directory is skipped above.
+ if (!(await sameFileContent(file, content))) await fsp.writeFile(file, content);
+ // Explicit chmod: writeFile's mode is masked by umask, and ignored outright when
+ // the file already exists (a reused, content-addressed directory).
+ await fsp.chmod(file, exec.has(rel) ? 0o755 : 0o644);
+ }
+ await fsp.writeFile(marker, sha);
+ return dir;
+ }
+
+ /** Points the registry at this version's assets (or clears it when a push has none). */
+ private publishAssets(dir: string | null): void {
+ if (dir === null) this.resources.release(ASSETS_RESOURCE_ID);
+ else this.resources.register(ASSETS_RESOURCE_ID, dir);
+ }
+
private async persistVersion(
platformContent: string,
cliContent: string,
webGz: Buffer,
webSha: string,
+ assetsDir: string | null,
): Promise<boolean> {
try {
const platformSha = sha1(platformContent).slice(0, 16);
@@ -437,6 +535,9 @@ export class HmrHost {
platform: { bundle: `store/platform/${platformSha}.mjs` },
cli: { bundle: `store/cli/${cliSha}.mjs` },
web: { manifest: `store/web/${webSha}.webz` },
+ ...(assetsDir === null
+ ? {}
+ : { assets: { dir: path.relative(this.hmrDir, assetsDir).split(path.sep).join("/") } }),
}));
return true;
} catch (err) {
@@ -522,6 +623,16 @@ export class HmrHost {
webRef,
(sha) => fsp.rm(path.join(webDir, `${sha}.webz`), { force: true }),
);
+
+ // Assets are directories, not single files; otherwise the same keep-newest rule.
+ const assetsRoot = path.join(this.storeDir, "assets");
+ const assetsRef = manifest.assets?.dir.match(/([0-9a-f]+)$/)?.[1] ?? null;
+ await keepNewest(
+ assetsRoot,
+ (name) => (/^[0-9a-f]+$/.test(name) ? name : null),
+ assetsRef,
+ (sha) => fsp.rm(path.join(assetsRoot, sha), { recursive: true, force: true }),
+ );
}
/** Process-exit sweep only; never part of an upgrade. */
@@ -548,6 +659,17 @@ function filesDigest(files: Record<string, string>): string {
}
/** No absolute paths, no `..` segments — the map is looked up by exact key, but a malformed key must never be stored. */
+/** Whether `file` already holds exactly these bytes (missing/unreadable counts as no). */
+async function sameFileContent(file: string, content: Buffer): Promise<boolean> {
+ try {
+ const stat = await fsp.stat(file);
+ if (!stat.isFile() || stat.size !== content.length) return false;
+ return (await fsp.readFile(file)).equals(content);
+ } catch {
+ return false;
+ }
+}
+
function isSafeRelPath(rel: string): boolean {
if (rel === "" || rel.startsWith("/") || rel.includes("\\")) return false;
return rel.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
diff --git a/packages/server/src/hmr/manifest.ts b/packages/server/src/hmr/manifest.ts
index ca097628..972269e9 100644
--- a/packages/server/src/hmr/manifest.ts
+++ b/packages/server/src/hmr/manifest.ts
@@ -40,6 +40,14 @@ export interface Manifest {
cli?: { bundle: string };
/** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */
web?: { manifest: string };
+ /**
+ * Files the pushed platform needs as REAL files on disk, unpacked under this directory
+ * (relative to hmrDir). The web artifact stays in memory because it is only ever served
+ * as bytes; an asset is something the platform hands to the OS — a native `.node` the
+ * loader must resolve by path, a helper binary it execs — so it has to exist on the
+ * filesystem, with its exec bit intact.
+ */
+ assets?: { dir: string };
}
/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */
diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.ts
index 34f10de9..a79da446 100644
--- a/packages/server/src/hmr/routes.ts
+++ b/packages/server/src/hmr/routes.ts
@@ -117,6 +117,7 @@ export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
platform?: string;
cli?: string;
web?: { files?: Record<string, string> };
+ assets?: { files?: Record<string, string>; exec?: string[] };
source?: { repo: string; revision: string };
};
try {
@@ -148,6 +149,16 @@ export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
platform: payload.platform,
cli: payload.cli,
web: payload.web.files,
+ // Optional: a push that needs no real files on disk (no native module, no helper
+ // binary) simply omits it, and older pushers keep working unchanged.
+ ...(payload.assets?.files
+ ? {
+ assets: {
+ files: payload.assets.files,
+ ...(payload.assets.exec ? { exec: payload.assets.exec } : {}),
+ },
+ }
+ : {}),
...(payload.source ? { source: payload.source } : {}),
});
} catch (err) {
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index d78f7990..6e5fea1f 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -11,6 +11,7 @@
*/
import fs from "node:fs";
import path from "node:path";
+import type { Server as HttpServer } from "node:http";
import { config as loadDotenv } from "dotenv";
import { serve } from "@hono/node-server";
import { buildAppDeps, createApp } from "./app.js";
@@ -23,6 +24,7 @@ import {
storeInitialAdminPassword,
} from "./initial-password.js";
import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";
+import { attachTerminalWebSocket } from "./terminal/ws.js";
import { loopbackHostRoles } from "./services/preview-token.js";
import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";
@@ -129,6 +131,13 @@ function writePortFile(file: string, port: number): void {
fs.renameSync(tmp, file);
}
+/** Terminal WebSocket wiring, shared by every listener this process opens. */
+const terminalWebSocketDeps = {
+ hmr: deps.hmr,
+ authService: deps.authService,
+ log: (line: string) => console.log(line),
+};
+
const server = serve({ fetch: app.fetch, hostname: config.host, port: config.port }, (info) => {
console.log(`penguin-server started: http://${appHost}:${info.port}`);
console.log(`Data root: ${config.root}`);
@@ -155,8 +164,13 @@ const server = serve({ fetch: app.fetch, hostname: config.host, port: config.por
`[server] IPv6 loopback listener unavailable (${err.code ?? err.message}); previews via localhost may not resolve.`,
);
});
+ // The terminal stream is a WebSocket upgrade, which never reaches the Hono fetch
+ // handler — it has to be bound on each Node listener, this one included, or the
+ // terminal only works on whichever address the browser happened to resolve.
+ attachTerminalWebSocket(ipv6Loopback as unknown as HttpServer, terminalWebSocketDeps);
}
});
+attachTerminalWebSocket(server as unknown as HttpServer, terminalWebSocketDeps);
/** Removes the instance lock and port file (best-effort; runs on both exit paths). */
function cleanupInstanceFiles(): void {
diff --git a/packages/server/src/platform/hono-seam.ts b/packages/server/src/platform/hono-seam.ts
new file mode 100644
index 00000000..6801f420
--- /dev/null
+++ b/packages/server/src/platform/hono-seam.ts
@@ -0,0 +1,40 @@
+/**
+ * The Hono ↔ seam bridge, shared by every platform-side Hono app (terminal routes,
+ * the business app).
+ *
+ * The seam contract is `Request → Response | null` (hmr/http-seam.ts): null declines the
+ * request to whatever is next in line. A Hono router already distinguishes "no route
+ * matched" (its notFound handler) from "a route matched and answered" — so a platform app
+ * declares decline by returning {@link declined} from notFound, and {@link seamHttp}
+ * translates that marker to null.
+ *
+ * The marker is a header rather than a bare 404 on purpose: a real 404 from a matched
+ * route ("no such terminal", "no such session") is the platform's own answer and must
+ * reach the caller as-is — never fall through to some older handler behind the seam with
+ * different semantics.
+ */
+
+const DECLINE_HEADER = "x-penguin-platform-decline";
+/**
+ * Random per boot, compared by VALUE in seamHttp. The header name is guessable, and this
+ * adapter is meant for every platform-side app — including ones that might one day copy
+ * response headers from an upstream. A fixed marker would let that upstream inject the
+ * header and silently decline the platform's own answer into whatever older handler sits
+ * behind the seam; a value nothing outside this module instance knows cannot be forged.
+ */
+const DECLINE_TOKEN = crypto.randomUUID();
+
+/** The marked response a platform app's notFound returns to decline the request. */
+export function declined(): Response {
+ return new Response(null, { status: 404, headers: { [DECLINE_HEADER]: DECLINE_TOKEN } });
+}
+
+/** Bridges a Hono app (structurally: anything fetch-shaped) onto the seam contract. */
+export function seamHttp(app: {
+ fetch: (request: Request) => Response | Promise<Response>;
+}): (request: Request) => Promise<Response | null> {
+ return async (request) => {
+ const response = await app.fetch(request);
+ return response.headers.get(DECLINE_HEADER) === DECLINE_TOKEN ? null : response;
+ };
+}
diff --git a/packages/server/src/platform/platform.ts b/packages/server/src/platform/platform.ts
index 73167128..24cbc289 100644
--- a/packages/server/src/platform/platform.ts
+++ b/packages/server/src/platform/platform.ts
@@ -22,32 +22,69 @@
* own routes do and answers null for the ones it does not own, so adding or
* changing an endpoint needs no runtime change.
*/
+import type { WebSocket } from "ws";
import type { Impl, Json, Park } from "@prismshadow/penguin-core/kernel";
import { defineIface, schema, type } from "@prismshadow/penguin-core/kernel";
import type { PlatformBundle } from "../hmr/host.js";
+import { TerminalManager } from "./terminal/manager.js";
+import type { TerminalSession } from "./terminal/session.js";
+import { terminalHttp } from "./terminal/routes.js";
+import { identityFrom } from "./terminal/identity.js";
+import { bindTerminalStream } from "./terminal/stream.js";
export interface PlatformApi extends Park {
info(): Json;
+ /**
+ * The HTTP seam (hmr/http-seam.ts): every request is offered here first, and null
+ * declines it to the runtime's own routes. This is how a business API ships by push
+ * instead of by rebuilding and redeploying every installation.
+ */
+ http(request: Request): Promise<Response | null>;
+ /**
+ * In-process accessors for the one thing the seam cannot carry: a live socket. The
+ * runtime's ws transport authenticates an upgrade, then asks for the session and hands
+ * the socket back for the platform's protocol to drive.
+ */
+ terminals(): TerminalManager;
+ attachStream(ws: WebSocket, session: TerminalSession, url: URL, log: (l: string) => void): void;
}
-export type PlatformCtx = { motd: string };
+/**
+ * `terminals` is the linear-state half of this document: the pty processes themselves live
+ * in the runtime's resource registry (they must — a swap disposes this tree), and the
+ * document carries only their handle ids so the next instance can claim them back.
+ */
+export type PlatformCtx = { motd: string; terminals?: string[] };
export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({
name: "platform",
version: 1,
- context: schema<PlatformCtx>(type({ motd: "string" })),
- methods: ["park", "info"],
+ context: schema<PlatformCtx>(type({ motd: "string", "terminals?": "string[]" })),
+ methods: ["park", "info", "http", "terminals", "attachStream"],
});
export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
- create(_ctx, context) {
+ create(ctx, context) {
+ const terminals = new TerminalManager(ctx.resources);
+ // Shells started before this instance existed are still running in the registry: claim
+ // them back so a push is invisible to whoever was typing in one.
+ terminals.adopt(context.terminals ?? []);
+ const http = terminalHttp(terminals, identityFrom(ctx.resources));
+
return {
- park: () => ({ motd: context.motd }),
+ // Deliberately NOT disposing the terminals here (no ctx.effect): the shells are
+ // resources, and outliving a swap is the whole point. Process exit sweeps them
+ // through the registry's own disposers.
+ park: () => ({ motd: context.motd, terminals: terminals.handleIds() }),
info: () => ({
impl: "packaged",
ifaceVersion: PlatformIface.version,
motd: context.motd,
+ terminals: terminals.handleIds().length,
}),
+ http,
+ terminals: () => terminals,
+ attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),
};
},
};
diff --git a/packages/server/src/platform/terminal/frames.ts b/packages/server/src/platform/terminal/frames.ts
new file mode 100644
index 00000000..9ca4a516
--- /dev/null
+++ b/packages/server/src/platform/terminal/frames.ts
@@ -0,0 +1,101 @@
+/**
+ * Terminal stream binary frame codec.
+ *
+ * Terminal traffic is the one place where JSON framing actually hurts: a build's output is
+ * megabytes of bytes that would otherwise be escaped, re-parsed and re-allocated on both
+ * ends, on the same event loop that carries every other message. So the data plane is raw
+ * bytes behind a 2-byte header and the control plane (create / list / kill / capture) stays
+ * ordinary JSON over HTTP.
+ *
+ * byte 0 opcode
+ * byte 1 slot (stream index within one socket)
+ * byte 2+ payload (raw UTF-8 terminal bytes, or JSON for the control opcodes)
+ *
+ * `slot` is always 0 today — this server opens one socket per terminal. It is in the wire
+ * format from the start because the alternative (adding it later) is a protocol break, and
+ * because multiplexing every terminal of a page onto one socket is the obvious next step.
+ */
+
+export const TerminalStreamOpcode = {
+ /** Server -> client: terminal output bytes. */
+ Output: 0x01,
+ /** Client -> server: keyboard/paste input bytes. */
+ Input: 0x02,
+ /** Client -> server: viewport size, JSON `{cols, rows, intent}`. */
+ Resize: 0x03,
+ /** Server -> client: full-screen restore stream (ANSI), sent once on attach. */
+ Restore: 0x05,
+ /** Server -> client: the pty exited, JSON `{exitCode, signal}`. */
+ Exit: 0x06,
+} as const;
+
+export type TerminalStreamOpcode = (typeof TerminalStreamOpcode)[keyof typeof TerminalStreamOpcode];
+
+export interface TerminalStreamFrame {
+ opcode: TerminalStreamOpcode;
+ slot: number;
+ payload: Uint8Array;
+}
+
+const OPCODES = new Set<number>(Object.values(TerminalStreamOpcode));
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+export function encodeTerminalFrame(input: {
+ opcode: TerminalStreamOpcode;
+ slot?: number;
+ payload?: Uint8Array | string;
+}): Uint8Array {
+ const payload =
+ typeof input.payload === "string"
+ ? encoder.encode(input.payload)
+ : (input.payload ?? new Uint8Array(0));
+ const bytes = new Uint8Array(2 + payload.byteLength);
+ bytes[0] = input.opcode;
+ bytes[1] = (input.slot ?? 0) & 0xff;
+ bytes.set(payload, 2);
+ return bytes;
+}
+
+/** Decodes a frame; returns null for anything malformed (a client must never crash the daemon). */
+export function decodeTerminalFrame(bytes: Uint8Array): TerminalStreamFrame | null {
+ if (bytes.byteLength < 2) return null;
+ const opcode = bytes[0] as number;
+ if (!OPCODES.has(opcode)) return null;
+ return {
+ opcode: opcode as TerminalStreamOpcode,
+ slot: bytes[1] as number,
+ payload: bytes.subarray(2),
+ };
+}
+
+export function framePayloadText(frame: TerminalStreamFrame): string {
+ return decoder.decode(frame.payload);
+}
+
+export interface TerminalResizePayload {
+ cols: number;
+ rows: number;
+ /** `claim` takes size ownership for this connection; `update` only applies if it already owns it. */
+ intent: "claim" | "update";
+}
+
+/** Parses a Resize payload, returning null when the client sent something unusable. */
+export function parseResizePayload(frame: TerminalStreamFrame): TerminalResizePayload | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(framePayloadText(frame));
+ } catch {
+ return null;
+ }
+ if (typeof parsed !== "object" || parsed === null) return null;
+ const { cols, rows, intent } = parsed as Record<string, unknown>;
+ if (!Number.isInteger(cols) || !Number.isInteger(rows)) return null;
+ if ((cols as number) < 1 || (rows as number) < 1) return null;
+ return {
+ cols: Math.min(cols as number, 1000),
+ rows: Math.min(rows as number, 500),
+ intent: intent === "update" ? "update" : "claim",
+ };
+}
diff --git a/packages/server/src/platform/terminal/identity.ts b/packages/server/src/platform/terminal/identity.ts
new file mode 100644
index 00000000..003a4f92
--- /dev/null
+++ b/packages/server/src/platform/terminal/identity.ts
@@ -0,0 +1,31 @@
+/**
+ * Who a seam request belongs to.
+ *
+ * The platform is offered every request BEFORE the runtime's auth middleware runs — that
+ * ordering is deliberate (a push must be able to decide its own authentication), but it
+ * means `c.var.user` does not exist here. Rather than re-implement session lookup in
+ * pushed code, the runtime publishes this capability through the resource registry:
+ * authenticating is the runtime layer's own job ("boots, transports, authenticates"), and
+ * a copy of it inside a bundle would be a second implementation to keep in step with
+ * cookie names, session TTLs and renewal.
+ */
+import type { Resources } from "@prismshadow/penguin-core/kernel";
+
+/** Registry key the runtime publishes its resolver under. */
+export const IDENTITY_RESOURCE_ID = "runtime:identity";
+
+export interface IdentifiedUser {
+ userId: string;
+}
+
+export type Identity = (request: Request) => Promise<IdentifiedUser | null>;
+
+/**
+ * The published resolver, or one that authenticates nobody. A runtime too old to publish
+ * it must not silently hand out terminals — an unattributable request is not a request
+ * from everyone.
+ */
+export function identityFrom(resources: Resources): Identity {
+ const resolver = resources.claim<Identity>(IDENTITY_RESOURCE_ID);
+ return resolver ?? (async () => null);
+}
diff --git a/packages/server/src/platform/terminal/input-mode.ts b/packages/server/src/platform/terminal/input-mode.ts
new file mode 100644
index 00000000..9866f117
--- /dev/null
+++ b/packages/server/src/platform/terminal/input-mode.ts
@@ -0,0 +1,90 @@
+/**
+ * DEC private mode tracker.
+ *
+ * A snapshot of the screen grid restores what is *displayed*, but not how the terminal is
+ * supposed to *behave*: with bracketed paste (2004) or application cursor keys (1) lost, a
+ * reattached client sends the wrong bytes and a running shell/TUI misreads every arrow key
+ * and every paste. Those modes are set once, long before the reattach, so they can only be
+ * recovered by remembering them.
+ *
+ * So every pty chunk is scanned for `CSI ? Pm h|l` and the current state of a small
+ * whitelist is kept. `preamble()` re-emits it ahead of the restored screen.
+ */
+
+/** Modes worth replaying — everything else is either display state (already in the snapshot) or noise. */
+const TRACKED_MODES = new Set([
+ 1, // DECCKM, application cursor keys
+ 7, // DECAWM, auto-wrap
+ 12, // cursor blink
+ 25, // DECTCEM, cursor visibility
+ 66, // DECNKM, application keypad
+ 1000, // mouse: click tracking
+ 1002, // mouse: button-event tracking
+ 1003, // mouse: any-event tracking
+ 1004, // focus reporting
+ 1005, // mouse: utf-8 coordinates
+ 1006, // mouse: SGR coordinates
+ 1015, // mouse: urxvt coordinates
+ 1016, // mouse: SGR pixel coordinates
+ 2004, // bracketed paste
+]);
+
+/** Modes that are on unless something turned them off (so "not seen" != "off"). */
+const DEFAULT_ON = new Set([7, 25]);
+
+/** Longest sequence we may have to hold across a chunk boundary: ESC [ ? + params + final. */
+const MAX_CARRY = 64;
+
+const DEC_PRIVATE_MODE_PATTERN = /\x1b\[\?([0-9;]*)([hl])/g;
+
+export class TerminalInputModeTracker {
+ private readonly enabled = new Set<number>(DEFAULT_ON);
+ /** Tail of the previous chunk that may hold the start of a split escape sequence. */
+ private carry = "";
+
+ feed(chunk: string): void {
+ const text = this.carry + chunk;
+ DEC_PRIVATE_MODE_PATTERN.lastIndex = 0;
+ let match: RegExpExecArray | null;
+ let lastEnd = 0;
+ while ((match = DEC_PRIVATE_MODE_PATTERN.exec(text)) !== null) {
+ lastEnd = match.index + match[0].length;
+ const on = match[2] === "h";
+ for (const raw of (match[1] ?? "").split(";")) {
+ if (raw === "") continue;
+ const mode = Number.parseInt(raw, 10);
+ if (!TRACKED_MODES.has(mode)) continue;
+ if (on) this.enabled.add(mode);
+ else this.enabled.delete(mode);
+ }
+ }
+ // Keep only what could still be the head of an unfinished sequence. Anything before the
+ // last complete match is settled, and a sequence can never be longer than MAX_CARRY.
+ const tailStart = Math.max(lastEnd, text.length - MAX_CARRY);
+ const tail = text.slice(tailStart);
+ const escIndex = tail.lastIndexOf("\x1b");
+ this.carry = escIndex === -1 ? "" : tail.slice(escIndex);
+ }
+
+ isEnabled(mode: number): boolean {
+ return this.enabled.has(mode);
+ }
+
+ /**
+ * Escape sequences that put a freshly attached client back into the modes the running
+ * program believes it is in. Emitted right after the restored screen content.
+ */
+ preamble(): string {
+ const on: number[] = [];
+ const off: number[] = [];
+ for (const mode of TRACKED_MODES) {
+ const enabled = this.enabled.has(mode);
+ if (enabled === DEFAULT_ON.has(mode)) continue; // already the client's default
+ (enabled ? on : off).push(mode);
+ }
+ let out = "";
+ if (on.length > 0) out += `\x1b[?${on.join(";")}h`;
+ if (off.length > 0) out += `\x1b[?${off.join(";")}l`;
+ return out;
+ }
+}
diff --git a/packages/server/src/platform/terminal/manager.ts b/packages/server/src/platform/terminal/manager.ts
new file mode 100644
index 00000000..7538395d
--- /dev/null
+++ b/packages/server/src/platform/terminal/manager.ts
@@ -0,0 +1,221 @@
+/**
+ * Terminal registry: create / look up / list / kill, plus the lifetime rules.
+ *
+ * Ownership is per user, not per project: a shell runs as the OS account hosting the server
+ * and can read and write everything that account can, so it is not a project-scoped
+ * resource and must never be reachable by another account.
+ *
+ * Two lifetime rules matter:
+ * - A session that has exited is kept for a short grace period instead of being dropped, so
+ * a reload right after `exit` still shows the final screen.
+ * - A live session is *not* tied to any connection. Closing the tab leaves the shell (and
+ * whatever it is running) alive — that is the entire point of a server-side terminal.
+ */
+import fsp from "node:fs/promises";
+import type { Resources } from "@prismshadow/penguin-core/kernel";
+import path from "node:path";
+import { HttpError } from "../../http/errors.js";
+import { spawnHelperHint } from "../../terminal/spawn-helper.js";
+import {
+ TerminalSession,
+ expandHomePath,
+ type CreateTerminalSessionOptions,
+ type TerminalSessionInfo,
+} from "./session.js";
+
+/** How long an exited session stays listable/attachable before it is disposed. */
+export const EXITED_SESSION_GRACE_MS = 5 * 60 * 1000;
+/** Cap per user; a runaway UI loop would otherwise fork shells until the box gives up. */
+export const MAX_TERMINALS_PER_USER = 12;
+
+export interface CreateTerminalRequest {
+ cwd: string;
+ ownerUserId: string;
+ name?: string;
+ cols?: number;
+ rows?: number;
+ shell?: string;
+}
+
+export class TerminalManager {
+ /**
+ * The kernel's resource registry, threaded to every session it creates: a native module
+ * reaches the platform through it (pty-module.ts), and live ptys are registered in it so
+ * a hot swap hands them to the next platform instead of killing them.
+ */
+ constructor(
+ private readonly resources: Resources,
+ private readonly graceMs: number = EXITED_SESSION_GRACE_MS,
+ ) {}
+
+ private readonly sessions = new Map<string, TerminalSession>();
+ private readonly reapTimers = new Map<string, ReturnType<typeof setTimeout>>();
+
+ async create(request: CreateTerminalRequest): Promise<TerminalSession> {
+ const cwd = await resolveCwd(request.cwd);
+
+ const owned = this.list(request.ownerUserId).filter((session) => session.alive);
+ if (owned.length >= MAX_TERMINALS_PER_USER) {
+ throw new HttpError(
+ 429,
+ "terminal_limit_reached",
+ `You already have ${MAX_TERMINALS_PER_USER} open terminals. Close one first.`,
+ );
+ }
+
+ // Unnamed terminals auto-increment per user ("tmp", "tmp 2", …): several shells in
+ // the same directory would otherwise be indistinguishable in every list.
+ let name = request.name;
+ if (name === undefined) {
+ const base = path.basename(cwd) || "terminal";
+ const taken = new Set(owned.map((session) => session.info().name));
+ name = base;
+ for (let n = 2; taken.has(name); n += 1) name = `${base} ${n}`;
+ }
+
+ // Stable display number: smallest free among the user's live terminals, and it stays
+ // with this terminal for life. (Positional numbering would renumber tabs on every
+ // reorder — a dragged tab must keep its number so the user can see where it went.)
+ const usedSeqs = new Set(owned.map((session) => session.seq));
+ let seq = 1;
+ while (usedSeqs.has(seq)) seq += 1;
+
+ const options: CreateTerminalSessionOptions = {
+ cwd,
+ ownerUserId: request.ownerUserId,
+ seq,
+ name,
+ resources: this.resources,
+ ...(request.cols !== undefined ? { cols: request.cols } : {}),
+ ...(request.rows !== undefined ? { rows: request.rows } : {}),
+ ...(request.shell !== undefined ? { shell: request.shell } : {}),
+ };
+
+ let session: TerminalSession;
+ try {
+ session = new TerminalSession(options);
+ } catch (err) {
+ // A bare "posix_spawnp failed." says nothing; when the cause is node-pty's
+ // non-executable spawn-helper, name the file and the fix.
+ const hint = spawnHelperHint();
+ throw new HttpError(
+ 500,
+ "terminal_spawn_failed",
+ `Could not start a shell: ${err instanceof Error ? err.message : String(err)}` +
+ (hint === null ? "" : ` (${hint})`),
+ );
+ }
+
+ this.track(session);
+ return session;
+ }
+
+ /**
+ * Takes a session into this manager AND into the runtime's resource registry. The
+ * registry is what makes a pty outlive a platform swap: it sits outside the reloadable
+ * tree, so the shell keeps running and the next instance claims it back (see
+ * hmr/resources.ts). The parked context carries only these ids.
+ */
+ private track(session: TerminalSession): void {
+ this.sessions.set(session.id, session);
+ session.onExit(() => this.scheduleReap(session.id));
+ this.resources.register(resourceId(session.id), session, () => session.dispose());
+ }
+
+ /**
+ * Reclaims the sessions a previous instance parked. An id the registry no longer knows
+ * is simply dropped: its shell died with the process that owned it, and a manager
+ * holding a handle to nothing would only fail later, further from the cause.
+ */
+ adopt(ids: readonly string[]): void {
+ for (const id of ids) {
+ const session = this.resources.claim<TerminalSession>(resourceId(id));
+ if (session === undefined) continue;
+ this.sessions.set(session.id, session);
+ session.onExit(() => this.scheduleReap(session.id));
+ }
+ }
+
+ /** Handle ids for the parked context document — live sessions only. */
+ handleIds(): string[] {
+ return [...this.sessions.values()].filter((s) => s.alive).map((s) => s.id);
+ }
+
+ /** Looks up a session, enforcing ownership. Unknown and not-yours are both 404 — no probing. */
+ require(id: string, userId: string): TerminalSession {
+ const session = this.sessions.get(id);
+ if (!session || session.ownerUserId !== userId) {
+ throw new HttpError(404, "terminal_not_found", "Terminal does not exist or has been closed.");
+ }
+ return session;
+ }
+
+ get(id: string): TerminalSession | undefined {
+ return this.sessions.get(id);
+ }
+
+ list(userId: string): TerminalSession[] {
+ return [...this.sessions.values()]
+ .filter((session) => session.ownerUserId === userId)
+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
+ }
+
+ listInfo(userId: string): TerminalSessionInfo[] {
+ return this.list(userId).map((session) => session.info());
+ }
+
+ kill(id: string, userId: string): void {
+ const session = this.require(id, userId);
+ session.kill();
+ this.scheduleReap(id, 2000);
+ }
+
+ /** Drops the session once nothing can usefully be read from it any more. */
+ private scheduleReap(id: string, delayMs = this.graceMs): void {
+ const existing = this.reapTimers.get(id);
+ if (existing) clearTimeout(existing);
+ const timer = setTimeout(() => {
+ this.reapTimers.delete(id);
+ this.sessions.get(id)?.dispose();
+ this.sessions.delete(id);
+ // Out of the registry too: a disposed pty must not be claimable by the next boot.
+ this.resources.release(resourceId(id));
+ }, delayMs);
+ timer.unref?.();
+ this.reapTimers.set(id, timer);
+ }
+
+ /** Server shutdown: every pty is a child process and must not outlive us. */
+ disposeAll(): void {
+ for (const timer of this.reapTimers.values()) clearTimeout(timer);
+ this.reapTimers.clear();
+ for (const session of this.sessions.values()) session.dispose();
+ this.sessions.clear();
+ }
+}
+
+/** Expands `~`, requires an absolute path, and verifies it is a readable directory. */
+async function resolveCwd(input: string): Promise<string> {
+ const expanded = expandHomePath((input ?? "").trim() || "~");
+ // A relative path would silently resolve against the *server process* cwd — never what
+ // the caller meant, and it leaks where the server was started from.
+ if (!path.isAbsolute(expanded)) {
+ throw new HttpError(400, "cwd_not_absolute", `Working directory must be absolute: ${expanded}`);
+ }
+ let real: string;
+ try {
+ real = await fsp.realpath(expanded);
+ } catch {
+ throw new HttpError(400, "cwd_not_found", `Directory does not exist: ${expanded}`);
+ }
+ const stat = await fsp.stat(real);
+ if (!stat.isDirectory()) {
+ throw new HttpError(400, "cwd_not_a_dir", `Not a directory: ${real}`);
+ }
+ return real;
+}
+
+/** Registry key for a session's live pty (namespaced so kinds cannot collide). */
+function resourceId(sessionId: string): string {
+ return `terminal:${sessionId}`;
+}
diff --git a/packages/server/src/platform/terminal/output-coalescer.ts b/packages/server/src/platform/terminal/output-coalescer.ts
new file mode 100644
index 00000000..76095f1c
--- /dev/null
+++ b/packages/server/src/platform/terminal/output-coalescer.ts
@@ -0,0 +1,67 @@
+/**
+ * Per-stream output throttle.
+ *
+ * A pty emits many small chunks; forwarding each one as its own socket frame floods the
+ * event loop under build output. This merges chunks inside a short window — but as a
+ * **leading + trailing** throttle, not a plain trailing one: the first chunk after an idle
+ * window flushes synchronously, so a keystroke echo never pays the window. Only sustained
+ * bursts wait for the trailing timer.
+ *
+ * Reverting this to trailing-only is the classic regression here: it adds a full window
+ * (~5ms) to every single keystroke and the terminal immediately feels mushy.
+ */
+
+export const DEFAULT_COALESCE_WINDOW_MS = 5;
+
+export class TerminalOutputCoalescer {
+ private pending = "";
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private lastFlushAt = 0;
+
+ constructor(
+ private readonly flushFn: (data: string) => void,
+ private readonly windowMs: number = DEFAULT_COALESCE_WINDOW_MS,
+ private readonly now: () => number = () => Date.now(),
+ ) {}
+
+ push(data: string): void {
+ if (data.length === 0) return;
+ this.pending += data;
+
+ if (this.timer !== null) return; // a trailing flush is already scheduled
+
+ const elapsed = this.now() - this.lastFlushAt;
+ if (elapsed >= this.windowMs) {
+ this.flush(); // leading edge: straight through, no added latency
+ return;
+ }
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ this.flush();
+ }, this.windowMs - elapsed);
+ }
+
+ /**
+ * Flushes anything buffered. Callers must invoke this before sending an out-of-band
+ * message (restore, exit) so ordering with the output stream is preserved.
+ */
+ flush(): void {
+ if (this.timer !== null) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ this.lastFlushAt = this.now();
+ if (this.pending.length === 0) return;
+ const data = this.pending;
+ this.pending = "";
+ this.flushFn(data);
+ }
+
+ dispose(): void {
+ if (this.timer !== null) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ this.pending = "";
+ }
+}
diff --git a/packages/server/src/platform/terminal/pty-module.ts b/packages/server/src/platform/terminal/pty-module.ts
new file mode 100644
index 00000000..2d43ab70
--- /dev/null
+++ b/packages/server/src/platform/terminal/pty-module.ts
@@ -0,0 +1,68 @@
+/**
+ * How the platform gets hold of node-pty.
+ *
+ * node-pty is a native module, and a pushed platform bundle cannot carry one: the bundle
+ * is imported from `<dataRoot>/hmr/store/platform/<sha>.mjs`, where neither node-pty's own
+ * relative `build/Release/pty.node` nor a bare `require("node-pty")` resolves (verified —
+ * the binding fails with "Failed to load native module: pty.node"). So the binary travels
+ * as a push ASSET (see hmr/host.ts's UpgradeAssets) and is loaded from the directory the
+ * runtime publishes through the resource registry.
+ *
+ * Order matters: the runtime's own copy is tried FIRST when this code runs as part of the
+ * packaged server, because that binary is built for the machine it is running on. A pushed
+ * asset comes from whatever machine ran the deploy, so it is the fallback — right for the
+ * hot path it exists to serve, but never allowed to displace a known-good local build.
+ */
+import { createRequire } from "node:module";
+import path from "node:path";
+import type { Resources } from "@prismshadow/penguin-core/kernel";
+import { ASSETS_RESOURCE_ID } from "../../hmr/host.js";
+
+/** The slice of node-pty this package uses (kept narrow so the fallback stays checkable). */
+export interface NodePty {
+ spawn(
+ file: string,
+ args: string[] | string,
+ options: {
+ name?: string;
+ cols?: number;
+ rows?: number;
+ cwd?: string;
+ env?: Record<string, string>;
+ },
+ ): import("node-pty").IPty;
+}
+
+let cached: NodePty | null = null;
+
+/**
+ * Resolves node-pty once per platform instance. `resources` comes from the kernel's node
+ * context; a runtime that published no assets simply leaves the fallback unused.
+ */
+export function loadNodePty(resources: Resources): NodePty {
+ if (cached !== null) return cached;
+
+ const attempts: Array<() => NodePty> = [
+ // Packaged server: this module is part of the runtime's own graph.
+ () => createRequire(import.meta.url)("node-pty") as NodePty,
+ // Pushed bundle: the binary rides along as an asset, laid out as a real package dir.
+ () => {
+ const dir = resources.claim<string>(ASSETS_RESOURCE_ID);
+ if (dir === undefined) throw new Error("no assets directory published");
+ // A require anchored inside the assets dir resolves `node_modules/node-pty` there,
+ // which lets node-pty's own relative loader find its binary as it normally would.
+ return createRequire(path.join(dir, "index.mjs"))("node-pty") as NodePty;
+ },
+ ];
+
+ const failures: string[] = [];
+ for (const attempt of attempts) {
+ try {
+ cached = attempt();
+ return cached;
+ } catch (err) {
+ failures.push(err instanceof Error ? err.message : String(err));
+ }
+ }
+ throw new Error(`node-pty is unavailable to the platform: ${failures.join(" / ")}`);
+}
diff --git a/packages/server/src/platform/terminal/routes.ts b/packages/server/src/platform/terminal/routes.ts
new file mode 100644
index 00000000..344570b0
--- /dev/null
+++ b/packages/server/src/platform/terminal/routes.ts
@@ -0,0 +1,179 @@
+/**
+ * Terminal control plane: `/api/terminals`, served by the PLATFORM through the HTTP seam.
+ *
+ * A Hono app on the seam contract (see ../hono-seam.ts): unknown paths and methods fall
+ * to notFound, which declines to whatever is next in line — so this app owns exactly the
+ * six routes below and nothing else under its prefix. The identity gate is attached
+ * per-route, not as a prefix middleware, so a request nothing here serves declines
+ * BEFORE authentication, same as a request outside the prefix.
+ *
+ * Identity is resolved through a runtime capability, not re-implemented here: the seam
+ * runs BEFORE the auth middleware (app.ts mounts it there on purpose, so a push can
+ * decide its own authentication), and "who is this request from" is exactly what the
+ * runtime layer owns — it boots, transports and authenticates. Body limits and the
+ * JSON-only rule for writes DO apply already: both middlewares sit above the seam.
+ *
+ * Split the way this server is built: JSON over HTTP for control, and a separate binary
+ * WebSocket for the byte stream (the runtime's terminal/ws.ts hands the socket over; its
+ * `/:id/stream` path is deliberately not a route here, so it declines).
+ *
+ * GET /api/terminals list the caller's terminals
+ * POST /api/terminals create one (cwd defaults to the home directory)
+ * GET /api/terminals/:id one terminal's metadata
+ * DELETE /api/terminals/:id kill it
+ * GET /api/terminals/:id/capture plain-text screen contents
+ * POST /api/terminals/:id/keys send text or key tokens
+ *
+ * `capture` and `keys` exist because a terminal should be readable and drivable by things
+ * that are not a rendering client — the e2e check for reload fidelity uses them, and they
+ * are the same two primitives an agent needs to run a command and read the result.
+ */
+import { Hono } from "hono";
+import type { MiddlewareHandler } from "hono";
+import { HttpError } from "../../http/errors.js";
+import { badRequest } from "../../http/validate.js";
+import { declined, seamHttp } from "../hono-seam.js";
+import type { TerminalManager } from "./manager.js";
+import type { IdentifiedUser, Identity } from "./identity.js";
+
+/**
+ * Key tokens accepted by POST /keys, so a caller can send Enter or Ctrl-C without
+ * hand-encoding control bytes.
+ */
+const KEY_TOKENS: Record<string, string> = {
+ Enter: "\r",
+ Tab: "\t",
+ Escape: "\x1b",
+ Backspace: "\x7f",
+ Space: " ",
+ Up: "\x1b[A",
+ Down: "\x1b[B",
+ Right: "\x1b[C",
+ Left: "\x1b[D",
+ Home: "\x1b[H",
+ End: "\x1b[F",
+ PageUp: "\x1b[5~",
+ PageDown: "\x1b[6~",
+ Delete: "\x1b[3~",
+};
+
+/** Resolves `keys` into bytes: literal text, or `Enter` / `C-c`-style tokens. */
+export function resolveKeys(keys: string, literal: boolean): string {
+ if (literal) return keys;
+ if (keys in KEY_TOKENS) return KEY_TOKENS[keys] as string;
+ const ctrl = /^C-([a-z@[\]\\^_])$/i.exec(keys);
+ if (ctrl) {
+ const ch = (ctrl[1] as string).toUpperCase();
+ return String.fromCharCode(ch.charCodeAt(0) & 0x1f);
+ }
+ return keys;
+}
+
+function optionalInt(value: unknown, field: string): number | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (!Number.isInteger(value)) throw badRequest(`${field} must be an integer.`);
+ return value as number;
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json; charset=UTF-8" },
+ });
+}
+
+/** The App's error body shape, so a platform failure reads like every other API error. */
+function errorResponse(err: unknown): Response {
+ if (err instanceof HttpError) {
+ return json({ error: { code: err.code, message: err.message } }, err.status);
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return json({ error: { code: "internal", message } }, 500);
+}
+
+async function readBody(request: Request): Promise<Record<string, unknown>> {
+ try {
+ return (await request.json()) as Record<string, unknown>;
+ } catch {
+ return {};
+ }
+}
+
+type TerminalEnv = { Variables: { user: IdentifiedUser } };
+
+/**
+ * Serves the terminal API, or returns null for a request this platform does not own.
+ * `identity` is the runtime's capability; a request it cannot attribute is 401 here rather
+ * than falling through, because falling through would hand an unauthenticated caller
+ * whatever older handler sits behind the seam.
+ */
+export function terminalHttp(
+ manager: TerminalManager,
+ identity: Identity,
+): (request: Request) => Promise<Response | null> {
+ const app = new Hono<TerminalEnv>();
+ app.notFound(() => declined());
+ app.onError((err) => errorResponse(err));
+
+ const gate: MiddlewareHandler<TerminalEnv> = async (c, next) => {
+ const user = await identity(c.req.raw);
+ if (user === null) {
+ return json({ error: { code: "unauthorized", message: "Not signed in." } }, 401);
+ }
+ c.set("user", user);
+ await next();
+ };
+
+ app.get("/api/terminals", gate, (c) => json({ terminals: manager.listInfo(c.var.user.userId) }));
+ app.post("/api/terminals", gate, async (c) =>
+ json(await create(c.req.raw, manager, c.var.user.userId), 201),
+ );
+ app.get("/api/terminals/:id", gate, (c) =>
+ json(manager.require(c.req.param("id"), c.var.user.userId).info()),
+ );
+ app.delete("/api/terminals/:id", gate, (c) => {
+ manager.kill(c.req.param("id"), c.var.user.userId);
+ return new Response(null, { status: 204 });
+ });
+ app.get("/api/terminals/:id/capture", gate, (c) => {
+ const session = manager.require(c.req.param("id"), c.var.user.userId);
+ const start = c.req.query("start");
+ const end = c.req.query("end");
+ return json(
+ session.capture({
+ ...(start !== undefined ? { start: Number.parseInt(start, 10) } : {}),
+ ...(end !== undefined ? { end: Number.parseInt(end, 10) } : {}),
+ }),
+ );
+ });
+ app.post("/api/terminals/:id/keys", gate, async (c) => {
+ const session = manager.require(c.req.param("id"), c.var.user.userId);
+ const body = await readBody(c.req.raw);
+ if (typeof body.keys !== "string") throw badRequest("keys must be a string.");
+ if (!session.alive) {
+ throw new HttpError(409, "terminal_exited", "This terminal's shell has exited.");
+ }
+ session.write(resolveKeys(body.keys, body.literal === true));
+ return json({ ok: true });
+ });
+
+ return seamHttp(app);
+}
+
+async function create(request: Request, manager: TerminalManager, ownerUserId: string) {
+ const body = await readBody(request);
+ const cwd = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : "~";
+ const name = typeof body.name === "string" ? body.name : undefined;
+ // Optional shell override (default: the user's login shell). Not an escalation — the
+ // terminal already runs arbitrary commands as the server's account.
+ const shell = typeof body.shell === "string" && body.shell.trim() ? body.shell.trim() : undefined;
+ const session = await manager.create({
+ cwd,
+ ownerUserId,
+ ...(name !== undefined ? { name } : {}),
+ ...(shell !== undefined ? { shell } : {}),
+ ...(optionalInt(body.cols, "cols") !== undefined ? { cols: body.cols as number } : {}),
+ ...(optionalInt(body.rows, "rows") !== undefined ? { rows: body.rows as number } : {}),
+ });
+ return session.info();
+}
diff --git a/packages/server/src/platform/terminal/session.ts b/packages/server/src/platform/terminal/session.ts
new file mode 100644
index 00000000..df760e5f
--- /dev/null
+++ b/packages/server/src/platform/terminal/session.ts
@@ -0,0 +1,425 @@
+/**
+ * One terminal session: a pty plus the daemon's authoritative view of its screen.
+ *
+ * The important idea is that the *server* owns the emulator: every pty byte is fed into a
+ * headless xterm here, so the daemon always knows the full screen, cursor and title.
+ * Clients are then just views that can come and go — which is what makes reload/reattach,
+ * plain-text capture and multi-device viewing possible at all. A client-only emulator
+ * would lose all of that the moment the tab closes.
+ *
+ * Sessions deliberately run in-process rather than in a forked terminal worker. A worker
+ * would keep pty parsing off the daemon's event loop under heavy build output, but costs
+ * an IPC protocol and a second process to supervise. Worth doing when this is under load,
+ * not on day one — the seam (this module is the only thing that touches node-pty) is where
+ * that split would go.
+ */
+import os from "node:os";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import xterm, { type Terminal } from "@xterm/headless";
+import type { IPty } from "node-pty";
+import type { Resources } from "@prismshadow/penguin-core/kernel";
+import { loadNodePty } from "./pty-module.js";
+import { defaultTerminalShell, shellArgs } from "./shell.js";
+import { TerminalInputModeTracker } from "./input-mode.js";
+import { ensureSpawnHelperExecutable } from "../../terminal/spawn-helper.js";
+import {
+ captureLines,
+ renderRestoreAnsi,
+ type CaptureLinesOptions,
+ type CaptureLinesResult,
+} from "./snapshot.js";
+import {
+ applyTerminalSize,
+ releaseTerminalSize,
+ type TerminalSizeState,
+} from "./size-ownership.js";
+
+const { Terminal: HeadlessTerminal } = xterm;
+
+const DEFAULT_COLS = 80;
+const DEFAULT_ROWS = 24;
+const SCROLLBACK_LINES = 5000;
+const TITLE_DEBOUNCE_MS = 150;
+const EXIT_OUTPUT_LINE_LIMIT = 12;
+
+/**
+ * Answers to capability queries. A headless emulator has no display to ask, so the daemon
+ * answers on its behalf — without this, anything that probes the terminal (nvim, less,
+ * fzf, some prompts) waits for a reply that never comes and appears to hang on startup.
+ */
+const OSC_COLOR_QUERY_RESPONSES = new Map<number, string>([
+ [10, "rgb:e6e6/e6e6/e6e6"], // foreground
+ [11, "rgb:1414/1717/1a1a"], // background
+ [12, "rgb:e6e6/e6e6/e6e6"], // cursor
+]);
+
+export interface TerminalExitInfo {
+ exitCode: number;
+ signal: number | null;
+ lastOutputLines: string[];
+}
+
+export interface CreateTerminalSessionOptions {
+ id?: string;
+ /** Absolute working directory (already resolved and validated by the manager). */
+ cwd: string;
+ /** Owning user id — a shell is the most privileged thing this server hands out. */
+ ownerUserId: string;
+ /**
+ * Stable per-user display number (tmux-style), assigned by the manager at creation. It
+ * travels with the terminal for its whole life — UI numbering must never depend on list
+ * position, which changes under user-reordered tabs.
+ */
+ seq?: number;
+ name?: string;
+ shell?: string;
+ cols?: number;
+ rows?: number;
+ env?: Record<string, string>;
+ /**
+ * Where node-pty comes from. The platform cannot import a native module directly (see
+ * pty-module.ts): the kernel's resource registry is how the runtime hands it over.
+ */
+ resources: Resources;
+}
+
+export interface TerminalSessionInfo {
+ id: string;
+ seq: number;
+ name: string;
+ cwd: string;
+ ownerUserId: string;
+ title: string | null;
+ cols: number;
+ rows: number;
+ pid: number;
+ createdAt: string;
+ alive: boolean;
+ exit: TerminalExitInfo | null;
+}
+
+export type TerminalOutputListener = (data: string) => void;
+export type TerminalExitListener = (info: TerminalExitInfo) => void;
+export type TerminalTitleListener = (title: string | null) => void;
+
+/**
+ * Environment for the pty. `TERM`/`COLORTERM` are what make colour and 256-colour output
+ * work at all; the rest of the parent environment is inherited so the shell behaves like the
+ * user's own (PATH, proxies, language).
+ */
+function buildTerminalEnv(
+ extra: Record<string, string> | undefined,
+ cwd: string,
+): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) {
+ if (typeof value === "string") env[key] = value;
+ }
+ Object.assign(env, extra ?? {});
+ env.TERM = "xterm-256color";
+ env.COLORTERM = "truecolor";
+ env.PENGUIN_TERMINAL = "1";
+ env.PWD = cwd;
+ // Inherited from the server process; a pty is not that server and these would point the
+ // shell (and anything it starts) at the wrong runtime.
+ delete env.NODE_OPTIONS;
+ return env;
+}
+
+export class TerminalSession {
+ readonly id: string;
+ readonly seq: number;
+ readonly cwd: string;
+ readonly ownerUserId: string;
+ readonly createdAt = new Date();
+
+ private name: string;
+ private readonly terminal: Terminal;
+ private readonly ptyProcess: IPty;
+ private readonly inputMode = new TerminalInputModeTracker();
+ private readonly outputListeners = new Set<TerminalOutputListener>();
+ private readonly exitListeners = new Set<TerminalExitListener>();
+ private readonly titleListeners = new Set<TerminalTitleListener>();
+
+ private title: string | null = null;
+ private pendingTitle: string | null = null;
+ private titleTimer: ReturnType<typeof setTimeout> | null = null;
+ private sizeState: TerminalSizeState;
+ private exitInfo: TerminalExitInfo | null = null;
+ private disposed = false;
+
+ constructor(options: CreateTerminalSessionOptions) {
+ this.id = options.id ?? randomUUID();
+ this.seq = options.seq ?? 1;
+ this.cwd = options.cwd;
+ this.ownerUserId = options.ownerUserId;
+ this.name = options.name ?? (path.basename(options.cwd) || "terminal");
+
+ const cols = clampDimension(options.cols, DEFAULT_COLS, 1000);
+ const rows = clampDimension(options.rows, DEFAULT_ROWS, 500);
+ this.sizeState = { ownerId: null, cols, rows };
+
+ this.terminal = new HeadlessTerminal({
+ cols,
+ rows,
+ scrollback: SCROLLBACK_LINES,
+ allowProposedApi: true,
+ });
+
+ const shell = options.shell ?? defaultTerminalShell();
+ // Before the first spawn on macOS: node-pty's prebuilt spawn-helper ships without an
+ // exec bit, and posix_spawnp refuses it (see spawn-helper.ts).
+ ensureSpawnHelperExecutable();
+ this.ptyProcess = loadNodePty(options.resources).spawn(shell, shellArgs(shell), {
+ name: "xterm-256color",
+ cols,
+ rows,
+ cwd: options.cwd,
+ env: buildTerminalEnv(options.env, options.cwd),
+ });
+
+ this.registerCapabilityResponders();
+
+ this.terminal.onTitleChange((next) => {
+ this.pendingTitle = next.trim() || null;
+ if (this.titleTimer) return;
+ // A shell that writes the title on every prompt would otherwise fan out an event per
+ // keystroke to every attached client.
+ this.titleTimer = setTimeout(() => {
+ this.titleTimer = null;
+ if (this.pendingTitle === this.title) return;
+ this.title = this.pendingTitle;
+ for (const listener of [...this.titleListeners]) safely(() => listener(this.title));
+ }, TITLE_DEBOUNCE_MS);
+ });
+
+ this.ptyProcess.onData((chunk) => {
+ this.inputMode.feed(chunk);
+ // Publish only once the emulator has consumed the chunk (`write` parses async).
+ // Publishing eagerly opens a gap where a client attaches after the publication but
+ // before the parse: the snapshot it restores from lacks the bytes AND its output
+ // subscription started too late — the chunk is simply lost to that client. Ordering
+ // behind the write callback makes every byte either part of the snapshot or
+ // delivered through the subscription, never neither.
+ this.terminal.write(chunk, () => {
+ for (const listener of [...this.outputListeners]) safely(() => listener(chunk));
+ });
+ });
+
+ this.ptyProcess.onExit(({ exitCode, signal }) => {
+ // The screen is still readable after the shell exits, so the tail is captured and the
+ // session is kept (briefly) by the manager — a reload right after `exit` shows what
+ // happened instead of an empty box. Capture must wait for the emulator to drain its
+ // async write queue, or the final burst of output is missing from the tail.
+ const finalize = (): void => {
+ if (this.exitInfo) return;
+ this.exitInfo = {
+ exitCode,
+ signal: signal ?? null,
+ lastOutputLines: this.disposed
+ ? []
+ : lastNonEmptyLines(this.terminal, EXIT_OUTPUT_LINE_LIMIT),
+ };
+ for (const listener of [...this.exitListeners]) safely(() => listener(this.exitInfo!));
+ };
+ if (this.disposed) return finalize(); // a disposed emulator accepts no more writes
+ this.terminal.write("", finalize);
+ });
+ }
+
+ /** DA1 / DSR / OSC colour queries — see OSC_COLOR_QUERY_RESPONSES. */
+ private registerCapabilityResponders(): void {
+ this.terminal.parser.registerCsiHandler({ final: "c" }, (params) => {
+ if (params.length === 0 || (params.length === 1 && params[0] === 0)) {
+ this.ptyProcess.write("\x1b[?62;4;22c"); // VT220 + sixel-less, matching a modern xterm
+ return true;
+ }
+ return false;
+ });
+ this.terminal.parser.registerCsiHandler({ final: "n" }, (params) => {
+ if (params.length !== 1) return false;
+ if (params[0] === 5) {
+ this.ptyProcess.write("\x1b[0n"); // device OK
+ return true;
+ }
+ if (params[0] === 6) {
+ const buffer = this.terminal.buffer.active;
+ this.ptyProcess.write(`\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R`);
+ return true;
+ }
+ return false;
+ });
+ this.terminal.parser.registerCsiHandler({ prefix: "?", final: "n" }, (params) => {
+ if (params.length !== 1 || params[0] !== 6) return false;
+ const buffer = this.terminal.buffer.active;
+ this.ptyProcess.write(`\x1b[?${buffer.cursorY + 1};${buffer.cursorX + 1}R`);
+ return true;
+ });
+ for (const [code, response] of OSC_COLOR_QUERY_RESPONSES) {
+ this.terminal.parser.registerOscHandler(code, (data) => {
+ if (data.trim() !== "?") return false;
+ this.ptyProcess.write(`\x1b]${code};${response}\x1b\\`);
+ return true;
+ });
+ }
+ }
+
+ get alive(): boolean {
+ return this.exitInfo === null && !this.disposed;
+ }
+
+ get exit(): TerminalExitInfo | null {
+ return this.exitInfo;
+ }
+
+ info(): TerminalSessionInfo {
+ return {
+ id: this.id,
+ seq: this.seq,
+ name: this.name,
+ cwd: this.cwd,
+ ownerUserId: this.ownerUserId,
+ title: this.title,
+ cols: this.sizeState.cols,
+ rows: this.sizeState.rows,
+ pid: this.ptyProcess.pid,
+ createdAt: this.createdAt.toISOString(),
+ alive: this.alive,
+ exit: this.exitInfo,
+ };
+ }
+
+ rename(name: string): void {
+ const trimmed = name.trim();
+ if (trimmed) this.name = trimmed;
+ }
+
+ write(data: string): void {
+ if (!this.alive) return;
+ this.ptyProcess.write(data);
+ }
+
+ /**
+ * Applies a size request under the claim/update ownership rule, resizing both the pty and
+ * the daemon's emulator so snapshots keep matching what the shell laid out.
+ */
+ resize(request: {
+ connectionId: string;
+ cols: number;
+ rows: number;
+ intent: "claim" | "update";
+ }): boolean {
+ const cols = clampDimension(request.cols, DEFAULT_COLS, 1000);
+ const rows = clampDimension(request.rows, DEFAULT_ROWS, 500);
+ const decision = applyTerminalSize(this.sizeState, { ...request, cols, rows });
+ this.sizeState = decision.state;
+ if (!decision.apply || !this.alive) return false;
+ this.terminal.resize(cols, rows);
+ try {
+ this.ptyProcess.resize(cols, rows);
+ } catch {
+ // The pty can exit between the alive check and here; the exit path handles teardown.
+ }
+ return true;
+ }
+
+ releaseSize(connectionId: string): void {
+ this.sizeState = releaseTerminalSize(this.sizeState, connectionId);
+ }
+
+ get size(): { cols: number; rows: number } {
+ return { cols: this.sizeState.cols, rows: this.sizeState.rows };
+ }
+
+ /** The attach payload: the whole screen as an ANSI stream (see snapshot.ts). */
+ restoreStream(options: { scrollbackLines?: number } = {}): string {
+ return renderRestoreAnsi(this.terminal, {
+ ...options,
+ inputModePreamble: this.inputMode.preamble(),
+ });
+ }
+
+ capture(options: CaptureLinesOptions = {}): CaptureLinesResult {
+ return captureLines(this.terminal, options);
+ }
+
+ onOutput(listener: TerminalOutputListener): () => void {
+ this.outputListeners.add(listener);
+ return () => this.outputListeners.delete(listener);
+ }
+
+ onExit(listener: TerminalExitListener): () => void {
+ this.exitListeners.add(listener);
+ return () => this.exitListeners.delete(listener);
+ }
+
+ onTitleChange(listener: TerminalTitleListener): () => void {
+ this.titleListeners.add(listener);
+ return () => this.titleListeners.delete(listener);
+ }
+
+ kill(signal?: string): void {
+ if (!this.alive) return;
+ try {
+ this.ptyProcess.kill(signal);
+ } catch {
+ // Already gone.
+ }
+ }
+
+ dispose(): void {
+ if (this.disposed) return;
+ if (this.titleTimer) clearTimeout(this.titleTimer);
+ // Order matters: kill() no-ops once `disposed` flips `alive` to false, so the polite
+ // SIGHUP has to go out first (that ordering bug once left every shell running after
+ // server shutdown — only the test process exiting hid it).
+ this.kill();
+ this.disposed = true;
+ // SIGHUP is also advisory: a server started under `nohup` has HUP ignored, children
+ // inherit that, and the hangup silently does nothing. Disposal is final — escalate.
+ if (process.platform !== "win32" && this.exitInfo === null) {
+ try {
+ this.ptyProcess.kill("SIGKILL");
+ } catch {
+ // Already gone.
+ }
+ }
+ this.outputListeners.clear();
+ this.exitListeners.clear();
+ this.titleListeners.clear();
+ this.terminal.dispose();
+ }
+}
+
+function clampDimension(value: number | undefined, fallback: number, max: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.min(Math.max(Math.trunc(value), 1), max);
+}
+
+function lastNonEmptyLines(terminal: Terminal, limit: number): string[] {
+ const buffer = terminal.buffer.active;
+ const total = buffer.baseY + terminal.rows;
+ const lines: string[] = [];
+ for (let y = total - 1; y >= 0 && lines.length < limit; y -= 1) {
+ const text = buffer.getLine(y)?.translateToString(true) ?? "";
+ if (text.trim() === "" && lines.length === 0) continue; // skip the blank tail
+ lines.push(text);
+ }
+ return lines.reverse();
+}
+
+function safely(fn: () => void): void {
+ try {
+ fn();
+ } catch {
+ // One bad listener must not take down the pty pump.
+ }
+}
+
+/** Home-directory expansion for the API's `cwd` (the UI sends `~`). */
+export function expandHomePath(input: string): string {
+ if (input === "~") return os.homedir();
+ if (input.startsWith("~/")) return path.join(os.homedir(), input.slice(2));
+ return input;
+}
diff --git a/packages/server/src/platform/terminal/shell.ts b/packages/server/src/platform/terminal/shell.ts
new file mode 100644
index 00000000..2189a5ed
--- /dev/null
+++ b/packages/server/src/platform/terminal/shell.ts
@@ -0,0 +1,98 @@
+/**
+ * Which shell a terminal session runs, and how it is invoked.
+ *
+ * This is deliberately NOT core's `resolveShell()` (environment/tools/command/shell.ts).
+ * That one picks a shell for the *agent* to run commands in: it prefers a POSIX bash on
+ * Windows because Skills are written for one, and it passes `-NoProfile` to PowerShell so
+ * two machines behave identically. Both choices are wrong for a human at a keyboard, who
+ * expects the shell their OS gives them, with their own profile in effect — the prompt,
+ * the aliases, the PATH edits. So the two resolvers stay separate on purpose.
+ *
+ * `PENGUIN_SHELL` is honoured first on every platform, so a user who has already told the
+ * harness which shell to use is not asked twice.
+ */
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+
+/** Injection points for unit tests; production callers use the defaults. */
+export interface ResolveTerminalShellOptions {
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ /** Whether an executable name resolves on PATH (win32 only); default probes with `where`. */
+ onPath?: (cmd: string) => boolean;
+}
+
+/** Basename without a trailing .exe/.cmd/.bat, lowercased ("C:\...\pwsh.EXE" -> "pwsh"). */
+function shellName(shell: string): string {
+ // path.win32 handles both separators, so /usr/bin/zsh still yields "zsh".
+ return path.win32
+ .basename(shell)
+ .replace(/\.(exe|cmd|bat)$/i, "")
+ .toLowerCase();
+}
+
+/** Default PATH probe (win32 only, one subprocess per name, cached by the caller). */
+function defaultOnPath(cmd: string): boolean {
+ try {
+ const res = spawnSync("where", [cmd], {
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ });
+ return res.status === 0 && (res.stdout?.toString("utf8").trim().length ?? 0) > 0;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The shell to spawn when the request names none.
+ *
+ * POSIX takes `$SHELL` — the user's own login shell, exactly what a terminal emulator
+ * opens. Windows has no such variable, and `%ComSpec%` (cmd.exe) reads no profile at all,
+ * so PowerShell comes first: pwsh when installed, else the Windows PowerShell that every
+ * machine has. cmd.exe remains the last resort rather than the default.
+ */
+export function resolveDefaultShell(
+ env: NodeJS.ProcessEnv = process.env,
+ platform: NodeJS.Platform = process.platform,
+ opts: ResolveTerminalShellOptions = {},
+): string {
+ const explicit = env.PENGUIN_SHELL?.trim();
+ if (explicit) return explicit;
+ if (platform !== "win32") return env.SHELL || "/bin/sh";
+
+ const onPath = opts.onPath ?? defaultOnPath;
+ if (onPath("pwsh")) return "pwsh.exe";
+ if (onPath("powershell")) return "powershell.exe";
+ return env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe";
+}
+
+/**
+ * Arguments that make the shell interactive *with the user's profile loaded* — the whole
+ * point of a terminal, and the one thing every shell spells differently.
+ *
+ * - POSIX shells: `-l`. A login shell reads the profile chain (`~/.zprofile`,
+ * `~/.bash_profile`/`~/.profile`), and an interactive one reads its rc file on top,
+ * which is what a pty already makes it. It is also what MinGit's bash needs on Windows
+ * to pick up `etc/profile` and its PATH.
+ * - PowerShell: nothing but `-NoLogo`. Profiles load by default; passing `-l` would be an
+ * error on Windows, and `-NoProfile` would defeat the purpose.
+ * - cmd.exe: has neither concept.
+ */
+export function shellArgs(shell: string): string[] {
+ const name = shellName(shell);
+ if (name === "pwsh" || name === "powershell") return ["-NoLogo"];
+ if (name === "cmd") return [];
+ return ["-l"];
+}
+
+let cachedDefault: string | null = null;
+
+/**
+ * The process-wide default shell. Cached because the Windows probe costs a subprocess and
+ * the answer cannot change while the server runs.
+ */
+export function defaultTerminalShell(): string {
+ if (cachedDefault === null) cachedDefault = resolveDefaultShell();
+ return cachedDefault;
+}
diff --git a/packages/server/src/platform/terminal/size-ownership.ts b/packages/server/src/platform/terminal/size-ownership.ts
new file mode 100644
index 00000000..98561aa8
--- /dev/null
+++ b/packages/server/src/platform/terminal/size-ownership.ts
@@ -0,0 +1,55 @@
+/**
+ * Terminal size ownership.
+ *
+ * A pty has exactly one size, but a terminal can be attached from several places at once
+ * (two browser tabs, a phone, a leftover background tab). If every attachment simply
+ * applied its own geometry, the smallest idle viewport would keep squashing the one the
+ * user is actually typing into.
+ *
+ * So size has a single claimant. Focusing or interacting sends `claim`, which transfers
+ * ownership even when the dimensions are identical; subsequent geometry changes from that
+ * same connection send `update`. An `update` from any other connection is ignored.
+ */
+
+export interface TerminalSizeState {
+ ownerId: string | null;
+ cols: number;
+ rows: number;
+}
+
+export interface TerminalSizeRequest {
+ connectionId: string;
+ cols: number;
+ rows: number;
+ intent: "claim" | "update";
+}
+
+export interface TerminalSizeDecision {
+ state: TerminalSizeState;
+ /** Whether the pty should actually be resized. */
+ apply: boolean;
+}
+
+export function applyTerminalSize(
+ state: TerminalSizeState,
+ request: TerminalSizeRequest,
+): TerminalSizeDecision {
+ if (request.intent === "update" && state.ownerId !== request.connectionId) {
+ return { state, apply: false };
+ }
+ const nextState: TerminalSizeState = {
+ ownerId: request.connectionId,
+ cols: request.cols,
+ rows: request.rows,
+ };
+ const unchanged = state.cols === request.cols && state.rows === request.rows;
+ return { state: nextState, apply: !unchanged };
+}
+
+/** Ownership is released when the owning connection goes away, so the next claimant wins. */
+export function releaseTerminalSize(
+ state: TerminalSizeState,
+ connectionId: string,
+): TerminalSizeState {
+ return state.ownerId === connectionId ? { ...state, ownerId: null } : state;
+}
diff --git a/packages/server/src/platform/terminal/snapshot.ts b/packages/server/src/platform/terminal/snapshot.ts
new file mode 100644
index 00000000..49f49849
--- /dev/null
+++ b/packages/server/src/platform/terminal/snapshot.ts
@@ -0,0 +1,189 @@
+/**
+ * Screen snapshot -> ANSI restore stream, plus plain-text capture.
+ *
+ * This is what makes a browser refresh (or a reconnect from a second device) show the
+ * terminal exactly as it was: the daemon keeps an authoritative headless xterm per pty, and
+ * on attach it *re-renders* that grid as an escape-sequence stream the client's real xterm
+ * replays into an identical screen. That beats the two obvious alternatives:
+ *
+ * - Replaying the raw pty byte log: unbounded, and full-screen programs (vim, top) replay
+ * as a flicker of stale frames.
+ * - Sending a JSON cell grid: a 200k-object payload per attach, parsed on the UI thread.
+ *
+ * Cursor alignment is the subtle part. The restore writes `scrollback + rows` lines, so the
+ * client's viewport ends up holding exactly the server's viewport, and only then is the
+ * cursor placed with a viewport-relative CUP. Trailing blank rows are therefore written on
+ * purpose — dropping them would shift every subsequent row and land the cursor in the wrong
+ * place.
+ */
+import type { IBufferCell, IBufferLine, Terminal } from "@xterm/headless";
+
+/** How much scrollback a restore carries by default. Enough to scroll back through, small enough to stay instant. */
+export const DEFAULT_RESTORE_SCROLLBACK_LINES = 400;
+export const MAX_RESTORE_SCROLLBACK_LINES = 2000;
+
+export interface RenderRestoreOptions {
+ scrollbackLines?: number;
+ /** Appended after the cursor is positioned; see TerminalInputModeTracker.preamble(). */
+ inputModePreamble?: string;
+}
+
+/** SGR parameters describing a cell's style, or "" for the default style. */
+function styleOf(cell: IBufferCell): string {
+ const params: string[] = [];
+ if (cell.isBold()) params.push("1");
+ if (cell.isDim()) params.push("2");
+ if (cell.isItalic()) params.push("3");
+ if (cell.isUnderline()) params.push("4");
+ if (cell.isBlink()) params.push("5");
+ if (cell.isInverse()) params.push("7");
+ if (cell.isInvisible()) params.push("8");
+ if (cell.isStrikethrough()) params.push("9");
+ if (cell.isOverline()) params.push("53");
+
+ if (cell.isFgRGB()) {
+ const rgb = cell.getFgColor();
+ params.push(`38;2;${(rgb >> 16) & 0xff};${(rgb >> 8) & 0xff};${rgb & 0xff}`);
+ } else if (cell.isFgPalette()) {
+ params.push(`38;5;${cell.getFgColor()}`);
+ }
+
+ if (cell.isBgRGB()) {
+ const rgb = cell.getBgColor();
+ params.push(`48;2;${(rgb >> 16) & 0xff};${(rgb >> 8) & 0xff};${rgb & 0xff}`);
+ } else if (cell.isBgPalette()) {
+ params.push(`48;5;${cell.getBgColor()}`);
+ }
+
+ return params.join(";");
+}
+
+/**
+ * An untouched cell: never written and carrying no styling.
+ *
+ * A written space is deliberately NOT blank here — `echo "a "` and a line that merely ends
+ * early are different buffers, and copying a restored screen should give back what was
+ * actually printed. Only the never-written tail is dropped.
+ */
+function isUntouched(cell: IBufferCell): boolean {
+ return cell.getChars() === "" && cell.isAttributeDefault();
+}
+
+function renderLine(line: IBufferLine, cols: number, scratch: IBufferCell): string {
+ // The never-written tail carries no information; dropping it keeps a restore of a
+ // mostly-empty screen small (and avoids painting a background colour the user never set).
+ let lastMeaningful = -1;
+ for (let x = 0; x < cols; x += 1) {
+ const cell = line.getCell(x, scratch);
+ if (cell && !isUntouched(cell)) lastMeaningful = x;
+ }
+ if (lastMeaningful === -1) return "";
+
+ let out = "";
+ let currentStyle = "";
+ for (let x = 0; x <= lastMeaningful; x += 1) {
+ const cell = line.getCell(x, scratch);
+ if (!cell) continue;
+ const width = cell.getWidth();
+ if (width === 0) continue; // right half of a wide character: already emitted
+
+ const style = styleOf(cell);
+ if (style !== currentStyle) {
+ // Always reset first: an SGR run is absolute, so a style that only *removes* an
+ // attribute (bold -> plain) still has to be expressed.
+ out += style === "" ? "\x1b[0m" : `\x1b[0;${style}m`;
+ currentStyle = style;
+ }
+ const chars = cell.getChars();
+ out += chars === "" ? " " : chars;
+ }
+ if (currentStyle !== "") out += "\x1b[0m";
+ return out;
+}
+
+/**
+ * Renders the terminal's current screen as a self-contained ANSI stream: reset + clear,
+ * scrollback, viewport, cursor placement, input-mode preamble.
+ *
+ * The client must already be at the terminal's cols/rows — the caller resizes the pty from
+ * the attaching client's geometry before calling this, so both sides agree on the width the
+ * lines were laid out at.
+ */
+export function renderRestoreAnsi(terminal: Terminal, options: RenderRestoreOptions = {}): string {
+ const buffer = terminal.buffer.active;
+ const scratch = buffer.getNullCell();
+ const rows = terminal.rows;
+ const cols = terminal.cols;
+ const isAlternate = buffer.type === "alternate";
+
+ const requested = Math.min(
+ Math.max(options.scrollbackLines ?? DEFAULT_RESTORE_SCROLLBACK_LINES, 0),
+ MAX_RESTORE_SCROLLBACK_LINES,
+ );
+ // The alternate buffer (vim, less, top) has no scrollback by definition, and a full-screen
+ // program repaints on its own terms — restore only its viewport.
+ const scrollbackLines = isAlternate ? 0 : Math.min(requested, buffer.baseY);
+ const firstLine = buffer.baseY - scrollbackLines;
+ const lastLine = buffer.baseY + rows - 1;
+
+ const parts: string[] = [];
+ // Reset attributes, leave the alternate buffer if we are in it, then clear screen +
+ // scrollback so a reattach can never stack two copies of the screen.
+ parts.push("\x1b[0m\x1b[?1049l\x1b[H\x1b[2J\x1b[3J");
+ if (isAlternate) parts.push("\x1b[?1049h\x1b[H");
+
+ for (let y = firstLine; y <= lastLine; y += 1) {
+ if (y > firstLine) parts.push("\r\n");
+ const line = buffer.getLine(y);
+ if (line) parts.push(renderLine(line, cols, scratch));
+ }
+
+ // Viewport-relative: after writing exactly `rows` viewport lines, the client's viewport is
+ // the server's viewport, so cursorY/cursorX map straight onto it.
+ parts.push(`\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}H`);
+ if (options.inputModePreamble) parts.push(options.inputModePreamble);
+ return parts.join("");
+}
+
+export interface CaptureLinesOptions {
+ /** Line index into scrollback+viewport; negative counts from the end (-1 = last line). */
+ start?: number;
+ end?: number;
+}
+
+export interface CaptureLinesResult {
+ lines: string[];
+ totalLines: number;
+}
+
+function resolveIndex(value: number | undefined, total: number, fallback: "start" | "end"): number {
+ if (total === 0) return fallback === "start" ? 0 : -1;
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ return fallback === "start" ? 0 : total - 1;
+ }
+ const resolved = value < 0 ? total + value : value;
+ if (resolved < 0) return 0;
+ if (resolved >= total) return total - 1;
+ return resolved;
+}
+
+/**
+ * Plain-text view of the screen. This is the read path for
+ * anything that is not a rendering client — tests, and later agents that need to see what a
+ * command printed without parsing escape sequences.
+ */
+export function captureLines(
+ terminal: Terminal,
+ options: CaptureLinesOptions = {},
+): CaptureLinesResult {
+ const buffer = terminal.buffer.active;
+ const totalLines = buffer.baseY + terminal.rows;
+ const all: string[] = [];
+ for (let y = 0; y < totalLines; y += 1) {
+ all.push(buffer.getLine(y)?.translateToString(true) ?? "");
+ }
+ const startIndex = resolveIndex(options.start, totalLines, "start");
+ const endIndex = resolveIndex(options.end, totalLines, "end");
+ if (totalLines === 0 || startIndex > endIndex) return { lines: [], totalLines };
+ return { lines: all.slice(startIndex, endIndex + 1), totalLines };
+}
diff --git a/packages/server/src/platform/terminal/stream.ts b/packages/server/src/platform/terminal/stream.ts
new file mode 100644
index 00000000..39d99fc7
--- /dev/null
+++ b/packages/server/src/platform/terminal/stream.ts
@@ -0,0 +1,167 @@
+/**
+ * The terminal stream's PROTOCOL: frames, coalescing, the restore-first attach sequence,
+ * size ownership and the lagging-viewer resync.
+ *
+ * This is platform code even though the socket is the runtime's. The seam cannot carry a
+ * stream — a handler returns one whole Response — so the runtime keeps the upgrade
+ * handshake and its authentication (terminal/ws.ts) and hands the live socket here. What
+ * flows over it afterwards is behaviour, and behaviour a push must be able to change:
+ * every byte of the wire format, the ~5ms coalescing window and both backpressure
+ * watermarks are decided in this file.
+ *
+ * Attach sequence — the part that makes a browser reload look seamless:
+ * 1. the client's geometry (?cols=&rows=) resizes the pty FIRST, so the snapshot is
+ * rendered at the width the client is about to display it at;
+ * 2. one Restore frame replays the whole screen;
+ * 3. live output follows, coalesced.
+ * Any output produced between 2 and 3 would be a lost line, so the output subscription is
+ * opened before the snapshot is rendered and buffered until the Restore frame is out.
+ */
+import { randomUUID } from "node:crypto";
+import type { WebSocket } from "ws";
+import {
+ TerminalStreamOpcode,
+ decodeTerminalFrame,
+ encodeTerminalFrame,
+ framePayloadText,
+ parseResizePayload,
+} from "./frames.js";
+import { TerminalOutputCoalescer } from "./output-coalescer.js";
+import type { TerminalSession } from "./session.js";
+
+const BACKPRESSURE_HIGH_WATER = 1024 * 1024;
+const BACKPRESSURE_LOW_WATER = 64 * 1024;
+const BACKPRESSURE_POLL_MS = 250;
+
+export function bindTerminalStream(
+ ws: WebSocket,
+ session: TerminalSession,
+ url: URL,
+ log: (line: string) => void,
+): void {
+ const connectionId = randomUUID();
+ ws.binaryType = "nodebuffer";
+
+ const send = (bytes: Uint8Array): void => {
+ if (ws.readyState === ws.OPEN) ws.send(bytes);
+ };
+
+ // Lagging-viewer state (see the watermark comment above): while desynced, this viewer's
+ // live output is dropped and a slow poll waits for its socket to drain for the resync.
+ let desynced = false;
+ let resyncTimer: ReturnType<typeof setInterval> | null = null;
+ const stopResyncPoll = (): void => {
+ if (resyncTimer) clearInterval(resyncTimer);
+ resyncTimer = null;
+ };
+
+ const sendOutput = (data: string): void => {
+ if (desynced) return; // dropped: the emulator keeps every byte; the resync repaints
+ send(encodeTerminalFrame({ opcode: TerminalStreamOpcode.Output, payload: data }));
+ if (ws.bufferedAmount <= BACKPRESSURE_HIGH_WATER) return;
+ desynced = true;
+ log(`[terminal] stream ${session.id}: viewer ${ws.bufferedAmount}B behind, pausing for resync`);
+ resyncTimer = setInterval(() => {
+ if (ws.readyState !== ws.OPEN) return stopResyncPoll();
+ if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) return;
+ stopResyncPoll();
+ desynced = false; // flip first: output parsed after this snapshot flows live again
+ try {
+ send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Restore,
+ payload: session.restoreStream(),
+ }),
+ );
+ } catch {
+ // The session was reaped while this viewer lagged; the Exit frame (sent directly,
+ // never dropped) already told it the story.
+ }
+ }, BACKPRESSURE_POLL_MS);
+ };
+
+ // Buffers output until the Restore frame has been sent (see the attach sequence above).
+ let restored = false;
+ let preRestore = "";
+ const coalescer = new TerminalOutputCoalescer(sendOutput);
+
+ const unsubscribeOutput = session.onOutput((data) => {
+ if (!restored) {
+ preRestore += data;
+ return;
+ }
+ coalescer.push(data);
+ });
+
+ const unsubscribeExit = session.onExit((info) => {
+ coalescer.flush();
+ send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Exit,
+ payload: JSON.stringify({ exitCode: info.exitCode, signal: info.signal }),
+ }),
+ );
+ });
+
+ // The attaching client's geometry wins: it is the viewport the user is looking at, and the
+ // snapshot below is laid out for it.
+ const cols = Number.parseInt(url.searchParams.get("cols") ?? "", 10);
+ const rows = Number.parseInt(url.searchParams.get("rows") ?? "", 10);
+ if (Number.isInteger(cols) && Number.isInteger(rows)) {
+ session.resize({ connectionId, cols, rows, intent: "claim" });
+ }
+
+ send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Restore,
+ payload: session.restoreStream(),
+ }),
+ );
+ restored = true;
+ if (preRestore) {
+ coalescer.push(preRestore);
+ preRestore = "";
+ }
+ if (!session.alive && session.exit) {
+ send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Exit,
+ payload: JSON.stringify({ exitCode: session.exit.exitCode, signal: session.exit.signal }),
+ }),
+ );
+ }
+
+ ws.on("message", (raw: Buffer, isBinary: boolean) => {
+ if (!isBinary) return; // the data plane is binary-only
+ const frame = decodeTerminalFrame(new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength));
+ if (!frame) return;
+ switch (frame.opcode) {
+ case TerminalStreamOpcode.Input:
+ session.write(framePayloadText(frame));
+ break;
+ case TerminalStreamOpcode.Resize: {
+ const size = parseResizePayload(frame);
+ if (size) session.resize({ connectionId, ...size });
+ break;
+ }
+ default:
+ break; // server-only opcodes echoed back by a confused client
+ }
+ });
+
+ const teardown = (): void => {
+ unsubscribeOutput();
+ unsubscribeExit();
+ stopResyncPoll();
+ coalescer.dispose();
+ // Closing a view must not resize or kill the shell — only give up size ownership so the
+ // next client to attach can claim it.
+ session.releaseSize(connectionId);
+ };
+
+ ws.on("close", teardown);
+ ws.on("error", (err: Error) => {
+ log(`[terminal] stream ${session.id} socket error: ${err.message}`);
+ teardown();
+ });
+}
diff --git a/packages/server/src/terminal/spawn-helper.ts b/packages/server/src/terminal/spawn-helper.ts
new file mode 100644
index 00000000..bb6cd6bf
--- /dev/null
+++ b/packages/server/src/terminal/spawn-helper.ts
@@ -0,0 +1,101 @@
+/**
+ * macOS only: repair node-pty's `spawn-helper` file mode.
+ *
+ * On darwin node-pty does not exec the shell directly — it spawns a small `spawn-helper`
+ * binary that hands the child its controlling terminal. node-pty's npm tarball ships the
+ * prebuilt helper with mode 0644 (no exec bit), and its install script skips the source
+ * build whenever a `prebuilds/<platform>-<arch>` directory exists. The addon itself still
+ * loads (a dylib needs no exec bit), so everything looks healthy right up to the point
+ * where `posix_spawnp` refuses the helper and every terminal fails to start with a bare
+ * "posix_spawnp failed." — which is how the terminal panel came to open blank on macOS
+ * with nothing in any log.
+ *
+ * The repair is a chmod, done once per process before the first pty is created. Where it
+ * cannot be done (a signed .app under /Applications is not writable by the running user),
+ * `spawnHelperHint()` turns the residual spawn failure into a message that names the file
+ * and what is wrong with it — and the desktop packaging step fixes the mode in the staged
+ * tree so a shipped app never gets there.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { createRequire } from "node:module";
+
+/** Exec bits for user/group/other. */
+const EXEC_BITS = 0o111;
+
+/**
+ * Adds the exec bit to every `spawn-helper` under `pkgDir` that lacks it, following
+ * node-pty's own native-module search order (build/Release, build/Debug, then the
+ * platform prebuild). Returns the paths it changed. Exported for tests: the logic is
+ * plain filesystem work, so it is verifiable on any platform.
+ */
+export function repairSpawnHelpers(pkgDir: string, arch: string = process.arch): string[] {
+ const candidates = [
+ path.join(pkgDir, "build", "Release", "spawn-helper"),
+ path.join(pkgDir, "build", "Debug", "spawn-helper"),
+ path.join(pkgDir, "prebuilds", `darwin-${arch}`, "spawn-helper"),
+ ];
+ const repaired: string[] = [];
+ for (const helper of candidates) {
+ let mode: number;
+ try {
+ mode = fs.statSync(helper).mode;
+ } catch {
+ continue; // node-pty did not ship/build this variant
+ }
+ if ((mode & EXEC_BITS) !== 0) continue;
+ try {
+ fs.chmodSync(helper, mode | EXEC_BITS);
+ repaired.push(helper);
+ } catch {
+ // Read-only install: spawnHelperHint() reports it when the spawn then fails.
+ }
+ }
+ return repaired;
+}
+
+/** node-pty's package directory, or null when it cannot be resolved from here. */
+function nodePtyDir(): string | null {
+ try {
+ return path.dirname(createRequire(import.meta.url).resolve("node-pty/package.json"));
+ } catch {
+ return null;
+ }
+}
+
+let repairAttempted = false;
+
+/** Idempotent, darwin-only: run the repair once, before the first pty spawn. */
+export function ensureSpawnHelperExecutable(): void {
+ if (process.platform !== "darwin" || repairAttempted) return;
+ repairAttempted = true;
+ const pkgDir = nodePtyDir();
+ if (pkgDir === null) return;
+ for (const fixed of repairSpawnHelpers(pkgDir)) {
+ console.log(`[terminal] restored the exec bit on ${fixed} (node-pty ships it as 0644)`);
+ }
+}
+
+/**
+ * A one-line explanation to append to a spawn failure, when a helper is present but still
+ * not executable — the case the repair could not fix. Null when that is not the problem,
+ * so an unrelated failure is never mislabelled.
+ */
+export function spawnHelperHint(): string | null {
+ if (process.platform !== "darwin") return null;
+ const pkgDir = nodePtyDir();
+ if (pkgDir === null) return null;
+ for (const helper of [
+ path.join(pkgDir, "build", "Release", "spawn-helper"),
+ path.join(pkgDir, "prebuilds", `darwin-${process.arch}`, "spawn-helper"),
+ ]) {
+ try {
+ if ((fs.statSync(helper).mode & EXEC_BITS) === 0) {
+ return `${helper} is not executable — run: chmod +x "${helper}"`;
+ }
+ } catch {
+ continue;
+ }
+ }
+ return null;
+}
diff --git a/packages/server/src/terminal/ws.ts b/packages/server/src/terminal/ws.ts
new file mode 100644
index 00000000..2537a482
--- /dev/null
+++ b/packages/server/src/terminal/ws.ts
@@ -0,0 +1,124 @@
+/**
+ * Terminal stream transport: `GET /api/terminals/:id/stream` (Upgrade).
+ *
+ * Runtime, and only the transport. A WebSocket cannot cross the platform seam — a seam
+ * handler returns one whole Response — so the runtime keeps what an upgrade needs: the
+ * handshake itself, the Origin check, and the session-cookie authentication it already
+ * owns. The moment the socket is live it is handed to the platform, which owns the
+ * protocol that flows over it (platform/terminal/stream.ts): frames, coalescing, restore
+ * and backpressure are all pushable, the socket plumbing is not.
+ *
+ * Auth: the session cookie rides along on the upgrade request, so the same credential as
+ * the REST API is used, plus an Origin check — a WebSocket handshake is not subject to
+ * CORS, so without it any page the user visits could open a shell on this machine.
+ */
+import type { IncomingMessage, Server as HttpServer } from "node:http";
+import type { Duplex } from "node:stream";
+import { WebSocketServer } from "ws";
+import type { AuthService } from "../auth/service.js";
+import { SESSION_COOKIE } from "../auth/middleware.js";
+import type { HmrHost } from "../hmr/host.js";
+
+const STREAM_PATH = /^\/api\/terminals\/([^/]+)\/stream$/;
+
+/**
+ * Per-viewer backpressure watermarks. `ws.send` queues without limit when the peer cannot
+ * drain, so a viewer more than HIGH_WATER behind stops receiving live output — the bytes
+ * keep feeding the server emulator, nothing of the session is lost — and once its socket
+ * drains below LOW_WATER it is repainted with one fresh Restore frame (the same
+ * self-contained repaint an attach uses) and live output resumes. Skipping ahead beats
+ * both alternatives: replaying megabytes the viewer could only fast-forward through, or
+ * disconnecting it (the client treats a closed stream as a dead pane, not a retry). The
+ * high watermark is therefore a LAG bound — how far behind a viewer may fall before it is
+ * fast-forwarded — and doubles as the per-viewer memory bound.
+ */
+const BACKPRESSURE_HIGH_WATER = 1024 * 1024;
+const BACKPRESSURE_LOW_WATER = 64 * 1024;
+const BACKPRESSURE_POLL_MS = 250;
+
+export interface TerminalWebSocketDeps {
+ /** The booted platform owns the terminals; the runtime asks it per upgrade. */
+ hmr: HmrHost;
+ authService: AuthService;
+ log: (line: string) => void;
+}
+
+export function attachTerminalWebSocket(server: HttpServer, deps: TerminalWebSocketDeps): void {
+ const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false });
+
+ server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const match = STREAM_PATH.exec(url.pathname);
+ // Not ours: leave the socket alone so another upgrade handler (or the default
+ // "no handler -> destroy" behaviour) can deal with it.
+ if (!match) return;
+
+ if (!isAllowedOrigin(req)) return refuse(socket, 403, "Forbidden");
+
+ const token = readCookie(req.headers.cookie, SESSION_COOKIE);
+ const authed = token ? deps.authService.authenticateWithMeta(token) : null;
+ if (!authed) return refuse(socket, 401, "Unauthorized");
+
+ // The platform may be mid-swap; ensure() resolves the instance that owns the
+ // terminals right now, which is also the one whose protocol should serve this socket.
+ void deps.hmr
+ .ensure()
+ .then((platform) => {
+ const manager = platform.api.terminals?.();
+ const session = manager?.get(match[1] as string);
+ if (!session || session.ownerUserId !== authed.user.userId) {
+ return refuse(socket, 404, "Not Found");
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ platform.api.attachStream?.(ws, session, url, deps.log);
+ });
+ })
+ .catch((err: unknown) => {
+ deps.log(`[terminal] stream upgrade failed: ${err instanceof Error ? err.message : err}`);
+ refuse(socket, 500, "Internal Server Error");
+ });
+ });
+}
+
+/**
+ * A WebSocket handshake bypasses CORS entirely, so any origin may attempt one and the cookie
+ * still rides along. Only a genuinely same-origin page may connect: host AND port must match
+ * the Host the browser targeted. Cookies are port-agnostic, so anything looser (hostname-only,
+ * or a blanket loopback allowance) would let a page served by any other local server ride the
+ * session cookie into a shell. The Vite dev server proxies with `changeOrigin: false`, so the
+ * browser's own Host survives the proxy and this comparison holds in development too.
+ */
+function isAllowedOrigin(req: IncomingMessage): boolean {
+ const origin = req.headers.origin;
+ if (!origin) return true; // non-browser client (CLI, tests): no ambient cookie to abuse
+ let parsed: URL;
+ try {
+ parsed = new URL(origin);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
+ return parsed.host === (req.headers.host ?? "");
+}
+
+function readCookie(header: string | undefined, name: string): string | null {
+ if (!header) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() !== name) continue;
+ try {
+ return decodeURIComponent(part.slice(eq + 1).trim());
+ } catch {
+ // A malformed percent escape is an invalid credential, not a server error — this
+ // runs in the `upgrade` handler, where a throw would take the whole process down.
+ return null;
+ }
+ }
+ return null;
+}
+
+function refuse(socket: Duplex, status: number, text: string): void {
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\n\r\n`);
+ socket.destroy();
+}
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 112b8949..f00c1ac2 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -82,6 +82,8 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
root,
adminPassword,
cleanup: async () => {
+ // Terminals are real child processes owned by the platform: disposing the hot host
+ // sweeps its resource registry, which is where every live pty is registered.
deps.hmr.dispose();
deps.channels.dispose();
deps.db.close();
diff --git a/packages/server/test/hmr-host.test.ts b/packages/server/test/hmr-host.test.ts
index 2e6eadba..3d1ec6e4 100644
--- a/packages/server/test/hmr-host.test.ts
+++ b/packages/server/test/hmr-host.test.ts
@@ -5,6 +5,7 @@
* and the durability flag an upgrade's HTTP response carries.
*/
import fs from "node:fs/promises";
+import fsSync from "node:fs";
import path from "node:path";
import zlib from "node:zlib";
import { afterEach, describe, expect, it } from "vitest";
@@ -299,3 +300,93 @@ describe("upgrade outcome: persisted flag", () => {
expect(await ping.json()).toEqual({ servedBy: "unpersisted", pathname: "/api/demo/ping" });
});
});
+
+describe("upgrade assets: an unchanged set is not copied again", () => {
+ let t: TestApp | undefined;
+
+ afterEach(async () => {
+ if (t) await t.cleanup();
+ t = undefined;
+ });
+
+ /** One push carrying a native-module-shaped asset tree. */
+ async function pushWithAssets(app: Hono<AppEnv>, cookie: string, id: string) {
+ const gz = zlib.gzipSync(
+ Buffer.from(
+ JSON.stringify({
+ platform: platformServing([`/api/demo/${id}`], id),
+ cli: MINIMAL_CLI,
+ web: { files: MINIMAL_WEB },
+ assets: {
+ files: {
+ "node_modules/demo-native/package.json":
+ Buffer.from('{"name":"demo-native"}').toString("base64"),
+ "node_modules/demo-native/build/Release/demo.node":
+ Buffer.from("\0binary").toString("base64"),
+ },
+ exec: ["node_modules/demo-native/build/Release/demo.node"],
+ },
+ }),
+ ),
+ );
+ return app.request("/api/hmr/upgrade", {
+ method: "POST",
+ headers: { cookie, "content-type": "application/gzip" },
+ body: gz,
+ });
+ }
+
+ /** The single assets directory the pushes above content-address to. */
+ async function assetsDirOf(root: string): Promise<string> {
+ const base = path.join(root, "hmr", "store", "assets");
+ const entries = await fs.readdir(base);
+ expect(entries).toHaveLength(1); // identical content, so one directory serves both pushes
+ return path.join(base, entries[0]!);
+ }
+
+ it("leaves the files untouched on a re-push, so a mapped native module cannot EBUSY", async () => {
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ expect((await pushWithAssets(t.app, cookie, "first")).status).toBe(200);
+
+ const binary = path.join(
+ await assetsDirOf(t.root),
+ "node_modules/demo-native/build/Release/demo.node",
+ );
+ const before = await fs.stat(binary);
+ // Windows has no POSIX permission bits at all — stat() reports none and chmod() only
+ // toggles the read-only attribute — so the exec list is a POSIX-only claim.
+ if (process.platform !== "win32") expect(before.mode & 0o111).not.toBe(0);
+
+ // Windows keeps an open handle on a loaded .node, so a second write to it fails with
+ // EBUSY and takes the whole upgrade down. Read-only stands in for that lock here (on
+ // Windows that IS the read-only attribute, and it refuses writes just the same).
+ await fs.chmod(binary, 0o444);
+ try {
+ expect((await pushWithAssets(t.app, cookie, "second")).status).toBe(200);
+
+ const after = await fs.stat(binary);
+ expect(after.mtimeMs).toBe(before.mtimeMs);
+ } finally {
+ // Windows refuses to delete a read-only file, which would fail the temp-root cleanup.
+ await fs.chmod(binary, 0o644);
+ }
+ });
+
+ it("repairs a directory whose materialization was interrupted", async () => {
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ expect((await pushWithAssets(t.app, cookie, "first")).status).toBe(200);
+
+ // A push killed before it finished leaves files but no completion marker — and here,
+ // one truncated file.
+ const dir = await assetsDirOf(t.root);
+ const manifest = path.join(dir, "node_modules/demo-native/package.json");
+ await fs.rm(path.join(dir, ".materialized"));
+ await fs.writeFile(manifest, "trunc");
+
+ expect((await pushWithAssets(t.app, cookie, "second")).status).toBe(200);
+ expect(await fs.readFile(manifest, "utf8")).toBe('{"name":"demo-native"}');
+ expect(fsSync.existsSync(path.join(dir, ".materialized"))).toBe(true);
+ });
+});
diff --git a/packages/server/test/terminal-shell.test.ts b/packages/server/test/terminal-shell.test.ts
new file mode 100644
index 00000000..180f50e5
--- /dev/null
+++ b/packages/server/test/terminal-shell.test.ts
@@ -0,0 +1,56 @@
+/**
+ * Shell selection for interactive terminals. The rule under test is the one that broke on
+ * Windows: the shell a terminal opens must run the user's profile, and %ComSpec% (cmd.exe)
+ * never does.
+ */
+import { describe, expect, it } from "vitest";
+import { resolveDefaultShell, shellArgs } from "../src/platform/terminal/shell.js";
+
+const NO_PATH = { onPath: () => false };
+const HAS = (...names: string[]) => ({ onPath: (cmd: string) => names.includes(cmd) });
+
+describe("resolveDefaultShell", () => {
+ it("takes the user's login shell on POSIX", () => {
+ expect(resolveDefaultShell({ SHELL: "/bin/zsh" }, "linux")).toBe("/bin/zsh");
+ expect(resolveDefaultShell({}, "darwin")).toBe("/bin/sh");
+ });
+
+ it("prefers PowerShell over cmd.exe on Windows, since cmd reads no profile", () => {
+ const env = { ComSpec: "C:\\Windows\\System32\\cmd.exe" };
+ expect(resolveDefaultShell(env, "win32", HAS("pwsh", "powershell"))).toBe("pwsh.exe");
+ expect(resolveDefaultShell(env, "win32", HAS("powershell"))).toBe("powershell.exe");
+ });
+
+ it("falls back to %ComSpec% only when no PowerShell is installed", () => {
+ expect(resolveDefaultShell({ ComSpec: "C:\\cmd.exe" }, "win32", NO_PATH)).toBe("C:\\cmd.exe");
+ expect(resolveDefaultShell({}, "win32", NO_PATH)).toBe("C:\\Windows\\System32\\cmd.exe");
+ });
+
+ it("honours PENGUIN_SHELL on every platform, without probing", () => {
+ const env = { PENGUIN_SHELL: "C:\\Program Files\\Git\\bin\\bash.exe", SHELL: "/bin/zsh" };
+ const explode = {
+ onPath: (): boolean => {
+ throw new Error("must not probe");
+ },
+ };
+ expect(resolveDefaultShell(env, "win32", explode)).toBe(env.PENGUIN_SHELL);
+ expect(resolveDefaultShell(env, "linux", explode)).toBe(env.PENGUIN_SHELL);
+ });
+});
+
+describe("shellArgs", () => {
+ it("makes POSIX shells login shells, so the profile chain runs", () => {
+ expect(shellArgs("/bin/zsh")).toEqual(["-l"]);
+ expect(shellArgs("C:\\Program Files\\Git\\bin\\bash.exe")).toEqual(["-l"]);
+ });
+
+ it("passes PowerShell no -l (an error there) and no -NoProfile", () => {
+ for (const shell of ["pwsh.exe", "powershell.EXE", "C:\\pwsh\\pwsh.exe"]) {
+ expect(shellArgs(shell)).toEqual(["-NoLogo"]);
+ }
+ });
+
+ it("passes cmd.exe nothing, having neither concept", () => {
+ expect(shellArgs("C:\\Windows\\System32\\cmd.exe")).toEqual([]);
+ });
+});
diff --git a/packages/server/test/terminal-stream.test.ts b/packages/server/test/terminal-stream.test.ts
new file mode 100644
index 00000000..386777fc
--- /dev/null
+++ b/packages/server/test/terminal-stream.test.ts
@@ -0,0 +1,571 @@
+/**
+ * Terminal WebSocket data-plane tests, over a real listening server (the stream is an HTTP
+ * Upgrade, which app.request() can never exercise).
+ *
+ * Scenarios: handshake auth (cookie, origin, ownership), the Restore-first attach
+ * contract, reattach fidelity, multi-client behaviour, size ownership, exit notification,
+ * and hostile-input tolerance. These are the promises the web dock and /terminal page are
+ * built on.
+ */
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { serve } from "@hono/node-server";
+import type { Server as HttpServer } from "node:http";
+import { WebSocket } from "ws";
+import { createTestApp, loginAdmin, provisionUser, apiClient } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+import { attachTerminalWebSocket } from "../src/terminal/ws.js";
+import {
+ TerminalStreamOpcode,
+ decodeTerminalFrame,
+ encodeTerminalFrame,
+} from "../src/platform/terminal/frames.js";
+
+const TEST_TIMEOUT = 20_000;
+
+/**
+ * Real ptys only on POSIX: Windows CI runs headless, where ConPTY's console-list agent
+ * dies with "AttachConsole failed" and node-pty leaks unhandled IPC rejections. The pure
+ * suites (frames, restore, ownership, …) in terminal.test.ts still run everywhere.
+ */
+const IS_WINDOWS = process.platform === "win32";
+const describePty = describe.skipIf(IS_WINDOWS);
+
+let t: TestApp;
+let port: number;
+let server: ReturnType<typeof serve>;
+let adminCookie: string;
+let api: ReturnType<typeof apiClient>;
+/** Everything terminal/ws.ts logged for this suite (see the log hook in beforeAll). */
+const serverLogs: string[] = [];
+
+beforeAll(async () => {
+ if (IS_WINDOWS) return;
+ t = await createTestApp();
+ const admin = await loginAdmin(t.app);
+ adminCookie = admin.cookie;
+ api = apiClient(t.app, adminCookie);
+ await new Promise<void>((resolve) => {
+ server = serve({ fetch: t.app.fetch, hostname: "127.0.0.1", port: 0 }, (info) => {
+ port = info.port;
+ resolve();
+ });
+ });
+ attachTerminalWebSocket(server as unknown as HttpServer, {
+ hmr: t.deps.hmr,
+ authService: t.deps.authService,
+ // Kept, not discarded: the backpressure test's precondition (the server deciding a
+ // viewer is too far behind) is only observable through this line.
+ log: (line) => serverLogs.push(line),
+ });
+});
+
+afterAll(async () => {
+ if (IS_WINDOWS) return;
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await t.cleanup();
+});
+
+interface TerminalInfoJson {
+ id: string;
+ cols: number;
+ rows: number;
+ alive: boolean;
+}
+
+async function createTerminal(cols = 80, rows = 24): Promise<TerminalInfoJson> {
+ // Pinned to /bin/sh: the default (the developer's login shell) may repaint prompts or
+ // flip terminal modes on its own, which would make mode/restore assertions racy.
+ const res = await api.post("/api/terminals", { cwd: "~", cols, rows, shell: "/bin/sh" });
+ expect(res.status).toBe(201);
+ return (await res.json()) as TerminalInfoJson;
+}
+
+async function terminalInfo(id: string): Promise<TerminalInfoJson> {
+ const res = await api.get(`/api/terminals/${id}`);
+ expect(res.status).toBe(200);
+ return (await res.json()) as TerminalInfoJson;
+}
+
+interface StreamClient {
+ ws: WebSocket;
+ frames: Array<{ opcode: number; text: string }>;
+ /** Concatenation of every Output payload so far. */
+ outputText(): string;
+ /** Payload of the first Restore frame (the attach snapshot). */
+ restoreText(): string;
+ sendInput(text: string): void;
+ sendResize(cols: number, rows: number, intent: "claim" | "update"): void;
+ waitFor(predicate: () => boolean, what: string, timeoutMs?: number): Promise<void>;
+ close(): Promise<void>;
+}
+
+function streamUrl(id: string, cols?: number, rows?: number): string {
+ const size = cols !== undefined && rows !== undefined ? `?cols=${cols}&rows=${rows}` : "";
+ return `ws://127.0.0.1:${port}/api/terminals/${id}/stream${size}`;
+}
+
+/** Opens a stream and resolves once connected; every received frame must decode. */
+function attach(
+ id: string,
+ options: { cookie?: string; cols?: number; rows?: number; origin?: string } = {},
+): Promise<StreamClient> {
+ const headers: Record<string, string> = { cookie: options.cookie ?? adminCookie };
+ if (options.origin !== undefined) headers.origin = options.origin;
+ const ws = new WebSocket(streamUrl(id, options.cols ?? 80, options.rows ?? 24), { headers });
+ const frames: StreamClient["frames"] = [];
+ // Every server-sent frame must decode; checked from waitFor (throwing inside the ws
+ // 'message' listener would surface as an uncaught exception, not a test failure).
+ let undecodable = 0;
+
+ ws.on("message", (raw: Buffer) => {
+ const frame = decodeTerminalFrame(new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength));
+ if (!frame) {
+ undecodable += 1;
+ return;
+ }
+ frames.push({ opcode: frame.opcode, text: new TextDecoder().decode(frame.payload) });
+ });
+
+ const client: StreamClient = {
+ ws,
+ frames,
+ outputText: () =>
+ frames
+ .filter((f) => f.opcode === TerminalStreamOpcode.Output)
+ .map((f) => f.text)
+ .join(""),
+ restoreText: () => frames.find((f) => f.opcode === TerminalStreamOpcode.Restore)?.text ?? "",
+ sendInput: (text) =>
+ ws.send(encodeTerminalFrame({ opcode: TerminalStreamOpcode.Input, payload: text })),
+ sendResize: (cols, rows, intent) =>
+ ws.send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Resize,
+ payload: JSON.stringify({ cols, rows, intent }),
+ }),
+ ),
+ waitFor: async (predicate, what, timeoutMs = 15_000) => {
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {
+ if (undecodable > 0) throw new Error(`Received ${undecodable} undecodable frame(s).`);
+ if (Date.now() > deadline) {
+ throw new Error(`Timed out waiting for ${what}. Frames: ${JSON.stringify(frames)}`);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ if (undecodable > 0) throw new Error(`Received ${undecodable} undecodable frame(s).`);
+ },
+ close: () =>
+ new Promise((resolve) => {
+ if (ws.readyState === WebSocket.CLOSED) return resolve();
+ ws.once("close", () => resolve());
+ ws.close();
+ }),
+ };
+
+ return new Promise((resolve, reject) => {
+ ws.once("open", () => resolve(client));
+ ws.once("unexpected-response", (_req, res) =>
+ reject(new Error(`handshake rejected: ${res.statusCode}`)),
+ );
+ ws.once("error", (err) => reject(err));
+ });
+}
+
+/** Asserts the handshake is refused with the given HTTP status. */
+function expectRefused(id: string, headers: Record<string, string>, status: number): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const ws = new WebSocket(streamUrl(id, 80, 24), { headers });
+ ws.once("open", () => reject(new Error("handshake unexpectedly accepted")));
+ ws.once("unexpected-response", (_req, res) => {
+ try {
+ expect(res.statusCode).toBe(status);
+ resolve();
+ } catch (err) {
+ reject(err);
+ } finally {
+ ws.terminate();
+ }
+ });
+ ws.once("error", (err) => reject(err));
+ });
+}
+
+/** Runs a command on the stream and waits until its marker shows up in the output. */
+async function runAndWait(client: StreamClient, command: string, marker: string): Promise<void> {
+ client.sendInput(`${command}\r`);
+ await client.waitFor(() => client.outputText().includes(marker), `output marker ${marker}`);
+}
+
+/** Polls the capture API until the given text is on the server-side screen. */
+async function waitForCapture(id: string, marker: string, timeoutMs = 15_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const res = await api.get(`/api/terminals/${id}/capture`);
+ const { lines } = (await res.json()) as { lines: string[] };
+ if (lines.some((line) => line.includes(marker))) return;
+ if (Date.now() > deadline) throw new Error(`capture never showed ${marker}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+
+describePty("terminal stream handshake", () => {
+ it(
+ "refuses the stream without a session cookie",
+ async () => {
+ const terminal = await createTerminal();
+ await expectRefused(terminal.id, {}, 401);
+ await expectRefused(terminal.id, { cookie: "penguin_session=not-a-real-token" }, 401);
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "refuses a cross-origin browser handshake even with a valid cookie",
+ async () => {
+ const terminal = await createTerminal();
+ await expectRefused(
+ terminal.id,
+ { cookie: adminCookie, origin: "http://evil.example.com" },
+ 403,
+ );
+ },
+ TEST_TIMEOUT,
+ );
+
+ // The refusal cases below use a bogus id on purpose: cookie and origin are checked
+ // before the session lookup, and not creating a terminal keeps this suite's total under
+ // the per-user cap the later scenarios rely on.
+ it(
+ "treats a malformed cookie escape as unauthenticated, not as a server error",
+ async () => {
+ // "%" is an invalid percent escape: decodeURIComponent throws, and in the `upgrade`
+ // handler an uncaught throw would take down the whole server (unauthenticated DoS).
+ await expectRefused("irrelevant", { cookie: "penguin_session=%" }, 401);
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "refuses a same-host origin on a different port — cookies are port-agnostic",
+ async () => {
+ await expectRefused(
+ "irrelevant",
+ { cookie: adminCookie, origin: `http://127.0.0.1:${port + 1}` },
+ 403,
+ );
+ // The old check blanket-allowed every loopback origin; any local dev server's page
+ // could ride the session cookie into a shell.
+ await expectRefused(
+ "irrelevant",
+ { cookie: adminCookie, origin: "http://localhost:5173" },
+ 403,
+ );
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "accepts the genuinely same-origin handshake",
+ async () => {
+ const terminal = await createTerminal();
+ try {
+ const client = await attach(terminal.id, { origin: `http://127.0.0.1:${port}` });
+ await client.close();
+ } finally {
+ await api.delete(`/api/terminals/${terminal.id}`);
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "answers 404 for unknown ids and for another user's terminal",
+ async () => {
+ const terminal = await createTerminal();
+ await expectRefused("no-such-terminal", { cookie: adminCookie }, 404);
+ const other = await provisionUser(t.app, "streamintruder");
+ await expectRefused(terminal.id, { cookie: other.cookie }, 404);
+ },
+ TEST_TIMEOUT,
+ );
+});
+
+describePty("terminal stream backpressure", () => {
+ it("resyncs a lagging viewer with a fresh Restore instead of disconnecting it", async () => {
+ const terminal = await createTerminal();
+ try {
+ const client = await attach(terminal.id);
+ await client.waitFor(() => client.restoreText().length > 0, "attach restore");
+
+ // Stop reading: the TCP window and then the server's userland queue fill while
+ // the shell floods ~7 MB — far past the high watermark.
+ const socket = (client.ws as unknown as { _socket: { pause(): void; resume(): void } })
+ ._socket;
+ socket.pause();
+ // Flood until the server itself reports this viewer as lagging. A fixed burst is a
+ // coin flip: a paused reader still lets the kernel absorb megabytes into its socket
+ // buffers (autotuned), so the server's own send queue — the thing the watermark
+ // measures — may never cross 1 MiB however much the shell wrote. This suite failed
+ // that way roughly one run in three, locally and on CI.
+ const isLagging = (): boolean => serverLogs.some((l) => l.includes("pausing for resync"));
+ for (let round = 1; round <= 8 && !isLagging(); round += 1) {
+ client.sendInput(`yes 0123456789abcdef | head -n 400000; echo BURST-DONE-${round}\r`);
+ await waitForCapture(terminal.id, `BURST-DONE-${round}`, 60_000);
+ }
+ expect(isLagging(), "server never marked the paused viewer as lagging").toBe(true);
+
+ // The burst has fully landed server-side, and the lagging viewer is still attached.
+ expect(client.ws.readyState).toBe(WebSocket.OPEN);
+
+ // Catching up delivers one resync Restore carrying the final screen, and the
+ // stream is live again afterwards.
+ socket.resume();
+ const restores = (): number =>
+ client.frames.filter((f) => f.opcode === TerminalStreamOpcode.Restore).length;
+ await client.waitFor(() => restores() >= 2, "resync Restore frame", 60_000);
+ const resync = client.frames.filter((f) => f.opcode === TerminalStreamOpcode.Restore)[1]!;
+ expect(resync.text).toContain("BURST-DONE-");
+ await runAndWait(client, "echo LIVE-$((40+2))", "LIVE-42");
+ await client.close();
+ } finally {
+ await api.delete(`/api/terminals/${terminal.id}`);
+ }
+ // Megabytes through a pty, a paused socket and a drain: minutes of budget on a loaded
+ // runner, where the default would report a timeout rather than a real defect.
+ }, 120_000);
+});
+
+describePty("terminal stream attach", () => {
+ it(
+ "sends Restore first, then round-trips input to live output",
+ async () => {
+ const terminal = await createTerminal();
+ const client = await attach(terminal.id);
+ try {
+ await client.waitFor(() => client.frames.length > 0, "first frame");
+ expect(client.frames[0]?.opcode).toBe(TerminalStreamOpcode.Restore);
+ await runAndWait(client, "echo stream-attach-ok", "stream-attach-ok");
+ } finally {
+ await client.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "a reattaching client's Restore carries the previous output",
+ async () => {
+ const terminal = await createTerminal();
+ const first = await attach(terminal.id);
+ try {
+ await runAndWait(first, "echo restore-me-marker", "restore-me-marker");
+ } finally {
+ await first.close();
+ }
+
+ const second = await attach(terminal.id);
+ try {
+ await second.waitFor(() => second.restoreText() !== "", "restore frame");
+ expect(second.restoreText()).toContain("restore-me-marker");
+ // ...and the reattached stream is live, not a screenshot.
+ await runAndWait(second, "echo still-live-marker", "still-live-marker");
+ } finally {
+ await second.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "replays input modes a program enabled to a reattaching client",
+ async () => {
+ const terminal = await createTerminal();
+ const first = await attach(terminal.id);
+ try {
+ // Wait for the shell to reach a prompt first: `sh -l` sources a profile, and under
+ // load that output can land AFTER our command — resetting the very mode this test
+ // then expects to survive.
+ await runAndWait(first, "echo shell-ready-marker", "shell-ready-marker");
+ // Hide the cursor (DECTCSM reset) — a mode a reattached view must reproduce.
+ await runAndWait(first, "printf '\\033[?25l'; echo mode-set-marker", "mode-set-marker");
+ } finally {
+ await first.close();
+ }
+
+ const second = await attach(terminal.id);
+ try {
+ await second.waitFor(() => second.restoreText() !== "", "restore frame");
+ expect(second.restoreText()).toContain("\x1b[?25l");
+ } finally {
+ await second.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "delivers output to every attached client, and either client can type",
+ async () => {
+ const terminal = await createTerminal();
+ const a = await attach(terminal.id);
+ const b = await attach(terminal.id);
+ try {
+ a.sendInput("echo from-client-a\r");
+ await a.waitFor(() => a.outputText().includes("from-client-a"), "a sees a's output");
+ await b.waitFor(() => b.outputText().includes("from-client-a"), "b sees a's output");
+
+ b.sendInput("echo from-client-b\r");
+ await a.waitFor(() => a.outputText().includes("from-client-b"), "a sees b's output");
+ await b.waitFor(() => b.outputText().includes("from-client-b"), "b sees b's output");
+ } finally {
+ await a.close();
+ await b.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+});
+
+describePty("terminal stream size ownership", () => {
+ it(
+ "the latest claim owns the pty size; updates from non-owners are ignored",
+ async () => {
+ const terminal = await createTerminal(80, 24);
+ const a = await attach(terminal.id, { cols: 80, rows: 24 });
+ const b = await attach(terminal.id, { cols: 100, rows: 30 });
+ try {
+ // B attached last: its claim owns the geometry.
+ expect(await terminalInfo(terminal.id)).toMatchObject({ cols: 100, rows: 30 });
+
+ // A's passive update must not squash the owner's viewport…
+ a.sendResize(60, 20, "update");
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(await terminalInfo(terminal.id)).toMatchObject({ cols: 100, rows: 30 });
+
+ // …but an explicit claim (the user went back to that view) takes over.
+ a.sendResize(60, 20, "claim");
+ const deadline = Date.now() + 5000;
+ for (;;) {
+ const info = await terminalInfo(terminal.id);
+ if (info.cols === 60 && info.rows === 20) break;
+ if (Date.now() > deadline) throw new Error(`size never claimed: ${JSON.stringify(info)}`);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ } finally {
+ await a.close();
+ await b.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "a disconnecting owner releases the size for the next claimant",
+ async () => {
+ const terminal = await createTerminal(80, 24);
+ const owner = await attach(terminal.id, { cols: 120, rows: 40 });
+ expect(await terminalInfo(terminal.id)).toMatchObject({ cols: 120, rows: 40 });
+ await owner.close();
+
+ const next = await attach(terminal.id, { cols: 90, rows: 28 });
+ try {
+ expect(await terminalInfo(terminal.id)).toMatchObject({ cols: 90, rows: 28 });
+ } finally {
+ await next.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+});
+
+describePty("terminal stream robustness", () => {
+ it(
+ "survives malformed, empty and non-binary frames",
+ async () => {
+ const terminal = await createTerminal();
+ const client = await attach(terminal.id);
+ try {
+ client.ws.send("plain text is not a frame");
+ client.ws.send(new Uint8Array(0));
+ client.ws.send(new Uint8Array([0x7f, 0x00, 0x41])); // unknown opcode
+ client.ws.send(encodeTerminalFrame({ opcode: TerminalStreamOpcode.Input, payload: "" }));
+ client.ws.send(
+ encodeTerminalFrame({ opcode: TerminalStreamOpcode.Resize, payload: "not json" }),
+ );
+ client.ws.send(
+ encodeTerminalFrame({
+ opcode: TerminalStreamOpcode.Resize,
+ payload: '{"cols":-5,"rows":1e99,"intent":"claim"}',
+ }),
+ );
+ // Server-only opcodes echoed back by a confused client must be ignored too.
+ client.ws.send(
+ encodeTerminalFrame({ opcode: TerminalStreamOpcode.Exit, payload: '{"exitCode":0}' }),
+ );
+
+ await runAndWait(client, "echo still-alive-marker", "still-alive-marker");
+ } finally {
+ await client.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "keeps frames decodable and the shell usable through a large output burst",
+ async () => {
+ const terminal = await createTerminal();
+ const client = await attach(terminal.id);
+ try {
+ // ~200KB of 'x' in one go; every received frame is decode-checked in attach().
+ await runAndWait(
+ client,
+ "head -c 200000 /dev/zero | tr '\\0' 'x'; echo burst-done-marker",
+ "burst-done-marker",
+ );
+ await runAndWait(client, "echo after-burst-marker", "after-burst-marker");
+ } finally {
+ await client.close();
+ }
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ "notifies attached clients when the shell exits, and the screen stays attachable",
+ async () => {
+ const terminal = await createTerminal();
+ const client = await attach(terminal.id);
+ try {
+ await runAndWait(client, "echo exit-scenario-marker", "exit-scenario-marker");
+ client.sendInput("exit\r");
+ await client.waitFor(
+ () => client.frames.some((f) => f.opcode === TerminalStreamOpcode.Exit),
+ "exit frame",
+ );
+ } finally {
+ await client.close();
+ }
+
+ // During the post-exit grace the terminal is still there: a fresh attach shows the
+ // final screen and is told immediately that the shell is gone.
+ const late = await attach(terminal.id);
+ try {
+ await late.waitFor(
+ () => late.frames.some((f) => f.opcode === TerminalStreamOpcode.Exit),
+ "exit frame on late attach",
+ );
+ expect(late.frames[0]?.opcode).toBe(TerminalStreamOpcode.Restore);
+ expect(late.restoreText()).toContain("exit-scenario-marker");
+ } finally {
+ await late.close();
+ }
+
+ // The control plane agrees: keystrokes to an exited shell are a 409, not a hang.
+ const res = await api.post(`/api/terminals/${terminal.id}/keys`, { keys: "Enter" });
+ expect(res.status).toBe(409);
+ },
+ TEST_TIMEOUT,
+ );
+});
diff --git a/packages/server/test/terminal.test.ts b/packages/server/test/terminal.test.ts
new file mode 100644
index 00000000..3b3a999d
--- /dev/null
+++ b/packages/server/test/terminal.test.ts
@@ -0,0 +1,648 @@
+/**
+ * Terminal tests: the pure pieces (restore rendering, mode tracking, size ownership, output
+ * coalescing) plus one end-to-end pass over the HTTP control plane with a real pty.
+ *
+ * The restore tests are where the value is — they encode the promise that a reattaching
+ * client can rebuild the exact screen, which is what a browser refresh depends on.
+ */
+import { describe, expect, it, vi, afterEach } from "vitest";
+import fs from "node:fs/promises";
+import fsSync from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import xterm from "@xterm/headless";
+import { createTestApp, loginAdmin, apiClient } from "./helpers.js";
+import { TerminalManager, MAX_TERMINALS_PER_USER } from "../src/platform/terminal/manager.js";
+import { expandHomePath } from "../src/platform/terminal/session.js";
+import { repairSpawnHelpers } from "../src/terminal/spawn-helper.js";
+import { TerminalInputModeTracker } from "../src/platform/terminal/input-mode.js";
+import { TerminalOutputCoalescer } from "../src/platform/terminal/output-coalescer.js";
+import { applyTerminalSize, releaseTerminalSize } from "../src/platform/terminal/size-ownership.js";
+import { captureLines, renderRestoreAnsi } from "../src/platform/terminal/snapshot.js";
+import { resolveKeys } from "../src/platform/terminal/routes.js";
+import {
+ TerminalStreamOpcode,
+ decodeTerminalFrame,
+ encodeTerminalFrame,
+ parseResizePayload,
+} from "../src/platform/terminal/frames.js";
+
+const { Terminal } = xterm;
+
+/** Real ptys only on POSIX — see terminal-stream.test.ts for the Windows CI rationale. */
+const describePty = describe.skipIf(process.platform === "win32");
+
+/** A headless terminal fed with `input`, standing in for one whose pty produced it. */
+function terminalWith(input: string, cols = 40, rows = 6) {
+ const terminal = new Terminal({ cols, rows, scrollback: 100, allowProposedApi: true });
+ terminal.write(input);
+ return terminal;
+}
+
+/** Replays an ANSI stream into a fresh terminal — i.e. does what an attaching client does. */
+async function replay(ansi: string, cols = 40, rows = 6): Promise<string[]> {
+ const terminal = new Terminal({ cols, rows, scrollback: 100, allowProposedApi: true });
+ // xterm parses writes asynchronously; read only once the parser has drained.
+ await new Promise<void>((resolve) => terminal.write(ansi, resolve));
+ return captureLines(terminal).lines;
+}
+
+function flush(terminal: xterm.Terminal): Promise<void> {
+ return new Promise((resolve) => terminal.write("", resolve));
+}
+
+describe("restore rendering", () => {
+ it("replays into an identical screen", async () => {
+ const source = terminalWith("first line\r\nsecond line\r\n$ ");
+ await flush(source);
+
+ const restored = await replay(renderRestoreAnsi(source));
+
+ expect(restored).toEqual(captureLines(source).lines);
+ expect(restored[0]).toBe("first line");
+ expect(restored[2]).toBe("$ ");
+ });
+
+ it("keeps colours and attributes", async () => {
+ const source = terminalWith("\x1b[1;32mgreen bold\x1b[0m plain \x1b[41mred bg\x1b[0m");
+ await flush(source);
+
+ const ansi = renderRestoreAnsi(source);
+
+ // Colours survive as SGR runs, not as plain text.
+ expect(ansi).toMatch(/\x1b\[0;1;38;5;\d+m/);
+ expect(ansi).toMatch(/48;5;\d+m/);
+ expect((await replay(ansi))[0]).toBe("green bold plain red bg");
+ });
+
+ it("restores the cursor position, not just the text", async () => {
+ // Three lines of output, then the cursor parked mid-line on row 2.
+ const source = terminalWith("aaa\r\nbbb\r\nccc");
+ source.write("\x1b[2;2H");
+ await flush(source);
+
+ const target = new Terminal({ cols: 40, rows: 6, allowProposedApi: true });
+ target.write(renderRestoreAnsi(source));
+ await flush(target);
+
+ expect(target.buffer.active.cursorY).toBe(source.buffer.active.cursorY);
+ expect(target.buffer.active.cursorX).toBe(source.buffer.active.cursorX);
+ });
+
+ it("carries scrollback so the reattached client can scroll back", async () => {
+ const lines = Array.from({ length: 20 }, (_, i) => `line-${i}`).join("\r\n");
+ const source = terminalWith(lines);
+ await flush(source);
+
+ const restored = await replay(renderRestoreAnsi(source, { scrollbackLines: 50 }));
+
+ expect(restored).toContain("line-0");
+ expect(restored.at(-1)).toBe("line-19");
+ });
+
+ it("caps scrollback when asked to", async () => {
+ const lines = Array.from({ length: 30 }, (_, i) => `line-${i}`).join("\r\n");
+ const source = terminalWith(lines);
+ await flush(source);
+
+ const restored = await replay(renderRestoreAnsi(source, { scrollbackLines: 3 }));
+
+ expect(restored).not.toContain("line-0");
+ expect(restored.at(-1)).toBe("line-29");
+ });
+
+ it("re-enters the alternate buffer for a full-screen program", async () => {
+ const source = terminalWith("shell scrollback\r\n\x1b[?1049h\x1b[Hfull screen app");
+ await flush(source);
+
+ const ansi = renderRestoreAnsi(source);
+
+ expect(ansi).toContain("\x1b[?1049h");
+ expect((await replay(ansi))[0]).toBe("full screen app");
+ // The alternate buffer has no scrollback of its own; the shell's is not mixed in.
+ expect(await replay(ansi)).not.toContain("shell scrollback");
+ });
+
+ it("does not stack two screens when a client reattaches twice", async () => {
+ const source = terminalWith("only once\r\n$ ");
+ await flush(source);
+
+ const ansi = renderRestoreAnsi(source);
+ const twice = (await replay(ansi + ansi)).filter((line) => line === "only once");
+
+ expect(twice).toHaveLength(1);
+ });
+});
+
+describe("input mode tracker", () => {
+ it("replays modes the program turned on", () => {
+ const tracker = new TerminalInputModeTracker();
+ tracker.feed("\x1b[?2004h\x1b[?1h");
+
+ const preamble = tracker.preamble();
+
+ expect(preamble).toContain("2004");
+ expect(preamble).toContain("1;"); // application cursor keys, alongside bracketed paste
+ expect(preamble.endsWith("h")).toBe(true);
+ });
+
+ it("replays modes the program turned off", () => {
+ const tracker = new TerminalInputModeTracker();
+ tracker.feed("\x1b[?25l"); // hidden cursor
+
+ expect(tracker.preamble()).toBe("\x1b[?25l");
+ });
+
+ it("emits nothing when everything is at its default", () => {
+ const tracker = new TerminalInputModeTracker();
+ tracker.feed("plain output\r\n\x1b[1;32mcoloured\x1b[0m");
+
+ expect(tracker.preamble()).toBe("");
+ });
+
+ it("handles a sequence split across two pty chunks", () => {
+ const tracker = new TerminalInputModeTracker();
+ tracker.feed("output\x1b[?20");
+ tracker.feed("04h");
+
+ expect(tracker.isEnabled(2004)).toBe(true);
+ });
+
+ it("tracks the last transition when a mode flips repeatedly", () => {
+ const tracker = new TerminalInputModeTracker();
+ tracker.feed("\x1b[?1049h\x1b[?1049l\x1b[?1000h\x1b[?1000l");
+
+ expect(tracker.preamble()).toBe("");
+ });
+});
+
+describe("size ownership", () => {
+ const initial = { ownerId: null, cols: 80, rows: 24 };
+
+ it("gives ownership to a claim", () => {
+ const decision = applyTerminalSize(initial, {
+ connectionId: "a",
+ cols: 100,
+ rows: 30,
+ intent: "claim",
+ });
+
+ expect(decision.apply).toBe(true);
+ expect(decision.state.ownerId).toBe("a");
+ });
+
+ it("transfers ownership on a claim even when the size is unchanged", () => {
+ const owned = { ownerId: "a", cols: 80, rows: 24 };
+
+ const decision = applyTerminalSize(owned, {
+ connectionId: "b",
+ cols: 80,
+ rows: 24,
+ intent: "claim",
+ });
+
+ expect(decision.state.ownerId).toBe("b");
+ expect(decision.apply).toBe(false); // nothing to resize, but the owner moved
+ });
+
+ it("ignores an update from a connection that does not own the size", () => {
+ const owned = { ownerId: "a", cols: 80, rows: 24 };
+
+ const decision = applyTerminalSize(owned, {
+ connectionId: "background-tab",
+ cols: 40,
+ rows: 10,
+ intent: "update",
+ });
+
+ expect(decision.apply).toBe(false);
+ expect(decision.state).toEqual(owned);
+ });
+
+ it("releases ownership only for the owning connection", () => {
+ const owned = { ownerId: "a", cols: 80, rows: 24 };
+
+ expect(releaseTerminalSize(owned, "b").ownerId).toBe("a");
+ expect(releaseTerminalSize(owned, "a").ownerId).toBe(null);
+ });
+});
+
+describe("output coalescer", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it("flushes the first chunk immediately", () => {
+ vi.useFakeTimers();
+ const flushed: string[] = [];
+ const coalescer = new TerminalOutputCoalescer((data) => flushed.push(data), 5);
+
+ coalescer.push("a");
+
+ expect(flushed).toEqual(["a"]); // no timer advance: a keystroke echo pays nothing
+ });
+
+ it("merges a burst into one flush", () => {
+ vi.useFakeTimers();
+ const flushed: string[] = [];
+ const coalescer = new TerminalOutputCoalescer((data) => flushed.push(data), 5);
+
+ coalescer.push("a");
+ coalescer.push("b");
+ coalescer.push("c");
+ vi.advanceTimersByTime(5);
+
+ expect(flushed).toEqual(["a", "bc"]);
+ });
+
+ it("flushes pending output on demand so ordering is preserved", () => {
+ vi.useFakeTimers();
+ const flushed: string[] = [];
+ const coalescer = new TerminalOutputCoalescer((data) => flushed.push(data), 5);
+
+ coalescer.push("a");
+ coalescer.push("b");
+ coalescer.flush();
+
+ expect(flushed).toEqual(["a", "b"]);
+ });
+});
+
+describe("frame codec", () => {
+ it("round-trips an output frame", () => {
+ const frame = decodeTerminalFrame(
+ encodeTerminalFrame({ opcode: TerminalStreamOpcode.Output, payload: "hi" }),
+ );
+
+ expect(frame?.opcode).toBe(TerminalStreamOpcode.Output);
+ expect(new TextDecoder().decode(frame?.payload)).toBe("hi");
+ });
+
+ it("rejects malformed frames instead of throwing", () => {
+ expect(decodeTerminalFrame(new Uint8Array([0x01]))).toBeNull();
+ expect(decodeTerminalFrame(new Uint8Array([0x7f, 0x00, 0x41]))).toBeNull();
+ });
+
+ it("rejects a resize payload that is not a usable size", () => {
+ const bad = decodeTerminalFrame(
+ encodeTerminalFrame({ opcode: TerminalStreamOpcode.Resize, payload: '{"cols":0,"rows":24}' }),
+ );
+
+ expect(parseResizePayload(bad!)).toBeNull();
+ });
+});
+
+describe("key tokens", () => {
+ it("maps named keys and control chords", () => {
+ expect(resolveKeys("Enter", false)).toBe("\r");
+ expect(resolveKeys("C-c", false)).toBe("\x03");
+ expect(resolveKeys("Up", false)).toBe("\x1b[A");
+ });
+
+ it("sends literal text as-is when asked", () => {
+ expect(resolveKeys("Enter", true)).toBe("Enter");
+ expect(resolveKeys("ls -la", false)).toBe("ls -la");
+ });
+});
+
+describePty("terminal API", () => {
+ /** Polls the capture endpoint until the shell has produced what we are waiting for. */
+ async function waitForLine(
+ read: () => Promise<string[]>,
+ match: RegExp,
+ timeoutMs = 15000,
+ ): Promise<string[]> {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const lines = await read();
+ if (lines.some((line) => match.test(line))) return lines;
+ if (Date.now() > deadline)
+ throw new Error(`Timed out waiting for ${match}; got: ${lines.join("|")}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ }
+
+ it("creates, drives, captures and kills a terminal", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const api = apiClient(t.app, admin.cookie);
+
+ const created = await api.post("/api/terminals", { cwd: "~", cols: 80, rows: 24 });
+ expect(created.status).toBe(201);
+ const terminal = (await created.json()) as { id: string; cwd: string; alive: boolean };
+ expect(terminal.alive).toBe(true);
+
+ const read = async (): Promise<string[]> => {
+ const res = await api.get(`/api/terminals/${terminal.id}/capture`);
+ return ((await res.json()) as { lines: string[] }).lines;
+ };
+
+ await api.post(`/api/terminals/${terminal.id}/keys`, {
+ keys: "echo penguin-terminal-ok",
+ literal: true,
+ });
+ await api.post(`/api/terminals/${terminal.id}/keys`, { keys: "Enter" });
+ const lines = await waitForLine(read, /^penguin-terminal-ok$/);
+ expect(lines.some((line) => line === "penguin-terminal-ok")).toBe(true);
+
+ const listed = await api.get("/api/terminals");
+ expect(((await listed.json()) as { terminals: unknown[] }).terminals).toHaveLength(1);
+
+ expect((await api.delete(`/api/terminals/${terminal.id}`)).status).toBe(204);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("does not expose one user's terminal to another", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const adminApi = apiClient(t.app, admin.cookie);
+ const created = await adminApi.post("/api/terminals", { cwd: "~" });
+ const terminal = (await created.json()) as { id: string };
+
+ const { provisionUser } = await import("./helpers.js");
+ const other = await provisionUser(t.app, "someoneelse");
+ const otherApi = apiClient(t.app, other.cookie);
+
+ // 404, not 403: a terminal id belonging to someone else must not be confirmable.
+ expect((await otherApi.get(`/api/terminals/${terminal.id}`)).status).toBe(404);
+ expect(
+ ((await (await otherApi.get("/api/terminals")).json()) as { terminals: unknown[] })
+ .terminals,
+ ).toHaveLength(0);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("rejects a working directory that does not exist", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).post("/api/terminals", {
+ cwd: "/definitely/not/a/directory",
+ });
+
+ expect(res.status).toBe(400);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("rejects a relative working directory instead of resolving it against the server", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const api = apiClient(t.app, admin.cookie);
+
+ // "." exists relative to the server process cwd — which is exactly why it must not
+ // be accepted: the caller has no idea where the server was started from.
+ for (const cwd of [".", "relative/dir", "./tmp"]) {
+ const res = await api.post("/api/terminals", { cwd });
+ expect(res.status, `cwd=${cwd}`).toBe(400);
+ }
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("rejects a working directory that is a file, not a directory", async () => {
+ const t = await createTestApp();
+ try {
+ const file = path.join(t.root, "a-file.txt");
+ await fs.writeFile(file, "not a dir");
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).post("/api/terminals", { cwd: file });
+
+ expect(res.status).toBe(400);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+// POSIX file modes only: Windows has no exec bit (chmod there toggles the read-only
+// flag), so a 0644 helper and a 0755 one are indistinguishable to fs.stat. The repair
+// itself never runs off darwin, so nothing is left unguarded by skipping here.
+describe.skipIf(process.platform === "win32")("spawn-helper repair", () => {
+ // node-pty's npm tarball ships its darwin prebuild's spawn-helper as 0644 (no exec
+ // bit), and darwin's posix_spawnp then refuses it — the macOS "terminal opens blank"
+ // bug.
+ async function helperTree(relative: string[], mode: number): Promise<string> {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-pty-"));
+ const file = path.join(root, ...relative);
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, "#!/bin/sh\n", { mode });
+ await fs.chmod(file, mode); // writeFile honours umask; pin the mode exactly
+ return root;
+ }
+
+ it("adds the exec bit to a prebuilt helper that lacks it", async () => {
+ const root = await helperTree(["prebuilds", "darwin-arm64", "spawn-helper"], 0o644);
+ const helper = path.join(root, "prebuilds", "darwin-arm64", "spawn-helper");
+
+ expect(repairSpawnHelpers(root, "arm64")).toEqual([helper]);
+ expect(fsSync.statSync(helper).mode & 0o111).not.toBe(0);
+ });
+
+ it("leaves an already-executable helper alone", async () => {
+ const root = await helperTree(["build", "Release", "spawn-helper"], 0o755);
+
+ expect(repairSpawnHelpers(root, "arm64")).toEqual([]);
+ });
+
+ it("is a no-op when node-pty shipped no helper (every non-darwin install)", async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-pty-"));
+
+ expect(repairSpawnHelpers(root, "x64")).toEqual([]);
+ });
+});
+
+describe("home path expansion", () => {
+ it("expands ~ and ~/ but leaves other paths alone", () => {
+ expect(expandHomePath("~")).toBe(os.homedir());
+ expect(expandHomePath("~/sub/dir")).toBe(path.join(os.homedir(), "sub/dir"));
+ expect(expandHomePath("/absolute/path")).toBe("/absolute/path");
+ // `~user` expansion is deliberately not supported; it must pass through (and then be
+ // rejected as non-absolute) rather than being misread as the caller's home.
+ expect(expandHomePath("~otheruser/dir")).toBe("~otheruser/dir");
+ });
+});
+
+describe("capture ranges", () => {
+ it("supports negative indices counting from the end", async () => {
+ const source = terminalWith("one\r\ntwo\r\nthree\r\nfour", 40, 4);
+ await flush(source);
+
+ expect(captureLines(source, { start: -2 }).lines).toEqual(["three", "four"]);
+ expect(captureLines(source, { start: -3, end: -2 }).lines).toEqual(["two", "three"]);
+ });
+
+ it("clamps out-of-range indices instead of failing", async () => {
+ const source = terminalWith("one\r\ntwo", 40, 2);
+ await flush(source);
+
+ expect(captureLines(source, { start: -100 }).lines[0]).toBe("one");
+ expect(captureLines(source, { start: 0, end: 100 }).totalLines).toBe(2);
+ // An inverted range is empty, not an error.
+ expect(captureLines(source, { start: 1, end: 0 }).lines).toEqual([]);
+ });
+});
+
+describePty("terminal manager lifecycle", () => {
+ /**
+ * Direct manager (no HTTP) with a short grace so reap timing is testable. The registry is
+ * the real one's stand-in: these tests exercise manager policy, not resource hand-off.
+ */
+ function shortGraceManager(graceMs = 80): TerminalManager {
+ const registry = new Map<string, unknown>();
+ return new TerminalManager(
+ {
+ register: (id, resource) => void registry.set(id, resource),
+ claim: <T>(id: string) => registry.get(id) as T | undefined,
+ release: (id) => void registry.delete(id),
+ },
+ graceMs,
+ );
+ }
+
+ async function waitUntil(cond: () => boolean, timeoutMs = 10_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!cond()) {
+ if (Date.now() > deadline) throw new Error("waitUntil timed out");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ }
+
+ it("keeps an exited session readable for the grace period, then reaps it", async () => {
+ const manager = shortGraceManager(80);
+ try {
+ const session = await manager.create({
+ cwd: os.tmpdir(),
+ ownerUserId: "u1",
+ shell: "/bin/sh",
+ });
+ session.write("exit 3\n");
+ await waitUntil(() => !session.alive);
+
+ // Still there right after exiting: the final screen and exit info are readable.
+ expect(manager.get(session.id)).toBeDefined();
+ const info = session.info();
+ expect(info.alive).toBe(false);
+ expect(info.exit?.exitCode).toBe(3);
+
+ // ...and gone once the grace period has passed.
+ await waitUntil(() => manager.get(session.id) === undefined, 5000);
+ } finally {
+ manager.disposeAll();
+ }
+ }, 20_000);
+
+ it("caps live terminals per user, not exited ones, and not other users", async () => {
+ const manager = shortGraceManager(60_000); // long grace: exited sessions stay listed
+ try {
+ const request = (owner: string) => ({
+ cwd: os.tmpdir(),
+ ownerUserId: owner,
+ shell: "/bin/sh",
+ });
+ const sessions = await Promise.all(
+ Array.from({ length: MAX_TERMINALS_PER_USER }, () => manager.create(request("u1"))),
+ );
+
+ await expect(manager.create(request("u1"))).rejects.toMatchObject({ status: 429 });
+ // Another user's budget is their own.
+ const other = await manager.create(request("u2"));
+ expect(other.alive).toBe(true);
+
+ // A session that exited frees its slot even while still listable in the grace window.
+ const first = sessions[0]!;
+ first.write("exit\n");
+ await waitUntil(() => !first.alive);
+ expect(manager.get(first.id)).toBeDefined();
+ const replacement = await manager.create(request("u1"));
+ expect(replacement.alive).toBe(true);
+ } finally {
+ manager.disposeAll();
+ }
+ }, 30_000);
+
+ it("auto-increments default names per user; explicit names pass through", async () => {
+ const manager = shortGraceManager(60_000);
+ try {
+ const request = (owner: string, name?: string) => ({
+ cwd: os.tmpdir(),
+ ownerUserId: owner,
+ shell: "/bin/sh",
+ ...(name !== undefined ? { name } : {}),
+ });
+ const base = path.basename(os.tmpdir());
+
+ const a = await manager.create(request("u1"));
+ const b = await manager.create(request("u1"));
+ const c = await manager.create(request("u1"));
+ expect(a.info().name).toBe(base);
+ expect(b.info().name).toBe(`${base} 2`);
+ expect(c.info().name).toBe(`${base} 3`);
+ expect([a.seq, b.seq, c.seq]).toEqual([1, 2, 3]);
+ // Another user's numbering is their own, and explicit names are never rewritten.
+ const other = await manager.create(request("u2"));
+ expect(other.info().name).toBe(base);
+ expect(other.seq).toBe(1);
+ expect((await manager.create(request("u1", "custom"))).info().name).toBe("custom");
+
+ // Seqs are STABLE: a terminal keeps its number for life; ending one frees its
+ // number for the next create but never renumbers the survivors.
+ b.write("exit\n");
+ await waitUntil(() => !b.alive);
+ const d = await manager.create(request("u1"));
+ expect(d.seq).toBe(2);
+ expect(a.seq).toBe(1);
+ expect(c.seq).toBe(3);
+ } finally {
+ manager.disposeAll();
+ }
+ }, 20_000);
+
+ it("disposeAll kills the underlying shell processes", async () => {
+ const manager = shortGraceManager();
+ const session = await manager.create({
+ cwd: os.tmpdir(),
+ ownerUserId: "u1",
+ shell: "/bin/sh",
+ });
+ const pid = session.info().pid;
+ manager.disposeAll();
+
+ // Dead means "no longer running": either the pid is gone entirely, or it lingers only
+ // as a zombie (state Z) until reaped — kill(pid, 0) alone cannot tell those apart.
+ const isDead = (): boolean => {
+ try {
+ const stat = fsSync.readFileSync(`/proc/${pid}/stat`, "utf8");
+ return / [ZX] /.test(stat.slice(stat.lastIndexOf(")")));
+ } catch {
+ return true; // /proc entry gone (or non-Linux): the process no longer exists
+ }
+ };
+ await waitUntil(isDead, 10_000);
+ expect(manager.get(session.id)).toBeUndefined();
+ }, 20_000);
+
+ it("closing a viewer must not kill the shell (sessions are connection-independent)", async () => {
+ const manager = shortGraceManager();
+ try {
+ const session = await manager.create({
+ cwd: os.tmpdir(),
+ ownerUserId: "u1",
+ shell: "/bin/sh",
+ });
+ // Simulates every client going away: only size ownership is released.
+ session.releaseSize("some-connection");
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(session.alive).toBe(true);
+ } finally {
+ manager.disposeAll();
+ }
+ }, 20_000);
+});
diff --git a/packages/web/e2e/terminal-dock.spec.mjs b/packages/web/e2e/terminal-dock.spec.mjs
new file mode 100644
index 00000000..92911a9c
--- /dev/null
+++ b/packages/web/e2e/terminal-dock.spec.mjs
@@ -0,0 +1,1045 @@
+/**
+ * In-app terminal dock (the Codex-style integrated terminal) and the chat toolbar's panel
+ * switcher:
+ * - Ctrl+` toggles a terminal panel at the bottom of the app;
+ * - the shell keeps running while the dock is closed; reopening reattaches to it;
+ * - "Detach" hands the terminal off to /terminal?id=… in a new window — same shell, same
+ * screen — and the dock forgets it, so its next shell is a fresh one;
+ * - the chat toolbar (top-right) shows icon-only triggers for the pinned panels plus an
+ * "all panels" dropdown (智能体面板 / 终端 / 工作区) with per-panel pin toggles that
+ * persist; agents + workspace are pinned by default, the terminal is opt-in.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "dockuser";
+const P = "password123";
+
+/**
+ * A Project without model credentials pops the onboarding overlay (fixed inset-0) as soon
+ * as /chat loads, which would swallow every click on the dock; configure the mock model
+ * first, like the other app-shell specs do.
+ */
+async function configureProjectModel(request) {
+ const projectId = (await (await request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ return projectId;
+}
+
+/** The chat toolbar only renders on a real Session, so make one through the API. */
+async function createSession(request, projectId) {
+ const res = await request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { provider: "custom", modelId: "claude-4-8" } },
+ );
+ expect(res.ok(), "create session").toBeTruthy();
+ return (await res.json()).session.sessionId;
+}
+
+/**
+ * The dock attaches the user's newest live terminal before creating one, so a leftover
+ * shell from a previous test would leak into the next test's screen. Each test starts from
+ * zero terminals; kill is async (SIGHUP → pty exit), so poll until none is alive.
+ */
+async function killAllTerminals(request) {
+ const { terminals } = await (await request.get(`${BASE}/api/terminals`)).json();
+ for (const t of terminals) await request.delete(`${BASE}/api/terminals/${t.id}`);
+ await expect
+ .poll(
+ async () => {
+ const res = await (await request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+ },
+ { timeout: 10000 },
+ )
+ .toBe(0);
+}
+
+// The pane the user sees. A displaced or just-closed side pane lingers in the DOM for its
+// 200ms collapse — inert, width 0 — so the bare testid can briefly match two elements.
+const dock = (page) => page.locator('[data-testid="terminal-dock"]:not([inert])');
+const dockScreenText = (page) => dock(page).locator(".xterm-rows").innerText();
+
+async function runInDock(page, command) {
+ await dock(page).locator(".xterm-screen").click();
+ await page.keyboard.type(command);
+ await page.keyboard.press("Enter");
+}
+
+/**
+ * Waits until the dock's shell is really at a prompt (see terminal.spec.mjs). The sentinel
+ * is typed quote-split (echo TA''G) so the command's own echo never contains the tag, and
+ * matched at end-of-line: a resize reflow right after attach can glue the echoed command
+ * and its output onto one DOM row, where a ^tag$ match would never fire.
+ */
+async function waitForDockShell(page, tag) {
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await runInDock(page, `echo ${tag.slice(0, 2)}''${tag.slice(2)}`);
+ await expect
+ .poll(() => dockScreenText(page), { timeout: 30000 })
+ .toMatch(new RegExp(`${tag}$`, "m"));
+}
+
+test("Ctrl+` toggles the dock; the shell survives close and reopen", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ // Open with the keyboard, like Codex/VS Code.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "DOCK_UP_1");
+
+ await runInDock(page, "echo DOCK_KEEPS_RUNNING");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("DOCK_KEEPS_RUNNING");
+
+ // Close via the header X: the view goes away, the shell does not.
+ await page.locator('[data-testid="terminal-dock-close"]').click();
+ await expect(dock(page)).toBeHidden();
+
+ // Reopen with the shortcut: same shell, same screen.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("DOCK_KEEPS_RUNNING");
+});
+
+test("Detach hands the terminal to /terminal?id=… and the dock lets go", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "DOCK_UP_2");
+ await runInDock(page, "echo DETACH_MARKER");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("DETACH_MARKER");
+
+ const [popup] = await Promise.all([
+ page.waitForEvent("popup"),
+ page.locator('[data-testid="terminal-dock-detach"]').click(),
+ ]);
+
+ // The dock closed; the popup is the standalone page attached to the same terminal.
+ await expect(dock(page)).toBeHidden();
+ expect(popup.url()).toMatch(/\/terminal\?id=/);
+ await expect(popup.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect
+ .poll(() => popup.locator(".xterm-rows").innerText(), { timeout: 15000 })
+ .toContain("DETACH_MARKER");
+
+ // The detached window is live, not a snapshot.
+ await popup.click(".xterm-screen");
+ await popup.keyboard.type("echo DETACHED_LIVE");
+ await popup.keyboard.press("Enter");
+ await expect
+ .poll(() => popup.locator(".xterm-rows").innerText(), { timeout: 15000 })
+ .toContain("DETACHED_LIVE");
+
+ // Reopening the dock reattaches the last-opened terminal — the same shell the window
+ // now holds (the stream supports multiple attached clients), per the persistence rules.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("DETACH_MARKER");
+});
+
+test("panel switcher: default pins, all-panels dropdown, pin/unpin persists", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const sessionId = await createSession(page.request, projectId);
+ await page.goto(`${BASE}/chat/${sessionId}`);
+
+ // Default pins: agents + workspace icons in the toolbar, no terminal icon.
+ const toolbar = page.locator('[data-testid="panels-toolbar"]');
+ await expect(toolbar).toBeVisible({ timeout: 20000 });
+ await expect(page.locator('[data-testid="panel-btn-agents"]')).toBeVisible();
+ await expect(page.locator('[data-testid="panel-btn-workspace"]')).toBeVisible();
+ await expect(page.locator('[data-testid="panel-btn-terminal"]')).toHaveCount(0);
+ // Icon-only triggers: the accessible name lives in aria-label, not visible text.
+ expect((await page.locator('[data-testid="panel-btn-agents"]').innerText()).trim()).toBe("");
+
+ // The "all panels" dropdown lists every panel with its name.
+ await page.locator('[data-testid="panels-all"]').click();
+ await expect(page.locator('[data-testid="panels-menu-agents"]')).toContainText("智能体面板");
+ await expect(page.locator('[data-testid="panels-menu-terminal"]')).toContainText("终端");
+ await expect(page.locator('[data-testid="panels-menu-workspace"]')).toContainText("工作区");
+
+ // A row click opens that panel (and dismisses the menu): the terminal dock appears.
+ await page.locator('[data-testid="panels-menu-terminal"]').click();
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="panels-menu-terminal"]')).toBeHidden();
+
+ // Pin the terminal, unpin the workspace — the menu stays open across pin toggles.
+ await page.locator('[data-testid="panels-all"]').click();
+ await page.locator('[data-testid="panels-pin-terminal"]').click();
+ await expect(page.locator('[data-testid="panel-btn-terminal"]')).toBeVisible();
+ await page.locator('[data-testid="panels-pin-workspace"]').click();
+ await expect(page.locator('[data-testid="panel-btn-workspace"]')).toHaveCount(0);
+ await page.keyboard.press("Escape");
+
+ // The pinned terminal icon toggles the dock like any other panel trigger.
+ await page.locator('[data-testid="panel-btn-terminal"]').click();
+ await expect(dock(page)).toBeHidden();
+ await page.locator('[data-testid="panel-btn-terminal"]').click();
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+
+ // Pins persist across a reload.
+ await page.reload();
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await expect(page.locator('[data-testid="panel-btn-terminal"]')).toBeVisible();
+ await expect(page.locator('[data-testid="panel-btn-workspace"]')).toHaveCount(0);
+ await expect(page.locator('[data-testid="panel-btn-agents"]')).toBeVisible();
+});
+
+test("dock tabs: list every shell, switch between them, kill one", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ const tabs = page.locator('[data-testid="terminal-tab"]');
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "TAB_SHELL_A");
+ await runInDock(page, "echo IN_TAB_A");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("IN_TAB_A");
+ await expect(tabs).toHaveCount(1, { timeout: 15000 });
+
+ // "+" opens a second shell in a new tab; both are listed, the new one is active.
+ await page.locator('[data-testid="terminal-dock-new-shell"]').click();
+ await waitForDockShell(page, "TAB_SHELL_B");
+ await runInDock(page, "echo IN_TAB_B");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("IN_TAB_B");
+ await expect(tabs).toHaveCount(2, { timeout: 15000 });
+ await expect(tabs.last()).toHaveAttribute("data-active", "true");
+
+ // Clicking the first tab switches back to shell A's screen (list order = creation order)…
+ await tabs.first().locator("button").first().click();
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("IN_TAB_A");
+ await expect(tabs.first()).toHaveAttribute("data-active", "true");
+
+ // …and the second tab brings shell B back.
+ await tabs.last().locator("button").first().click();
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("IN_TAB_B");
+
+ // Killing the background tab (A) ends that shell; the current one is untouched. The
+ // strip reacts to the user's own kill optimistically — no server round-trip to wait for.
+ await tabs.first().hover();
+ await tabs.first().locator('[data-testid="terminal-tab-kill"]').click();
+ await expect(tabs).toHaveCount(1, { timeout: 2000 });
+ expect(await dockScreenText(page)).toContain("IN_TAB_B");
+
+ // Killing the last tab means "done with terminals": the dock closes rather than
+ // spawning a replacement nobody asked for.
+ await tabs.first().hover();
+ await tabs.first().locator('[data-testid="terminal-tab-kill"]').click();
+ await expect(dock(page)).toBeHidden({ timeout: 15000 });
+
+ // Reopening starts fresh — nothing left to reattach.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "TAB_SHELL_C");
+ expect(await dockScreenText(page)).not.toContain("IN_TAB_B");
+ await expect(tabs).toHaveCount(1, { timeout: 15000 });
+});
+
+test("tab interactions: reorder by drag, live title, detach keeps the dock", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "TAB_I_A");
+ await runInDock(page, "echo FIRST_TAB_MARK");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("FIRST_TAB_MARK");
+
+ await page.locator('[data-testid="terminal-dock-new-shell"]').click();
+ await waitForDockShell(page, "TAB_I_B");
+ const tabs = page.locator('[data-testid="terminal-tab"]');
+ await expect(tabs).toHaveCount(2, { timeout: 5000 });
+
+ // The "+" lives outside the scrollable strip, so it stays reachable however many tabs.
+ await expect(page.locator('[data-testid="terminal-dock-new-shell"]')).toBeVisible();
+
+ // Live title: the shell's OSC title lands on the active tab's label (sleep keeps the
+ // title up until the assertion has run — the next prompt may reset it).
+ await runInDock(page, "printf '\\033]0;LIVE_TITLE_X\\007'; sleep 2");
+ await expect(tabs.last()).toContainText("LIVE_TITLE_X", { timeout: 5000 });
+ const titledId = await tabs.last().getAttribute("data-terminal-id");
+
+ // A `user@host` marker (the bash/zsh default title shape) is dropped at display time —
+ // the host is noise in a single-server UI.
+ await runInDock(page, "printf '\\033]0;someone@somehost: CLEAN_TITLE\\007'; sleep 2");
+ await expect(tabs.last()).toContainText("CLEAN_TITLE", { timeout: 5000 });
+ expect(await tabs.last().innerText()).not.toContain("somehost");
+
+ // The spaceless variant (`user@host:~/path`) keeps its path — a greedy strip once ate
+ // the whole title here and the tab fell back to the assigned name.
+ await runInDock(page, "printf '\\033]0;someone@somehost:~/spaceless\\007'; sleep 2");
+ await expect(tabs.last()).toContainText("~/spaceless", { timeout: 5000 });
+ expect(await tabs.last().innerText()).not.toContain("somehost");
+ await runInDock(page, "printf '\\033]0;LIVE_TITLE_X\\007'; sleep 2"); // restore for later steps
+
+ // Reorder: drag the titled tab (B, currently last) in front of A. Its NUMBER travels
+ // with it — numbering is the terminal's stable seq, not its position, so after the drag
+ // the strip reads "2:, 1:" and you can see exactly what went where.
+ const ab = await tabs.first().boundingBox();
+ const bb = await tabs.last().boundingBox();
+ await page.mouse.move(bb.x + bb.width / 2, bb.y + bb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(ab.x + 4, ab.y + ab.height / 2, { steps: 6 });
+ await page.mouse.up();
+ await expect(tabs.first()).toHaveAttribute("data-terminal-id", titledId);
+ await expect(tabs.first()).toContainText("2: ");
+ await expect(tabs.last()).toContainText("1: ");
+
+ // The order persists across a reload.
+ await page.reload();
+ // A reload starts with the dock closed by design (the arrangement persists, being open
+ // does not), so reopening is what brings the stored arrangement back. Wait for the app
+ // first: /chat resolves to a Session id a moment after load, and a keypress before that
+ // opens the dock in the placeholder scope instead of the conversation's.
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 20000 });
+ await expect(tabs).toHaveCount(2, { timeout: 15000 });
+ await expect(tabs.first()).toHaveAttribute("data-terminal-id", titledId);
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+
+ // Detach with another terminal open: the current shell goes to its own window and the
+ // dock STAYS, switched onto the remaining tab (its screen restores).
+ const [popup] = await Promise.all([
+ page.waitForEvent("popup"),
+ page.locator('[data-testid="terminal-dock-detach"]').click(),
+ ]);
+ expect(popup.url()).toMatch(/\/terminal\?id=/);
+ await expect(dock(page)).toBeVisible();
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect(
+ page.locator('[data-testid="terminal-tab"][data-active="true"]'),
+ ).not.toHaveAttribute("data-terminal-id", titledId);
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("FIRST_TAB_MARK");
+});
+
+test("tabs are numbered; drag-out splits the tab into a new pane", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "NUM_A");
+ await page.locator('[data-testid="terminal-dock-new-shell"]').click();
+ await waitForDockShell(page, "NUM_B");
+
+ // Index prefixes keep identical names/titles apart (and the server numbers default
+ // names too: both shells were created in the same directory).
+ const tabs = page.locator('[data-testid="terminal-tab"]');
+ await expect(tabs).toHaveCount(2, { timeout: 5000 });
+ await expect(tabs.first()).toContainText("1: ");
+ await expect(tabs.last()).toContainText("2: ");
+ const firstLabel = await tabs.first().innerText();
+ const lastLabel = await tabs.last().innerText();
+ expect(firstLabel).not.toBe(lastLabel);
+
+ const bottomPane = page.locator('[data-testid="terminal-dock"][data-position="bottom"]');
+ const leftPane = page.locator('[data-testid="terminal-dock"][data-position="left"]');
+
+ // The current shell (B) must not reconnect while A is split away: remember its xterm.
+ await page.evaluate(() => {
+ window.__xtermB = document.querySelector(
+ '[data-testid="terminal-dock"][data-position="bottom"] .xterm',
+ );
+ });
+
+ // Drag the background tab (A) out of the strip: the edge overlay appears; dropping on
+ // the "left" target splits A into a NEW PANE on the left (no browser window involved).
+ const draggedId = await tabs.first().getAttribute("data-terminal-id");
+ const fb = await tabs.first().boundingBox();
+ await page.mouse.move(fb.x + fb.width / 2, fb.y + fb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(fb.x + fb.width / 2 + 10, fb.y + 120, { steps: 5 });
+ const leftTarget = page.locator('[data-dock-pos="left"]');
+ await expect(leftTarget).toBeVisible();
+ const lt = await leftTarget.boundingBox();
+ await page.mouse.move(lt.x + lt.width / 2, lt.y + lt.height / 2, { steps: 4 });
+ await expect(page.locator('[data-testid="dock-layout-preview"]')).toHaveAttribute(
+ "data-pos",
+ "left",
+ );
+ await page.mouse.up();
+
+ // Both panes exist: A's tab lives in the left pane (its screen restored there), B stays
+ // in the bottom pane — same xterm DOM node, so B never reconnected.
+ await expect(leftPane).toBeVisible({ timeout: 10000 });
+ await expect(
+ leftPane.locator(`[data-testid="terminal-tab"][data-terminal-id="${draggedId}"]`),
+ ).toBeVisible();
+ await expect
+ .poll(() => leftPane.locator(".xterm-rows").innerText(), { timeout: 20000 })
+ .toContain("NUM_A");
+ await expect(bottomPane.locator("[data-testid='terminal-tab']")).toHaveCount(1);
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelector('[data-testid="terminal-dock"][data-position="bottom"] .xterm') ===
+ window.__xtermB,
+ ),
+ "bottom pane's xterm survived the split",
+ ).toBe(true);
+ expect(await bottomPane.locator(".xterm-rows").innerText()).toContain("NUM_B");
+
+ // The split pane is a full pane: its shell is interactive.
+ await leftPane.locator(".xterm-screen").click();
+ await page.keyboard.type("echo IN_SPLIT_PANE");
+ await page.keyboard.press("Enter");
+ await expect
+ .poll(() => leftPane.locator(".xterm-rows").innerText(), { timeout: 15000 })
+ .toContain("IN_SPLIT_PANE");
+
+ // The arrangement survives a reload.
+ await page.reload();
+ // A reload starts with the dock closed by design (the arrangement persists, being open
+ // does not), so reopening is what brings the stored arrangement back. Wait for the app
+ // first: /chat resolves to a Session id a moment after load, and a keypress before that
+ // opens the dock in the placeholder scope instead of the conversation's.
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(leftPane).toBeVisible({ timeout: 20000 });
+ await expect(bottomPane).toBeVisible();
+ await expect(
+ leftPane.locator(`[data-testid="terminal-tab"][data-terminal-id="${draggedId}"]`),
+ ).toBeVisible({ timeout: 15000 });
+});
+
+test("dock layout: drag to an edge or onto the drop targets, preview then apply", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "LAYOUT_SHELL");
+ await expect(dock(page)).toHaveAttribute("data-position", "bottom"); // the default
+
+ // Scoped to the visible pane: a just-moved pane's predecessor lingers inert with its own grip.
+ const header = dock(page).locator('[data-testid="terminal-dock-grip"]');
+ const ready = page.locator('[data-testid="terminal-dock"][data-status="ready"]');
+
+ // Repositioning must not remount the terminal (a remount would drop the WebSocket and
+ // repaint the screen): remember the live xterm DOM node to compare after the moves.
+ await page.evaluate(() => {
+ window.__xtermBeforeMove = document.querySelector('[data-testid="terminal-dock"] .xterm');
+ });
+
+ // Method 2: drag the header onto the "left" rectangle of the left/right container.
+ let hb = await header.boundingBox();
+ await page.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(hb.x + 90, hb.y - 60, { steps: 4 }); // past the threshold → overlay
+ const leftTarget = page.locator('[data-dock-pos="left"]');
+ await expect(leftTarget).toBeVisible();
+ const lt = await leftTarget.boundingBox();
+ await page.mouse.move(lt.x + lt.width / 2, lt.y + lt.height / 2, { steps: 4 });
+ await expect(page.locator('[data-testid="dock-layout-preview"]')).toHaveAttribute(
+ "data-pos",
+ "left",
+ );
+ const previewBox = await page.locator('[data-testid="dock-layout-preview"]').boundingBox();
+ await page.mouse.up();
+ await expect(dock(page)).toHaveAttribute("data-position", "left");
+
+ // The preview promised the real final region: the landed dock occupies (within a couple
+ // of px of border rounding) exactly the rectangle that was previewed. Polled — a freshly
+ // created side pane slides in over 200ms, so a one-shot read lands mid-animation.
+ await expect
+ .poll(async () => {
+ const landedBox = await dock(page).boundingBox();
+ if (!landedBox) return Infinity;
+ return Math.max(
+ ...["x", "y", "width", "height"].map((side) =>
+ Math.abs(landedBox[side] - previewBox[side]),
+ ),
+ );
+ }, "preview vs landed geometry")
+ .toBeLessThan(3);
+
+ // The move kept the very same terminal instance — same xterm DOM node, same connection,
+ // screen intact without any restore repaint — and it stays interactive.
+ await expect(ready).toBeVisible({ timeout: 20000 });
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelector('[data-testid="terminal-dock"] .xterm') === window.__xtermBeforeMove,
+ ),
+ "xterm survived the reposition",
+ ).toBe(true);
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("LAYOUT_SHELL");
+ await runInDock(page, "echo AFTER_MOVE_LEFT");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("AFTER_MOVE_LEFT");
+
+ // Method 1: drag straight into the top edge band of the content area.
+ hb = await header.boundingBox();
+ const host = await page.locator("[data-dock-host]").boundingBox();
+ await page.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(host.x + host.width / 2, host.y + 30, { steps: 6 });
+ await expect(page.locator('[data-testid="dock-layout-preview"]')).toHaveAttribute(
+ "data-pos",
+ "top",
+ );
+ await page.mouse.up();
+ await expect(dock(page)).toHaveAttribute("data-position", "top");
+ await expect(ready).toBeVisible({ timeout: 20000 });
+
+ // Releasing in the neutral middle changes nothing.
+ hb = await header.boundingBox();
+ await page.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(host.x + host.width / 2, host.y + host.height / 2, { steps: 4 });
+ await expect(page.locator('[data-testid="dock-layout-preview"]')).toHaveCount(0);
+ await page.mouse.up();
+ await expect(dock(page)).toHaveAttribute("data-position", "top");
+
+ // The position survives a reload.
+ await page.reload();
+ // A reload starts with the dock closed by design (the arrangement persists, being open
+ // does not), so reopening is what brings the stored arrangement back. Wait for the app
+ // first: /chat resolves to a Session id a moment after load, and a keypress before that
+ // opens the dock in the placeholder scope instead of the conversation's.
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 20000 });
+ await expect(dock(page)).toHaveAttribute("data-position", "top");
+});
+
+test("dock resize: drag the boundary; the ratio survives reposition and reload", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "RESIZE_SHELL");
+
+ // Grow the bottom dock ~120px by dragging the boundary upward.
+ const before = await dock(page).boundingBox();
+ const rz = await page.locator('[data-testid="terminal-dock-resizer"]').boundingBox();
+ await page.mouse.move(rz.x + rz.width / 2, rz.y + rz.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(rz.x + rz.width / 2, rz.y + rz.height / 2 - 120, { steps: 6 });
+ await page.mouse.up();
+ const grown = await dock(page).boundingBox();
+ expect(grown.height - before.height).toBeGreaterThan(100);
+
+ // Live resize, no reconnect: the shell answers immediately at the new size.
+ await runInDock(page, "echo RESIZED_OK");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("RESIZED_OK");
+
+ // Repositioning to the top keeps the height ratio (same orientation, same row height).
+ const hb = await dock(page).locator('[data-testid="terminal-dock-grip"]').boundingBox();
+ const host = await page.locator("[data-dock-host]").boundingBox();
+ await page.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(host.x + host.width / 2, host.y + 30, { steps: 6 });
+ await page.mouse.up();
+ await expect(dock(page)).toHaveAttribute("data-position", "top");
+ const atTop = await dock(page).boundingBox();
+ expect(Math.abs(atTop.height - grown.height), "ratio kept across reposition").toBeLessThan(8);
+
+ // The size survives a reload…
+ await page.reload();
+ // A reload starts with the dock closed by design (the arrangement persists, being open
+ // does not), so reopening is what brings the stored arrangement back. Wait for the app
+ // first: /chat resolves to a Session id a moment after load, and a keypress before that
+ // opens the dock in the placeholder scope instead of the conversation's.
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 20000 });
+ const reloaded = await dock(page).boundingBox();
+ expect(Math.abs(reloaded.height - grown.height), "ratio kept across reload").toBeLessThan(8);
+
+ // …and double-clicking the boundary resets to the default 40% of the row.
+ const rz2 = await page.locator('[data-testid="terminal-dock-resizer"]').boundingBox();
+ await page.mouse.dblclick(rz2.x + rz2.width / 2, rz2.y + rz2.height / 2);
+ const resetBox = await dock(page).boundingBox();
+ // Height ratios resolve against the host column (the pane is its direct child).
+ const hostBox = await page.locator("[data-dock-host]").boundingBox();
+ expect(Math.abs(resetBox.height - hostBox.height * 0.4), "double-click reset").toBeLessThan(10);
+});
+
+test("terminal clipboard: keyboard copy/paste, right-click, focus", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "CLIP_SHELL");
+
+ // Copy: double-click selects the word, Ctrl+Shift+C puts it on the clipboard.
+ await runInDock(page, "echo COPY_ME_TOKEN");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toMatch(/^COPY_ME_TOKEN$/m);
+ await dock(page).locator(".xterm-rows").getByText("COPY_ME_TOKEN").last().dblclick();
+ await page.keyboard.press("Control+Shift+C");
+ await expect
+ .poll(() => page.evaluate(() => navigator.clipboard.readText()), { timeout: 10000 })
+ .toContain("COPY_ME_TOKEN");
+
+ // Paste via Ctrl+Shift+V (rides the browser's native paste event — exactly once).
+ await page.evaluate(() => navigator.clipboard.writeText("echo PASTE_VIA_KEYS"));
+ await dock(page).locator(".xterm-screen").click();
+ await page.keyboard.press("Control+Shift+V");
+ await expect
+ .poll(() => dockScreenText(page), { timeout: 15000 })
+ .toContain("echo PASTE_VIA_KEYS");
+ await page.keyboard.press("Enter");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toMatch(/^PASTE_VIA_KEYS$/m);
+ // …exactly once: the command line appears a single time before its output.
+ expect((await dockScreenText(page)).match(/echo PASTE_VIA_KEYS/g)).toHaveLength(1);
+
+ // Right-click with no selection pastes (and the page context menu is suppressed —
+ // if it opened, the keystrokes below would land in the menu, not the shell). The
+ // async-clipboard read means the text lands a beat later; wait before executing.
+ await page.evaluate(() => navigator.clipboard.writeText("echo PASTE_VIA_MOUSE"));
+ await dock(page).locator(".xterm-screen").click({ button: "right" });
+ await expect
+ .poll(() => dockScreenText(page), { timeout: 15000 })
+ .toContain("echo PASTE_VIA_MOUSE");
+ await page.keyboard.press("Enter");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toMatch(/^PASTE_VIA_MOUSE$/m);
+
+ // Focus mechanism: clicking the view's padding (outside the xterm screen itself) still
+ // routes subsequent typing into the shell.
+ const view = dock(page).locator(".xterm").locator("..");
+ const vb = await view.boundingBox();
+ await page.mouse.click(vb.x + vb.width - 4, vb.y + vb.height - 4); // bottom-right padding
+ await page.keyboard.type("echo FOCUS_BY_CLICK");
+ await page.keyboard.press("Enter");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toMatch(/^FOCUS_BY_CLICK$/m);
+});
+
+test("tab strip squeezes when crowded and wheel-scrolls", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ // A narrow left pane makes the strip overflow with few tabs. Its width is the one shared
+ // with the chat's side panels (use-panel-width.ts), so the floor is seeded there.
+ await page.addInitScript(() => {
+ localStorage.setItem("penguin.panelWidth", "320");
+ // One entry per Session scope (terminal-dock-state.ts); "~none" is the one a /chat
+ // without a Session id uses, and it is handed to the Session that route resolves to.
+ localStorage.setItem(
+ "penguin.terminal.dock",
+ JSON.stringify({
+ "~none": { visible: true, panes: ["left"], assignments: {}, currents: {} },
+ }),
+ );
+ });
+ await page.goto(`${BASE}/chat`);
+ // The seeded arrangement is restored, but a load never opens the dock by itself.
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 20000 });
+ await waitForDockShell(page, "SQUEEZE_UP");
+
+ const tabs = page.locator('[data-testid="terminal-tab"]');
+ const soloWidth = (await tabs.first().boundingBox()).width;
+
+ for (let i = 2; i <= 6; i += 1) {
+ await page.locator('[data-testid="terminal-dock-new-shell"]').click();
+ await expect(tabs).toHaveCount(i, { timeout: 10000 });
+ }
+
+ // Crowded tabs squeeze browser-style instead of holding full width.
+ const widths = await tabs.evaluateAll((els) => els.map((el) => el.getBoundingClientRect().width));
+ expect(Math.max(...widths)).toBeLessThan(Math.max(soloWidth, 80));
+ expect(Math.min(...widths)).toBeGreaterThanOrEqual(38); // the number stays readable
+
+ // Once the squeeze floor is hit the strip overflows — and the wheel scrolls it.
+ const strip = page.locator('[data-testid="terminal-tab-strip"]');
+ const overflow = await strip.evaluate((el) => el.scrollWidth - el.clientWidth);
+ expect(overflow).toBeGreaterThan(0);
+ await strip.evaluate((el) => {
+ el.scrollLeft = 0;
+ });
+ await strip.hover();
+ await page.mouse.wheel(0, 240);
+ await expect
+ .poll(() => strip.evaluate((el) => el.scrollLeft), { timeout: 5000 })
+ .toBeGreaterThan(0);
+});
+
+test("hover menus: create opens on hover; terminal lists on both levels", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const sessionId = await createSession(page.request, projectId);
+
+ // Seed one live terminal through the API, with a marker on its screen.
+ const created = await page.request.post(`${BASE}/api/terminals`, {
+ data: { cwd: "/tmp", cols: 100, rows: 30 },
+ });
+ expect(created.status()).toBe(201);
+ const { id: seededId } = await created.json();
+ await page.request.post(`${BASE}/api/terminals/${seededId}/keys`, {
+ data: { keys: "echo HOVER_PICK_MARKER", literal: true },
+ });
+ await page.request.post(`${BASE}/api/terminals/${seededId}/keys`, { data: { keys: "Enter" } });
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`${BASE}/api/terminals/${seededId}/capture`);
+ return (await res.json()).lines.join("\n");
+ },
+ { timeout: 20000 },
+ )
+ .toMatch(/^HOVER_PICK_MARKER$/m);
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+
+ // 1. Hovering 创建 opens the menu — no click involved; the terminal row opens the dock
+ // on the seeded shell.
+ await page.locator('[data-testid="panels-all"]').hover();
+ await expect(page.locator('[data-testid="panels-menu-terminal"]')).toBeVisible({
+ timeout: 5000,
+ });
+ // A hover-opened menu must not pull focus: the programmatic focus a click-opened menu
+ // wants would draw a stray :focus-visible ring on the first row of a freshly loaded page.
+ expect(
+ await page.evaluate(
+ () => document.activeElement?.getAttribute("data-testid") ?? document.activeElement?.tagName,
+ ),
+ "hover-open left focus alone",
+ ).not.toBe("panels-menu-agents");
+ await page.locator('[data-testid="panels-menu-terminal"]').click();
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("HOVER_PICK_MARKER");
+
+ // 2. Pin the terminal: hovering ITS icon shows the terminal list; picking the seeded
+ // terminal keeps the dock on it.
+ await page.locator('[data-testid="panels-all"]').hover();
+ await page.locator('[data-testid="panels-pin-terminal"]').click();
+ await page.keyboard.press("Escape");
+ await page.mouse.move(10, 10); // clear hover state before targeting the pinned icon
+ await page.locator('[data-testid="panel-btn-terminal"]').hover();
+ const item = page.locator(
+ `[data-testid="terminal-hover-menu"] [data-testid="terminal-menu-item"][data-terminal-id="${seededId}"]`,
+ );
+ await expect(item).toBeVisible({ timeout: 5000 });
+ await item.click();
+ await expect(dock(page)).toBeVisible();
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("HOVER_PICK_MARKER");
+});
+
+test("a failed shell create shows its error in the pane, and retry recovers", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+
+ // Make terminal creation fail the way a broken pty does server-side (spawn failure).
+ await page.route("**/api/terminals", (route) => {
+ if (route.request().method() === "POST") {
+ return route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({
+ code: "terminal_spawn_failed",
+ message: "Could not start a shell: posix_spawn failed (mock)",
+ }),
+ });
+ }
+ return route.continue();
+ });
+
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+
+ // The pane says WHY instead of sitting blank — the server's message included.
+ const errorCard = page.locator('[data-testid="terminal-dock-error"]');
+ await expect(errorCard).toBeVisible({ timeout: 10000 });
+ await expect(errorCard).toContainText("posix_spawn failed (mock)");
+
+ // Server recovers (unroute) → retry starts a real shell.
+ await page.unroute("**/api/terminals");
+ await page.locator('[data-testid="terminal-dock-retry"]').click();
+ await expect(errorCard).toBeHidden({ timeout: 10000 });
+ await waitForDockShell(page, "RECOVERED_UP");
+});
+
+test("terminal count badge and last-opened persistence", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const sessionId = await createSession(page.request, projectId);
+
+ // Seed one live terminal entirely through the API, with a marker on its screen.
+ const created = await page.request.post(`${BASE}/api/terminals`, {
+ data: { cwd: "/tmp", cols: 100, rows: 30 },
+ });
+ expect(created.status()).toBe(201);
+ const { id: seededId } = await created.json();
+ await page.request.post(`${BASE}/api/terminals/${seededId}/keys`, {
+ data: { keys: "echo LAST_OPENED_MARKER", literal: true },
+ });
+ await page.request.post(`${BASE}/api/terminals/${seededId}/keys`, { data: { keys: "Enter" } });
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`${BASE}/api/terminals/${seededId}/capture`);
+ return (await res.json()).lines.join("\n");
+ },
+ { timeout: 20000 },
+ )
+ .toMatch(/^LAST_OPENED_MARKER$/m);
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+
+ // The badge counts THIS conversation's terminals, and it holds none yet: the seeded shell
+ // belongs to no conversation until one adopts it, and a count of shells this panel would
+ // not show is a count that can never reach zero from here.
+ const badge = page.locator('[data-testid="terminal-count-badge"]');
+ await expect(badge).toHaveCount(0);
+
+ // (A shell no conversation holds is still reachable from the pinned terminal icon's hover
+ // list — covered by the hover-menus test.)
+
+ // Opening the panel from the dropdown adopts the seeded shell rather than creating a
+ // second one: its marker is on the dock screen, and it is now this conversation's one
+ // terminal, so the badge appears at 1.
+ await page.locator('[data-testid="panels-all"]').click();
+ await page.locator('[data-testid="panels-menu-terminal"]').click();
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("LAST_OPENED_MARKER");
+ await expect(badge).toHaveText("1", { timeout: 15000 });
+ await expect(
+ page.locator('[data-testid="panels-all"] [data-testid="terminal-count-badge"]'),
+ ).toBeVisible();
+
+ // The dropdown's terminal row carries the same count.
+ await page.locator('[data-testid="panels-all"]').click();
+ await expect(page.locator('[data-testid="panels-menu-terminal-count"]')).toHaveText("1");
+ await page.keyboard.press("Escape");
+
+ // Pinning the terminal moves the badge onto the terminal's own trigger.
+ await page.locator('[data-testid="panels-all"]').click();
+ await page.locator('[data-testid="panels-pin-terminal"]').click();
+ await page.keyboard.press("Escape");
+ await expect(
+ page.locator('[data-testid="panel-btn-terminal"] [data-testid="terminal-count-badge"]'),
+ ).toBeVisible();
+ await expect(
+ page.locator('[data-testid="panels-all"] [data-testid="terminal-count-badge"]'),
+ ).toHaveCount(0);
+
+ // "New shell" leaves the old shell running: two live terminals now, counted as soon as
+ // the create returns (optimistic list update, not the next poll).
+ await page.locator('[data-testid="terminal-dock-new-shell"]').click();
+ await expect(badge).toHaveText("2", { timeout: 5000 });
+ await waitForDockShell(page, "SECOND_SHELL_UP");
+
+ // Killing every terminal clears the badge entirely (0 renders nothing). A background
+ // terminal dying does not push anything to the tab — the count re-syncs on focus (or the
+ // slow poll), so nudge a focus event while polling instead of waiting out the interval.
+ await killAllTerminals(page.request);
+ await expect
+ .poll(
+ async () => {
+ await page.evaluate(() => window.dispatchEvent(new Event("focus")));
+ return badge.count();
+ },
+ { timeout: 15000 },
+ )
+ .toBe(0);
+});
+
+test("the dock belongs to its Session: switching hides it, coming back restores it", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const first = await createSession(page.request, projectId);
+ const second = await createSession(page.request, projectId);
+
+ await page.goto(`${BASE}/chat/${first}`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await waitForDockShell(page, "SCOPED_SHELL_UP");
+ await runInDock(page, "echo SCOPED_MARKER");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("SCOPED_MARKER");
+
+ // The other conversation never opened a terminal, so it has none to show — the shell
+ // itself keeps running, it is just not this conversation's.
+ await page.locator(`[data-testid="session-row"][data-session-id="${second}"]`).click();
+ await expect(page).toHaveURL(new RegExp(`/chat/${second}$`));
+ await expect(dock(page)).toBeHidden();
+ const { terminals } = await (await page.request.get(`${BASE}/api/terminals`)).json();
+ expect(terminals.filter((t) => t.alive)).toHaveLength(1);
+
+ // Back: the same pane, the same shell, the same screen.
+ await page.locator(`[data-testid="session-row"][data-session-id="${first}"]`).click();
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("SCOPED_MARKER");
+});
+
+test("a side pane and the Workspace panel take turns: whichever was asked for last", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const sessionId = await createSession(page.request, projectId);
+
+ // A dock already arranged on the RIGHT, where it competes with the Workspace panel for
+ // the same horizontal half (terminal-dock-state.ts seeds one entry per Session scope).
+ await page.addInitScript((scope) => {
+ localStorage.setItem(
+ "penguin.terminal.dock",
+ JSON.stringify({
+ [scope]: { visible: true, panes: ["right"], assignments: {}, currents: {} },
+ }),
+ );
+ }, sessionId);
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote"); // a load never opens the dock by itself
+ await expect(dock(page)).toBeVisible({ timeout: 20000 });
+ await waitForDockShell(page, "SIDE_SWAP_UP");
+ await runInDock(page, "echo SIDE_SWAP_MARKER");
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("SIDE_SWAP_MARKER");
+
+ const workspace = page.locator('[data-testid="panel-btn-workspace"]');
+ const paneBox = await dock(page).boundingBox();
+ const paneWidth = paneBox.width;
+ // Where the chat column ends: the outer edge of the resize handle, which the panel counts
+ // as layout and the pane has to as well, or swapping them nudges the column sideways.
+ const paneEdge = (await page.locator('[data-testid="terminal-dock-resizer"]').boundingBox()).x;
+ const topbarWidth = await page.locator('[data-testid="panels-toolbar"]').evaluate((el) => {
+ const bar = el.closest("header") ?? el.parentElement;
+ return Math.round(bar.getBoundingClientRect().width);
+ });
+
+ // Workspace wins: the side pane goes away, and the shell behind it keeps running.
+ await workspace.click();
+ await expect(workspace).toHaveAttribute("aria-expanded", "true");
+ await expect(dock(page)).toBeHidden();
+ // Collapsed, not unmounted — that is what lets the width animate rather than pop, and it
+ // is why the shell's view survives the swap. (Raw selector: the collapsed pane is inert,
+ // which the dock() helper deliberately filters out.)
+ await expect(page.locator('[data-testid="terminal-dock"]')).toHaveCount(1);
+
+ // Same slot, same width: the panel opens exactly as wide as the pane it displaced
+ // (use-panel-width.ts is one value for all three side surfaces). Polled — the open is
+ // sequenced behind the pane's retraction and then slides, so a one-shot read races it.
+ await expect
+ .poll(async () => {
+ const box = await page.locator('[data-testid="files-panel"]').boundingBox();
+ return Math.abs((box?.width ?? 0) - paneWidth);
+ })
+ .toBeLessThanOrEqual(2);
+ // The page's own top bar is untouched either way: both surfaces sit inside the chat body
+ // row, below it — the pane used to flank <main> and squeeze the header with the content.
+ expect(topbarWidth, "top bar width").toBe(
+ await page.locator('[data-testid="panels-toolbar"]').evaluate((el) => {
+ const bar = el.closest("header") ?? el.parentElement;
+ return Math.round(bar.getBoundingClientRect().width);
+ }),
+ );
+ // Same slot down to the handle: identical left edges, so the chat column does not shift.
+ const panelBox = await page.locator('[data-testid="files-panel"]').boundingBox();
+ expect(Math.abs(panelBox.x - paneBox.x), "panel vs pane left edge").toBeLessThanOrEqual(2);
+ const panelEdge = (await page.locator('[data-testid="files-panel-resizer"]').boundingBox()).x;
+ expect(Math.abs(panelEdge - paneEdge), "handle left edge").toBeLessThanOrEqual(2);
+ const { terminals } = await (await page.request.get(`${BASE}/api/terminals`)).json();
+ expect(terminals.filter((t) => t.alive)).toHaveLength(1);
+
+ // Closing it gives the pane back, on the same edge, with its screen intact.
+ await workspace.click();
+ await expect(workspace).toHaveAttribute("aria-expanded", "false");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(dock(page)).toHaveAttribute("data-position", "right");
+ await expect(page.locator('[data-testid="terminal-dock"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("SIDE_SWAP_MARKER");
+
+ // And the other direction: asking for the terminal retracts the panel.
+ await workspace.click();
+ await expect(dock(page)).toBeHidden();
+ await page.keyboard.press("Control+Backquote");
+ await expect(dock(page)).toBeVisible({ timeout: 10000 });
+ await expect(workspace).toHaveAttribute("aria-expanded", "false");
+});
diff --git a/packages/web/e2e/terminal.spec.mjs b/packages/web/e2e/terminal.spec.mjs
new file mode 100644
index 00000000..f6bfe5d9
--- /dev/null
+++ b/packages/web/e2e/terminal.spec.mjs
@@ -0,0 +1,159 @@
+/**
+ * Terminal page (/terminal), the behaviour the whole server-side design exists for:
+ * - a real shell runs in the server and echoes what is typed into it;
+ * - a browser reload reattaches to that same shell and repaints the screen it had —
+ * scrollback, colours and cursor included — instead of starting over;
+ * - the reattached page is a live terminal, not a screenshot of one;
+ * - work started before the reload is still running after it (the shell never restarted);
+ * - "New shell" is the one action that deliberately drops the session;
+ * - the page is deep-linkable: ?id= attaches an existing terminal (the dock's detach
+ * handoff), ?cwd= picks the starting directory of a new one.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const U = "terminaluser";
+const P = "password123";
+
+/** Live shells accumulate across spec reruns on one server; MAX 12/user would 429. */
+async function killAllTerminals(request) {
+ const { terminals } = await (await request.get(`${BASE}/api/terminals`)).json();
+ for (const t of terminals) await request.delete(`${BASE}/api/terminals/${t.id}`);
+ await expect
+ .poll(
+ async () => {
+ const res = await (await request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+ },
+ { timeout: 10000 },
+ )
+ .toBe(0);
+}
+
+/** The DOM renderer keeps the rows as text, so the screen is readable without pixels. */
+const screenText = (page) => page.locator(".xterm-rows").innerText();
+
+async function run(page, command) {
+ await page.click(".xterm-screen");
+ await page.keyboard.type(command);
+ await page.keyboard.press("Enter");
+}
+
+/**
+ * "ready" only means the stream is attached; a login shell may still be sourcing profiles,
+ * and input typed meanwhile sits in the tty buffer until it wakes up. Every test needs a
+ * shell that is actually at a prompt, so probe with a sentinel and wait for its output.
+ */
+async function waitForShell(page, tag) {
+ await expect(page.locator(".xterm-rows")).toBeVisible({ timeout: 20000 });
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ // Quote-split sentinel: the typed command's echo never contains the tag, and the match
+ // is end-of-line — a resize reflow right after attach can glue rows together.
+ await run(page, `echo ${tag.slice(0, 2)}''${tag.slice(2)}`);
+ await expect.poll(() => screenText(page), { timeout: 30000 }).toMatch(new RegExp(`${tag}$`, "m"));
+}
+
+test("keeps the shell and its screen across a reload", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await waitForShell(page, "SHELL_UP_1");
+
+ // Attaching writes the terminal id into the URL so the session survives even a reload
+ // that loses localStorage (and the address is now shareable across windows).
+ expect(page.url()).toMatch(/[?&]id=/);
+
+ // A file only this run writes, appended to by a background loop: proof later that the very
+ // same shell process (not a fresh one) survived the reload.
+ await run(
+ page,
+ "rm -f /tmp/penguin-e2e-ticks; (for i in $(seq 1 30); do echo t >> /tmp/penguin-e2e-ticks; sleep 0.4; done &)",
+ );
+ await run(page, "echo BEFORE_RELOAD_MARKER");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("BEFORE_RELOAD_MARKER");
+ const lastLineBefore = (await screenText(page)).trim().split("\n").at(-1).trim();
+
+ await page.reload();
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+
+ // The screen came back, not a fresh prompt.
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("BEFORE_RELOAD_MARKER");
+ expect(await screenText(page)).toContain(lastLineBefore);
+
+ // ...and it is still interactive.
+ await run(page, "echo AFTER_RELOAD_MARKER");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("AFTER_RELOAD_MARKER");
+
+ // ...and the background loop kept running while no browser was attached, which it could
+ // only do if the shell itself was never restarted.
+ await run(page, "echo ticks=$(wc -l < /tmp/penguin-e2e-ticks)");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toMatch(/^ticks=[2-9]\d*$/m);
+ await run(page, "pkill -f 'penguin-e2e-ticks' >/dev/null 2>&1; rm -f /tmp/penguin-e2e-ticks");
+});
+
+test("New shell starts a fresh session", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await waitForShell(page, "SHELL_UP_2");
+
+ await run(page, "echo DISPOSABLE_MARKER");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("DISPOSABLE_MARKER");
+
+ await page.locator('[data-testid="terminal-new-shell"]').click();
+ await waitForShell(page, "SHELL_UP_3");
+
+ expect(await screenText(page)).not.toContain("DISPOSABLE_MARKER");
+ // The dropped session's id is gone from the URL too (a reload keeps the new shell).
+ await run(page, "echo NEW_URL_CHECK");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("NEW_URL_CHECK");
+});
+
+test("?cwd= starts the shell in the requested directory", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal?cwd=/tmp`);
+ await waitForShell(page, "SHELL_UP_CWD");
+
+ await run(page, "pwd");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toMatch(/^\/tmp$/m);
+});
+
+test("?id= attaches an existing terminal with its screen (deep link)", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+
+ // Drive a terminal entirely through the HTTP control plane first…
+ const created = await page.request.post(`${BASE}/api/terminals`, {
+ data: { cwd: "/tmp", cols: 100, rows: 30 },
+ });
+ expect(created.status()).toBe(201);
+ const { id } = await created.json();
+ await page.request.post(`${BASE}/api/terminals/${id}/keys`, {
+ data: { keys: "echo DEEP_LINK_MARKER", literal: true },
+ });
+ await page.request.post(`${BASE}/api/terminals/${id}/keys`, { data: { keys: "Enter" } });
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`${BASE}/api/terminals/${id}/capture`);
+ return (await res.json()).lines.join("\n");
+ },
+ { timeout: 20000 },
+ )
+ .toMatch(/^DEEP_LINK_MARKER$/m);
+
+ // …then the deep link shows that same screen, live.
+ await page.goto(`${BASE}/terminal?id=${id}`);
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("DEEP_LINK_MARKER");
+ await run(page, "echo DEEP_LINK_LIVE");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("DEEP_LINK_LIVE");
+});
diff --git a/packages/web/package.json b/packages/web/package.json
index 706d3ee7..2b521667 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -16,6 +16,9 @@
"@prismshadow/penguin-core": "workspace:*",
"@shikijs/langs": "^4.3.1",
"@shikijs/themes": "^4.3.1",
+ "@xterm/addon-fit": "^0.10.0",
+ "@xterm/addon-web-links": "^0.11.0",
+ "@xterm/xterm": "^5.5.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index df151c97..bc82df0c 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -4,7 +4,8 @@
* - <md: top thin bar (hamburger -> sidebar drawer + brand name) + main content.
* All chrome uses solid backgrounds and avoids stacking contexts (frosted-glass/transform would trap overlay z-index).
*/
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useState, useSyncExternalStore } from "react";
+import { createPortal } from "react-dom";
import { NavLink, Outlet, useMatch, useNavigate } from "react-router";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
@@ -21,6 +22,22 @@ import { NEW_CHAT_ICON, Sidebar } from "./sidebar";
import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";
import { parkActiveDraft } from "../../features/chat/draft-sessions";
import { ChangePasswordDialog } from "../account/change-password-dialog";
+import { TerminalDock } from "../../features/terminal/terminal-dock";
+import { TerminalDockRuntime } from "../../features/terminal/terminal-view-pool";
+import {
+ dockSlot,
+ dockSlotVersion,
+ subscribeDockSlots,
+} from "../../features/terminal/terminal-dock-slot";
+import {
+ dockStateVersion,
+ isTerminalDockOpen,
+ setDockScope,
+ paneHasSlot,
+ SIDE_SLOT_TRANSITION_MS,
+ visiblePanes,
+ subscribeTerminalDock,
+} from "../../features/terminal/terminal-dock-state";
/** "Last conversation" glyph (chat lines + resume arrow), used only by the rail. */
const LAST_CHAT_ICON = "M8 10h8M8 14h5M21 12a9 9 0 1 1-4.2-7.6L21 4v5h-5";
@@ -169,8 +186,61 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
);
}
+/**
+ * Keeps a side pane mounted through its 200ms collapse after its slot goes away (Ctrl+`,
+ * closing the pane, moving it to another edge). Unmounting the moment the slot empties is
+ * a pop: a width transition needs the node on both ends of it. The pane renders `open`
+ * false for the grace period — width 0, inert — and then unmounts for real, which is what
+ * finally lets the view pool dispose the xterm view.
+ */
+function useLingeringSlot(slot: boolean): boolean {
+ const [lingering, setLingering] = useState(false);
+ useEffect(() => {
+ if (slot) {
+ setLingering(true);
+ return;
+ }
+ if (!lingering) return;
+ const timer = window.setTimeout(() => setLingering(false), SIDE_SLOT_TRANSITION_MS);
+ return () => window.clearTimeout(timer);
+ }, [slot, lingering]);
+ return slot || lingering;
+}
+
export function AppLayout() {
const { user, desktopMode } = useAuth();
+ // The terminal dock belongs to the conversation it was opened in, so switching Sessions
+ // switches the arrangement with it. Pages with no Session of their own leave the scope
+ // where it was — visiting Settings is not leaving the conversation. Layout effect, not a
+ // plain one: it has to land before the panes below paint, or the outgoing conversation's
+ // dock flashes on the incoming one.
+ const dockScope = useMatch("/chat/:sessionId")?.params.sessionId ?? null;
+ useLayoutEffect(() => {
+ if (dockScope !== null) setDockScope(dockScope);
+ }, [dockScope]);
+ // Any dock-state change (panes opening/closing/moving) re-renders the slots below.
+ useSyncExternalStore(subscribeTerminalDock, dockStateVersion);
+ const dockVisible = isTerminalDockOpen();
+ // The arrangement minus anything a chat side panel is displacing (terminal-dock-state.ts).
+ const panes = visiblePanes();
+ // A displaced SIDE pane stays mounted so it can slide out and back on the same 200ms as
+ // the panel that took its place; it renders collapsed (TerminalDock's `open`). Hiding the
+ // dock outright still unmounts, which is what disposes the view. Note this cannot key off
+ // dockVisible: that already answers "is anything on screen", which a displaced pane is not.
+ const hasPane = (p: string) => dockVisible && panes.includes(p as never);
+ // Mounted through the exit collapse too — see useLingeringSlot.
+ const leftMounted = useLingeringSlot(paneHasSlot("left"));
+ const rightMounted = useLingeringSlot(paneHasSlot("right"));
+ // A page may donate a spot for its side panes (terminal-dock-slot.tsx). The chat page does,
+ // so a pane lines up with the panels it shares the slot with — below the page's own top
+ // bar, not squeezing it. Without a donation the pane stays here, beside <main>.
+ useSyncExternalStore(subscribeDockSlots, dockSlotVersion);
+ const sidePane = (position: "left" | "right", mounted: boolean) => {
+ if (!mounted) return null;
+ const pane = <TerminalDock position={position} open={hasPane(position)} />;
+ const slot = dockSlot(position);
+ return slot === null ? pane : createPortal(pane, slot);
+ };
// Desktop shell only (gated inside): system notification when a task finishes while
// the window is unfocused.
useCompletionNotifications();
@@ -230,7 +300,9 @@ export function AppLayout() {
)}
</aside>
- <div className="flex min-w-0 flex-1 flex-col">
+ {/* data-dock-host: the drag-to-dock overlay measures this box for its edge bands,
+ drop-target widget and landing preview (terminal-dock-layout.tsx). */}
+ <div data-dock-host className="flex min-w-0 flex-1 flex-col">
{/* Mobile: top thin bar (hamburger + brand) */}
<header className="flex h-12 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-2 md:hidden dark:border-gray-800 dark:bg-gray-950">
<button
@@ -296,9 +368,21 @@ export function AppLayout() {
</div>
)}
- <main className="min-h-0 flex-1 overflow-hidden">
- <Outlet />
- </main>
+ {/* Integrated terminal (Codex-style), on every page, toggled via Ctrl+` or the
+ chat toolbar. The dock is a set of PANES, at most one per edge; the xterm
+ views live in TerminalDockRuntime's pool and are adopted into pane bodies by
+ DOM handoff, so pane churn (opening, closing, moving edges) never reconnects
+ a terminal. data-dock-row anchors the drag preview's geometry. */}
+ {hasPane("top") && <TerminalDock position="top" />}
+ <div data-dock-row className="flex min-h-0 min-w-0 flex-1">
+ {sidePane("left", leftMounted)}
+ <main className="min-h-0 min-w-0 flex-1 overflow-hidden">
+ <Outlet />
+ </main>
+ {sidePane("right", rightMounted)}
+ </div>
+ {hasPane("bottom") && <TerminalDock position="bottom" />}
+ <TerminalDockRuntime />
</div>
<ChangePasswordDialog
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 2350501e..1b80698d 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -42,7 +42,7 @@ import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import type { LangPref } from "../../state/locale";
import { ACCENT_SWATCHES, useTheme } from "../../state/theme";
-import type { Accent, Currency, FontScale, ThemeMode } from "../../state/theme";
+import type { Accent, Currency, FontScale, TerminalThemeMode, ThemeMode } from "../../state/theme";
import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
import {
@@ -287,8 +287,18 @@ export function Sidebar({
}) {
const navigate = useNavigate();
const { user, logout, desktopMode, sessionVia } = useAuth();
- const { mode, setMode, fontScale, setFontScale, accent, setAccent, currency, setCurrency } =
- useTheme();
+ const {
+ mode,
+ setMode,
+ fontScale,
+ setFontScale,
+ accent,
+ setAccent,
+ currency,
+ setCurrency,
+ terminalMode,
+ setTerminalMode,
+ } = useTheme();
const { lang, locale, setLang } = useLocale();
const {
projects,
@@ -1128,6 +1138,13 @@ export function Sidebar({
{ value: "zh", label: S.settings.langZh },
{ value: "system", label: S.settings.followSystem },
];
+ // The terminal keeps its own light/dark rather than inheriting the app's — see
+ // TerminalThemeMode. "跟随主题" is the opt-in that couples them.
+ const terminalThemeOptions: ReadonlyArray<{ value: TerminalThemeMode; label: string }> = [
+ { value: "light", label: S.settings.themeLight },
+ { value: "dark", label: S.settings.themeDark },
+ { value: "app", label: S.settings.followAppTheme },
+ ];
const fontOptions: ReadonlyArray<{ value: FontScale; label: string }> = [
{ value: "sm", label: S.settings.fontSmall },
{ value: "md", label: S.settings.fontMedium },
@@ -1739,6 +1756,13 @@ export function Sidebar({
<SettingRow label={S.settings.theme}>
<Segmented options={themeOptions} value={mode} onChange={setMode} />
</SettingRow>
+ <SettingRow label={S.settings.terminalTheme}>
+ <Segmented
+ options={terminalThemeOptions}
+ value={terminalMode}
+ onChange={setTerminalMode}
+ />
+ </SettingRow>
<SettingRow label={S.settings.fontSize}>
<Segmented options={fontOptions} value={fontScale} onChange={setFontScale} />
</SettingRow>
@@ -2270,6 +2294,8 @@ function SessionRow({
>
<button
type="button"
+ data-testid="session-row"
+ data-session-id={s.sessionId}
// A press-and-hold that opened the context menu must not also open the Session:
// touch screens replay the held press as a click once the finger lifts.
onClick={() => {
diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsx
index 7a610e2d..3266c056 100644
--- a/packages/web/src/components/ui/dropdown.tsx
+++ b/packages/web/src/components/ui/dropdown.tsx
@@ -58,6 +58,7 @@ export function Dropdown({
anchorRect,
returnFocus,
onEscape,
+ focusOnOpen,
}: {
button: ReactNode;
open: boolean;
@@ -89,6 +90,14 @@ export function Dropdown({
* click means "commit" but Escape means "cancel"). Outside clicks still call setOpen(false).
*/
onEscape?: () => void;
+ /**
+ * Whether opening moves focus into the panel (default true — a click/keyboard-opened
+ * menu must be operable from the keyboard). Pass false for a menu that opens on hover:
+ * the programmatic focus would otherwise draw the `:focus-visible` ring on its first row
+ * (browsers treat scripted focus as keyboard-ish until the page has seen a mouse click),
+ * so merely sweeping the pointer past the trigger leaves a stray outline behind.
+ */
+ focusOnOpen?: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
@@ -121,8 +130,12 @@ export function Dropdown({
// Opening moves focus into the panel (first item), so the menu is operable from the
// keyboard at all. Runs after the panel has mounted, portal or in-flow alike.
+ // Read through a ref so the effect still depends on `open` alone: a caller that flips
+ // focusOnOpen while the menu is open must not make focus jump into the panel.
+ const focusOnOpenRef = useRef(focusOnOpen);
+ focusOnOpenRef.current = focusOnOpen;
useEffect(() => {
- if (!open) return;
+ if (!open || focusOnOpenRef.current === false) return;
panelItems()[0]?.focus();
}, [open, panelItems]);
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 6f0545f3..7767c17b 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -163,4 +163,6 @@ export const NAV_ICONS = {
/** Benchmark center (a trophy: cup + two handles + base). */
benchmark:
"M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",
+ /** Terminal (a `>_` prompt in a window frame). */
+ terminal: "M3 5h18v14H3zM7 9l3 3-3 3M13 15h4",
} as const;
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 1fdcb52a..b5a0dc7e 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -14,7 +14,7 @@
* chosen before sending, and everything except approval mode is locked once the Session is
* created. The Session list and the new-chat entry point live in the global sidebar.
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { ReactNode } from "react";
import { useLocation, useNavigate, useParams } from "react-router";
import type {
@@ -32,6 +32,15 @@ import type {
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
+import {
+ adoptDockScope,
+ chatSidePanelOpen,
+ dockStateVersion,
+ SIDE_SLOT_TRANSITION_MS,
+ setChatSidePanelOpen,
+ subscribeTerminalDock,
+ visiblePanes,
+} from "../terminal/terminal-dock-state";
import { apiErrorText } from "../../lib/api-error";
import { pathFileName } from "../../lib/file-path";
import { useDocumentTitle } from "../../lib/use-document-title";
@@ -101,6 +110,7 @@ import { FilesPanel } from "./files-panel";
import { useFilesPanel } from "./use-files-panel";
import type { FilesPanelState } from "./use-files-panel";
import { SubagentsPanel } from "./subagents-panel";
+import { TerminalDockSlot } from "../terminal/terminal-dock-slot";
import {
advancePanelTaskScope,
createPanelTaskScope,
@@ -109,6 +119,7 @@ import {
import type { SubagentsPanelState } from "./use-subagents-panel";
import { useSessionDraft } from "./use-session-draft";
import { useSessionStream } from "./use-session-stream";
+import { PanelsToolbar } from "./panels-toolbar";
const STAT_ICONS = {
// Tokens (database / stacked cylinders)
@@ -134,7 +145,6 @@ const PROCESS_POLL_MS = 15_000;
* (files-panel.tsx / subagents-panel.tsx) — shorter would cut the retract off, longer
* would leave a dead gap.
*/
-const PANEL_SWAP_MS = 200;
/** Iconized stat item: a symbol + a value, with the title giving the full meaning. */
function StatChip({ icon, value, label }: { icon: string; value: ReactNode; label: string }) {
@@ -350,37 +360,82 @@ export function ChatPage() {
}
};
useEffect(() => cancelPanelSwap, []);
- /** Opens `open` after retracting `closeFirst` when a docked swap needs sequencing; instant otherwise. */
+ /**
+ * Opens `open` after retracting `closeFirst` when a docked swap needs sequencing; instant
+ * otherwise. `retractingPane` extends the same courtesy to a side terminal pane the open
+ * is displacing: it collapses on the same 200ms a closing panel takes, and opening over
+ * it mid-collapse is the wipe the sequencing exists to avoid.
+ */
const swapPanels = (
closeFirst: { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
open: (v: boolean) => void,
+ retractingPane = false,
) => {
closeFirst.setOpen(false);
- if (closeFirst.open && closeFirst.isDocked) {
+ if ((closeFirst.open && closeFirst.isDocked) || retractingPane) {
panelSwapTimer.current = window.setTimeout(() => {
panelSwapTimer.current = null;
open(true);
- }, PANEL_SWAP_MS);
+ }, SIDE_SLOT_TRANSITION_MS);
} else {
open(true);
}
};
+ // The exclusivity above extends to the terminal dock's LEFT and RIGHT panes, which want the
+ // same horizontal half of the content area: opening a panel displaces them, and opening a
+ // side pane retracts the panels. Whichever the user asked for last is what they get. The
+ // dock only learns that a panel is up (setChatSidePanelOpen); it keeps its arrangement, so
+ // closing the panel brings the pane back where it was. Top/bottom panes are unaffected —
+ // they cost height, not width.
+ /** A visible left/right terminal pane — read BEFORE the flag below starts hiding it. */
+ const sidePaneShowing = () => visiblePanes().some((p) => p === "left" || p === "right");
const filesPanel: FilesPanelState = {
...filesPanelRaw,
setOpen: (next: boolean) => {
cancelPanelSwap();
- if (next) swapPanels(subagentsPanelRaw, filesPanelRaw.setOpen);
- else filesPanelRaw.setOpen(false);
+ if (next) {
+ const retracting = sidePaneShowing();
+ setChatSidePanelOpen(true);
+ swapPanels(subagentsPanelRaw, filesPanelRaw.setOpen, retracting);
+ } else {
+ filesPanelRaw.setOpen(false);
+ // The OTHER panel decides whether the side is still held: this one's `open` is the
+ // render-time value and still reads true here.
+ setChatSidePanelOpen(subagentsPanelRaw.open);
+ }
},
};
const subagentsPanel: SubagentsPanelState = {
...subagentsPanelRaw,
setOpen: (next: boolean) => {
cancelPanelSwap();
- if (next) swapPanels(filesPanelRaw, subagentsPanelRaw.setOpen);
- else subagentsPanelRaw.setOpen(false);
+ if (next) {
+ const retracting = sidePaneShowing();
+ setChatSidePanelOpen(true);
+ swapPanels(filesPanelRaw, subagentsPanelRaw.setOpen, retracting);
+ } else {
+ subagentsPanelRaw.setOpen(false);
+ setChatSidePanelOpen(filesPanelRaw.open);
+ }
},
};
+ // The other direction. The store flips this the moment anything puts a terminal on screen
+ // (see terminalTakesTheSide), which is the only signal the page needs: retract both panels
+ // and let the pane render. Edge-triggered, so a panel the user opens is not immediately
+ // closed again — it sets the flag back on its way up.
+ useSyncExternalStore(subscribeTerminalDock, dockStateVersion);
+ const terminalHasTheSide = !chatSidePanelOpen();
+ useEffect(() => {
+ if (!terminalHasTheSide) return;
+ // A sequenced open still waiting on its timer must die with the panels it belongs to:
+ // firing after the terminal reclaimed the side would open a panel over the pane with
+ // the exclusion flag already false — visibly both at once, and nothing to clear it.
+ cancelPanelSwap();
+ filesPanelRaw.setOpen(false);
+ subagentsPanelRaw.setOpen(false);
+ // Panel objects are recreated every render; the raw hooks' setters are stable.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [terminalHasTheSide]);
// Parked draft conversations (`/chat/draft-…`) render the same DraftView as `/chat/new`,
// just bound to their own stored entry — every "this is a draft, not a Session" branch
// below treats the two alike.
@@ -496,6 +551,7 @@ export function ChatPage() {
cancelPanelSwap();
filesPanelRaw.setOpen(false);
subagentsPanelRaw.setOpen(false);
+ setChatSidePanelOpen(false); // nothing holds the side any more: side panes come back
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [draft]);
@@ -528,6 +584,7 @@ export function ChatPage() {
!subagentsPanelRaw.open &&
!filesPanelRaw.open
) {
+ setChatSidePanelOpen(true);
subagentsPanelRaw.setOpen(true);
}
// The panel objects are rebuilt every render; the tracker only acts on real transitions of
@@ -942,6 +999,9 @@ export function ChatPage() {
async (currentId: string, respondedId: string) => {
if (respondedId === currentId) return;
await reloadSessions();
+ // Same conversation under a new id: its terminals follow, or they are stranded under
+ // an id nothing routes to again.
+ adoptDockScope(respondedId);
navigate(`/chat/${respondedId}`, { replace: true });
},
[reloadSessions, navigate],
@@ -1579,73 +1639,18 @@ export function ChatPage() {
)}
</div>
- {/* Subagents panel toggle: latest-Task call graph + child conversations dock on the right (use-subagents-panel.ts); opening closes the Files panel (wrapped setOpen). */}
- <button
- type="button"
- aria-expanded={subagentsPanel.open}
- onClick={() => subagentsPanel.setOpen(!subagentsPanel.open)}
- title={S.chat.openAgents}
- aria-label={S.chat.openAgents}
- className={`flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${
- subagentsPanel.open
- ? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
- : "text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- }`}
- >
- {/* Nodes/network glyph (spawn tree). */}
- <svg
- width="15"
- height="15"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- aria-hidden
- >
- <circle cx="5" cy="12" r="2.5" />
- <circle cx="19" cy="5.5" r="2.5" />
- <circle cx="19" cy="18.5" r="2.5" />
- <path d="M7.4 11 16.7 6.6M7.4 13l9.3 4.4" />
- </svg>
- {/* At md widths the pinned sidebar leaves less room than the viewport breakpoint
- suggests. Keep both panel actions icon-only until lg so the running status and
- live stats retain their own layout space. */}
- <span className="hidden lg:inline">{S.chat.openAgents}</span>
- {/* A pending approval inside a subagent: amber dot (the chip in the stream carries the accessible announcement). */}
- {anySubagentPending && (
- <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-amber-500" />
- )}
- </button>
-
- {/* Files panel toggle: docks on the right of the chat instead of replacing it full-screen (use-files-panel.ts); opening closes the subagents panel (wrapped setOpen). */}
- <button
- type="button"
- aria-expanded={filesPanel.open}
- onClick={() => filesPanel.setOpen(!filesPanel.open)}
- title={S.chat.openWorkspace}
- aria-label={S.chat.openWorkspace}
- className={`flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${
- filesPanel.open
- ? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
- : "text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- }`}
- >
- <svg
- width="15"
- height="15"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- aria-hidden
- >
- <path d={STAT_ICONS.folder} />
- </svg>
- {/* Below lg the button is icon-only (title/aria keep the name): between md and lg
- the pinned sidebar makes the chat toolbar substantially narrower than the
- viewport, so the action labels would squeeze the status into the Token stats. */}
- <span className="hidden lg:inline">{S.chat.openWorkspace}</span>
- </button>
+ {/* Panel switcher (icon-only): pinned panel triggers + the "all panels" dropdown
+ with per-panel pin toggles. Subagents panel docks the latest-Task call graph
+ (use-subagents-panel.ts), Workspace docks the files panel (use-files-panel.ts) —
+ opening either closes the other (wrapped setOpen) — and the terminal toggles the
+ app-wide dock (terminal-dock.tsx). */}
+ <PanelsToolbar
+ agentsOpen={subagentsPanel.open}
+ onToggleAgents={() => subagentsPanel.setOpen(!subagentsPanel.open)}
+ agentsPending={anySubagentPending}
+ workspaceOpen={filesPanel.open}
+ onToggleWorkspace={() => filesPanel.setOpen(!filesPanel.open)}
+ />
{/* Conversation index fallback: exactly when the gutter tick rail can't show
(phones without a hover pointer; a desktop window whose gutter a docked panel
@@ -1912,13 +1917,18 @@ export function ChatPage() {
</div>
)}
- {/* Body: chat column + the docked panels on the right (message file cards jump to and locate a file in the tree via onOpenFile). */}
- <div className="flex min-h-0 flex-1">
+ {/* Body: chat column + the docked panels on the right (message file cards jump to and
+ locate a file in the tree via onOpenFile), and the dock's side panes, which share
+ that slot and so belong on this row rather than around <main> — otherwise they
+ squeeze the header above. data-dock-side-row is what the drop preview measures for
+ a left/right landing. */}
+ <div data-dock-side-row className="flex min-h-0 flex-1">
+ <TerminalDockSlot position="left" />
{/* The chat area, and the only region a dragged file may be dropped on (#311): it
covers the conversation and the composer in both branches below, and nothing else
— the sidebar, the mobile top bar, the toolbar above and the docked panels beside
- it are all outside, where a file drop is inert (see drop-zone.tsx). `relative`
- bounds the drop overlay to this column. */}
+ it (terminal panes included) are all outside, where a file drop is inert (see
+ drop-zone.tsx). `relative` bounds the drop overlay to this column. */}
<ChatDropRegion className="relative flex min-h-0 min-w-0 flex-1 flex-col">
{draft ? (
// Draft state: DraftView's vertically centered input card + Agent / Workspace
@@ -2039,6 +2049,7 @@ export function ChatPage() {
/>
)}
{selected && <FilesPanel session={selected} panel={filesPanel} />}
+ <TerminalDockSlot position="right" />
</div>
<Modal
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 4e51331b..6e47e914 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -48,6 +48,7 @@ import type {
TaskInputPart,
} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
+import { adoptDockScope } from "../terminal/terminal-dock-state";
import { S } from "../../lib/strings";
import { formatMonthDay } from "../../lib/format";
import { apiErrorText } from "../../lib/api-error";
@@ -627,6 +628,10 @@ export function DraftView({
const res = await api.postTask(createdId, { input, ...(goal ? { goal } : {}) });
add(created.session);
if (!keepDraft) discardDraft();
+ // The draft now has an id of its own, so its terminals move with it: every draft
+ // shares one dock scope, and anything left behind under that key would surface in
+ // the NEXT new conversation instead (terminal-dock-state.ts).
+ adoptDockScope(res.sessionId);
navigate(`/chat/${res.sessionId}`, { replace: true });
return true;
} catch (e) {
diff --git a/packages/web/src/features/chat/files-panel.tsx b/packages/web/src/features/chat/files-panel.tsx
index 6609aa7e..f80cb32e 100644
--- a/packages/web/src/features/chat/files-panel.tsx
+++ b/packages/web/src/features/chat/files-panel.tsx
@@ -48,6 +48,7 @@ export function FilesPanel({ session, panel }: { session: SessionInfo; panel: Fi
<>
{panel.open && (
<div
+ data-testid="files-panel-resizer"
onMouseDown={panel.startResize}
onDoubleClick={panel.resetWidth}
title={S.files.resizeHandle}
@@ -57,6 +58,7 @@ export function FilesPanel({ session, panel }: { session: SessionInfo; panel: Fi
/>
)}
<div
+ data-testid="files-panel"
ref={panel.panelRef}
style={{ width: panel.open ? panel.width : 0 }}
// Use inert rather than unmounting when closed: the width transition needs the node to
diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsx
new file mode 100644
index 00000000..a4a85b18
--- /dev/null
+++ b/packages/web/src/features/chat/panels-toolbar.tsx
@@ -0,0 +1,441 @@
+/**
+ * Top-right panel switcher of the chat toolbar (Codex-style): icon-only buttons for the
+ * pinned panels, then an "all panels" dropdown listing every panel with icon + name.
+ *
+ * Three panels exist: the subagents panel ("智能体面板"), the terminal dock and the
+ * Workspace files panel. Which of them get their own toolbar icon is user-configurable via
+ * the pin toggles inside the dropdown (persisted per browser); the default pins the
+ * subagents panel and the Workspace, leaving the terminal reachable through the dropdown
+ * (or Ctrl+`) until pinned.
+ *
+ * The open/close state itself lives with each panel's own hook/store — this component only
+ * renders triggers, so pinning/unpinning never touches panel state.
+ */
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import type { ReactNode } from "react";
+import { S } from "../../lib/strings";
+import { Dropdown } from "../../components/ui/dropdown";
+import { NAV_ICONS } from "../../components/ui/icons";
+import {
+ dockStateVersion,
+ holdsTerminal,
+ showTerminal,
+ subscribeTerminalDock,
+ toggleTerminalDock,
+} from "../terminal/terminal-dock-state";
+import { displayTitle, useTerminalDockOpen } from "../terminal/terminal-dock";
+import { liveTerminals, subscribeTerminals, terminalApiSupported } from "../terminal/terminal-list";
+
+export type PanelKey = "agents" | "terminal" | "workspace";
+
+const PIN_STORAGE_KEY = "penguin.chat.pinnedPanels";
+const DEFAULT_PINS: readonly PanelKey[] = ["agents", "workspace"];
+/** Display order of pinned icons and dropdown rows (the product-specified order). */
+const PANEL_ORDER: readonly PanelKey[] = ["agents", "terminal", "workspace"];
+
+/** Folder glyph, duplicated from the chat stats icons to avoid exporting page internals. */
+const FOLDER_ICON = "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z";
+/** Plus: the "create" trigger opening the panels menu. */
+const CREATE_ICON = "M12 5v14M5 12h14";
+/** Pin (map-pin style tack), shown filled while pinned. */
+const PIN_ICON = "M12 17v5M7 4h10l-1.5 6.5L18 13H6l2.5-2.5z";
+
+function loadPins(): PanelKey[] {
+ try {
+ const raw = localStorage.getItem(PIN_STORAGE_KEY);
+ if (!raw) return [...DEFAULT_PINS];
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [...DEFAULT_PINS];
+ return PANEL_ORDER.filter((key) => parsed.includes(key));
+ } catch {
+ return [...DEFAULT_PINS];
+ }
+}
+
+/** The subagents spawn-tree glyph is multi-element (circles + edges), so it is a component. */
+function AgentsGlyph({ size = 15 }: { size?: number }) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ aria-hidden
+ >
+ <circle cx="5" cy="12" r="2.5" />
+ <circle cx="19" cy="5.5" r="2.5" />
+ <circle cx="19" cy="18.5" r="2.5" />
+ <path d="M7.4 11 16.7 6.6M7.4 13l9.3 4.4" />
+ </svg>
+ );
+}
+
+function PathGlyph({ d, size = 15 }: { d: string; size?: number }) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <path d={d} />
+ </svg>
+ );
+}
+
+export interface PanelsToolbarProps {
+ agentsOpen: boolean;
+ onToggleAgents: () => void;
+ /** A pending approval inside a subagent: amber dot on the agents trigger. */
+ agentsPending: boolean;
+ workspaceOpen: boolean;
+ onToggleWorkspace: () => void;
+}
+
+interface PanelEntry {
+ key: PanelKey;
+ /** Dropdown row copy (the short panel name). */
+ label: string;
+ /** Pinned icon tooltip/aria — kept distinct where an established name exists. */
+ buttonLabel: string;
+ glyph: () => ReactNode;
+ open: boolean;
+ toggle: () => void;
+ pending?: boolean;
+}
+
+const triggerClass = (active: boolean) =>
+ `relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${
+ active
+ ? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
+ : "text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ }`;
+
+/**
+ * Floating count of live terminals. It rides on the terminal's own trigger when the
+ * terminal is pinned, and on the "all panels" trigger otherwise — so the number stays
+ * visible wherever the terminal is actually reachable from. Zero renders nothing.
+ */
+function TerminalCountBadge({ count }: { count: number }) {
+ if (count === 0) return null;
+ return (
+ <span
+ data-testid="terminal-count-badge"
+ aria-hidden
+ className="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-gray-700 px-0.5 text-[9px] font-semibold leading-none text-white dark:bg-gray-300 dark:text-gray-900"
+ >
+ {count}
+ </span>
+ );
+}
+
+/**
+ * Hover-open disclosure: enter opens immediately, leave closes after a short grace so the
+ * pointer can travel from the trigger into the panel without the menu vanishing.
+ */
+function useHoverMenu(): {
+ open: boolean;
+ setOpen: (v: boolean) => void;
+ hoverProps: { onMouseEnter: () => void; onMouseLeave: () => void };
+ /** False while the menu was opened by the pointer — see Dropdown's `focusOnOpen`. */
+ focusOnOpen: boolean;
+} {
+ const [open, setOpen] = useState(false);
+ const [openedByHover, setOpenedByHover] = useState(false);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => () => {
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ },
+ [],
+ );
+ const cancelClose = () => {
+ if (closeTimer.current) {
+ clearTimeout(closeTimer.current);
+ closeTimer.current = null;
+ }
+ };
+ return {
+ open,
+ // Explicit opens (the trigger's click, hence also its keyboard activation) take focus.
+ setOpen: (v: boolean) => {
+ cancelClose();
+ setOpenedByHover(false);
+ setOpen(v);
+ },
+ hoverProps: {
+ onMouseEnter: () => {
+ cancelClose();
+ setOpenedByHover(true);
+ setOpen(true);
+ },
+ onMouseLeave: () => {
+ cancelClose();
+ closeTimer.current = setTimeout(() => setOpen(false), 160);
+ },
+ },
+ focusOnOpen: !openedByHover,
+ };
+}
+
+/**
+ * Rows of live terminals; picking one brings it on screen in its pane. The pick fires on
+ * mousedown: the flyout variant lives outside the Dropdown's panel, whose outside-click
+ * dismissal would otherwise unmount the row before its click event ever dispatched.
+ */
+function TerminalListMenu({ onPick }: { onPick: (id: string) => void }) {
+ const terminals = useSyncExternalStore(subscribeTerminals, liveTerminals);
+ if (terminals.length === 0) {
+ return (
+ <div className="px-3 py-1.5 text-xs text-gray-400 dark:text-gray-500">
+ {S.terminal.noTerminals}
+ </div>
+ );
+ }
+ return (
+ <>
+ {terminals.map((terminal, index) => (
+ <button
+ key={terminal.id}
+ type="button"
+ data-testid="terminal-menu-item"
+ data-terminal-id={terminal.id}
+ onMouseDown={() => onPick(terminal.id)}
+ className="mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">
+ <PathGlyph d={NAV_ICONS.terminal} size={13} />
+ </span>
+ <span className="min-w-0 truncate">
+ {terminal.seq ?? index + 1}: {displayTitle(terminal.title) || terminal.name}
+ </span>
+ </button>
+ ))}
+ </>
+ );
+}
+
+export function PanelsToolbar(props: PanelsToolbarProps) {
+ const terminalOpen = useTerminalDockOpen();
+ // This conversation's terminals, not every live shell. The panel shows one group per
+ // conversation (terminal-dock-state.ts), so a global count promises tabs this panel will
+ // not show: closing the last terminal here would leave the badge sitting at another
+ // conversation's, with no way to reach zero from this one. The menu below still lists
+ // every live shell, which is how one opened elsewhere stays reachable.
+ const allTerminals = useSyncExternalStore(subscribeTerminals, liveTerminals);
+ useSyncExternalStore(subscribeTerminalDock, dockStateVersion);
+ const terminalCount = allTerminals.filter((t) => holdsTerminal(t.id)).length;
+ const [pins, setPins] = useState<PanelKey[]>(loadPins);
+ const createMenu = useHoverMenu();
+ const terminalMenu = useHoverMenu();
+ const terminalPinned = pins.includes("terminal");
+ const menuOpen = createMenu.open;
+ const setMenuOpen = createMenu.setOpen;
+
+ const pickTerminal = (id: string): void => {
+ showTerminal(id);
+ setMenuOpen(false);
+ terminalMenu.setOpen(false);
+ };
+
+ const togglePin = (key: PanelKey): void => {
+ setPins((current) => {
+ const next = current.includes(key)
+ ? current.filter((k) => k !== key)
+ : PANEL_ORDER.filter((k) => current.includes(k) || k === key);
+ try {
+ localStorage.setItem(PIN_STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ // Private-mode storage failures only cost persistence.
+ }
+ return next;
+ });
+ };
+
+ // An older runtime (hot update can leave the Web App ahead of it) has no terminal API;
+ // offering the panel would only produce a 404 on click.
+ const terminalSupported = useSyncExternalStore(subscribeTerminals, terminalApiSupported);
+ const entries: PanelEntry[] = [
+ {
+ key: "agents",
+ label: S.chat.openAgents,
+ buttonLabel: S.chat.openAgents,
+ glyph: () => <AgentsGlyph />,
+ open: props.agentsOpen,
+ toggle: props.onToggleAgents,
+ pending: props.agentsPending,
+ },
+ {
+ key: "terminal",
+ label: S.terminal.title,
+ buttonLabel: S.terminal.title,
+ glyph: () => <PathGlyph d={NAV_ICONS.terminal} />,
+ open: terminalOpen,
+ toggle: toggleTerminalDock,
+ },
+ {
+ key: "workspace",
+ label: S.chat.workspacePanel,
+ // The established accessible name ("打开工作区") — several flows and tests target it.
+ buttonLabel: S.chat.openWorkspace,
+ glyph: () => <PathGlyph d={FOLDER_ICON} />,
+ open: props.workspaceOpen,
+ toggle: props.onToggleWorkspace,
+ },
+ ];
+
+ const panels = entries.filter((entry) => entry.key !== "terminal" || terminalSupported);
+
+ return (
+ <div className="flex shrink-0 items-center gap-1" data-testid="panels-toolbar">
+ {/* Pinned panels: icon-only triggers in fixed order. The terminal trigger also
+ shows the terminal list on hover (first-level dropdown); its click still toggles
+ the dock. */}
+ {panels
+ .filter((entry) => pins.includes(entry.key))
+ .map((entry) => {
+ const trigger = (
+ <button
+ key={entry.key}
+ type="button"
+ aria-expanded={entry.open}
+ onClick={() => {
+ entry.toggle();
+ if (entry.key === "terminal") terminalMenu.setOpen(false);
+ }}
+ title={entry.buttonLabel}
+ aria-label={entry.buttonLabel}
+ data-testid={`panel-btn-${entry.key}`}
+ className={triggerClass(entry.open)}
+ >
+ {entry.glyph()}
+ {entry.pending && (
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-amber-500" />
+ )}
+ {entry.key === "terminal" && <TerminalCountBadge count={terminalCount} />}
+ </button>
+ );
+ if (entry.key !== "terminal" || terminalCount === 0) return trigger;
+ return (
+ <div key={entry.key} {...terminalMenu.hoverProps}>
+ <Dropdown
+ open={terminalMenu.open}
+ setOpen={terminalMenu.setOpen}
+ focusOnOpen={terminalMenu.focusOnOpen}
+ menuClass="right-0 top-full mt-1 w-56 origin-top-right"
+ button={trigger}
+ >
+ <div data-testid="terminal-hover-menu">
+ <TerminalListMenu onPick={pickTerminal} />
+ </div>
+ </Dropdown>
+ </div>
+ );
+ })}
+
+ {/* "Create" menu: opens on hover (click keeps it open for touch/keyboard); every
+ panel as a row with a pin toggle, and the terminal row carries a second-level
+ terminal list on hover. */}
+ <div {...createMenu.hoverProps}>
+ <Dropdown
+ open={menuOpen}
+ setOpen={setMenuOpen}
+ focusOnOpen={createMenu.focusOnOpen}
+ menuClass="right-0 top-full mt-1 w-56 origin-top-right"
+ button={
+ <button
+ type="button"
+ aria-expanded={menuOpen}
+ onClick={() => setMenuOpen(true)}
+ title={S.chat.panelsCreate}
+ aria-label={S.chat.panelsCreate}
+ data-testid="panels-all"
+ className={triggerClass(menuOpen)}
+ >
+ <PathGlyph d={CREATE_ICON} />
+ {!terminalPinned && <TerminalCountBadge count={terminalCount} />}
+ </button>
+ }
+ >
+ {panels.map((entry) => {
+ const pinned = pins.includes(entry.key);
+ return (
+ <div
+ key={entry.key}
+ className={`group relative mx-1 flex items-center gap-2 rounded-md px-2 py-1.5 text-sm ${
+ entry.open
+ ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
+ : "text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ }`}
+ >
+ {/* The row body toggles the panel and dismisses the menu. */}
+ <button
+ type="button"
+ data-testid={`panels-menu-${entry.key}`}
+ onClick={() => {
+ setMenuOpen(false);
+ entry.toggle();
+ }}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">{entry.glyph()}</span>
+ <span className="min-w-0 truncate">{entry.label}</span>
+ {/* Live shell count, right beside the name — the row's right edge belongs
+ to the pin toggle (a hover-revealed slot that must not look like a gap
+ next to content). */}
+ {entry.key === "terminal" && terminalCount > 0 && (
+ <span
+ data-testid="panels-menu-terminal-count"
+ className="shrink-0 rounded-full bg-gray-200 px-1.5 text-[10px] font-semibold leading-4 text-gray-700 dark:bg-gray-700 dark:text-gray-200"
+ >
+ {terminalCount}
+ </span>
+ )}
+ <span className="min-w-0 flex-1" />
+ {entry.pending && (
+ <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500" />
+ )}
+ </button>
+ {/* Pin toggle: keeps the menu open so several pins can be adjusted in one go. */}
+ <button
+ type="button"
+ title={pinned ? S.chat.unpinPanel : S.chat.pinPanel}
+ aria-label={pinned ? S.chat.unpinPanel : S.chat.pinPanel}
+ aria-pressed={pinned}
+ data-testid={`panels-pin-${entry.key}`}
+ onClick={() => togglePin(entry.key)}
+ className={`shrink-0 rounded p-1 transition-colors duration-150 ${
+ pinned
+ ? "text-gray-700 dark:text-gray-200"
+ : "text-gray-300 opacity-0 hover:text-gray-600 group-hover:opacity-100 focus-visible:opacity-100 dark:text-gray-600 dark:hover:text-gray-300"
+ }`}
+ >
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill={pinned ? "currentColor" : "none"}
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <path d={PIN_ICON} />
+ </svg>
+ </button>
+ </div>
+ );
+ })}
+ </Dropdown>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/use-panel-width.ts b/packages/web/src/features/chat/use-panel-width.ts
index 1f313933..4449808e 100644
--- a/packages/web/src/features/chat/use-panel-width.ts
+++ b/packages/web/src/features/chat/use-panel-width.ts
@@ -1,11 +1,14 @@
/**
- * Width shared by the chat page's two docked panels (Workspace files and Agents), plus the
- * drag-to-resize machinery both of them mount.
+ * Width shared by everything that docks beside the chat: the Workspace files panel, the
+ * Agents panel, and a left or right terminal pane — plus the drag-to-resize machinery the
+ * two panels mount.
*
- * The panels are MUTUALLY EXCLUSIVE — opening one closes the other — so to the user they read
- * as a single right-hand panel that swaps its content. Two independent widths made that swap
- * jump, which is why the width is one value here rather than a per-panel preference: a width
- * dragged on either panel is the width the other one opens at, immediately and after a reload.
+ * All three are MUTUALLY EXCLUSIVE — opening one displaces the others — so to the user they
+ * read as a single side panel that swaps its content. Independent widths made that swap
+ * jump, which is why the width is one value here rather than a per-surface preference: a
+ * width dragged on any of them is the width the next one opens at, immediately and after a
+ * reload. The terminal pane brings its own resize gesture (it can dock on either side) and
+ * writes through setPanelWidth.
*
* "Immediately" is what rules out two `useState`s over one storage key: only the panel that was
* mounted and dragged would update, and the other would keep a stale copy until its next
@@ -21,21 +24,6 @@ import { createStore } from "zustand/vanilla";
const MIN_WIDTH = 320;
const WIDTH_STORAGE_KEY = "penguin.panelWidth";
-/**
- * Pre-unification per-panel keys, adopted once on first load so a dragged width survives the
- * merge instead of silently snapping back to the default. The WIDER of the two wins: the two
- * panels were sized independently, so picking either one arbitrarily could hand the merged
- * panel the narrower of the user's two choices — visibly a regression on the panel that used
- * to be wide. The migration deletes the keys as it reads, so it is already dead code for anyone
- * who has opened the app once since this shipped.
- *
- * REMOVAL: delete this constant and storedWidth()'s legacy branch while preparing the release
- * AFTER 0.2.0 — the 0.1.5 backward-compatibility entry schedules it for the second release
- * after the one shipping this change (0.2.0 was the first and deliberately kept it). Nothing
- * else in the repo reads these keys, so it is a pure deletion.
- * See changelog/0.1.5/2026-07-30-backward-compatibility.md.
- */
-const LEGACY_WIDTH_KEYS = ["penguin.filesPanelWidth", "penguin.subagentsPanelWidth"] as const;
/** Width cap: at most half the window (keeping the chat column usable), plus a hard 720px readability ceiling. */
export function maxWidthFor(windowWidth: number): number {
@@ -52,21 +40,11 @@ export function defaultWidthFor(windowWidth: number): number {
return Math.min(maxWidthFor(windowWidth), Math.max(MIN_WIDTH, Math.round(windowWidth * 0.4)));
}
-/** Reads the stored preference, migrating a legacy per-panel key the first time. Returns null when nothing is stored. */
+/** Reads the stored preference; null when nothing is stored (or storage is unreadable). */
function storedWidth(): number | null {
try {
const own = Number(localStorage.getItem(WIDTH_STORAGE_KEY));
- if (Number.isFinite(own) && own > 0) return own;
- let adopted: number | null = null;
- for (const key of LEGACY_WIDTH_KEYS) {
- const legacy = Number(localStorage.getItem(key));
- // Widest wins — see LEGACY_WIDTH_KEYS: the merged panel must not come out narrower than
- // either panel the user had sized.
- if (Number.isFinite(legacy) && legacy > 0) adopted = Math.max(adopted ?? 0, legacy);
- localStorage.removeItem(key);
- }
- if (adopted !== null) localStorage.setItem(WIDTH_STORAGE_KEY, String(Math.round(adopted)));
- return adopted;
+ return Number.isFinite(own) && own > 0 ? own : null;
} catch {
return null; // quota / private mode: fall back to the proportional default
}
@@ -111,6 +89,40 @@ export interface PanelWidthState {
panelRef: RefObject<HTMLDivElement | null>;
}
+/** The current shared width, read outside React (measuring a drop region mid-drag). */
+export function panelWidth(): number {
+ return readWidth();
+}
+
+/** Subscribes to the shared width alone — for a consumer with its own resize gesture. */
+export function usePanelWidthValue(): number {
+ return useStore(widthStore, () => readWidth());
+}
+
+/** Sets the shared width from another surface's drag, clamped to the same bounds. */
+export function setPanelWidth(px: number): void {
+ writeWidth(Math.min(maxWidthFor(window.innerWidth), Math.max(MIN_WIDTH, Math.round(px))));
+}
+
+/** Persists the current width; call once at the end of a drag, not per frame. */
+export function persistPanelWidth(): void {
+ try {
+ localStorage.setItem(WIDTH_STORAGE_KEY, String(Math.round(readWidth())));
+ } catch {
+ /* best-effort persistence (quota / private mode) */
+ }
+}
+
+/** Back to the window-proportional default, clearing the stored preference. */
+export function resetPanelWidth(): void {
+ writeWidth(defaultWidthFor(window.innerWidth));
+ try {
+ localStorage.removeItem(WIDTH_STORAGE_KEY);
+ } catch {
+ /* best-effort */
+ }
+}
+
/**
* The shared width plus this panel's own drag state. `resizing` and `panelRef` stay per-panel
* (each panel has its own DOM node and its own handle); only the width crosses between them.
@@ -133,11 +145,7 @@ export function usePanelWidth(): PanelWidthState {
// Only persist once the drag ends: mousemove fires every frame, and it's not worth writing to localStorage on every frame.
const onUp = () => {
setResizing(false);
- try {
- localStorage.setItem(WIDTH_STORAGE_KEY, String(Math.round(readWidth())));
- } catch {
- /* best-effort persistence (quota / private mode) */
- }
+ persistPanelWidth();
};
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
@@ -156,16 +164,9 @@ export function usePanelWidth(): PanelWidthState {
setResizing(true);
}, []);
- const resetWidth = useCallback(() => {
- writeWidth(defaultWidthFor(window.innerWidth));
- // Clears rather than writing the default value: this way the default keeps following the
- // window's proportion going forward, instead of being frozen at the current pixel value.
- try {
- localStorage.removeItem(WIDTH_STORAGE_KEY);
- } catch {
- /* best-effort */
- }
- }, []);
+ // Clears rather than writing the default value: this way the default keeps following the
+ // window's proportion going forward, instead of being frozen at the current pixel value.
+ const resetWidth = useCallback(resetPanelWidth, []);
// When the window shrinks, clamp the width back within the cap so the docked panel can't
// crowd out the chat column. Shrinks only, never grows back, and never overwrites the stored
diff --git a/packages/web/src/features/terminal/terminal-appearance.ts b/packages/web/src/features/terminal/terminal-appearance.ts
new file mode 100644
index 00000000..a3890373
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-appearance.ts
@@ -0,0 +1,68 @@
+/**
+ * The terminal's chrome palette, resolved in JS rather than through Tailwind's `dark:`.
+ *
+ * That variant is anchored on the root class (`&:where(.dark, .dark *)` in styles.css), so
+ * a subtree can opt IN to dark but never out of it — and the terminal's appearance is its
+ * own setting (see TerminalThemeMode), which means a light terminal inside a dark app has
+ * to be expressible. Hence whole class strings picked by a resolved boolean.
+ *
+ * The values are the same gray pairs the rest of the app uses; only the way they are
+ * selected differs. What the terminal SCREEN uses is a separate concern — the sixteen ANSI
+ * colours live in terminal-view.tsx.
+ */
+import { useTheme } from "../../state/theme";
+
+export interface TerminalChrome {
+ /** True when the terminal is painting dark, whatever the app is doing. */
+ dark: boolean;
+ /** Pane/page background and default text. */
+ surface: string;
+ /** Border colour for the pane edge and the header rule (pair with border-b/border-t/…). */
+ border: string;
+ /** Header icon buttons (detach, new shell, close). */
+ iconButton: string;
+ /** The header's drag grip. */
+ grip: string;
+ tabActive: string;
+ tabIdle: string;
+ /** The tab's hover-revealed kill button: an opaque backdrop matching the tab under it. */
+ tabKill: string;
+ /** Secondary text (a path, an error detail). */
+ muted: string;
+ /** Failure headline. */
+ danger: string;
+ /** Bordered text button (retry, detach on the standalone page). */
+ outlineButton: string;
+}
+
+const DARK: TerminalChrome = {
+ dark: true,
+ surface: "bg-gray-950 text-gray-100",
+ border: "border-gray-800",
+ iconButton: "text-gray-400 hover:bg-gray-800 hover:text-gray-200",
+ grip: "text-gray-600",
+ tabActive: "bg-gray-800 text-gray-100",
+ tabIdle: "text-gray-400 hover:bg-gray-800 hover:text-gray-200",
+ tabKill: "bg-gray-800 hover:bg-gray-700",
+ muted: "text-gray-400",
+ danger: "text-red-400",
+ outlineButton: "border-gray-700 text-gray-300 hover:bg-gray-800",
+};
+
+const LIGHT: TerminalChrome = {
+ dark: false,
+ surface: "bg-white text-gray-900",
+ border: "border-gray-200",
+ iconButton: "text-gray-500 hover:bg-gray-100 hover:text-gray-800",
+ grip: "text-gray-400",
+ tabActive: "bg-gray-100 text-gray-900",
+ tabIdle: "text-gray-500 hover:bg-gray-100 hover:text-gray-800",
+ tabKill: "bg-gray-100 hover:bg-gray-200",
+ muted: "text-gray-500",
+ danger: "text-red-600",
+ outlineButton: "border-gray-300 text-gray-600 hover:bg-gray-100",
+};
+
+export function useTerminalChrome(): TerminalChrome {
+ return useTheme().terminalDark ? DARK : LIGHT;
+}
diff --git a/packages/web/src/features/terminal/terminal-dock-layout.tsx b/packages/web/src/features/terminal/terminal-dock-layout.tsx
new file mode 100644
index 00000000..03088b45
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-dock-layout.tsx
@@ -0,0 +1,198 @@
+/**
+ * Drag-to-dock: the overlay UI and hit-testing behind dragging the dock's header to move
+ * the terminal panel to another edge of the content area.
+ *
+ * Two ways to pick a position while dragging, both live-previewing before anything moves:
+ * 1. drag straight into an edge band of the content area (`[data-dock-host]`, the column
+ * AppLayout lays the dock out in) — the nearest edge within the band is the candidate;
+ * 2. drop targets: a small widget in the bottom-right of the content area with two
+ * containers — a top/bottom pair and a left/right pair of rectangles — hovering a
+ * rectangle makes that edge the candidate (and wins over edge detection).
+ * The preview is a translucent region covering exactly where the dock would land;
+ * releasing the pointer applies the candidate, releasing anywhere else changes nothing.
+ *
+ * Hit-testing uses elementFromPoint because the drag runs under pointer capture (the
+ * header owns the pointer), so CSS hover never fires on the overlay.
+ */
+import { createPortal } from "react-dom";
+import { panelWidth } from "../chat/use-panel-width";
+import type { CSSProperties } from "react";
+import {
+ DOCK_MIN_HEIGHT_PX,
+ DOCK_RATIO_MAX,
+ isHorizontal,
+ paneRatio,
+ type DockPosition,
+} from "./terminal-dock-state";
+
+/** Fraction of the host's width/height that counts as an edge band for direct drops. */
+const EDGE_BAND = 0.45;
+
+function dockHostRect(): DOMRect | null {
+ return document.querySelector("[data-dock-host]")?.getBoundingClientRect() ?? null;
+}
+
+/**
+ * Everything needed to draw the preview as the region a pane at the candidate edge would
+ * REALLY occupy — measured from the live layout, not assumed:
+ * - a pane already open on that edge contributes its exact rendered rect;
+ * - otherwise the edge's stored ratio applies, clamped exactly like the pane's own CSS
+ * (px minimums, ratio ceiling);
+ * - `contentTop` excludes the host's non-dock chrome (mobile header, notice banner): the
+ * layout row starts below that chrome, so its top is the content top.
+ */
+interface DockGeometry {
+ host: DOMRect;
+ /** Top of the region a TOP pane would occupy: below the app chrome. */
+ contentTop: number;
+ /** Top of the region a SIDE pane would occupy: the page's donated row, when it has one. */
+ sideTop: number;
+}
+
+function clampSize(value: number, minPx: number, max: number): number {
+ return Math.min(max, Math.max(Math.min(minPx, max), value));
+}
+
+function measureDockGeometry(): DockGeometry | null {
+ const host = dockHostRect();
+ if (!host) return null;
+ const row = document.querySelector("[data-dock-row]")?.getBoundingClientRect() ?? null;
+ const contentTop = row ? Math.max(host.top, row.top) : host.top;
+ // A side pane lands wherever the page donated a slot (terminal-dock-slot.tsx) — on the
+ // chat page that is below its top bar, not the full dock row. The preview has to promise
+ // the region the drop actually gives, so it measures that row when there is one.
+ const sideRow = document.querySelector("[data-dock-side-row]")?.getBoundingClientRect();
+ const sideTop = sideRow ? Math.max(contentTop, sideRow.top) : contentTop;
+ return { host, contentTop, sideTop };
+}
+
+/** The rendered rect of an already-open pane at `position`, if any. */
+function openPaneRect(position: DockPosition): DOMRect | null {
+ return (
+ document
+ .querySelector<HTMLElement>(`[data-testid='terminal-dock'][data-position='${position}']`)
+ ?.getBoundingClientRect() ?? null
+ );
+}
+
+/** Resolves the drop candidate for a pointer position: widget rectangles first, then edge bands. */
+export function dockDropCandidate(x: number, y: number): DockPosition | null {
+ const overTarget = document
+ .elementFromPoint(x, y)
+ ?.closest?.("[data-dock-pos]") as HTMLElement | null;
+ if (overTarget?.dataset.dockPos) return overTarget.dataset.dockPos as DockPosition;
+
+ const rect = dockHostRect();
+ if (!rect || x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return null;
+ const fractions: Array<[DockPosition, number]> = [
+ ["left", (x - rect.left) / rect.width],
+ ["right", (rect.right - x) / rect.width],
+ ["top", (y - rect.top) / rect.height],
+ ["bottom", (rect.bottom - y) / rect.height],
+ ];
+ fractions.sort((a, b) => a[1] - b[1]);
+ const nearest = fractions[0]!;
+ return nearest[1] <= EDGE_BAND ? nearest[0] : null;
+}
+
+/** The exact region a pane at `position` would occupy after the drop. */
+function previewStyle(geometry: DockGeometry, position: DockPosition): CSSProperties {
+ const { host, contentTop, sideTop } = geometry;
+ const contentHeight = host.bottom - contentTop;
+ const sideHeight = host.bottom - sideTop;
+ const existing = openPaneRect(position);
+ // Height percentages resolve against the HOST column (top/bottom panes are its direct
+ // children), so the ratio's px value uses host.height — the region is then clipped to
+ // the content area below the chrome.
+ const height = Math.min(
+ existing && isHorizontal(position)
+ ? existing.height
+ : clampSize(
+ paneRatio(position) * host.height,
+ DOCK_MIN_HEIGHT_PX,
+ DOCK_RATIO_MAX * host.height,
+ ),
+ contentHeight,
+ );
+ // A side pane's width is the shared panel width in pixels (use-panel-width.ts), not a
+ // ratio of the host — the preview has to promise the same region the drop actually gives.
+ const width = Math.min(
+ existing && !isHorizontal(position) ? existing.width : panelWidth(),
+ host.width,
+ );
+ switch (position) {
+ case "top":
+ return { left: host.left, top: contentTop, width: host.width, height };
+ case "bottom":
+ return { left: host.left, top: host.bottom - height, width: host.width, height };
+ case "left":
+ return { left: host.left, top: sideTop, width, height: sideHeight };
+ case "right":
+ return { left: host.right - width, top: sideTop, width, height: sideHeight };
+ }
+}
+
+/** One drop rectangle. A div, not a button: it is only ever "clicked" by a pointer release. */
+function DropTarget(props: {
+ position: DockPosition;
+ candidate: DockPosition | null;
+ shape: string;
+}) {
+ const active = props.candidate === props.position;
+ return (
+ <div
+ data-dock-pos={props.position}
+ data-testid="dock-layout-target"
+ className={`${props.shape} rounded-[3px] border transition-colors duration-100 ${
+ active
+ ? "border-sky-400 bg-sky-500/60"
+ : "border-gray-400/70 bg-gray-500/10 dark:border-white/30 dark:bg-white/10"
+ }`}
+ />
+ );
+}
+
+/**
+ * Rendered (through a body portal) only while a header drag is in flight. `candidate` is
+ * what the drag currently points at; `null` means "release changes nothing".
+ */
+export function DockLayoutOverlay({ candidate }: { candidate: DockPosition | null }) {
+ const geometry = measureDockGeometry();
+ if (!geometry) return null;
+ const rect = geometry.host;
+
+ return createPortal(
+ <>
+ {/* Live preview of the exact region the dock would occupy after the move.
+ pointer-events-none so hit-testing underneath (elementFromPoint) keeps seeing the
+ drop targets, not the preview. */}
+ {candidate && (
+ <div
+ data-testid="dock-layout-preview"
+ data-pos={candidate}
+ aria-hidden
+ className="pointer-events-none fixed z-[65] rounded-sm border border-sky-400/70 bg-sky-500/20"
+ style={previewStyle(geometry, candidate)}
+ />
+ )}
+
+ {/* Drop-target widget: a top/bottom container and a left/right container, kept a
+ comfortable margin off the host's corner. */}
+ <div
+ data-testid="dock-layout-widget"
+ className="fixed z-[70] flex items-center gap-3"
+ style={{ left: rect.right - 172, top: rect.bottom - 96 }}
+ >
+ <div className="flex flex-col items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2.5 shadow-lg dark:border-white/20 dark:bg-gray-900/90">
+ <DropTarget position="top" candidate={candidate} shape="h-3.5 w-10" />
+ <DropTarget position="bottom" candidate={candidate} shape="h-3.5 w-10" />
+ </div>
+ <div className="flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2.5 shadow-lg dark:border-white/20 dark:bg-gray-900/90">
+ <DropTarget position="left" candidate={candidate} shape="h-9 w-4.5" />
+ <DropTarget position="right" candidate={candidate} shape="h-9 w-4.5" />
+ </div>
+ </div>
+ </>,
+ document.body,
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-dock-slot.tsx b/packages/web/src/features/terminal/terminal-dock-slot.tsx
new file mode 100644
index 00000000..3ce65f3a
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-dock-slot.tsx
@@ -0,0 +1,62 @@
+/**
+ * Where a page wants the dock's side panes to live.
+ *
+ * The dock is app-global — it renders on every route from AppLayout, which knows nothing
+ * about any page's insides. Left/right panes therefore sat beside `<main>`, taking width
+ * from the whole of it, which squeezed a page's own header along with its content. The chat
+ * page's Agents and Workspace panels do not do that: they live INSIDE the page, below its
+ * top bar, beside the content only. A pane that shares a slot with those panels has to sit
+ * where they sit.
+ *
+ * So a page may donate a position. `<TerminalDockSlot position="right" />` marks a spot in
+ * the page's own layout, and AppLayout portals the pane into it instead of using its own
+ * row. Pages that donate nothing keep the old placement, which is the right answer for a
+ * page with no panel of its own to line up with.
+ *
+ * The slot is `display: contents`, so it adds no box: the pane and its resize handle become
+ * flex children of the page's row directly, exactly as the panels are.
+ */
+import { useEffect, useRef } from "react";
+import type { DockPosition } from "./terminal-dock-state";
+
+type SideSlot = "left" | "right";
+
+const slots = new Map<SideSlot, HTMLElement>();
+const listeners = new Set<() => void>();
+let version = 0;
+
+function notify(): void {
+ version += 1;
+ for (const listener of [...listeners]) listener();
+}
+
+export function subscribeDockSlots(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Monotonic change counter — a useSyncExternalStore snapshot for slot registration. */
+export function dockSlotVersion(): number {
+ return version;
+}
+
+/** The node a page donated for this side, or null to use AppLayout's own row. */
+export function dockSlot(position: DockPosition): HTMLElement | null {
+ return position === "left" || position === "right" ? (slots.get(position) ?? null) : null;
+}
+
+export function TerminalDockSlot({ position }: { position: SideSlot }) {
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const node = ref.current;
+ if (!node) return;
+ slots.set(position, node);
+ notify();
+ return () => {
+ // Only if still ours: a remount registers the new node before the old one cleans up.
+ if (slots.get(position) === node) slots.delete(position);
+ notify();
+ };
+ }, [position]);
+ return <div ref={ref} className="contents" />;
+}
diff --git a/packages/web/src/features/terminal/terminal-dock-state.ts b/packages/web/src/features/terminal/terminal-dock-state.ts
new file mode 100644
index 00000000..6d2d976e
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-dock-state.ts
@@ -0,0 +1,586 @@
+/**
+ * State of the in-app terminal dock system, as a tiny module-level store.
+ *
+ * The dock is a set of PANES, at most one per edge of the content area. Terminals are
+ * assigned to a pane (dragging a tab onto an edge moves it, creating the pane on demand);
+ * each pane remembers which of its terminals it is showing. One `visible` flag hides and
+ * restores the whole arrangement (Ctrl+`), so a toggle never loses the layout.
+ *
+ * The arrangement is SCOPED to the conversation it was opened in. Switching Sessions
+ * switches the whole dock with it — a Session that never opened a terminal shows none, and
+ * coming back restores the panes and tabs that were there. The shells themselves are
+ * per-user and keep running regardless; a scope only decides which of them are on screen
+ * here. Pages with no Session of their own (settings, Agents, …) keep the last one's dock
+ * rather than blanking it, since navigating to a settings page is not leaving the
+ * conversation; and a dock opened before any conversation was chosen is handed to the
+ * first one that is (see setDockScope).
+ *
+ * A side pane and the chat's Agents/Workspace panel both want the horizontal half of the
+ * content area, so only one of them is on screen: whichever the user opened last. That is
+ * an exclusion, not a close — the losing side keeps its arrangement and comes back when the
+ * winner goes away (see setChatSidePanelOpen).
+ *
+ * A store (rather than component state) because the consumers live far apart: the chat
+ * toolbar and the global hotkey flip visibility, AppLayout renders a pane per open edge,
+ * and the drag/drop interactions inside any pane reshape the arrangement. Everything
+ * persists so a reload restores panes, sizes and assignments the same way the shells
+ * behind them survive server-side.
+ */
+
+/** Every scope's arrangement, in one entry: `Record<scope, DockScopeState>`. */
+const DOCK_KEY = "penguin.terminal.dock";
+/** How tall the user likes a pane is one preference, not one per conversation. */
+const RATIOS_KEY = "penguin.terminal.dockRatios";
+/** Scopes kept in storage; past that, the least recently touched conversations age out. */
+const MAX_SCOPES = 40;
+
+/** Which edge of the content area a pane occupies. */
+export type DockPosition = "top" | "bottom" | "left" | "right";
+
+const POSITIONS: readonly DockPosition[] = ["top", "bottom", "left", "right"];
+
+/**
+ * A top/bottom pane's HEIGHT is a ratio of the layout row. The px minimum (and the ratio
+ * ceiling, which also leaves the main content room) are enforced both by the pane's CSS and
+ * by the drag preview.
+ *
+ * A left/right pane's WIDTH is not here: it is the width shared with the chat's Workspace
+ * and Agents panels (use-panel-width.ts), since the three take turns in the same slot.
+ */
+export const DEFAULT_DOCK_HEIGHT_RATIO = 0.4;
+const DOCK_RATIO_MIN = 0.15;
+export const DOCK_RATIO_MAX = 0.85;
+export const DOCK_MIN_HEIGHT_PX = 140;
+
+export function isHorizontal(position: DockPosition): boolean {
+ return position === "top" || position === "bottom";
+}
+
+function clampRatio(value: number): number {
+ if (!Number.isFinite(value)) return DOCK_RATIO_MIN;
+ return Math.min(DOCK_RATIO_MAX, Math.max(DOCK_RATIO_MIN, value));
+}
+
+function readJson<T>(key: string, fallback: T): T {
+ try {
+ const raw = localStorage.getItem(key);
+ if (raw === null) return fallback;
+ const parsed: unknown = JSON.parse(raw);
+ // `null` parses fine and then blows up on the first property read.
+ return typeof parsed === "object" && parsed !== null ? (parsed as T) : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+function writeJson(key: string, value: unknown): void {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // Private-mode storage failures only cost persistence.
+ }
+}
+
+/**
+ * Last failure while resolving/creating a pane's shell (not persisted). Shown in the pane
+ * body: a blank panel with the cause swallowed is indistinguishable from "working" — the
+ * exact bug reported on macOS, where terminal creation failed server-side and nothing
+ * anywhere said so.
+ */
+let paneErrors: Partial<Record<DockPosition, string>> = {};
+
+/** One conversation's arrangement — everything `setDockScope` swaps. */
+interface DockScopeState {
+ visible: boolean;
+ panes: DockPosition[];
+ /** terminalId -> pane. This is also the MEMBERSHIP list: an id absent here is not shown. */
+ assignments: Record<string, DockPosition>;
+ /** Which terminal each pane is showing. */
+ currents: Partial<Record<DockPosition, string>>;
+}
+
+function emptyScope(): DockScopeState {
+ return { visible: false, panes: [], assignments: {}, currents: {} };
+}
+
+/**
+ * The scope the dock belongs to before any conversation is open — the login screen, a
+ * settings page reached directly by URL. A real Session id never collides with it.
+ */
+const NO_SESSION_SCOPE = "~none";
+
+/**
+ * One stored scope, made safe to use. Storage is user-writable and survives across
+ * versions, so a malformed entry has to degrade to an empty dock — this runs at module
+ * load, where a throw would take the whole app down with it.
+ */
+function sanitizeScope(raw: unknown): DockScopeState {
+ const state = (raw ?? {}) as Partial<DockScopeState>;
+ const panes = Array.isArray(state.panes)
+ ? state.panes.filter((p): p is DockPosition => POSITIONS.includes(p))
+ : [];
+ const entries = (value: unknown): Array<[string, unknown]> =>
+ typeof value === "object" && value !== null ? Object.entries(value) : [];
+ return {
+ // Deliberately NOT the stored value: a fresh load starts with the dock closed. The
+ // ARRANGEMENT persists — panes, tabs, which terminal each showed — so reopening comes
+ // back to exactly what was there; what does not persist is being open, because a
+ // terminal panel unfurling on its own at startup is not something anyone asked for.
+ // Within one page load it is remembered as usual: this only runs at the storage
+ // boundary, and scope switches read the in-memory map.
+ visible: false,
+ panes,
+ assignments: Object.fromEntries(
+ entries(state.assignments).filter((entry): entry is [string, DockPosition] =>
+ POSITIONS.includes(entry[1] as DockPosition),
+ ),
+ ),
+ currents: Object.fromEntries(
+ entries(state.currents).filter(
+ (entry): entry is [DockPosition, string] =>
+ POSITIONS.includes(entry[0] as DockPosition) && typeof entry[1] === "string",
+ ),
+ ),
+ };
+}
+
+let scopes: Record<string, DockScopeState> = Object.fromEntries(
+ Object.entries(readJson<Record<string, unknown>>(DOCK_KEY, {})).map(([key, value]) => [
+ key,
+ sanitizeScope(value),
+ ]),
+);
+let scope = NO_SESSION_SCOPE;
+
+let ratios: Partial<Record<DockPosition, number>> = readJson(RATIOS_KEY, {});
+
+// Unpacked into locals rather than read through `scopes[scope]` everywhere: the reads are
+// on every render path, and the stable references are what let `openPanes()` be a valid
+// useSyncExternalStore snapshot.
+let { visible, panes, assignments, currents } = scopes[scope] ?? emptyScope();
+
+/** Writes the live locals back into the scope map and persists it. */
+function persist(): void {
+ const state: DockScopeState = { visible, panes, assignments, currents };
+ // An untouched scope is not worth a storage entry: visiting a conversation without ever
+ // opening a terminal would otherwise leave one behind for every conversation visited.
+ if (panes.length === 0 && Object.keys(assignments).length === 0) {
+ const { [scope]: _dropped, ...rest } = scopes;
+ scopes = rest;
+ } else {
+ // Re-inserted last so key order is least-recently-touched first, which is what the cap
+ // below evicts by.
+ const { [scope]: _previous, ...rest } = scopes;
+ scopes = { ...rest, [scope]: state };
+ }
+ const keys = Object.keys(scopes);
+ if (keys.length > MAX_SCOPES) {
+ scopes = Object.fromEntries(keys.slice(keys.length - MAX_SCOPES).map((k) => [k, scopes[k]!]));
+ }
+ writeJson(DOCK_KEY, scopes);
+}
+
+/**
+ * Points the dock at a conversation. Everything on screen changes with it; the shells
+ * behind the tabs are untouched, so switching away and back costs nothing.
+ */
+export function setDockScope(next: string | null): void {
+ // A dock opened before a conversation was chosen belongs to the one that is chosen.
+ // /chat carries no Session id and resolves to one a moment after it loads (chat-page.tsx
+ // redirects to the newest conversation, or to a draft), so a terminal opened in between
+ // would otherwise be stranded in a scope nothing navigates back to. Only from that
+ // placeholder: an ordinary switch between two conversations carries nothing across.
+ switchScope(next ?? NO_SESSION_SCOPE, scope === NO_SESSION_SCOPE);
+}
+
+/**
+ * The draft this scope was holding has become a real Session: its arrangement moves to the
+ * new id. Every draft shares one scope, because a draft has no id to key on — so without
+ * this the terminal opened while drafting stays behind under that shared key, invisible to
+ * the conversation it was opened for and waiting to reappear in the NEXT draft, which is
+ * the same terminal showing up in a conversation that never asked for one.
+ *
+ * Called at the two points that turn a draft into a Session (its send paths), not on any
+ * navigation away from the draft: leaving a draft for an existing conversation must leave
+ * the draft's terminals where they are.
+ */
+export function adoptDockScope(sessionId: string): void {
+ switchScope(sessionId, true);
+}
+
+function switchScope(target: string, mayHandOver: boolean): void {
+ if (target === scope) return;
+ persist();
+ const staged = scopes[scope];
+ // Never clobbers: a target with an arrangement of its own keeps it.
+ const handedOver = mayHandOver && staged !== undefined && scopes[target] === undefined;
+ if (handedOver) {
+ const { [scope]: _moved, ...rest } = scopes;
+ scopes = { ...rest, [target]: staged };
+ // The move has to reach storage here. persist() above wrote the map as it was, under the
+ // OLD key; leaving it at that means a reload reads the arrangement back under a key
+ // nothing routes to — and, for a draft, hands it to the next draft instead.
+ writeJson(DOCK_KEY, scopes);
+ }
+ scope = target;
+ ({ visible, panes, assignments, currents } = scopes[scope] ?? emptyScope());
+ // Errors are about a pane that is no longer on screen — except after a hand-off, where
+ // the panes on screen are the same ones under a new name, and a failure they are still
+ // showing has not stopped being true.
+ if (!handedOver) paneErrors = {};
+ notify();
+}
+
+const listeners = new Set<() => void>();
+let version = 0;
+
+function notify(): void {
+ version += 1;
+ for (const listener of [...listeners]) listener();
+}
+
+/** Monotonic change counter — subscribe with this snapshot to re-render on ANY change. */
+export function dockStateVersion(): number {
+ return version;
+}
+
+export function subscribeTerminalDock(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+// ---------------------------------------------------------------------------- visibility
+
+/**
+ * Whether the dock is on screen — which is what every caller means by "open", including the
+ * toggle. A side pane displaced by a chat panel does not count: from the user's seat there
+ * is no terminal, so asking for one must bring it back rather than toggle it off.
+ */
+export function isTerminalDockOpen(): boolean {
+ return visible && visiblePanes().length > 0;
+}
+
+/**
+ * Whether a pane occupies its slot in the layout: it is in the arrangement, and the user has
+ * not hidden the dock. A displaced side pane still does — it stays mounted and collapses to
+ * zero width so the swap animates instead of popping — which is precisely where this parts
+ * ways with isTerminalDockOpen().
+ */
+export function paneHasSlot(position: DockPosition): boolean {
+ return visible && panes.includes(position);
+}
+
+export function setTerminalDockOpen(next: boolean): void {
+ if (next) terminalTakesTheSide();
+ visible = next;
+ if (next && panes.length === 0) panes = ["bottom"];
+ persist();
+ notify();
+}
+
+export function toggleTerminalDock(): void {
+ setTerminalDockOpen(!isTerminalDockOpen());
+}
+
+// Ctrl+` (the Codex/VS Code binding), registered at module scope: a React-effect listener
+// leaves a window after first paint where the shortcut is silently dead — an effect runs
+// after paint, and a keypress can land in between. The store is page-global anyway; on
+// routes without the dock (login, /terminal) the toggle just flips hidden state.
+if (typeof window !== "undefined") {
+ window.addEventListener("keydown", (event) => {
+ if (!event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
+ if (event.key !== "`" && event.code !== "Backquote") return;
+ event.preventDefault();
+ toggleTerminalDock();
+ });
+}
+
+// --------------------------------------------------------------------------------- panes
+
+/**
+ * The arrangement: every pane the dock would show. Stable reference until it changes.
+ *
+ * This is NOT what to render — a side pane displaced by a chat panel is still part of the
+ * arrangement, which is exactly what lets it come back. Renderers want visiblePanes().
+ */
+export function openPanes(): DockPosition[] {
+ return panes;
+}
+
+/**
+ * A chat side panel (Agents / Workspace) is on screen, displacing this dock's left and
+ * right panes. Not persisted: it mirrors panel state that is itself per-visit, and a reload
+ * with no panel open should show the panes again.
+ */
+let sidePanelDisplacing = false;
+
+/** Whether a chat side panel currently holds the side. */
+export function chatSidePanelOpen(): boolean {
+ return sidePanelDisplacing;
+}
+
+export function setChatSidePanelOpen(open: boolean): void {
+ if (open) cancelHandover(); // the panel is back: nothing left to hand over
+ if (sidePanelDisplacing === open) return;
+ sidePanelDisplacing = open;
+ notify();
+}
+
+/**
+ * The one duration of the side-slot choreography: a panel's retraction, a pane's collapse,
+ * the sequenced swap's wait, and the exit linger all use it — they are phases of the same
+ * motion, and any two drifting apart is what reads as "the old surface never left". The
+ * two `duration-200` Tailwind classes (terminal-dock.tsx, files-panel.tsx) must match it;
+ * CSS cannot read a JS constant.
+ */
+export const SIDE_SLOT_TRANSITION_MS = 200;
+
+/**
+ * The panel has been told to retract but is still on screen. The pane stays displaced for
+ * that long: expanding into a slot the outgoing panel still fills keeps the total width
+ * constant, and a constant total is exactly what reads as "the panel never left" — the
+ * reason the panels sequence their own swaps rather than crossfading.
+ */
+let handingOver = false;
+let handoverTimer: ReturnType<typeof setTimeout> | null = null;
+
+function cancelHandover(): void {
+ if (handoverTimer !== null) clearTimeout(handoverTimer);
+ handoverTimer = null;
+ handingOver = false;
+}
+
+/**
+ * Called by everything that puts a terminal on screen: the terminal is what the user just
+ * asked for, so it takes the side back. The chat page watches for this and retracts its
+ * panels — the store cannot reach into them, and should not know they exist beyond this
+ * one flag. The pane itself waits out the retraction (see handingOver) rather than
+ * expanding into a slot that is still occupied.
+ */
+function terminalTakesTheSide(): void {
+ if (!sidePanelDisplacing) return;
+ sidePanelDisplacing = false; // the chat page reads this and retracts its panels
+ handingOver = true;
+ if (handoverTimer !== null) clearTimeout(handoverTimer);
+ handoverTimer = setTimeout(() => {
+ handoverTimer = null;
+ handingOver = false;
+ notify();
+ }, SIDE_SLOT_TRANSITION_MS);
+}
+
+let visibleSnapshot: DockPosition[] = [];
+
+/** Panes to actually render: the arrangement minus what a chat side panel is displacing. */
+export function visiblePanes(): DockPosition[] {
+ const next = sidePanelDisplacing || handingOver ? panes.filter(isHorizontal) : panes;
+ if (next.length === panes.length) return panes; // nothing displaced: keep the stable ref
+ if (next.length !== visibleSnapshot.length || next.some((p, i) => p !== visibleSnapshot[i])) {
+ visibleSnapshot = next;
+ }
+ return visibleSnapshot;
+}
+
+/** The pane unassigned terminals belong to. */
+function primaryPane(): DockPosition {
+ return panes[0] ?? "bottom";
+}
+
+function ensurePaneOpen(position: DockPosition): void {
+ terminalTakesTheSide();
+ visible = true;
+ if (!panes.includes(position)) panes = [...panes, position];
+ persist();
+ notify();
+}
+
+/**
+ * Closes one pane. Its terminals fold back into the primary remaining pane (the shells
+ * keep running server-side either way); closing the last pane hides the dock.
+ *
+ * Closing the LAST pane keeps the membership rather than dropping it: the shells are still
+ * running, and reopening the dock has to come back to them, not spawn a replacement. There
+ * is no pane left to re-home them to, so the entries stay pointed at the pane that closed —
+ * paneOfTerminal() re-homes anything whose pane is not open to the primary one, which is
+ * the pane that reopening creates. Terminals that were killed rather than closed leave on
+ * the next pruneAssignments(), which is what finally empties the scope.
+ */
+export function closePane(position: DockPosition): void {
+ if (!panes.includes(position)) return;
+ panes = panes.filter((p) => p !== position);
+ const fallback = panes[0];
+ if (fallback) {
+ delete currents[position];
+ assignments = Object.fromEntries(
+ Object.entries(assignments).map(([id, pane]) => [id, pane === position ? fallback : pane]),
+ );
+ } else {
+ visible = false;
+ }
+ persist();
+ notify();
+}
+
+// -------------------------------------------------------------------------------- ratios
+
+/** A top/bottom pane's height, as a ratio of the layout row. Side panes are sized in px. */
+export function paneRatio(position: DockPosition): number {
+ const stored = ratios[position];
+ return typeof stored === "number" ? clampRatio(stored) : DEFAULT_DOCK_HEIGHT_RATIO;
+}
+
+export function setPaneRatio(position: DockPosition, next: number): void {
+ const clamped = clampRatio(next);
+ if (clamped === ratios[position]) return;
+ ratios = { ...ratios, [position]: clamped };
+ writeJson(RATIOS_KEY, ratios);
+ notify();
+}
+
+export function resetPaneRatio(position: DockPosition): void {
+ const { [position]: _dropped, ...rest } = ratios;
+ ratios = rest;
+ writeJson(RATIOS_KEY, ratios);
+ notify();
+}
+
+// --------------------------------------------------------------------- pane assignments
+
+/**
+ * The pane a terminal is shown in, or null when this scope does not hold it at all.
+ *
+ * Membership is explicit — a terminal belongs to the conversation it was opened in, not to
+ * whichever dock happens to be on screen. Falling back to the primary pane for an unknown
+ * id is what would leak every other conversation's shells into this one's tab strip.
+ * (An id assigned to a pane that is no longer open does re-home to the primary: that pane
+ * closed, but the terminal is still this scope's.)
+ */
+export function paneOfTerminal(id: string): DockPosition | null {
+ const assigned = assignments[id];
+ if (assigned === undefined) return null;
+ return panes.includes(assigned) ? assigned : primaryPane();
+}
+
+/**
+ * Whether this conversation holds a terminal at all — what the toolbar's badge counts, so
+ * it agrees with what opening the panel shows.
+ */
+export function holdsTerminal(id: string): boolean {
+ return assignments[id] !== undefined;
+}
+
+/**
+ * Of `ids`, the ones no conversation holds — created through the API or the CLI, or left
+ * behind by a conversation that let go of them. A dock opening with nothing of its own
+ * adopts one of these rather than spawning a second shell beside a perfectly good one.
+ */
+export function unownedTerminals(ids: readonly string[]): string[] {
+ const owned = new Set<string>(Object.keys(assignments)); // the live scope, ahead of `scopes`
+ for (const state of Object.values(scopes)) {
+ for (const id of Object.keys(state.assignments)) owned.add(id);
+ }
+ return ids.filter((id) => !owned.has(id));
+}
+
+/** Moves a terminal to a pane (opening it if needed) and shows it there. */
+export function assignTerminalToPane(id: string, position: DockPosition): void {
+ ensurePaneOpen(position);
+ assignments = { ...assignments, [id]: position };
+ persist();
+ setPaneCurrent(position, id);
+}
+
+/**
+ * Brings a terminal on screen: its pane opens (dock and all) showing it. A terminal this
+ * scope does not hold — one opened in another conversation, picked from the toolbar's
+ * list — joins the primary pane, which is what asking to see it here means.
+ */
+export function showTerminal(id: string): void {
+ const position = paneOfTerminal(id);
+ if (position === null) {
+ assignTerminalToPane(id, primaryPane());
+ return;
+ }
+ ensurePaneOpen(position);
+ setPaneCurrent(position, id);
+}
+
+/**
+ * Drops assignment entries for terminals that no longer exist — across every scope, not
+ * just the one on screen: a dead shell's id would otherwise sit in an inactive
+ * conversation's arrangement until that conversation aged out of storage.
+ */
+export function pruneAssignments(liveIds: ReadonlySet<string>): void {
+ let changed = false;
+ for (const [key, state] of Object.entries(scopes)) {
+ const kept = Object.entries(state.assignments).filter(([id]) => liveIds.has(id));
+ if (kept.length === Object.keys(state.assignments).length) continue;
+ scopes = { ...scopes, [key]: { ...state, assignments: Object.fromEntries(kept) } };
+ changed = true;
+ }
+ const kept = Object.entries(assignments).filter(([id]) => liveIds.has(id));
+ if (kept.length !== Object.keys(assignments).length) {
+ assignments = Object.fromEntries(kept);
+ changed = true;
+ }
+ if (!changed) return;
+ persist();
+ notify();
+}
+
+// ------------------------------------------------------------------------ pane currents
+
+export function paneCurrent(position: DockPosition): string | null {
+ return currents[position] ?? null;
+}
+
+export function paneError(position: DockPosition): string | null {
+ return paneErrors[position] ?? null;
+}
+
+export function setPaneError(position: DockPosition, message: string | null): void {
+ if ((paneErrors[position] ?? null) === message) return;
+ if (message === null) delete paneErrors[position];
+ else paneErrors = { ...paneErrors, [position]: message };
+ notify();
+}
+
+export function setPaneCurrent(position: DockPosition, id: string | null): void {
+ if ((currents[position] ?? null) === id) {
+ notify(); // assignment may still have changed alongside
+ return;
+ }
+ if (id === null) delete currents[position];
+ else currents = { ...currents, [position]: id };
+ persist();
+ notify();
+}
+
+/**
+ * Moves a whole pane to another edge: every terminal of the source pane (and its shown
+ * terminal) lands on the target, merging with anything already there; the source closes.
+ *
+ */
+export function movePane(from: DockPosition, to: DockPosition): void {
+ if (from === to) return;
+ const shown = currents[from] ?? null;
+ const movedIds = Object.keys(assignments).filter((id) => paneOfTerminal(id) === from);
+ // A top<->bottom move carries the pane's height along ("keep the ratio"): the user sized
+ // THIS pane, and it is the same pane on the other edge. Merges into an existing pane keep
+ // the target's own size, and a side pane has no size of its own to carry — its width is
+ // the shared one every side surface opens at.
+ if (!panes.includes(to) && isHorizontal(from) && isHorizontal(to) && ratios[from] !== undefined) {
+ ratios = { ...ratios, [to]: ratios[from] };
+ writeJson(RATIOS_KEY, ratios);
+ }
+ ensurePaneOpen(to);
+ assignments = {
+ ...assignments,
+ ...Object.fromEntries(movedIds.map((id) => [id, to])),
+ };
+ panes = panes.filter((p) => p !== from);
+ delete currents[from];
+ if (shown) currents = { ...currents, [to]: shown };
+ persist();
+ notify();
+}
diff --git a/packages/web/src/features/terminal/terminal-dock.tsx b/packages/web/src/features/terminal/terminal-dock.tsx
new file mode 100644
index 00000000..74a80180
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-dock.tsx
@@ -0,0 +1,804 @@
+/**
+ * One dock pane: a terminal panel on one edge of the content area (terminal-dock-state.ts
+ * owns which edges have panes). AppLayout renders a pane per open edge; the terminal
+ * views themselves live in the shared pool (terminal-view-pool.tsx) and are adopted into
+ * this pane's body by DOM handoff, so nothing about a pane's own lifecycle ever remounts
+ * an xterm or drops its stream.
+ *
+ * The header carries the pane's tab strip (the terminals assigned to this pane), a "+" to
+ * open another shell here, the current shell's status, detach-to-window and close. Tabs
+ * drag sideways to reorder; dragging a tab OUT of the strip brings up the edge overlay
+ * (bands + drop targets + landing preview) and dropping on another edge moves that
+ * terminal there — creating the pane if needed. Dragging the header itself moves the
+ * whole pane the same way (merging into an existing pane on that edge). The boundary with
+ * the main content resizes the pane (ratio-persisted; double-click resets).
+ */
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { S } from "../../lib/strings";
+import { useTerminalChrome } from "./terminal-appearance";
+import {
+ persistPanelWidth,
+ resetPanelWidth,
+ setPanelWidth,
+ usePanelWidthValue,
+} from "../chat/use-panel-width";
+import {
+ assignTerminalToPane,
+ closePane,
+ dockStateVersion,
+ isHorizontal,
+ isTerminalDockOpen,
+ movePane,
+ paneCurrent,
+ paneError,
+ paneOfTerminal,
+ unownedTerminals,
+ paneRatio,
+ resetPaneRatio,
+ setPaneCurrent,
+ setPaneError,
+ setPaneRatio,
+ subscribeTerminalDock,
+ type DockPosition,
+} from "./terminal-dock-state";
+import { DockLayoutOverlay, dockDropCandidate } from "./terminal-dock-layout";
+import { HttpStatusError, fetchJson, probeJson, type TerminalInfo } from "./terminal-view";
+import {
+ killTerminal,
+ liveTerminals,
+ noteTerminalCreated,
+ refreshTerminals,
+ setTerminalTabOrder,
+ subscribeTerminals,
+} from "./terminal-list";
+import {
+ subscribeTerminalViewStates,
+ terminalViewContainer,
+ terminalViewState,
+} from "./terminal-view-pool";
+
+/** The dock always opens new shells in the home directory (project cwd can come later). */
+const DOCK_CWD = "~";
+
+export function useTerminalDockOpen(): boolean {
+ return useSyncExternalStore(subscribeTerminalDock, isTerminalDockOpen);
+}
+
+/**
+ * Root sizing per position. Top/bottom are a HEIGHT RATIO of the layout row, with CSS
+ * clamps (the px minimums must equal the DOCK_MIN_*_PX constants the drag preview uses, at
+ * every font scale). Left/right are a WIDTH IN PIXELS, shared with the chat's Workspace and
+ * Agents panels (use-panel-width.ts) — the three take turns in the same slot, so a width
+ * dragged on any of them is the width the next one opens at. Their clamps live in that
+ * store, not in CSS, and the border belongs to the open state only: at width 0 a border-box
+ * still paints its 1px, leaving a hairline where nothing is.
+ */
+const POSITION_CLASSES: Record<DockPosition, string> = {
+ bottom: "w-full border-t min-h-[140px] max-h-[85%]",
+ top: "w-full border-b min-h-[140px] max-h-[85%]",
+ // No border here: it belongs to the open state only. With border-box sizing a collapsed
+ // pane still paints its 1px, which leaves a hairline where nothing is — and keeps the
+ // element from ever measuring zero.
+ left: "",
+ right: "",
+};
+
+/** Small icon-sized header button shared by the pane's controls. */
+function DockButton(props: { label: string; testId: string; onClick: () => void; d: string }) {
+ const chrome = useTerminalChrome();
+ return (
+ <button
+ type="button"
+ title={props.label}
+ aria-label={props.label}
+ data-testid={props.testId}
+ onClick={props.onClick}
+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded transition-colors duration-150 ${chrome.iconButton}`}
+ >
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <path d={props.d} />
+ </svg>
+ </button>
+ );
+}
+
+/**
+ * Shell titles usually open with a `user@host` marker (bash and zsh default title
+ * strings). The host says nothing useful in a single-server UI and eats the tab's width,
+ * so it is dropped at display time only — the stored title stays untouched.
+ *
+ * The host part must exclude `:` explicitly: in a spaceless title like
+ * `user@host:~/work`, a greedy `\S+` would swallow the path along with the host and leave
+ * nothing of the title at all.
+ */
+export function displayTitle(title: string | null | undefined): string {
+ return (title ?? "")
+ .trim()
+ .replace(/^[^@\s]+@[^:\s]+:?\s*/, "")
+ .trim();
+}
+
+/**
+ * One tab in the strip: number + name/title + a kill ×. Two sibling buttons, not nested —
+ * a button inside a button is invalid and unclickable.
+ */
+function TerminalTab(props: {
+ terminal: TerminalInfo;
+ /** Fallback numbering for servers without `seq`; position-based, so only a fallback. */
+ index: number;
+ active: boolean;
+ onSelect: () => void;
+ onKill: () => void;
+}) {
+ const { terminal, active } = props;
+ const chrome = useTerminalChrome();
+ // The `1:`-style prefix (tmux convention) keeps identically-named/-titled tabs apart.
+ // It is the terminal's STABLE seq, not its position: a dragged tab keeps its number, so
+ // where it went stays visible.
+ const label = `${terminal.seq ?? props.index + 1}: ${displayTitle(terminal.title) || terminal.name}`;
+ return (
+ <div
+ data-testid="terminal-tab"
+ data-terminal-id={terminal.id}
+ data-active={active}
+ className={`group relative flex h-6 min-w-10 max-w-40 items-center overflow-hidden rounded-md transition-colors duration-150 ${
+ active ? chrome.tabActive : chrome.tabIdle
+ }`}
+ >
+ {/* No shrink-0: crowded tabs squeeze browser-style down to min-w-10 — the label
+ clips hard (no ellipsis) so at the floor only the "N:" number stays readable. */}
+ <button
+ type="button"
+ title={`${terminal.name} — ${terminal.cwd}`}
+ onClick={props.onSelect}
+ className="flex h-full w-full min-w-0 items-center px-2 text-left"
+ >
+ <span className="block w-full overflow-hidden whitespace-nowrap">{label}</span>
+ </button>
+ {/* Kill: this ends the shell itself (server-side), not just a view of it. A
+ hover-revealed OVERLAY (absolute, own backdrop), so it costs no width while tabs
+ squeeze and never reflows the strip on hover. */}
+ <button
+ type="button"
+ title={S.terminal.killShell}
+ aria-label={`${S.terminal.killShell}: ${label}`}
+ data-testid="terminal-tab-kill"
+ onClick={props.onKill}
+ className={`absolute right-0.5 top-1/2 -translate-y-1/2 rounded p-0.5 opacity-0 transition-opacity duration-150 group-hover:opacity-100 focus-visible:opacity-100 ${chrome.tabKill}`}
+ >
+ <svg
+ width="10"
+ height="10"
+ viewBox="0 0 14 14"
+ fill="none"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path d="M2 2l10 10M12 2L2 12" strokeWidth="1.6" strokeLinecap="round" />
+ </svg>
+ </button>
+ </div>
+ );
+}
+
+/**
+ * Creates a fresh shell assigned to (and shown in) the given pane. Failures surface in
+ * the pane body (setPaneError) — a swallowed create leaves a blank panel that looks like
+ * nothing happened, which is exactly how a server-side spawn failure used to present.
+ */
+async function createShellInPane(position: DockPosition): Promise<void> {
+ try {
+ const created = await fetchJson<TerminalInfo>("/api/terminals", {
+ method: "POST",
+ body: JSON.stringify({ cwd: DOCK_CWD }),
+ });
+ setPaneError(position, null);
+ noteTerminalCreated(created);
+ assignTerminalToPane(created.id, position);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ // A 404 here is not "this terminal is gone" — the endpoint itself is absent, which
+ // means the server answering is older than the terminal API (the desktop shell also
+ // attaches to an already-running server rather than starting its own).
+ const detail =
+ err instanceof HttpStatusError && err.status === 404
+ ? `${message} — ${S.terminal.noTerminalApi}`
+ : message;
+ console.error(`[terminal] create failed (${position} pane):`, detail);
+ setPaneError(position, detail);
+ }
+}
+
+/**
+ * Shared pointer-drag state machine for the pane's gestures (header move, tab drag,
+ * boundary resize): capture on pointerdown so a fast pull can never escape the surface, a
+ * movement threshold separating taps from drags, and latest-callback refs so `onEnd`
+ * never sees stale state. Spread the returned props on the gesture's surface.
+ */
+function usePointerDrag<T>(options: {
+ /** Resolves the drag payload from the initial event; null refuses the gesture. */
+ begin: (event: React.PointerEvent<HTMLElement>) => T | null;
+ /** px of movement that turns the press into a drag (0 = immediately). */
+ threshold?: number;
+ onMove?: (event: React.PointerEvent<HTMLElement>, payload: T) => void;
+ /** Release: `dragged` distinguishes a completed drag from a plain tap. */
+ onEnd?: (payload: T, dragged: boolean) => void;
+ /** Abandoned gesture (pointercancel): clear visuals, apply nothing. */
+ onCancel?: () => void;
+}) {
+ const latest = useRef(options);
+ latest.current = options;
+ const state = useRef<{ payload: T; x: number; y: number; started: boolean } | null>(null);
+
+ return useMemo(
+ () => ({
+ onPointerDown: (event: React.PointerEvent<HTMLElement>) => {
+ if (event.button !== 0) return;
+ const payload = latest.current.begin(event);
+ if (payload === null) return;
+ state.current = { payload, x: event.clientX, y: event.clientY, started: false };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ },
+ onPointerMove: (event: React.PointerEvent<HTMLElement>) => {
+ const drag = state.current;
+ if (!drag) return;
+ if (!drag.started) {
+ const threshold = latest.current.threshold ?? 5;
+ if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < threshold) return;
+ drag.started = true;
+ }
+ latest.current.onMove?.(event, drag.payload);
+ },
+ onPointerUp: (event: React.PointerEvent<HTMLElement>) => {
+ const drag = state.current;
+ state.current = null;
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ if (drag) latest.current.onEnd?.(drag.payload, drag.started);
+ },
+ onPointerCancel: () => {
+ state.current = null;
+ latest.current.onCancel?.();
+ },
+ }),
+ [],
+ );
+}
+
+/** One resolution at a time per pane — mount effects can fire in quick succession. */
+const resolving = new Set<DockPosition>();
+
+/**
+ * First-show resolution for a pane: keep its stored terminal when still alive, else the
+ * newest live terminal assigned here, else one no conversation holds, else create one. Runs only when the pane has no
+ * usable current — a shell exiting later must NOT auto-respawn (the user sees the exit).
+ */
+async function resolvePaneCurrent(position: DockPosition): Promise<void> {
+ if (resolving.has(position)) return;
+ resolving.add(position);
+ try {
+ const storedId = paneCurrent(position);
+ if (storedId) {
+ const existing = await probeJson<TerminalInfo>(
+ `/api/terminals/${encodeURIComponent(storedId)}`,
+ ).catch(() => null);
+ if (existing?.alive) {
+ setPaneError(position, null);
+ return;
+ }
+ }
+ const listed = await fetchJson<{ terminals: TerminalInfo[] }>("/api/terminals").catch(
+ () => null,
+ );
+ const live = (listed?.terminals ?? []).filter((t) => t.alive);
+ const newest = live.filter((t) => paneOfTerminal(t.id) === position).at(-1);
+ if (newest) {
+ setPaneError(position, null);
+ setPaneCurrent(position, newest.id);
+ return;
+ }
+ // Nothing of this conversation's. A shell no conversation holds — started through the
+ // API or the CLI, or left behind — is adopted rather than answered with a second shell
+ // running beside it.
+ const adoptable = unownedTerminals(live.map((t) => t.id)).at(-1);
+ if (adoptable !== undefined) {
+ setPaneError(position, null);
+ assignTerminalToPane(adoptable, position);
+ return;
+ }
+ await createShellInPane(position);
+ } finally {
+ resolving.delete(position);
+ void refreshTerminals();
+ }
+}
+
+/**
+ * One pane of the dock. `open` is false only for a SIDE pane a chat panel has displaced:
+ * the pane stays mounted and collapses to zero width, so it slides out and back on the same
+ * 200ms the panels use rather than popping. Top/bottom panes are never displaced and are
+ * always passed true.
+ */
+export function TerminalDock({
+ position,
+ open = true,
+}: {
+ position: DockPosition;
+ open?: boolean;
+}) {
+ const chrome = useTerminalChrome();
+ useSyncExternalStore(subscribeTerminalDock, dockStateVersion);
+ const allTerminals = useSyncExternalStore(subscribeTerminals, liveTerminals);
+ const currentId = paneCurrent(position);
+ const resolveError = paneError(position);
+ const viewState = useSyncExternalStore(subscribeTerminalViewStates, () =>
+ terminalViewState(currentId),
+ );
+
+ const paneTerminals = useMemo(
+ () => allTerminals.filter((t) => paneOfTerminal(t.id) === position),
+ // paneOfTerminal reads dock-state; dockStateVersion above re-renders us on any change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [allTerminals, position, dockStateVersion()],
+ );
+
+ // First show: always resolve, even with a stored id — the stored terminal can be dead or
+ // reaped (server restart), and resolvePaneCurrent is what validates it against the
+ // server. Afterwards only an EMPTIED pane re-resolves: a shell exiting while shown must
+ // keep showing its exit, never auto-respawn. Gated on `open`: a pane that is collapsed —
+ // displaced by a chat panel, or lingering through its exit animation after a move cleared
+ // its current — must not create anything. The lingering case is the one that bites:
+ // without the gate, moving a pane to another edge respawned a shell on the edge it left.
+ const resolvedOnShow = useRef(false);
+ useEffect(() => {
+ if (!open) return;
+ if (!resolvedOnShow.current) {
+ resolvedOnShow.current = true;
+ void resolvePaneCurrent(position);
+ return;
+ }
+ if (currentId === null) void resolvePaneCurrent(position);
+ }, [currentId, position, open]);
+
+ // The shown tab keeps itself in view: with many tabs the strip scrolls, and a
+ // half-clipped active tab reads as a stray × button at the strip's edge.
+ const stripRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ if (currentId === null) return;
+ stripRef.current
+ ?.querySelector(`[data-terminal-id="${CSS.escape(currentId)}"]`)
+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [currentId, paneTerminals]);
+
+ // Wheel over the strip scrolls it sideways (there is no vertical axis to scroll, and a
+ // trackpad's deltaX works too). Native non-passive listener: React's synthetic onWheel
+ // is passive, so preventDefault there cannot stop the page handling the event.
+ useEffect(() => {
+ const strip = stripRef.current;
+ if (!strip) return;
+ const onWheel = (event: WheelEvent): void => {
+ const delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
+ if (delta === 0 || strip.scrollWidth <= strip.clientWidth) return;
+ event.preventDefault();
+ strip.scrollLeft += delta;
+ };
+ strip.addEventListener("wheel", onWheel, { passive: false });
+ return () => strip.removeEventListener("wheel", onWheel);
+ }, []);
+
+ // Adopt the shown terminal's pooled container into this pane's body.
+ const bodyRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const body = bodyRef.current;
+ if (!body || currentId === null) return;
+ const container = terminalViewContainer(currentId);
+ body.appendChild(container);
+ return () => {
+ if (container.parentElement === body) body.removeChild(container);
+ };
+ }, [currentId]);
+
+ const selectTerminal = useCallback(
+ (id: string) => {
+ if (id !== paneCurrent(position)) setPaneCurrent(position, id);
+ },
+ [position],
+ );
+
+ /** Fresh shell in a new tab of this pane; the current one keeps running. */
+ const newShell = useCallback(() => {
+ void createShellInPane(position);
+ }, [position]);
+
+ /** Kills a tab's shell; killing the last one closes the pane (never auto-respawns). */
+ const onKillTerminal = useCallback(
+ (id: string) => {
+ void killTerminal(id);
+ const remaining = paneTerminals.filter((t) => t.id !== id);
+ if (remaining.length === 0) {
+ closePane(position);
+ return;
+ }
+ if (id === paneCurrent(position)) {
+ setPaneCurrent(position, remaining.at(-1)!.id);
+ }
+ },
+ [paneTerminals, position],
+ );
+
+ /**
+ * Detach the shown terminal to its own /terminal window. The shell stays live (and
+ * listed — multi-client attach); the pane moves on to its newest other terminal, or
+ * closes when this was the only one.
+ */
+ const detach = useCallback(() => {
+ const id = paneCurrent(position);
+ if (!id) return;
+ window.open(`/terminal?id=${encodeURIComponent(id)}`, "_blank", "noopener");
+ const remaining = paneTerminals.filter((t) => t.id !== id);
+ if (remaining.length > 0) setPaneCurrent(position, remaining.at(-1)!.id);
+ else closePane(position);
+ }, [paneTerminals, position]);
+
+ // ------------------------------------------------------------------ header drag: move pane
+ const [headerDragState, setHeaderDragState] = useState<{
+ active: boolean;
+ candidate: DockPosition | null;
+ }>({ active: false, candidate: null });
+ const clearHeaderDrag = () => setHeaderDragState({ active: false, candidate: null });
+
+ const headerDragProps = usePointerDrag<object>({
+ begin: (event) =>
+ (event.target as HTMLElement).closest("button, [data-testid='terminal-tab']") ? null : {},
+ onMove: (event) =>
+ setHeaderDragState({
+ active: true,
+ candidate: dockDropCandidate(event.clientX, event.clientY),
+ }),
+ onEnd: (_payload, dragged) => {
+ const candidate = headerDragState.candidate;
+ clearHeaderDrag();
+ if (dragged && candidate && candidate !== position) movePane(position, candidate);
+ },
+ onCancel: clearHeaderDrag,
+ });
+
+ // --------------------------------------------------- tab drag: reorder or move to a pane
+ const [tabDragState, setTabDragState] = useState<{
+ active: boolean;
+ candidate: DockPosition | null;
+ }>({ active: false, candidate: null });
+ const clearTabDrag = () => setTabDragState({ active: false, candidate: null });
+
+ const stripDragProps = usePointerDrag<{ id: string }>({
+ threshold: 6,
+ begin: (event) => {
+ const target = event.target as HTMLElement;
+ if (target.closest("[data-testid='terminal-tab-kill']")) return null;
+ const id = target.closest<HTMLElement>("[data-terminal-id]")?.dataset.terminalId;
+ return id ? { id } : null;
+ },
+ onMove: (event, { id }) => {
+ // Out of the strip (with a little slack): the gesture becomes "move to an edge" —
+ // the same overlay as moving a pane, with the preview showing the new layout.
+ const strip = event.currentTarget.getBoundingClientRect();
+ if (event.clientY < strip.top - 20 || event.clientY > strip.bottom + 20) {
+ setTabDragState({
+ active: true,
+ candidate: dockDropCandidate(event.clientX, event.clientY),
+ });
+ return;
+ }
+ setTabDragState({ active: false, candidate: null });
+
+ // Within the strip: live reorder against the other tabs' midpoints.
+ const tabEls = [...event.currentTarget.querySelectorAll<HTMLElement>("[data-terminal-id]")];
+ const currentIds = tabEls.map((el) => el.dataset.terminalId as string);
+ const others = tabEls.filter((el) => el.dataset.terminalId !== id);
+ let insertAt = others.length;
+ for (let i = 0; i < others.length; i += 1) {
+ const rect = others[i]!.getBoundingClientRect();
+ if (event.clientX < rect.left + rect.width / 2) {
+ insertAt = i;
+ break;
+ }
+ }
+ const nextIds = others.map((el) => el.dataset.terminalId as string);
+ nextIds.splice(insertAt, 0, id);
+ if (nextIds.some((nextId, index) => nextId !== currentIds[index]))
+ setTerminalTabOrder(nextIds);
+ },
+ onEnd: ({ id }, dragged) => {
+ const { active, candidate } = tabDragState;
+ clearTabDrag();
+ // A tap resolves to select here: pointer capture retargets the browser click to the
+ // strip, so the tab's own click handler never fires from a mouse press.
+ if (!dragged) {
+ selectTerminal(id);
+ return;
+ }
+ if (!active || !candidate || candidate === position) return;
+ // Move the dragged terminal to the chosen edge (creating that pane on demand) and
+ // keep this pane on its next terminal — or close it when that was the last one.
+ const remaining = paneTerminals.filter((t) => t.id !== id);
+ assignTerminalToPane(id, candidate);
+ if (paneCurrent(position) === id || remaining.length === 0) {
+ if (remaining.length > 0) setPaneCurrent(position, remaining.at(-1)!.id);
+ else closePane(position);
+ }
+ },
+ onCancel: clearTabDrag,
+ });
+
+ // ------------------------------------------------------------------------ boundary resize
+ const [resizing, setResizing] = useState(false);
+
+ const resizerDragProps = usePointerDrag<object>({
+ threshold: 0,
+ begin: (event) => {
+ event.preventDefault(); // no text selection while dragging the boundary
+ setResizing(true);
+ return {};
+ },
+ onMove: (event) => {
+ // The ratio's basis must match what the CSS percentage resolves against: the host
+ // column for top/bottom panes (they are its direct children), whose width the
+ // layout row shares for left/right. The pane's own rect anchors the far edge.
+ const host = document.querySelector("[data-dock-host]")?.getBoundingClientRect();
+ const pane = event.currentTarget
+ .closest("[data-testid='terminal-dock']")
+ ?.getBoundingClientRect();
+ if (!host || !pane || host.width === 0 || host.height === 0) return;
+ switch (position) {
+ case "bottom":
+ setPaneRatio(position, (pane.bottom - event.clientY) / host.height);
+ break;
+ case "top":
+ setPaneRatio(position, (event.clientY - pane.top) / host.height);
+ break;
+ // Side panes are sized in pixels through the shared panel width; the numerators are
+ // already that width, they just used to be divided by the host.
+ case "left":
+ setPanelWidth(event.clientX - pane.left);
+ break;
+ case "right":
+ setPanelWidth(pane.right - event.clientX);
+ break;
+ }
+ },
+ onEnd: () => {
+ setResizing(false);
+ if (!isHorizontal(position)) persistPanelWidth(); // once per drag, not per frame
+ },
+ onCancel: () => setResizing(false),
+ });
+
+ const onResizerDoubleClick = useCallback(
+ () => (isHorizontal(position) ? resetPaneRatio(position) : resetPanelWidth()),
+ [position],
+ );
+
+ // ------------------------------------------------------------------------------- render
+ const horizontal = isHorizontal(position);
+ const ratio = paneRatio(position); // height ratio; side panes use sideWidth below
+ const sideWidth = usePanelWidthValue();
+
+ // First paint happens at width 0; `entered` flips a frame later. A node that MOUNTS at
+ // its target width has no transition to run, so a fresh side pane popped in while the
+ // chat panels slid — they never unmount, this one does. Double rAF: the first can land
+ // in the same frame as the initial paint, and a 0→width set within one frame is not a
+ // transition either. Height (top/bottom) stays unanimated on purpose: each intermediate
+ // height would refit xterm's grid.
+ const [entered, setEntered] = useState(false);
+ useEffect(() => {
+ let inner = 0;
+ const outer = requestAnimationFrame(() => {
+ inner = requestAnimationFrame(() => setEntered(true));
+ });
+ return () => {
+ cancelAnimationFrame(outer);
+ cancelAnimationFrame(inner);
+ };
+ }, []);
+ // No visible status indicator (the screen itself shows what the shell is doing); the
+ // machine-readable state stays on the root as data-status for tests and tooling.
+ const status = viewState.status;
+
+ const overlayActive = headerDragState.active || tabDragState.active;
+ const overlayCandidate = headerDragState.active
+ ? headerDragState.candidate
+ : tabDragState.candidate;
+
+ /**
+ * A side pane's own chrome: the divider on its inner edge, and the collapse transition —
+ * both scoped to the open state. With border-box sizing a collapsed pane would still paint
+ * its 1px, leaving a hairline where nothing is and keeping the element from ever measuring
+ * zero. The transition is dropped while resizing, where it would make the pane lag a frame
+ * behind the cursor. Top/bottom panes carry their border in POSITION_CLASSES and never
+ * collapse.
+ */
+ const sideClasses = horizontal
+ ? chrome.border
+ : [
+ open ? `${position === "left" ? "border-r" : "border-l"} ${chrome.border}` : "",
+ resizing ? "" : "transition-[width] duration-200",
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ /**
+ * A side pane's resize handle, as its own flex child rather than an overlay on the pane.
+ * The chat panels do it this way, and the slot they share has to measure the same either
+ * way: an overlay costs no layout width, so the chat column came out ~7px wider under a
+ * terminal than under the Workspace panel, and swapping the two nudged it sideways.
+ * Rendered only while open, or a displaced pane would leave a bare strip behind.
+ */
+ const sideHandle = !horizontal && open && (
+ <div
+ data-testid="terminal-dock-resizer"
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={S.terminal.resize}
+ title={S.terminal.resize}
+ {...resizerDragProps}
+ onDoubleClick={onResizerDoubleClick}
+ className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 ${
+ resizing ? "bg-sky-500/60" : "bg-transparent hover:bg-sky-500/40"
+ }`}
+ />
+ );
+
+ return (
+ <>
+ {position === "right" && sideHandle}
+ <div
+ data-testid="terminal-dock"
+ data-position={position}
+ data-status={status}
+ style={
+ horizontal ? { height: `${ratio * 100}%` } : { width: open && entered ? sideWidth : 0 }
+ }
+ // Mounted-but-collapsed rather than unmounted, exactly like the chat panels: the width
+ // transition needs the node, and `inert` keeps a pane nobody can see out of the tab
+ // order and the accessibility tree. Not applied while resizing — a transition would
+ // make the pane lag a frame behind the cursor.
+ inert={!open}
+ className={`relative flex min-h-0 min-w-0 flex-col overflow-hidden ${chrome.surface} ${POSITION_CLASSES[position]} ${sideClasses}`}
+ >
+ {/* Top/bottom: the handle straddles the boundary as an overlay, costing no height. A
+ side pane's is a layout sibling instead — see sideHandle. */}
+ {horizontal && (
+ <div
+ data-testid="terminal-dock-resizer"
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label={S.terminal.resize}
+ title={S.terminal.resize}
+ {...resizerDragProps}
+ onDoubleClick={onResizerDoubleClick}
+ // A 6px strip straddling the pane's inner edge, costing no layout height
+ // (side panes use a layout sibling instead — see sideHandle).
+ className={`absolute left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${
+ position === "bottom" ? "-top-[3px]" : "-bottom-[3px]"
+ } ${resizing ? "bg-sky-500/60" : "bg-transparent hover:bg-sky-500/40"}`}
+ />
+ )}
+
+ {/* Fixed-width content inside the clipping window (the chat panels do the same): while
+ the outer element animates through intermediate widths, the terminal must not
+ reflow frame by frame — xterm would refit its grid on every one of them. */}
+ <div
+ className="flex min-h-0 flex-1 flex-col"
+ style={horizontal ? undefined : { width: sideWidth }}
+ >
+ <header
+ data-testid="terminal-dock-header"
+ {...headerDragProps}
+ className={`flex shrink-0 cursor-grab select-none items-center gap-2 border-b px-3 py-1.5 text-xs ${chrome.border}`}
+ >
+ {/* Grip: the visual "this bar drags" affordance (any non-interactive spot of the
+ header drags the pane; the grip is the always-present, unmistakable one). */}
+ <span
+ data-testid="terminal-dock-grip"
+ aria-hidden
+ className={`flex h-6 shrink-0 items-center ${chrome.grip}`}
+ >
+ <svg width="10" height="14" viewBox="0 0 10 14" fill="currentColor">
+ <circle cx="2.5" cy="2.5" r="1.2" />
+ <circle cx="7.5" cy="2.5" r="1.2" />
+ <circle cx="2.5" cy="7" r="1.2" />
+ <circle cx="7.5" cy="7" r="1.2" />
+ <circle cx="2.5" cy="11.5" r="1.2" />
+ <circle cx="7.5" cy="11.5" r="1.2" />
+ </svg>
+ </span>
+
+ {/* Tab strip: this pane's terminals, current one highlighted; drag sideways to
+ reorder, drag out to move onto another edge. Scrolls when the shells outgrow
+ the header. */}
+ <div
+ ref={stripRef}
+ data-testid="terminal-tab-strip"
+ {...stripDragProps}
+ className="no-scrollbar flex min-w-0 items-center gap-1 overflow-x-auto"
+ >
+ {paneTerminals.map((terminal, index) => (
+ <TerminalTab
+ key={terminal.id}
+ terminal={terminal}
+ index={index}
+ active={terminal.id === currentId}
+ onSelect={() => selectTerminal(terminal.id)}
+ onKill={() => onKillTerminal(terminal.id)}
+ />
+ ))}
+ </div>
+ <span className="min-w-0 flex-1" />
+
+ {/* Right-hand action cluster with uniform spacing, ending in close. */}
+ <div className="flex shrink-0 items-center gap-1.5">
+ {/* Detach: box with an arrow escaping to the top right */}
+ <DockButton
+ label={S.terminal.detach}
+ testId="terminal-dock-detach"
+ onClick={detach}
+ d="M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5"
+ />
+ {/* New shell: plus, beside close per the product spec. */}
+ <DockButton
+ label={S.terminal.newShell}
+ testId="terminal-dock-new-shell"
+ onClick={newShell}
+ d="M12 5v14M5 12h14"
+ />
+ {/* Close pane: X (its shells keep running; they fold into the primary pane) */}
+ <DockButton
+ label={S.terminal.close}
+ testId="terminal-dock-close"
+ onClick={() => closePane(position)}
+ d="M6 6l12 12M18 6L6 18"
+ />
+ </div>
+ </header>
+
+ {/* The shown terminal's pooled view is adopted here (see the body effect). */}
+ <div ref={bodyRef} className="flex min-h-0 flex-1 flex-col overflow-hidden px-2 py-1" />
+ {/* Resolution/creation failure: say so instead of sitting blank. The server's error
+ message is shown verbatim (e.g. terminal_spawn_failed with the spawn error). */}
+ {currentId === null && resolveError !== null && (
+ <div
+ data-testid="terminal-dock-error"
+ className="absolute inset-x-0 bottom-0 top-9 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center"
+ >
+ <div className={`text-sm ${chrome.danger}`}>{S.terminal.createFailed}</div>
+ <div className={`max-w-xl break-all text-xs ${chrome.muted}`}>{resolveError}</div>
+ <button
+ type="button"
+ data-testid="terminal-dock-retry"
+ onClick={() => {
+ setPaneError(position, null);
+ void resolvePaneCurrent(position);
+ }}
+ className={`rounded border px-3 py-1 text-xs ${chrome.outlineButton}`}
+ >
+ {S.common.retry}
+ </button>
+ </div>
+ )}
+ </div>
+
+ {overlayActive && <DockLayoutOverlay candidate={overlayCandidate} />}
+ </div>
+ {position === "left" && sideHandle}
+ </>
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-frames.ts b/packages/web/src/features/terminal/terminal-frames.ts
new file mode 100644
index 00000000..26727249
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-frames.ts
@@ -0,0 +1,49 @@
+/**
+ * Client half of the terminal wire format. Must stay in step with
+ * `packages/server/src/terminal/frames.ts`: `[opcode, slot, ...payload]`.
+ *
+ * Output is decoded straight into a string and handed to xterm — no JSON parse on the hot
+ * path, which is what keeps a noisy build from stuttering the UI thread.
+ */
+
+export const TerminalOpcode = {
+ Output: 0x01,
+ Input: 0x02,
+ Resize: 0x03,
+ Restore: 0x05,
+ Exit: 0x06,
+} as const;
+
+export type TerminalOpcode = (typeof TerminalOpcode)[keyof typeof TerminalOpcode];
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+export function encodeFrame(opcode: TerminalOpcode, payload: string | Uint8Array = ""): Uint8Array {
+ const bytes = typeof payload === "string" ? encoder.encode(payload) : payload;
+ const frame = new Uint8Array(2 + bytes.byteLength);
+ frame[0] = opcode;
+ frame[1] = 0; // slot: single stream per socket today
+ frame.set(bytes, 2);
+ return frame;
+}
+
+export interface DecodedFrame {
+ opcode: number;
+ slot: number;
+ text: string;
+}
+
+export function decodeFrame(buffer: ArrayBuffer): DecodedFrame | null {
+ if (buffer.byteLength < 2) return null;
+ const head = new Uint8Array(buffer, 0, 2);
+ return {
+ opcode: head[0] as number,
+ slot: head[1] as number,
+ text: decoder.decode(new Uint8Array(buffer, 2)),
+ };
+}
+
+export function encodeResize(cols: number, rows: number, intent: "claim" | "update"): Uint8Array {
+ return encodeFrame(TerminalOpcode.Resize, JSON.stringify({ cols, rows, intent }));
+}
diff --git a/packages/web/src/features/terminal/terminal-list.ts b/packages/web/src/features/terminal/terminal-list.ts
new file mode 100644
index 00000000..ae46a10a
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-list.ts
@@ -0,0 +1,199 @@
+/**
+ * The user's live terminals, as a tiny module-level store. Every shell the user has is in
+ * here, whichever conversation it was opened in: the dock's tab strip and the toolbar's
+ * badge narrow it to the ones the current scope holds (terminal-dock-state.ts), while the
+ * toolbar's terminal menu lists all of them, so any shell can be pulled into view here.
+ *
+ * The server is the source of truth (`GET /api/terminals`, alive only); this store decides
+ * *when* to look. There is no push channel for terminal lifecycle yet, so:
+ * - every dock lifecycle step that can change the list calls refreshTerminals() directly
+ * (create, reattach, kill, exit);
+ * - while anyone is subscribed, a slow poll plus a window-focus refresh catch changes this
+ * tab cannot see (a shell exiting on its own, terminals opened from another window).
+ */
+import type { TerminalInfo } from "./terminal-view";
+import { pruneAssignments } from "./terminal-dock-state";
+
+const POLL_MS = 30_000;
+
+const ORDER_KEY = "penguin.terminal.tabOrder";
+
+/** Raw live list as the server reports it (creation order). */
+let raw: TerminalInfo[] = [];
+/** Stable sorted snapshot (same reference until contents change) for useSyncExternalStore. */
+let terminals: TerminalInfo[] = [];
+let fingerprint = "";
+let inflight: Promise<void> | null = null;
+const listeners = new Set<() => void>();
+let pollTimer: ReturnType<typeof setInterval> | null = null;
+/** True once the server answered 404 for the terminal API (an older runtime). */
+let unsupported = false;
+
+/**
+ * User-chosen tab order (ids), persisted. Presentation-only: ids the order does not know
+ * (new terminals, other devices) keep their creation order after the ranked ones.
+ */
+let order: string[] = (() => {
+ try {
+ const parsed: unknown = JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]");
+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
+ } catch {
+ return [];
+ }
+})();
+
+function applyOrder(list: TerminalInfo[]): TerminalInfo[] {
+ const rank = new Map(order.map((id, index) => [id, index]));
+ return list
+ .map((t, index) => ({ t, key: rank.get(t.id) ?? order.length + index }))
+ .sort((a, b) => a.key - b.key)
+ .map((entry) => entry.t);
+}
+
+/**
+ * Terminals the user just asked to kill, excluded from refresh results while the shell is
+ * still winding down (a DELETE only signals; `alive` flips when the pty exits a moment
+ * later). Without this, the reconciling refresh would resurrect the tab the user just
+ * closed. Entries clear when the server stops listing the id, or after a deadline.
+ */
+const pendingKills = new Map<string, number>();
+
+function isPendingKill(id: string): boolean {
+ const deadline = pendingKills.get(id);
+ if (deadline === undefined) return false;
+ if (Date.now() > deadline) {
+ pendingKills.delete(id);
+ return false;
+ }
+ return true;
+}
+
+function commit(next: TerminalInfo[]): void {
+ raw = next;
+ const sorted = applyOrder(next);
+ const nextFingerprint = JSON.stringify(sorted);
+ if (nextFingerprint === fingerprint) return;
+ terminals = sorted;
+ fingerprint = nextFingerprint;
+ for (const listener of [...listeners]) listener();
+}
+
+/**
+ * Persists a user-dragged tab order and re-sorts the snapshot. `ids` is one pane's tabs in
+ * their new relative order — but `order` is the single global ranking, so the reordered ids
+ * are spliced into the slots they already occupy globally, leaving every other pane's
+ * terminals ranked exactly where they were.
+ */
+export function setTerminalTabOrder(ids: string[]): void {
+ const moved = new Set(ids);
+ const queue = [...ids];
+ const merged = applyOrder(raw)
+ .map((t) => t.id)
+ .map((id) => (moved.has(id) ? queue.shift()! : id));
+ order = [...merged, ...queue]; // ids the raw list does not know yet keep their given order
+ try {
+ localStorage.setItem(ORDER_KEY, JSON.stringify(ids));
+ } catch {
+ // Private-mode storage failures only cost persistence.
+ }
+ commit(raw);
+}
+
+/** Live title update from the attached client's own xterm (OSC parsed locally). */
+export function noteTerminalTitle(id: string, title: string): void {
+ if (!raw.some((t) => t.id === id && (t.title ?? "") !== title)) return;
+ commit(raw.map((t) => (t.id === id ? { ...t, title } : t)));
+}
+
+/** Live terminals, ordered by creation time (the server's list order). */
+export function liveTerminals(): TerminalInfo[] {
+ return terminals;
+}
+
+/** Whether this server serves the terminal API at all (false on an older runtime). */
+export function terminalApiSupported(): boolean {
+ return !unsupported;
+}
+
+/** Re-reads the list from the server; concurrent calls share one request. */
+export function refreshTerminals(): Promise<void> {
+ if (inflight) return inflight;
+ inflight = (async () => {
+ try {
+ const res = await fetch("/api/terminals", { credentials: "same-origin" });
+ // 404 means the route does not exist at all: the running runtime predates the
+ // terminal API. Under hot update the Web App and the runtime can be different
+ // versions by design, so the UI has to notice rather than offer a dead control.
+ if (res.status === 404 && !unsupported) {
+ unsupported = true;
+ for (const listener of [...listeners]) listener();
+ return;
+ }
+ if (!res.ok) return; // signed out or server unreachable: keep the last known list
+ unsupported = false;
+ const data = (await res.json()) as { terminals: TerminalInfo[] };
+ const listed = new Set(data.terminals.map((t) => t.id));
+ for (const id of pendingKills.keys()) {
+ if (!listed.has(id)) pendingKills.delete(id); // fully gone: nothing left to hide
+ }
+ const live = data.terminals.filter((t) => t.alive && !isPendingKill(t.id));
+ pruneAssignments(new Set(live.map((t) => t.id)));
+ commit(live);
+ } catch {
+ // Network hiccup: the next poll/focus refresh will catch up.
+ } finally {
+ inflight = null;
+ }
+ })();
+ return inflight;
+}
+
+const onFocus = (): void => void refreshTerminals();
+
+export function subscribeTerminals(listener: () => void): () => void {
+ if (listeners.size === 0) {
+ void refreshTerminals();
+ pollTimer = setInterval(() => void refreshTerminals(), POLL_MS);
+ window.addEventListener("focus", onFocus);
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0 && pollTimer !== null) {
+ clearInterval(pollTimer);
+ pollTimer = null;
+ window.removeEventListener("focus", onFocus);
+ }
+ };
+}
+
+/**
+ * A terminal the user just created (the POST response in hand): into the list right away,
+ * so the count/tabs react to the user's own action instantly rather than after a re-fetch.
+ */
+export function noteTerminalCreated(info: TerminalInfo): void {
+ if (raw.some((t) => t.id === info.id)) return;
+ commit([...raw, info]);
+}
+
+/**
+ * Kills a terminal. Optimistic: the user's intent is immediate, so the entry leaves the
+ * list (count, tabs, badge) before the server round-trip; delayed refreshes reconcile once
+ * the pty has actually exited, with `pendingKills` keeping the dying shell from
+ * reappearing in between.
+ */
+export async function killTerminal(id: string): Promise<void> {
+ pendingKills.set(id, Date.now() + 10_000);
+ commit(raw.filter((t) => t.id !== id));
+ try {
+ await fetch(`/api/terminals/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ credentials: "same-origin",
+ });
+ } catch {
+ // The delayed refreshes below still reconcile with whatever the server thinks.
+ }
+ for (const delay of [300, 1500]) {
+ setTimeout(() => void refreshTerminals(), delay);
+ }
+}
diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsx
new file mode 100644
index 00000000..ebbc3292
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-page.tsx
@@ -0,0 +1,178 @@
+/**
+ * Standalone terminal page (`/terminal`): a full-window terminal outside the app shell.
+ * This is where the in-app dock "detach"es to (Codex-style), and it is deep-linkable:
+ *
+ * /terminal reattach to this page's last terminal, else create one in `~`
+ * /terminal?id=<id> attach exactly that terminal (the detach handoff)
+ * /terminal?cwd=/some/dir create the terminal in that directory
+ * /terminal?name=<name> display/session name for a newly created terminal
+ *
+ * Once a terminal is attached, its id is written back into the URL (replaceState, no
+ * navigation), so a reload — or copying the address to another window — reattaches to the
+ * same shell. The server answers reattach with a Restore frame that repaints the entire
+ * screen (scrollback, colours, cursor, input modes); the shell itself never notices.
+ *
+ * When `?id=` points at a terminal that no longer exists (server restart, reaped after
+ * exit), a fresh shell is created with the URL's cwd/name — the page always ends in a
+ * usable terminal rather than a dead end.
+ */
+import { useCallback, useMemo, useState } from "react";
+import { S } from "../../lib/strings";
+import { useTerminalChrome } from "./terminal-appearance";
+import {
+ TerminalView,
+ fetchJson,
+ probeJson,
+ type TerminalInfo,
+ type TerminalStatus,
+} from "./terminal-view";
+
+const STORAGE_KEY = "penguin.terminal.page.id";
+
+export interface TerminalPageParams {
+ id: string | null;
+ cwd: string;
+ name: string | null;
+}
+
+/** Parses the /terminal search string into attach parameters (exported for tests). */
+export function parseTerminalParams(search: string): TerminalPageParams {
+ const params = new URLSearchParams(search);
+ const id = params.get("id");
+ const cwd = params.get("cwd");
+ const name = params.get("name");
+ return {
+ id: id && id.trim() ? id.trim() : null,
+ cwd: cwd && cwd.trim() ? cwd.trim() : "~",
+ name: name && name.trim() ? name.trim() : null,
+ };
+}
+
+/** Rewrites `?id=` in place (keeping cwd/name so "new shell" can recreate alike). */
+function writeIdToUrl(id: string): void {
+ const url = new URL(location.href);
+ url.searchParams.set("id", id);
+ history.replaceState(null, "", url);
+}
+
+async function attachOrCreate(
+ params: TerminalPageParams,
+ cols: number,
+ rows: number,
+): Promise<TerminalInfo> {
+ // 1. An explicit id wins — this is the detach handoff. A dead-but-not-yet-reaped
+ // terminal is still returned so the user sees its final screen and exit status.
+ if (params.id) {
+ const existing = await probeJson<TerminalInfo>(`/api/terminals/${params.id}`).catch(() => null);
+ if (existing) return existing;
+ } else {
+ // 2. Bare visit: reattach to this page's previous terminal when it is still alive.
+ const storedId = localStorage.getItem(STORAGE_KEY);
+ if (storedId) {
+ const stored = await probeJson<TerminalInfo>(`/api/terminals/${storedId}`).catch(() => null);
+ if (stored?.alive) return stored;
+ }
+ }
+
+ // 3. Create afresh from the URL's cwd/name.
+ const created = await fetchJson<TerminalInfo>("/api/terminals", {
+ method: "POST",
+ body: JSON.stringify({
+ cwd: params.cwd,
+ cols,
+ rows,
+ ...(params.name !== null ? { name: params.name } : {}),
+ }),
+ });
+ return created;
+}
+
+export function TerminalPage() {
+ const chrome = useTerminalChrome();
+ const [status, setStatus] = useState<TerminalStatus>("connecting");
+ const [detail, setDetail] = useState<string>("");
+ const [info, setInfo] = useState<TerminalInfo | null>(null);
+ const [generation, setGeneration] = useState(0);
+
+ // window.location, not useLocation(): the id is written back with history.replaceState,
+ // which the router never observes — its location object would go stale after the first
+ // attach. Re-read on each restart (generation bump).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const params = useMemo(() => parseTerminalParams(window.location.search), [generation]);
+
+ const ensure = useCallback(
+ async (cols: number, rows: number): Promise<TerminalInfo> => {
+ const terminal = await attachOrCreate(
+ parseTerminalParams(window.location.search),
+ cols,
+ rows,
+ );
+ localStorage.setItem(STORAGE_KEY, terminal.id);
+ writeIdToUrl(terminal.id);
+ return terminal;
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [generation],
+ );
+
+ /** "New shell": drop the current session and recreate from cwd/name (id removed). */
+ const restart = useCallback(() => {
+ localStorage.removeItem(STORAGE_KEY);
+ const url = new URL(location.href);
+ url.searchParams.delete("id");
+ history.replaceState(null, "", url);
+ setStatus("connecting");
+ setDetail("");
+ setInfo(null);
+ setGeneration((n) => n + 1);
+ }, []);
+
+ const onStatus = useCallback((next: TerminalStatus, statusDetail: string) => {
+ setStatus(next);
+ setDetail(statusDetail);
+ }, []);
+
+ const statusText =
+ status === "exited" && detail
+ ? `${S.terminal.status.exited} — ${S.terminal.exitedWithCode(detail)}`
+ : `${S.terminal.status[status]}${status === "error" && detail ? ` — ${detail}` : ""}`;
+
+ return (
+ <div className={`flex h-screen w-screen flex-col ${chrome.surface}`}>
+ <header
+ className={`flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs ${chrome.border}`}
+ >
+ <span className="font-medium">{S.terminal.title}</span>
+ <span className={chrome.muted}>{info?.cwd ?? params.cwd}</span>
+ <span
+ data-testid="terminal-status"
+ data-status={status}
+ className={
+ status === "ready"
+ ? "text-emerald-400"
+ : status === "connecting"
+ ? "text-amber-400"
+ : "text-red-400"
+ }
+ >
+ ● {statusText}
+ </span>
+ <button
+ type="button"
+ data-testid="terminal-new-shell"
+ onClick={restart}
+ className={`ml-auto rounded border px-2 py-1 ${chrome.outlineButton}`}
+ >
+ {S.terminal.newShell}
+ </button>
+ </header>
+ <TerminalView
+ key={generation}
+ ensure={ensure}
+ onStatus={onStatus}
+ onInfo={setInfo}
+ className="min-h-0 flex-1 overflow-hidden px-2 py-1"
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-view-pool.tsx b/packages/web/src/features/terminal/terminal-view-pool.tsx
new file mode 100644
index 00000000..d5b43cbe
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-view-pool.tsx
@@ -0,0 +1,150 @@
+/**
+ * The dock's live terminal views, pooled OUTSIDE the pane components.
+ *
+ * Each shown terminal renders one TerminalView through a portal into a per-terminal
+ * container div that this module owns and never destroys while the terminal is shown.
+ * Panes adopt the container into their body with a plain appendChild. Because both the
+ * React element (keyed by terminal id) and the DOM subtree survive any pane change,
+ * moving a terminal between panes — or moving a whole pane to another edge — never
+ * remounts xterm and never drops the WebSocket; the pane chrome around it is all that
+ * re-renders.
+ *
+ * The pool also owns the per-terminal view state (status/info) the pane headers display,
+ * and the global Ctrl+` hotkey (mounted exactly once, dock visible or not).
+ */
+import { useEffect, useSyncExternalStore } from "react";
+import { createPortal } from "react-dom";
+import { TerminalView, probeJson, type TerminalInfo, type TerminalStatus } from "./terminal-view";
+import {
+ paneHasSlot,
+ openPanes,
+ paneCurrent,
+ subscribeTerminalDock,
+ toggleTerminalDock,
+} from "./terminal-dock-state";
+import { noteTerminalTitle, refreshTerminals } from "./terminal-list";
+
+export interface TerminalViewState {
+ status: TerminalStatus;
+ info: TerminalInfo | null;
+}
+
+const containers = new Map<string, HTMLDivElement>();
+const viewStates = new Map<string, TerminalViewState>();
+const stateListeners = new Set<() => void>();
+
+function notifyViewStates(): void {
+ for (const listener of [...stateListeners]) listener();
+}
+
+export function subscribeTerminalViewStates(listener: () => void): () => void {
+ stateListeners.add(listener);
+ return () => stateListeners.delete(listener);
+}
+
+const IDLE_STATE: TerminalViewState = { status: "connecting", info: null };
+
+export function terminalViewState(id: string | null): TerminalViewState {
+ return (id !== null ? viewStates.get(id) : undefined) ?? IDLE_STATE;
+}
+
+/** The stable DOM node a pane adopts to display a terminal. */
+export function terminalViewContainer(id: string): HTMLDivElement {
+ let container = containers.get(id);
+ if (!container) {
+ container = document.createElement("div");
+ container.className = "flex h-full w-full min-h-0 flex-col";
+ containers.set(id, container);
+ }
+ return container;
+}
+
+function setViewState(id: string, patch: Partial<TerminalViewState>): void {
+ const current = viewStates.get(id) ?? { ...IDLE_STATE };
+ viewStates.set(id, { ...current, ...patch });
+ notifyViewStates();
+}
+
+/** Attach-only ensure: pane logic creates terminals; the pool only ever attaches by id. */
+function attachById(id: string) {
+ return async (): Promise<TerminalInfo> => {
+ const info = await probeJson<TerminalInfo>(`/api/terminals/${encodeURIComponent(id)}`);
+ if (!info) throw new Error("Terminal no longer exists.");
+ return info;
+ };
+}
+
+/**
+ * The set of terminal ids that should have a live view right now — the whole arrangement,
+ * not just what is visible. A side pane a chat panel displaced is still mounted (collapsed
+ * to zero width, animating), so its view has to survive the swap: tearing it down would
+ * make the panel slide in over a blank box, and coming back would flash a reconnect. Hiding
+ * the dock outright is the case that disposes.
+ */
+function shownIds(): string[] {
+ const ids: string[] = [];
+ for (const pane of openPanes()) {
+ // paneHasSlot, not isTerminalDockOpen: the latter answers "is anything on screen", and a
+ // displaced side pane is not — but it is still mounted and mid-animation, so tearing its
+ // view down here is what would make the panel slide in over a blank box.
+ if (!paneHasSlot(pane)) continue;
+ const id = paneCurrent(pane);
+ if (id !== null && !ids.includes(id)) ids.push(id);
+ }
+ return ids;
+}
+
+/** Stable snapshot for useSyncExternalStore. */
+let shownSnapshot: string[] = [];
+function shownIdsSnapshot(): string[] {
+ const next = shownIds();
+ if (next.length !== shownSnapshot.length || next.some((id, i) => id !== shownSnapshot[i])) {
+ shownSnapshot = next;
+ }
+ return shownSnapshot;
+}
+
+export function TerminalDockRuntime() {
+ const ids = useSyncExternalStore(subscribeTerminalDock, shownIdsSnapshot);
+
+ // (The Ctrl+` hotkey is a module-scope listener in terminal-dock-state.ts — binding it
+ // in an effect here left a post-paint window where the shortcut was dead.)
+
+ // Containers and view state of terminals that are no longer shown can go; a re-shown
+ // terminal reattaches cleanly (server-side restore) with a fresh container.
+ useEffect(() => {
+ for (const id of [...containers.keys()]) {
+ if (!ids.includes(id)) {
+ containers.get(id)?.remove();
+ containers.delete(id);
+ viewStates.delete(id);
+ }
+ }
+ notifyViewStates();
+ }, [ids]);
+
+ return (
+ <>
+ {ids.map((id) =>
+ createPortal(
+ <TerminalView
+ key={id}
+ ensure={attachById(id)}
+ onStatus={(status) => {
+ setViewState(id, { status });
+ if (status === "exited") void refreshTerminals();
+ }}
+ onInfo={(info) => {
+ setViewState(id, { info });
+ void refreshTerminals();
+ }}
+ onTitle={(title) => noteTerminalTitle(id, title)}
+ className="min-h-0 flex-1 overflow-hidden"
+ />,
+ terminalViewContainer(id),
+ id,
+ ),
+ )}
+ </>
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsx
new file mode 100644
index 00000000..0a8b92c4
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-view.tsx
@@ -0,0 +1,427 @@
+/**
+ * The reusable terminal surface: one xterm attached to one server-side terminal over the
+ * binary WebSocket stream. Both terminal hosts render this — the standalone `/terminal`
+ * page and the in-app dock (terminal-dock.tsx) — so attach/restore/resize behaviour is
+ * identical wherever a terminal appears.
+ *
+ * The host decides *which* terminal to show via the `ensure` callback: it receives the
+ * fitted geometry and returns the terminal to attach (reattaching to a stored id, creating
+ * a fresh one, honouring URL parameters — whatever that host's policy is). This component
+ * only knows how to attach to whatever `ensure` resolved.
+ *
+ * To restart with a different terminal, remount it (change the React `key`).
+ */
+import { useEffect, useRef } from "react";
+import "@xterm/xterm/css/xterm.css";
+// Types only (erased at compile time): the xterm runtime stays behind loadXterm() below.
+import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";
+import { TerminalOpcode, decodeFrame, encodeFrame, encodeResize } from "./terminal-frames";
+import { useTheme } from "../../state/theme";
+
+/**
+ * xterm and its addons load lazily, on the first actual terminal render: their UMD
+ * bundles touch browser globals (`self`) at import time, so a static import would crash
+ * any Node context that merely reaches this module through the import graph — which is
+ * most of the app since the dock mounts in AppLayout (unit tests import pages, pages
+ * import the toolbar, the toolbar imports the dock…).
+ */
+function loadXterm() {
+ return Promise.all([
+ import("@xterm/xterm"),
+ import("@xterm/addon-fit"),
+ import("@xterm/addon-web-links"),
+ ]);
+}
+
+export interface TerminalInfo {
+ id: string;
+ /** Stable per-user display number (assigned at creation, never renumbered). */
+ seq?: number;
+ name: string;
+ cwd: string;
+ alive: boolean;
+ /** Last OSC window title the shell set (debounced server-side), if any. */
+ title?: string | null;
+}
+
+export type TerminalStatus = "connecting" | "ready" | "exited" | "error";
+
+/**
+ * The screen's own palette, one per appearance. Two things matter here.
+ *
+ * The surface colours are the app's, not a terminal's: `#000000`/`#ffffff` are the body
+ * tones (styles.css overrides the neutral gray scale to pure black in dark mode), and the
+ * selection matches `::selection` there. A panel docked inside the app that brought its
+ * own charcoal along read as a foreign window sitting on top of it.
+ *
+ * The sixteen ANSI slots are NOT the app's palette and must not be: programs pick them by
+ * meaning ("red = error"), so they have to stay recognisable, and legible against the
+ * background they land on — which is why light mode has its own set rather than a dimmed
+ * copy. These are the values editor terminals converged on; xterm's built-in defaults are
+ * VGA-bright and unreadable on white.
+ */
+const DARK_THEME = {
+ background: "#000000",
+ foreground: "#f3f4f6",
+ cursor: "#f3f4f6",
+ cursorAccent: "#000000",
+ selectionBackground: "rgba(255, 255, 255, 0.18)",
+ black: "#000000",
+ red: "#cd3131",
+ green: "#0dbc79",
+ yellow: "#e5e510",
+ blue: "#2472c8",
+ magenta: "#bc3fbc",
+ cyan: "#11a8cd",
+ white: "#e5e5e5",
+ brightBlack: "#666666",
+ brightRed: "#f14c4c",
+ brightGreen: "#23d18b",
+ brightYellow: "#f5f543",
+ brightBlue: "#3b8eea",
+ brightMagenta: "#d670d6",
+ brightCyan: "#29b8db",
+ brightWhite: "#ffffff",
+};
+
+const LIGHT_THEME = {
+ background: "#ffffff",
+ foreground: "#111827",
+ cursor: "#111827",
+ cursorAccent: "#ffffff",
+ selectionBackground: "rgba(0, 0, 0, 0.12)",
+ black: "#000000",
+ red: "#cd3131",
+ green: "#00bc00",
+ yellow: "#949800",
+ blue: "#0451a5",
+ magenta: "#bc05bc",
+ cyan: "#0598bc",
+ white: "#555555",
+ brightBlack: "#666666",
+ brightRed: "#cd3131",
+ brightGreen: "#14ce14",
+ brightYellow: "#b5ba00",
+ brightBlue: "#0451a5",
+ brightMagenta: "#bc05bc",
+ brightCyan: "#0598bc",
+ brightWhite: "#a5a5a5",
+};
+
+export function terminalTheme(dark: boolean): ITheme {
+ return dark ? DARK_THEME : LIGHT_THEME;
+}
+
+async function request(path: string, init?: RequestInit): Promise<Response> {
+ return fetch(path, {
+ credentials: "same-origin",
+ ...init,
+ headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
+ });
+}
+
+/**
+ * A failure the user can act on: the method, the path and the server's own words. A bare
+ * "Server did not return a terminal" was the opposite — it hid a 404 (a server without the
+ * terminal API, e.g. an older build the desktop shell attached to) behind wording that
+ * suggested the terminal itself failed to start.
+ */
+export class HttpStatusError extends Error {
+ constructor(
+ readonly status: number,
+ message: string,
+ ) {
+ super(message);
+ this.name = "HttpStatusError";
+ }
+}
+
+function httpError(
+ path: string,
+ init: RequestInit | undefined,
+ res: Response,
+ body: string,
+): HttpStatusError {
+ const method = init?.method ?? "GET";
+ const detail = body.trim() === "" ? res.statusText : body.trim();
+ return new HttpStatusError(res.status, `${method} ${path} → ${res.status} ${detail}`);
+}
+
+/** Any non-ok status is an error, 404 included — use probeJson where absence is expected. */
+export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await request(path, init);
+ if (!res.ok) throw httpError(path, init, res, await res.text());
+ return (await res.json()) as T;
+}
+
+/** Existence probe: 404 means "not there" and answers null; every other failure throws. */
+export async function probeJson<T>(path: string, init?: RequestInit): Promise<T | null> {
+ const res = await request(path, init);
+ if (res.status === 404) return null;
+ if (!res.ok) throw httpError(path, init, res, await res.text());
+ return (await res.json()) as T;
+}
+
+function streamUrl(id: string, cols: number, rows: number): string {
+ const scheme = location.protocol === "https:" ? "wss:" : "ws:";
+ return `${scheme}//${location.host}/api/terminals/${id}/stream?cols=${cols}&rows=${rows}`;
+}
+
+export interface TerminalViewProps {
+ /**
+ * Resolves the terminal to attach, given the geometry the fitted xterm ended up with.
+ * Runs once per mount; throwing reports status "error" with the message as detail.
+ */
+ ensure: (cols: number, rows: number) => Promise<TerminalInfo>;
+ onStatus?: (status: TerminalStatus, detail: string) => void;
+ onInfo?: (info: TerminalInfo) => void;
+ /** OSC window-title changes, parsed by this client's own xterm from the byte stream. */
+ onTitle?: (title: string) => void;
+ className?: string;
+}
+
+export function TerminalView({ ensure, onStatus, onInfo, onTitle, className }: TerminalViewProps) {
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ // The terminal's OWN appearance setting (light / dark / follow the app, defaulting to
+ // dark — see TerminalThemeMode), not the app's. It is repainted in place rather than
+ // remounted: the xterm instance, its scrollback and its WebSocket all outlive a switch
+ // (the view pool exists to keep exactly those alive). The ref is what lets the
+ // once-per-mount effect below read the current appearance without depending on it.
+ const { terminalDark } = useTheme();
+ const darkRef = useRef(terminalDark);
+ darkRef.current = terminalDark;
+ const termRef = useRef<XTerminal | null>(null);
+ useEffect(() => {
+ if (termRef.current) termRef.current.options.theme = terminalTheme(terminalDark);
+ }, [terminalDark]);
+ // Kept in refs so the (intentionally once-per-mount) effect always calls the latest
+ // callbacks without re-running when a parent re-renders with a new closure.
+ const callbacks = useRef({ ensure, onStatus, onInfo, onTitle });
+ callbacks.current = { ensure, onStatus, onInfo, onTitle };
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ let cancelled = false;
+ let teardown: (() => void) | null = null;
+
+ // Deferred by one macrotask on purpose. StrictMode mounts, unmounts and remounts this
+ // effect synchronously in development; opening an xterm and disposing it inside that
+ // window leaves xterm's own queued viewport sync to run against a disposed instance
+ // ("cannot read properties of undefined (reading 'dimensions')"). Starting a tick later
+ // means the throwaway mount never opens a terminal at all.
+ const startTimer = setTimeout(() => {
+ if (cancelled) return;
+ void startTerminal(host).then((dispose) => {
+ // The lazy xterm load can outlive a quick unmount: dispose immediately then.
+ if (cancelled) dispose();
+ else teardown = dispose;
+ });
+ }, 0);
+
+ return () => {
+ cancelled = true;
+ clearTimeout(startTimer);
+ teardown?.();
+ };
+
+ async function startTerminal(container: HTMLDivElement): Promise<() => void> {
+ const [{ Terminal }, { FitAddon }, { WebLinksAddon }] = await loadXterm();
+ let disposed = false;
+ let socket: WebSocket | null = null;
+ let exited = false;
+
+ const report = (status: TerminalStatus, detail = ""): void => {
+ if (!disposed) callbacks.current.onStatus?.(status, detail);
+ };
+
+ const term = new Terminal({
+ allowProposedApi: true,
+ cursorBlink: true,
+ fontFamily:
+ '"JetBrains Mono", "Fira Code", Menlo, Monaco, "DejaVu Sans Mono", Consolas, monospace',
+ fontSize: 13,
+ lineHeight: 1.2,
+ scrollback: 5000,
+ theme: terminalTheme(darkRef.current),
+ });
+ const fit = new FitAddon();
+ term.loadAddon(fit);
+ term.loadAddon(new WebLinksAddon());
+ termRef.current = term;
+ term.open(container);
+ fit.fit();
+
+ /** Copies the active selection and clears it — the visual ack that the copy happened. */
+ const copySelection = (): void => {
+ const selection = term.getSelection();
+ if (!selection) return;
+ void navigator.clipboard?.writeText(selection).catch(() => {});
+ term.clearSelection();
+ };
+ /** Async-clipboard paste (the paths where no native paste event exists). */
+ const pasteFromClipboard = (): void => {
+ void navigator.clipboard
+ ?.readText()
+ .then((text) => text && term.paste(text))
+ .catch(() => {}); // permission denied / insecure context: nothing to paste
+ };
+
+ /**
+ * Terminal clipboard keys (the Windows Terminal / VS Code conventions — the single
+ * Ctrl+Shift+C of the first cut was unreliable: Chrome grabs it for DevTools):
+ * - copy: Ctrl+Shift+C, Ctrl+Insert, or plain Ctrl+C while a selection exists
+ * (SIGINT still goes through when nothing is selected);
+ * - paste: Ctrl+V, Ctrl+Shift+V and Shift+Insert all ride the browser's NATIVE paste
+ * event into xterm's textarea (no clipboard permission involved) — the browser
+ * fires `paste` for every one of these, so returning false (skip xterm's own key
+ * handling, keep the browser default) is the whole implementation; calling the
+ * async clipboard API here as well double-pastes.
+ */
+ term.attachCustomKeyEventHandler((event) => {
+ if (event.type !== "keydown") return true;
+ const key = event.key.toLowerCase();
+ const copyCombo =
+ (event.ctrlKey && event.shiftKey && key === "c") ||
+ (event.ctrlKey && !event.shiftKey && event.key === "Insert") ||
+ (event.ctrlKey && !event.shiftKey && !event.altKey && key === "c" && term.hasSelection());
+ if (copyCombo) {
+ copySelection();
+ return false;
+ }
+ const pasteCombo =
+ (event.ctrlKey && !event.altKey && key === "v") ||
+ (!event.ctrlKey && event.shiftKey && event.key === "Insert");
+ if (pasteCombo) {
+ return false; // native paste path (see above)
+ }
+ return true;
+ });
+
+ /**
+ * Terminal mouse conventions. All of these step aside when a full-screen app (vim,
+ * htop) has turned mouse tracking on — the app owns the pointer then, and xterm
+ * forwards the events as escape codes.
+ */
+ const listenerAbort = new AbortController();
+ const { signal } = listenerAbort;
+ const appOwnsMouse = (): boolean => term.modes.mouseTrackingMode !== "none";
+ container.addEventListener(
+ "contextmenu",
+ (event) => {
+ event.preventDefault(); // a terminal never shows the page's context menu
+ if (appOwnsMouse()) return;
+ // PuTTY-style right click: copy the selection if there is one, else paste.
+ if (term.hasSelection()) copySelection();
+ else pasteFromClipboard();
+ },
+ { signal },
+ );
+ container.addEventListener(
+ "mousedown",
+ (event) => {
+ // Middle click: paste (the X11 convention; browser autoscroll is useless here).
+ if (event.button === 1 && !appOwnsMouse()) {
+ event.preventDefault();
+ pasteFromClipboard();
+ }
+ },
+ { signal },
+ );
+ // Click-to-focus anywhere in the view, padding included — finishing a selection drag
+ // also lands here, which is fine: focusing xterm's textarea keeps the selection.
+ container.addEventListener("mouseup", () => term.focus(), { signal });
+
+ // Size ownership follows the user's attention (see server size-ownership.ts): the pty
+ // is laid out for the most recent CLAIMING connection, and `update`s from anyone else
+ // are ignored. Attaching claims; refocusing this view must claim again, or after
+ // another window attaches this one could never win its geometry back.
+ container.addEventListener(
+ "focusin",
+ () => {
+ if (socket?.readyState === WebSocket.OPEN) {
+ socket.send(encodeResize(term.cols, term.rows, "claim"));
+ }
+ },
+ { signal },
+ );
+
+ term.onData((data) => {
+ if (socket?.readyState === WebSocket.OPEN) {
+ socket.send(encodeFrame(TerminalOpcode.Input, data));
+ }
+ });
+
+ // Title changes ride the ordinary byte stream (OSC 0/2); this client's xterm parses
+ // them, so the host can mirror the live title (e.g. onto the dock's tab strip).
+ term.onTitleChange((title) => {
+ if (!disposed) callbacks.current.onTitle?.(title);
+ });
+
+ void (async () => {
+ try {
+ const terminal = await callbacks.current.ensure(term.cols, term.rows);
+ if (disposed) return;
+ callbacks.current.onInfo?.(terminal);
+
+ socket = new WebSocket(streamUrl(terminal.id, term.cols, term.rows));
+ socket.binaryType = "arraybuffer";
+
+ socket.onopen = () => report("ready");
+ socket.onmessage = (event) => {
+ if (!(event.data instanceof ArrayBuffer)) return;
+ const frame = decodeFrame(event.data);
+ if (!frame) return;
+ switch (frame.opcode) {
+ // The restore stream is self-contained (reset + clear + repaint + cursor), so
+ // it is written like any other output; calling term.reset() here would race
+ // with xterm's parser instead.
+ case TerminalOpcode.Restore:
+ case TerminalOpcode.Output:
+ term.write(frame.text);
+ break;
+ case TerminalOpcode.Exit: {
+ const { exitCode } = JSON.parse(frame.text) as { exitCode: number };
+ exited = true;
+ report("exited", String(exitCode));
+ break;
+ }
+ default:
+ break;
+ }
+ };
+ socket.onerror = () => report("error", "stream error");
+ socket.onclose = () => {
+ if (!exited) report("error", "stream closed");
+ };
+ } catch (err) {
+ report("error", err instanceof Error ? err.message : String(err));
+ }
+ })();
+
+ // Geometry changes are `update`s: this connection claimed the size when it attached
+ // (?cols/?rows on the stream URL, and again on focusin above); an update only
+ // applies while this connection still holds ownership.
+ const observer = new ResizeObserver(() => {
+ if (disposed) return;
+ fit.fit();
+ if (socket?.readyState === WebSocket.OPEN) {
+ socket.send(encodeResize(term.cols, term.rows, "update"));
+ }
+ });
+ observer.observe(container);
+ term.focus();
+
+ return () => {
+ disposed = true;
+ termRef.current = null;
+ listenerAbort.abort();
+ observer.disconnect();
+ socket?.close();
+ term.dispose();
+ };
+ }
+ }, []);
+
+ return <div ref={hostRef} className={className ?? "min-h-0 flex-1 overflow-hidden"} />;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 8eefae79..5352282a 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -29,6 +29,34 @@ export const en: Strings = {
unpinGroup: "Unpin group",
},
+ /** Server-side terminal (the in-app dock and the standalone /terminal page). */
+ terminal: {
+ title: "Terminal",
+ newShell: "New shell",
+ /** Tab strip ×: kills the shell itself (server-side), unlike closing the dock. */
+ killShell: "Kill this terminal",
+ /** Boundary drag handle between the dock and the main content (double-click resets). */
+ resize: "Resize terminal panel",
+ /** Hover menu when the user has no live terminal yet. */
+ noTerminals: "No terminals",
+ /** Pane body when creating/attaching a shell failed (the server message follows). */
+ createFailed: "Could not start a terminal",
+ /** A create that 404s: the server predates the terminal API (or the shell attached to an older one). */
+ noTerminalApi:
+ "this server has no terminal API: the running runtime predates it. A hot push replaces the platform and Web App, but the terminal endpoints are runtime-owned — the runtime itself has to be updated (restarting will not help)",
+ /** Codex-style handoff: opens /terminal?id=… in a new window, the dock lets go. */
+ detach: "Open in new window",
+ close: "Close",
+ status: {
+ connecting: "connecting",
+ ready: "ready",
+ exited: "exited",
+ error: "error",
+ },
+ /** Suffix shown after `status.exited`; `code` is the shell's numeric exit code. */
+ exitedWithCode: (code: string): string => `exit code ${code}`,
+ },
+
settings: {
language: "Language",
/** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */
@@ -58,6 +86,8 @@ export const en: Strings = {
themeLight: "Light",
themeDark: "Dark",
followSystem: "System",
+ terminalTheme: "Terminal theme",
+ followAppTheme: "App",
langZh: "中文",
langEn: "English",
fontSize: "Font size",
@@ -1241,6 +1271,11 @@ Scenarios:
removeImage: "Remove image",
openWorkspace: "Open workspace",
openAgents: "Agents panel",
+ /** Panel switcher (chat toolbar top-right): the "create" dropdown and its pin toggles. */
+ panelsCreate: "Create",
+ workspacePanel: "Workspace",
+ pinPanel: "Pin to toolbar",
+ unpinPanel: "Unpin",
filesInMessage: (n: number) => `${n} ${n === 1 ? "file" : "files"}`,
imagesInMessage: (n: number) => `${n} ${n === 1 ? "image" : "images"}`,
openPreview: "Click to preview",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 5c5e37e2..73383778 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -31,6 +31,34 @@ export const zh = {
unpinGroup: "取消置顶",
},
+ /** Server-side terminal (the in-app dock and the standalone /terminal page). */
+ terminal: {
+ title: "终端",
+ newShell: "新建 Shell",
+ /** Tab strip ×: kills the shell itself (server-side), unlike closing the dock. */
+ killShell: "关闭此终端",
+ /** Boundary drag handle between the dock and the main content (double-click resets). */
+ resize: "调整终端面板大小",
+ /** Hover menu when the user has no live terminal yet. */
+ noTerminals: "暂无终端",
+ /** Pane body when creating/attaching a shell failed (the server message follows). */
+ createFailed: "终端创建失败",
+ /** A create that 404s: the server predates the terminal API (or the shell attached to an older one). */
+ noTerminalApi:
+ "该服务端没有终端接口:运行中的 runtime 早于该功能。热更新只替换平台与前端,终端接口属于 runtime,需更新 runtime 本身(重启无效)",
+ /** Codex-style handoff: opens /terminal?id=… in a new window, the dock lets go. */
+ detach: "在新窗口打开",
+ close: "关闭",
+ status: {
+ connecting: "连接中",
+ ready: "已连接",
+ exited: "已退出",
+ error: "连接错误",
+ },
+ /** Suffix shown after `status.exited`; `code` is the shell's numeric exit code. */
+ exitedWithCode: (code: string): string => `退出码 ${code}`,
+ },
+
settings: {
language: "语言",
/** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */
@@ -58,6 +86,8 @@ export const zh = {
themeLight: "浅色",
themeDark: "深色",
followSystem: "跟随系统",
+ terminalTheme: "终端主题",
+ followAppTheme: "跟随主题",
langZh: "中文",
langEn: "English",
fontSize: "字号",
@@ -1197,6 +1227,11 @@ Benchmark:
removeImage: "移除图片",
openWorkspace: "打开工作区",
openAgents: "智能体面板",
+ /** Panel switcher (chat toolbar top-right): the "create" dropdown and its pin toggles. */
+ panelsCreate: "创建",
+ workspacePanel: "工作区",
+ pinPanel: "置顶到栏目",
+ unpinPanel: "取消置顶",
/** File summary card at the end of a message (Codex-style): title, inline preview action, and collapsed row. */
filesInMessage: (n: number) => `${n} 个文件`,
imagesInMessage: (n: number) => `${n} 张图片`,
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index eed0a72a..c9354086 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -18,6 +18,7 @@ import { UsagePage } from "./features/usage/usage-page";
import { TracesPage } from "./features/traces/traces-page";
import { BenchmarkPage } from "./features/benchmark/benchmark-page";
import { AdminUsersPage } from "./features/admin/admin-users-page";
+import { TerminalPage } from "./features/terminal/terminal-page";
/** Route guard: shows blank while initializing, redirects to /login when not authenticated. */
function RequireAuth() {
@@ -33,6 +34,18 @@ function RequireAuth() {
);
}
+/**
+ * Login guard without the app shell: the terminal page is a standalone full-window surface
+ * (no sidebar, no Project context), it only needs the user to be signed in — the terminal
+ * WebSocket authenticates with the same session cookie.
+ */
+function RequireAuthBare({ children }: { children: React.ReactNode }) {
+ const { user } = useAuth();
+ if (user === undefined) return null;
+ if (user === null) return <Navigate to="/login" replace />;
+ return <>{children}</>;
+}
+
/** When already logged in, visiting /login redirects straight to the chat page. */
function LoginRoute() {
const { user } = useAuth();
@@ -45,6 +58,14 @@ export function AppRouter() {
<BrowserRouter>
<Routes>
<Route path="/login" element={<LoginRoute />} />
+ <Route
+ path="/terminal"
+ element={
+ <RequireAuthBare>
+ <TerminalPage />
+ </RequireAuthBare>
+ }
+ />
<Route element={<RequireAuth />}>
<Route index element={<Navigate to="/chat" replace />} />
<Route path="/chat/:sessionId?" element={<ChatPage />} />
diff --git a/packages/web/src/state/theme.tsx b/packages/web/src/state/theme.tsx
index a96202c1..3dd09630 100644
--- a/packages/web/src/state/theme.tsx
+++ b/packages/web/src/state/theme.tsx
@@ -6,6 +6,10 @@
* - Font size: scales the root font-size (rem-based text-* utilities scale along with it).
* - Theme color: html[data-accent] overrides --accent-bg/--accent-fg; defaults to neutral
* (gray/white, follows light/dark).
+ * - Terminal theme: its own light/dark/follow-the-app setting, defaulting to dark — see
+ * TerminalThemeMode. It drives no class or variable here; the terminal reads
+ * `terminalDark` and paints itself, because Tailwind's dark: variant is anchored on
+ * html.dark and cannot express a light subtree inside a dark app.
* All preferences persist to localStorage.
*/
import { createContext, useCallback, useContext, useEffect, useState } from "react";
@@ -14,6 +18,13 @@ import type { ReactNode } from "react";
export type ThemeMode = "light" | "dark" | "system";
export type FontScale = "sm" | "md" | "lg";
export type Accent = "neutral" | "blue" | "green" | "violet" | "rose" | "amber";
+/**
+ * The terminal's appearance, which is its own preference rather than a slice of the app's.
+ * A terminal is where people keep prompts, colour schemes and TUIs tuned for a dark
+ * screen, and plenty of them want exactly that inside an otherwise light app — so the
+ * default is "dark" regardless of the app, and "app" is the opt-in that couples the two.
+ */
+export type TerminalThemeMode = "light" | "dark" | "app";
/** Display currency (prices are always stored as USD/million Tokens; conversion happens only for display and input). */
export type Currency = "USD" | "CNY";
/** 1 USD ≈ 7 CNY (fixed conversion rate). */
@@ -23,6 +34,7 @@ const MODE_KEY = "penguin.theme";
const FONT_KEY = "penguin.fontScale";
const ACCENT_KEY = "penguin.accent";
const CURRENCY_KEY = "penguin.currency";
+const TERMINAL_KEY = "penguin.terminal.theme";
/** Font size tier → root font-size (px): overall slightly larger than the system default for readability. */
const FONT_PX: Record<FontScale, string> = { sm: "16px", md: "18px", lg: "20px" };
@@ -39,6 +51,10 @@ interface ThemeContextValue {
/** Display currency for prices (shared by Cost Center and Model Library; always stored as USD). */
currency: Currency;
setCurrency: (currency: Currency) => void;
+ terminalMode: TerminalThemeMode;
+ setTerminalMode: (mode: TerminalThemeMode) => void;
+ /** Resolved terminal appearance ("app" already resolved against the app's own). */
+ terminalDark: boolean;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
@@ -70,6 +86,12 @@ function initialAccent(): Accent {
return "neutral";
}
+function initialTerminalMode(): TerminalThemeMode {
+ const stored = localStorage.getItem(TERMINAL_KEY);
+ if (stored === "light" || stored === "dark" || stored === "app") return stored;
+ return "dark";
+}
+
function initialCurrency(): Currency {
return localStorage.getItem(CURRENCY_KEY) === "CNY" ? "CNY" : "USD";
}
@@ -84,8 +106,10 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
const [fontScale, setFontScaleState] = useState<FontScale>(initialFontScale);
const [accent, setAccentState] = useState<Accent>(initialAccent);
const [currency, setCurrencyState] = useState<Currency>(initialCurrency);
+ const [terminalMode, setTerminalModeState] = useState<TerminalThemeMode>(initialTerminalMode);
const dark = mode === "system" ? sysDark : mode === "dark";
+ const terminalDark = terminalMode === "app" ? dark : terminalMode === "dark";
useEffect(() => {
document.documentElement.classList.toggle("dark", dark);
@@ -131,6 +155,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
setCurrencyState(next);
}, []);
+ const setTerminalMode = useCallback((next: TerminalThemeMode) => {
+ localStorage.setItem(TERMINAL_KEY, next);
+ setTerminalModeState(next);
+ }, []);
+
return (
<ThemeContext.Provider
value={{
@@ -143,6 +172,9 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
setAccent,
currency,
setCurrency,
+ terminalMode,
+ setTerminalMode,
+ terminalDark,
}}
>
{children}
diff --git a/packages/web/test/context-menu.test.ts b/packages/web/test/context-menu.test.ts
index f1c60e71..54521647 100644
--- a/packages/web/test/context-menu.test.ts
+++ b/packages/web/test/context-menu.test.ts
@@ -269,8 +269,13 @@ describe("sourceFiles", () => {
describe("native-menu suppression scope", () => {
it("registers no global contextmenu listener, so the browser's own menu survives off the row", () => {
+ // Matched on the TARGET, not on the call: suppressing the native menu page-wide is the
+ // thing to forbid, and only window/document/globalThis can do that. A listener bound to
+ // one element suppresses it over that element alone, which is the same scope the
+ // sidebar row gets from its onContextMenu prop — the terminal view does exactly this,
+ // because a terminal's right-click is its own (copy the selection, else paste).
const global = sourceFiles().filter(([, src]) =>
- /addEventListener\(\s*["']contextmenu["']/.test(src),
+ /\b(window|document|globalThis)\.addEventListener\(\s*["']contextmenu["']/.test(src),
);
expect(global.map(([path]) => path)).toEqual([]);
});
diff --git a/packages/web/test/terminal-dock-scope.test.ts b/packages/web/test/terminal-dock-scope.test.ts
new file mode 100644
index 00000000..eacc6d1a
--- /dev/null
+++ b/packages/web/test/terminal-dock-scope.test.ts
@@ -0,0 +1,310 @@
+/**
+ * The terminal dock is scoped to the conversation it was opened in
+ * (terminal-dock-state.ts): switching Sessions switches the arrangement, switching back
+ * restores it, and one conversation's shells never show up in another's tab strip.
+ *
+ * The module reads localStorage at import time, so the stub is installed first and the
+ * module imported dynamically.
+ */
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+let dock: typeof import("../src/features/terminal/terminal-dock-state");
+/** The stub's backing map, so a test can assert what a RELOAD would read back. */
+let store: Map<string, string>;
+
+beforeAll(async () => {
+ store = new Map<string, string>();
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ },
+ });
+ dock = await import("../src/features/terminal/terminal-dock-state");
+});
+
+describe("dock scopes", () => {
+ it("switches the whole arrangement with the Session, and restores it on return", () => {
+ dock.setDockScope("session-a");
+ dock.assignTerminalToPane("term-a", "bottom");
+ expect(dock.isTerminalDockOpen()).toBe(true);
+ expect(dock.paneCurrent("bottom")).toBe("term-a");
+
+ // A conversation that never opened a terminal shows none — the dock is simply gone.
+ dock.setDockScope("session-b");
+ expect(dock.isTerminalDockOpen()).toBe(false);
+ expect(dock.openPanes()).toEqual([]);
+
+ dock.setDockScope("session-a");
+ expect(dock.isTerminalDockOpen()).toBe(true);
+ expect(dock.openPanes()).toEqual(["bottom"]);
+ expect(dock.paneCurrent("bottom")).toBe("term-a");
+ });
+
+ it("does not lend one Session's terminals to another's panes", () => {
+ dock.setDockScope("session-a");
+ dock.assignTerminalToPane("term-a", "bottom");
+ dock.setDockScope("session-c");
+ dock.setTerminalDockOpen(true); // opens a pane of its own
+
+ expect(dock.openPanes()).toEqual(["bottom"]);
+ // Membership is explicit: term-a belongs to session-a, so it is not a tab here.
+ expect(dock.paneOfTerminal("term-a")).toBeNull();
+ });
+
+ it("adopts a terminal picked from the toolbar into the current Session's pane", () => {
+ dock.setDockScope("session-a");
+ dock.assignTerminalToPane("term-a", "bottom");
+ dock.setDockScope("session-d");
+ dock.showTerminal("term-a");
+
+ expect(dock.paneOfTerminal("term-a")).toBe("bottom");
+ expect(dock.paneCurrent("bottom")).toBe("term-a");
+ // …and it stays in the Session it came from too.
+ dock.setDockScope("session-a");
+ expect(dock.paneOfTerminal("term-a")).toBe("bottom");
+ });
+
+ it("keeps pane sizes global — a body preference, not a per-conversation one", () => {
+ dock.setDockScope("session-a");
+ dock.setPaneRatio("bottom", 0.5);
+ dock.setDockScope("session-e");
+ expect(dock.paneRatio("bottom")).toBe(0.5);
+ });
+
+ it("forgets a Session whose terminals are all gone", () => {
+ dock.setDockScope("session-f");
+ dock.assignTerminalToPane("term-f", "bottom");
+ dock.pruneAssignments(new Set<string>());
+ dock.closePane("bottom");
+
+ dock.setDockScope("session-a");
+ dock.setDockScope("session-f");
+ expect(dock.isTerminalDockOpen()).toBe(false);
+ expect(dock.paneOfTerminal("term-f")).toBeNull();
+ });
+
+ it("keeps its terminals when the last pane closes, so reopening comes back to them", () => {
+ dock.setDockScope("session-g");
+ dock.assignTerminalToPane("term-g", "bottom");
+ dock.closePane("bottom"); // the header's X: the shell keeps running
+ expect(dock.isTerminalDockOpen()).toBe(false);
+
+ dock.setTerminalDockOpen(true);
+ expect(dock.paneOfTerminal("term-g")).toBe("bottom");
+ });
+});
+
+describe("the scope-less dock", () => {
+ it("is handed to the first Session chosen, since /chat resolves to one after it loads", () => {
+ dock.setDockScope(null);
+ dock.assignTerminalToPane("term-staged", "bottom");
+
+ dock.setDockScope("session-resolved");
+ expect(dock.isTerminalDockOpen()).toBe(true);
+ expect(dock.paneOfTerminal("term-staged")).toBe("bottom");
+ // Moved, not copied: going back to no Session shows nothing.
+ dock.setDockScope(null);
+ expect(dock.isTerminalDockOpen()).toBe(false);
+ });
+
+ it("keeps a pane's error across the hand-off, since the pane itself does not change", () => {
+ dock.setDockScope(null);
+ dock.assignTerminalToPane("term-erring", "bottom");
+ dock.setPaneError("bottom", "Could not start a shell");
+
+ dock.setDockScope("session-handed");
+ expect(dock.paneError("bottom")).toBe("Could not start a shell");
+ // A real switch does clear it: that pane left the screen.
+ dock.setDockScope("session-elsewhere");
+ expect(dock.paneError("bottom")).toBeNull();
+ });
+
+ it("never clobbers a Session that already has an arrangement", () => {
+ dock.setDockScope("session-owning");
+ dock.assignTerminalToPane("term-owned", "bottom");
+ dock.setDockScope(null);
+ dock.assignTerminalToPane("term-staged", "top");
+
+ dock.setDockScope("session-owning");
+ expect(dock.paneOfTerminal("term-owned")).toBe("bottom");
+ expect(dock.paneOfTerminal("term-staged")).toBeNull();
+ });
+});
+
+describe("the side, shared with the chat panels", () => {
+ it("displaces left and right panes while a panel holds it, and gives them back", () => {
+ dock.setDockScope("session-side");
+ dock.assignTerminalToPane("term-right", "right");
+ expect(dock.visiblePanes()).toEqual(["right"]);
+
+ dock.setChatSidePanelOpen(true);
+ expect(dock.visiblePanes()).toEqual([]);
+ // Displaced, not closed: the arrangement still holds it, which is what lets it return.
+ expect(dock.openPanes()).toEqual(["right"]);
+ expect(dock.paneOfTerminal("term-right")).toBe("right");
+
+ dock.setChatSidePanelOpen(false);
+ expect(dock.visiblePanes()).toEqual(["right"]);
+ });
+
+ it("leaves top and bottom alone — they cost height, not width", () => {
+ dock.setDockScope("session-bottom");
+ dock.assignTerminalToPane("term-bottom", "bottom");
+ dock.setChatSidePanelOpen(true);
+ expect(dock.visiblePanes()).toEqual(["bottom"]);
+ });
+
+ it("hands the side back the moment a terminal is put on screen", async () => {
+ vi.useFakeTimers();
+ try {
+ dock.setDockScope("session-retake");
+ dock.assignTerminalToPane("term-left", "left");
+ dock.setChatSidePanelOpen(true);
+ expect(dock.chatSidePanelOpen()).toBe(true);
+
+ // What the chat page watches: the flag drops, and it retracts its panels in response.
+ dock.showTerminal("term-left");
+ expect(dock.chatSidePanelOpen()).toBe(false);
+ // …but the pane holds at zero width while that retraction plays. Expanding into a slot
+ // the outgoing panel still fills keeps the total width constant, which reads as the
+ // panel never leaving.
+ expect(dock.visiblePanes()).toEqual([]);
+
+ vi.advanceTimersByTime(200);
+ expect(dock.visiblePanes()).toEqual(["left"]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("drops a pending handover when the panel comes straight back", () => {
+ vi.useFakeTimers();
+ try {
+ dock.setDockScope("session-flip");
+ dock.assignTerminalToPane("term-flip", "right");
+ dock.setChatSidePanelOpen(true);
+ dock.showTerminal("term-flip"); // handover starts
+ dock.setChatSidePanelOpen(true); // …and the user reopens the panel mid-retraction
+
+ vi.advanceTimersByTime(200);
+ // The handover's timer must not fire the pane back on: the panel holds the side now.
+ expect(dock.visiblePanes()).toEqual([]);
+ expect(dock.chatSidePanelOpen()).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("hands it back for the hotkey too, not just for a pane that already exists", () => {
+ dock.setDockScope("session-hotkey");
+ dock.setChatSidePanelOpen(true);
+ dock.setTerminalDockOpen(true);
+ expect(dock.chatSidePanelOpen()).toBe(false);
+ });
+});
+
+describe("the dock's own idea of being open", () => {
+ it("does not count a displaced side pane, so the toggle reclaims instead of closing", () => {
+ dock.setDockScope("session-toggle");
+ dock.assignTerminalToPane("term-side", "right");
+ dock.setChatSidePanelOpen(true);
+ expect(dock.isTerminalDockOpen()).toBe(false); // nothing on screen, whatever the arrangement says
+
+ vi.useFakeTimers();
+ try {
+ dock.toggleTerminalDock();
+ expect(dock.chatSidePanelOpen()).toBe(false);
+ vi.advanceTimersByTime(200); // the panel's retraction, which the pane waits out
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(dock.isTerminalDockOpen()).toBe(true);
+ expect(dock.visiblePanes()).toEqual(["right"]);
+ // No stray bottom pane invented along the way: the arrangement already had one.
+ expect(dock.openPanes()).toEqual(["right"]);
+ });
+});
+
+describe("a draft becoming a Session", () => {
+ it("takes its terminals with it, instead of leaving them for the next draft", () => {
+ // Every draft shares one scope — a draft has no id of its own to key on.
+ dock.setDockScope("new");
+ dock.assignTerminalToPane("term-drafted", "bottom");
+
+ dock.adoptDockScope("session-born");
+ expect(dock.paneOfTerminal("term-drafted")).toBe("bottom");
+ expect(dock.isTerminalDockOpen()).toBe(true);
+
+ // The next new conversation starts clean rather than inheriting that terminal.
+ dock.setDockScope("new");
+ expect(dock.isTerminalDockOpen()).toBe(false);
+ expect(dock.paneOfTerminal("term-drafted")).toBeNull();
+
+ // And it stays that way across a reload: the move has to reach storage, not just the
+ // in-memory map, or the draft key comes back with the terminal still under it.
+ const stored = JSON.parse(store.get("penguin.terminal.dock") ?? "{}") as Record<
+ string,
+ { assignments: Record<string, string> }
+ >;
+ expect(Object.keys(stored)).toContain("session-born");
+ expect(Object.keys(stored)).not.toContain("new");
+ expect(stored["session-born"]?.assignments).toHaveProperty("term-drafted");
+ });
+
+ it("leaves a draft's terminals alone when the user merely navigates away", () => {
+ dock.setDockScope("new");
+ dock.assignTerminalToPane("term-parked", "bottom");
+
+ dock.setDockScope("session-elsewhere-2"); // an ordinary switch, not a birth
+ expect(dock.paneOfTerminal("term-parked")).toBeNull();
+
+ dock.setDockScope("new");
+ expect(dock.paneOfTerminal("term-parked")).toBe("bottom");
+ });
+
+ it("never clobbers a Session that already has an arrangement of its own", () => {
+ dock.setDockScope("session-established");
+ dock.assignTerminalToPane("term-established", "bottom");
+ dock.setDockScope("new");
+ dock.assignTerminalToPane("term-newborn", "bottom");
+
+ dock.adoptDockScope("session-established");
+ expect(dock.paneOfTerminal("term-established")).toBe("bottom");
+ expect(dock.paneOfTerminal("term-newborn")).toBeNull();
+ });
+});
+
+describe("what the toolbar badge counts", () => {
+ it("is this conversation's terminals, so closing the last one can reach zero", () => {
+ dock.setDockScope("session-counting");
+ dock.assignTerminalToPane("term-here", "bottom");
+ expect(dock.holdsTerminal("term-here")).toBe(true);
+
+ // A shell running in another conversation is live, but it is not this panel's to show
+ // — counting it would leave a badge no action here could ever clear.
+ dock.setDockScope("session-counting-other");
+ expect(dock.holdsTerminal("term-here")).toBe(false);
+ });
+});
+
+describe("a fresh page load", () => {
+ it("keeps the arrangement but does not open the dock on its own", async () => {
+ dock.setDockScope("session-startup");
+ dock.assignTerminalToPane("term-startup", "right");
+ expect(dock.isTerminalDockOpen()).toBe(true);
+
+ // Reload: a second module instance reading the same storage back from scratch.
+ vi.resetModules();
+ const reloaded = await import("../src/features/terminal/terminal-dock-state");
+ reloaded.setDockScope("session-startup");
+ expect(reloaded.isTerminalDockOpen()).toBe(false); // no terminal unfurling by itself
+ expect(reloaded.openPanes()).toEqual(["right"]); // …but the arrangement is still there
+ expect(reloaded.paneOfTerminal("term-startup")).toBe("right");
+
+ reloaded.setTerminalDockOpen(true);
+ expect(reloaded.visiblePanes()).toEqual(["right"]); // and reopening comes back to it
+ });
+});
diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.ts
index 3f32e844..8d4f9a6c 100644
--- a/packages/web/vite.config.ts
+++ b/packages/web/vite.config.ts
@@ -40,6 +40,9 @@ export default defineConfig({
"/api": {
target: apiProxyTarget(),
changeOrigin: false,
+ // The terminal stream (/api/terminals/:id/stream) is a WebSocket upgrade; without
+ // this the proxy answers the handshake itself and the terminal never connects.
+ ws: true,
},
},
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dab4af07..c0bb4acc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -20,7 +20,7 @@ importers:
version: file:packages/cli([email protected])
'@prismshadow/penguin-core':
specifier: workspace:*
+ version: file:packages/core([email protected])([email protected])
'@types/node':
specifier: ^24.0.0
version: 24.13.3
@@ -56,7 +56,7 @@ importers:
version: link:../core
'@prismshadow/penguin-server':
specifier: workspace:*
- version: file:packages/server([email protected])([email protected])([email protected])
+ version: file:packages/server([email protected])([email protected])
'@prismshadow/penguin-skills':
specifier: workspace:*
version: link:../skills
@@ -142,7 +142,7 @@ importers:
version: file:packages/cli([email protected])
'@prismshadow/penguin-core':
specifier: workspace:*
+ version: file:packages/core([email protected])([email protected])
'@prismshadow/penguin-server':
specifier: workspace:*
version: link:../server
@@ -276,10 +276,13 @@ importers:
version: 2.0.12([email protected])
'@prismshadow/penguin-core':
specifier: workspace:*
+ version: file:packages/core([email protected])([email protected])
'@prismshadow/penguin-skills':
specifier: workspace:*
version: link:../skills
+ '@xterm/headless':
+ specifier: ^5.5.0
+ version: 5.5.0
dotenv:
specifier: ^17.0.0
version: 17.4.2
@@ -289,6 +292,9 @@ importers:
hono:
specifier: ^4.12.34
version: 4.12.34
+ node-pty:
+ specifier: ^1.1.0
+ version: 1.1.0
smol-toml:
specifier: ^1.3.0
version: 1.6.1
@@ -298,6 +304,9 @@ importers:
undici:
specifier: ^7.29.0
version: 7.29.0
+ ws:
+ specifier: ^8.18.3
+ version: 8.21.0
yaml:
specifier: ^2.5.0
version: 2.9.0
@@ -305,6 +314,9 @@ importers:
'@types/node':
specifier: ^24.0.0
version: 24.13.3
+ '@types/ws':
+ specifier: ^8.18.1
+ version: 8.18.1
tsup:
specifier: ^8.3.0
@@ -337,13 +349,22 @@ importers:
dependencies:
'@prismshadow/penguin-core':
specifier: workspace:*
+ version: file:packages/core([email protected])([email protected])
'@shikijs/langs':
specifier: ^4.3.1
version: 4.3.1
'@shikijs/themes':
specifier: ^4.3.1
version: 4.3.1
+ '@xterm/addon-fit':
+ specifier: ^0.10.0
+ version: 0.10.0(@xterm/[email protected])
+ '@xterm/addon-web-links':
+ specifier: ^0.11.0
+ version: 0.11.0(@xterm/[email protected])
+ '@xterm/xterm':
+ specifier: ^5.5.0
+ version: 5.5.0
react:
specifier: ^19.1.0
version: 19.2.7
@@ -1477,6 +1498,9 @@ packages:
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+
resolution: {integrity: sha512-5jsZFwgR5rTdKwidH9Qmat75RKwqfpKlWWB1frDkljN127mwqBu8K0PYo7/hFpF03IEJpfVPpCQDY/eDx3iHvA==}
@@ -1520,6 +1544,22 @@ packages:
engines: {node: '>=10.0.0'}
deprecated: this version has critical issues, please update to the latest version
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
+ peerDependencies:
+ '@xterm/xterm': ^5.0.0
+
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-nIHQ38pQI+a5kXnRaTgwqSHnX7KE6+4SVoceompgHL26unAxdfP6IPqUTSYPQgSwM56hsElfoNrrW5V7BUED/Q==}
+ peerDependencies:
+ '@xterm/xterm': ^5.0.0
+
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-5xXB7kdQlFBP82ViMJTwwEc3gKCLGKR/eoxQm4zge7GPBl86tCdI0IdPJjoKd8mUSFXz5V7i/25sfsEkP4j46g==}
+
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
+
resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}
engines: {node: ^20.17.0 || >=22.9.0}
@@ -2803,6 +2843,9 @@ packages:
resolution: {integrity: sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==}
engines: {node: '>=22.12.0'}
+ resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
+
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
@@ -2823,6 +2866,9 @@ packages:
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
+ resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}
+
resolution: {integrity: sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==}
engines: {node: '>=18'}
@@ -4457,6 +4503,21 @@ snapshots:
dependencies:
playwright: 1.61.1
+ dependencies:
+ '@anthropic-ai/bedrock-sdk': 0.26.4([email protected])
+ '@anthropic-ai/sdk': 0.91.1([email protected])
+ '@google/genai': 1.52.0([email protected])
+ express: 4.22.2([email protected])
+ transitivePeerDependencies:
+ - '@modelcontextprotocol/sdk'
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+ - zod
+
dependencies:
'@anthropic-ai/bedrock-sdk': 0.26.4([email protected])
@@ -4475,9 +4536,9 @@ snapshots:
'@prismshadow/penguin-cli@file:packages/cli([email protected])':
dependencies:
'@modelcontextprotocol/client': 2.0.0
- '@prismshadow/agenthub': 0.4.4([email protected])([email protected])([email protected])
- '@prismshadow/penguin-core': file:packages/core([email protected])([email protected])([email protected])
- '@prismshadow/penguin-server': file:packages/server([email protected])([email protected])([email protected])
+ '@prismshadow/agenthub': 0.4.4([email protected])([email protected])
+ '@prismshadow/penguin-core': file:packages/core([email protected])
+ '@prismshadow/penguin-server': file:packages/server([email protected])
'@prismshadow/penguin-skills': file:packages/skills
commander: 13.1.0
dotenv: 17.4.2
@@ -4491,6 +4552,38 @@ snapshots:
- ws
- zod
+ '@prismshadow/penguin-core@file:packages/core([email protected])':
+ dependencies:
+ '@modelcontextprotocol/client': 2.0.0
+ '@prismshadow/agenthub': 0.4.4([email protected])([email protected])
+ '@prismshadow/penguin-skills': file:packages/skills
+ arktype: 2.2.3
+ smol-toml: 1.6.1
+ yaml: 2.9.0
+ transitivePeerDependencies:
+ - '@modelcontextprotocol/sdk'
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+ - zod
+
+ '@prismshadow/penguin-core@file:packages/core([email protected])([email protected])':
+ dependencies:
+ '@modelcontextprotocol/client': 2.0.0
+ '@prismshadow/agenthub': 0.4.4([email protected])([email protected])
+ '@prismshadow/penguin-skills': file:packages/skills
+ arktype: 2.2.3
+ smol-toml: 1.6.1
+ yaml: 2.9.0
+ transitivePeerDependencies:
+ - '@modelcontextprotocol/sdk'
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+ - zod
+
'@prismshadow/penguin-core@file:packages/core([email protected])([email protected])([email protected])':
dependencies:
'@modelcontextprotocol/client': 2.0.0
@@ -4507,24 +4600,48 @@ snapshots:
- ws
- zod
- '@prismshadow/penguin-server@file:packages/server([email protected])([email protected])([email protected])':
+ '@prismshadow/penguin-server@file:packages/server([email protected])':
+ dependencies:
+ '@hono/node-server': 2.0.12([email protected])
+ '@prismshadow/penguin-core': file:packages/core([email protected])([email protected])
+ '@prismshadow/penguin-skills': file:packages/skills
+ '@xterm/headless': 5.5.0
+ dotenv: 17.4.2
+ fflate: 0.8.3
+ hono: 4.12.34
+ node-pty: 1.1.0
+ smol-toml: 1.6.1
+ tar: 7.5.22
+ undici: 7.29.0
+ ws: 8.21.0
+ yaml: 2.9.0
+ transitivePeerDependencies:
+ - '@modelcontextprotocol/sdk'
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - zod
+
+ '@prismshadow/penguin-server@file:packages/server([email protected])([email protected])':
dependencies:
'@hono/node-server': 2.0.12([email protected])
'@prismshadow/penguin-core': file:packages/core([email protected])([email protected])([email protected])
'@prismshadow/penguin-skills': file:packages/skills
+ '@xterm/headless': 5.5.0
dotenv: 17.4.2
fflate: 0.8.3
hono: 4.12.34
+ node-pty: 1.1.0
smol-toml: 1.6.1
tar: 7.5.22
undici: 7.29.0
+ ws: 8.21.0
yaml: 2.9.0
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- bufferutil
- supports-color
- utf-8-validate
- - ws
- zod
'@prismshadow/penguin-skills@file:packages/skills': {}
@@ -5058,6 +5175,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 24.13.3
+
'@ungap/[email protected]': {}
@@ -5116,6 +5237,18 @@ snapshots:
'@xmldom/[email protected]': {}
+ dependencies:
+ '@xterm/xterm': 5.5.0
+
+ dependencies:
+ '@xterm/xterm': 5.5.0
+
+ '@xterm/[email protected]': {}
+
+ '@xterm/[email protected]': {}
+
@@ -6752,6 +6885,8 @@ snapshots:
dependencies:
semver: 7.8.5
+
dependencies:
semver: 7.8.5
@@ -6779,6 +6914,10 @@ snapshots:
+ dependencies:
+ node-addon-api: 7.1.1
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 4682f38e..c4207e83 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -20,6 +20,9 @@ syncInjectedDepsAfterScripts:
allowBuilds:
"@google/genai": true
esbuild: true
+ # node-pty compiles its native pty binding (node-gyp) on install; without this the
+ # terminal server has no pty and every session fails to spawn.
+ node-pty: true
protobufjs: true
# electron's postinstall downloads the platform runtime binary; without this allow
# entry pnpm skips it and `electron .` has nothing to launch.
diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs
index c50f777e..c8ddefe5 100644
--- a/scripts/deploy.mjs
+++ b/scripts/deploy.mjs
@@ -154,6 +154,51 @@ async function readWebManifest() {
return files;
}
+/**
+ * Native modules the pushed platform needs as real files. A bundle cannot carry one: it is
+ * imported from the runtime's data root, where node-pty's own relative `build/Release/
+ * pty.node` does not resolve. So the package ships whole — its JS, its prebuilds and its
+ * darwin `spawn-helper` — and the runtime unpacks it next to the bundle (hmr/host.ts's
+ * UpgradeAssets), where node-pty's normal resolution works again.
+ *
+ * `exec` carries the files whose exec bit must survive the trip: base64 has no mode, and a
+ * spawn-helper without it makes every terminal fail to start on macOS.
+ */
+async function readNativeAssets() {
+ const ptyDir = path.dirname(
+ require.resolve("node-pty/package.json", {
+ paths: [path.join(ROOT, "packages", "server")],
+ }),
+ );
+ const files = {};
+ const exec = [];
+ // Only what the loader reads at runtime. `.pdb` files are Windows debug symbols that
+ // nothing ever loads and are 90% of the package's bytes (58 MB → 3 MB without them),
+ // which is the difference between a push that crosses an ssh tunnel and one that does
+ // not; `.lib` are link-time import libraries, equally never read at runtime.
+ const wanted = (rel) =>
+ !rel.endsWith(".pdb") &&
+ !rel.endsWith(".lib") &&
+ (rel === "package.json" ||
+ rel.startsWith("lib/") ||
+ rel.startsWith("build/Release/") ||
+ rel.startsWith("prebuilds/"));
+ for (const entry of await fsp.readdir(ptyDir, { recursive: true, withFileTypes: true })) {
+ if (!entry.isFile()) continue;
+ const abs = path.join(entry.parentPath, entry.name);
+ const rel = path.relative(ptyDir, abs).split(path.sep).join("/");
+ if (!wanted(rel)) continue;
+ const target = `node_modules/node-pty/${rel}`;
+ files[target] = (await fsp.readFile(abs)).toString("base64");
+ // node-pty ships its prebuilt spawn-helper as 0644; the runtime restores the bit from
+ // this list, so push it regardless of how it looks on this machine.
+ if (rel.endsWith("spawn-helper") || ((await fsp.stat(abs)).mode & 0o111) !== 0) {
+ exec.push(target);
+ }
+ }
+ return { files, exec };
+}
+
async function main() {
if (skipWebBuild) {
if (!fs.existsSync(path.join(WEB_DIST, "index.html"))) {
@@ -173,17 +218,19 @@ async function main() {
await compileEntry(CLI_ENTRY, CLI_BUNDLE);
const files = await readWebManifest();
+ const assets = await readNativeAssets();
const gz = zlib.gzipSync(
Buffer.from(
JSON.stringify({
platform: await fsp.readFile(PLATFORM_BUNDLE, "utf8"),
cli: await fsp.readFile(CLI_BUNDLE, "utf8"),
web: { files },
+ assets,
}),
),
);
log(
- `pushing ${Object.keys(files).length} web files + 2 bundles (${(gz.length / 1048576).toFixed(1)} MB) to ${baseUrl}…`,
+ `pushing ${Object.keys(files).length} web files + ${Object.keys(assets.files).length} native assets + 2 bundles (${(gz.length / 1048576).toFixed(1)} MB) to ${baseUrl}…`,
);
const cookie = await login();