Skip to content

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

feat(web): tabbed dock sidebars for all side elements (Codex-style right/bottom docks) (#394)

Yaowei Zheng78da94563367
diff --git a/changelog/unreleased/2026-08-21-dock-tab-sidebars.md b/changelog/unreleased/2026-08-21-dock-tab-sidebars.md
new file mode 100644
index 00000000..f5b6e4ad
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-dock-tab-sidebars.md
@@ -0,0 +1,68 @@
+# Tabbed dock sidebars for every side element
+
+- **Date:** 2026-08-21
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#394](https://github.com/Prism-Shadow/penguin-harness/pull/394)
+- **Breaking:** yes — previously saved per-conversation terminal dock arrangements (browser localStorage) are not carried over; the docks start closed once, and running shells stay reachable from any dock's "+" menu.
+
+[中文版](2026-08-21-dock-tab-sidebars.zh.md)
+
+Replaced the chat page's drawer-style side panels and the old terminal pane system with
+two uniform dock surfaces, one on the right and one at the bottom of the chat page
+(Codex-style). Every side element — the subagents panel, the Workspace files panel, the
+Memory panel, the new Trace panel, and any number of terminals — became a closable tab in
+either dock: both docks can be open at once, tabs switch by click, reorder by drag within
+a strip, move to the other edge by drag or by the dock's move button, and every tab
+carries an always-visible × in its own slot (never overlapping the label). The old
+mutual-exclusion between panels (and between panels and terminal panes) was removed with
+the drawers.
+
+## Details
+
+- The chat toolbar's panel switcher became exactly two pull-open buttons — bottom dock,
+ right dock — replacing the per-element icons, their pin system and the create menu. An
+ opened dock with no tabs shows a centered picker (agents / terminal / workspace /
+ memory / trace) choosing what to open there; each dock's own "+" menu adds more tabs, a
+ fresh shell, or any live shell no conversation holds.
+- The arrangement is per conversation, like each browser window managing its own tabs:
+ tabs, active tab and open docks switch with the Session, no conversation's tabs depend
+ on another's, and everything survives a reload (least-recently-used conversations age
+ out of storage). An arrangement made while drafting is handed to the Session the first
+ send creates. Dock sizes (right width, bottom height) stay one preference.
+- Panels opened from the conversation — a message file card, a subagent chip, a
+ memory-change row, the spawn auto-open — land on the right dock by default.
+- The Trace panel shows the current conversation's Trace files (file pills, raw-file
+ export, and the performance timeline + event list reused from the traces page). The
+ Traces entry left the left navigation; the /traces browsing page stays reachable
+ through its deep links (Agents page, session details popover, benchmark runs).
+- The subagents panel's identity strip gained a jump button that opens the selected
+ child's own Session in the chat area.
+- Ctrl+` walks the conversation's terminal states: front when a panel covers it, hide
+ when shown, restore — or adopt/create a shell when no terminal tab exists here. A
+ failed shell create surfaces as an error toast.
+- A shell opened from a dock starts in the conversation's Workspace (the Workspace picked
+ in the draft, while drafting); a Workspace the server rejects falls back to the home
+ directory rather than leaving the user with no terminal.
+- Opening and closing a dock animates (a 200ms slide, contents pinned at their settled
+ size so nothing reflows mid-transition); cross-dock moves and conversation switches
+ apply instantly. The bottom surface's picker lays its choices out in a row, the right
+ one as a list. A terminal tab's × confirms before ending the shell, and detaching a
+ terminal to its own window returns the tab to the dock it left when that window closes.
+- Below 1024px the two docks render as one merged bottom surface listing both docks'
+ tabs; the stored arrangement splits back apart when the window widens. The mobile
+ bottom-Sheet variant of the panels was removed with the drawers.
+- Fixed the Trace panel's dev-mode first load: under React StrictMode's double-invoked
+ effects the listing fetch was cancelled and never retried, leaving the skeleton up
+ until the tab was toggled. Also fixed the right dock's resize handle, which could not
+ reach the box it resizes (it is a layout sibling of the dock, not a descendant).
+
+## Compatibility
+
+The dock arrangement is stored under a new localStorage key (`penguin.dock.layout`). The
+old keys (`penguin.terminal.dock`, `penguin.terminal.dockRatios`,
+`penguin.terminal.tabOrder`) are no longer read or written and are left in place; there is
+no migration. The one-time effect is that docks start closed after the update — shells
+keep running server-side, and every live shell no conversation holds can be pulled back in
+from a dock's "+" menu or the picker's terminal row. The shared side-panel width
+(`penguin.panelWidth`) carries over unchanged.
diff --git a/changelog/unreleased/2026-08-21-dock-tab-sidebars.zh.md b/changelog/unreleased/2026-08-21-dock-tab-sidebars.zh.md
new file mode 100644
index 00000000..46939355
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-dock-tab-sidebars.zh.md
@@ -0,0 +1,28 @@
+# 全部侧边元素的 Tab 式停靠侧边栏
+
+- **Date:** 2026-08-21
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#394](https://github.com/Prism-Shadow/penguin-harness/pull/394)
+- **Breaking:** yes — 此前保存的终端停靠布局(浏览器 localStorage)不再沿用;停靠区一次性回到关闭状态,运行中的 Shell 仍可从任一停靠区的「+」菜单找回。
+
+[English](2026-08-21-dock-tab-sidebars.md)
+
+将聊天页抽屉式侧边面板与旧的终端 pane 体系,替换为聊天页右侧与下方两个统一的停靠区(Codex 风格)。所有侧边元素——智能体面板、工作区文件面板、记忆面板、新增的轨迹面板,以及任意数量的终端——都成为停靠区里可关闭的 Tab:两个停靠区可同时打开,Tab 点击切换、在栏内拖拽排序、拖拽或通过停靠区的移动按钮移到另一边;每个 Tab 的关闭 × 常驻并占用独立位置,从不与标题重叠。原先面板之间(以及面板与终端 pane 之间)的互斥关系随抽屉一并移除。
+
+## 细节
+
+- 聊天工具栏的面板切换器改为恰好两个拉开按钮——下侧栏、右侧栏——取代逐元素图标、置顶体系与创建菜单。拉开一个还没有 Tab 的停靠区会显示居中的选择列表(智能体面板 / 终端 / 工作区 / 记忆 / 轨迹),选中即在该处打开;每个停靠区自己的「+」菜单可继续添加面板、新建 Shell,或接入任何无会话持有的在运行 Shell。
+- 布局按会话独立,如同每个浏览器窗口管理自己的标签页:Tab、当前 Tab 与停靠区开合随 Session 切换,任何会话的 Tab 都不依赖其他会话,且刷新后保持(最久未使用的会话布局自动老化出存储)。草稿页上的布局会交给首次发送创建出的 Session。停靠区尺寸(右宽、下高)仍是全局偏好。
+- 从对话内打开的面板——消息文件卡、子智能体行、记忆变更行、派生自动打开——默认落在右侧栏。
+- 轨迹面板展示当前会话的 Trace 文件(文件分页块、原始文件导出,以及复用自轨迹页的性能时间线与事件列表)。左侧导航的轨迹入口移除;/traces 浏览页仍可经其深链接(智能体页、会话详情弹层、评估运行)到达。
+- 智能体面板的身份条新增跳转按钮,可在对话区打开所选子智能体自己的 Session。
+- Ctrl+` 按本会话的终端状态流转:面板遮住时唤到前台、可见时收起、再按恢复——没有终端 Tab 时接入或新建 Shell。Shell 创建失败以错误 toast 呈现。
+- 从停靠区打开的 Shell 以当前会话的工作区为初始目录(草稿页则用草稿中选定的工作区);服务端拒绝该目录时回退到 home,而不是让用户开不出终端。
+- 停靠区的收起与展开带动画(200ms 滑动,内容固定在最终尺寸、过渡中不回流);跨停靠区移动与会话切换即时生效。下方表面的选择列表横向排布,右侧为纵向列表。终端 Tab 的 × 先确认再结束 Shell;分离到独立窗口的终端,在该窗口关闭后自动回到原停靠区。
+- 窗口窄于 1024px 时两个停靠区合并为一个下方表面,列出两边的 Tab;窗口拉宽后按存储布局重新拆分。面板的移动端底部 Sheet 形态随抽屉一并移除。
+- 修复轨迹面板在 dev 模式下的首次加载:React StrictMode 双调 effect 时列表请求被取消且不再重试,骨架屏会一直停留到手动切换 Tab。另修复右侧栏拖拽把手无法定位其所调整的容器(把手是停靠区的布局兄弟节点而非后代)。
+
+## 兼容性
+
+停靠布局存储于新的 localStorage 键(`penguin.dock.layout`)。旧键(`penguin.terminal.dock`、`penguin.terminal.dockRatios`、`penguin.terminal.tabOrder`)不再读写、原样留存;没有迁移。一次性影响是更新后停靠区回到关闭状态——Shell 在服务端继续运行,所有无会话持有的在运行 Shell 都可从停靠区「+」菜单或选择列表的终端行接回。共享的侧面板宽度(`penguin.panelWidth`)原样沿用。
diff --git a/packages/web/e2e/background-subagent.spec.mjs b/packages/web/e2e/background-subagent.spec.mjs
index db5784d8..16a86645 100644
--- a/packages/web/e2e/background-subagent.spec.mjs
+++ b/packages/web/e2e/background-subagent.spec.mjs
@@ -58,11 +58,16 @@ test("a run_in_background subagent runs to completion and reports back unprompte
});
// The subagents panel knows the child exists (auto-open on spawn, or via the toggle).
- const agentsToggle = page.getByRole("button", { name: "智能体面板" });
- if ((await agentsToggle.getAttribute("aria-expanded")) !== "true") {
- await agentsToggle.click();
+ // Auto-open should have brought the tab up; fall back to the right-dock picker if not.
+ if ((await page.locator('[data-tab-id="agents"][data-active="true"]').count()) === 0) {
+ await page.getByTestId("dock-toggle-right").click();
+ const picker = page.getByTestId("dock-pick-agents");
+ if (await picker.isVisible().catch(() => false)) await picker.click();
+ else await page.locator('[data-tab-id="agents"]').click();
}
- await expect(page.getByRole("heading", { name: "智能体面板" })).toBeVisible();
+ await expect(
+ page.locator('[data-testid="dock-tab"][data-tab-id="agents"][data-active="true"]'),
+ ).toBeVisible();
// No interaction from here: the child's live activity streams in (its exec_command call
// is visible without any poll), then the completion notice and the model's follow-up.
diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjs
index 976212dd..b11e595a 100644
--- a/packages/web/e2e/chat.spec.mjs
+++ b/packages/web/e2e/chat.spec.mjs
@@ -280,7 +280,8 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })
expect(up.ok(), "upload html").toBeTruthy();
await page.goto(`${BASE}/chat/${sessionId}`);
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
+ await page.getByTestId("dock-pick-workspace").click();
const fileNode = page.getByText("demo.html").first();
await expect(fileNode).toBeVisible();
await fileNode.click();
diff --git a/packages/web/e2e/dock.spec.mjs b/packages/web/e2e/dock.spec.mjs
new file mode 100644
index 00000000..826c5f59
--- /dev/null
+++ b/packages/web/e2e/dock.spec.mjs
@@ -0,0 +1,506 @@
+/**
+ * The dock system (features/dock) and the chat toolbar's two dock toggles: every side
+ * element — subagents panel, Workspace files, Memory, Trace, terminals — is a tab in the
+ * right or bottom dock.
+ * - the toolbar has exactly two pull-open buttons; an opened dock with no tabs shows a
+ * picker (choose what to open here), and each dock's own "+" menu adds more tabs;
+ * - Ctrl+` toggles the terminal tabs (front → hide → restore); the shell keeps running
+ * while hidden and reattaches on reopen;
+ * - tabs of different kinds mix in one strip with always-visible per-tab ×s: a panel
+ * tab's × closes the panel, a terminal tab's × kills the shell, the last tab closing
+ * puts the dock away;
+ * - a whole dock moves to the other edge via its header button, a single tab via drag
+ * onto the drop targets;
+ * - the arrangement is PER CONVERSATION (each one manages its own tabs, browser-window
+ * style) and survives a reload; the bottom dock's height ratio is a global preference;
+ * - a new shell starts in the conversation's Workspace, not the home directory;
+ * - "Detach" hands the terminal off to /terminal?id=… in a new window and its tab leaves;
+ * - a failed shell create surfaces as an error toast instead of silence.
+ */
+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;
+}
+
+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 adopts a live shell no conversation holds 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.
+ * The persisted arrangement is per-browser-context (fresh per test), so only the
+ * server-side shells need cleaning.
+ */
+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);
+}
+
+const dockAt = (page, position) =>
+ page.locator(`[data-testid="dock"][data-position="${position}"]`);
+const anyDock = (page) => page.locator('[data-testid="dock"]');
+const terminalBody = (page) => page.locator('[data-testid="dock-terminal-body"]:visible');
+const screenText = (page) => terminalBody(page).locator(".xterm-rows").innerText();
+
+/** Pull a dock open from the toolbar and pick an element on its picker. */
+async function openViaPicker(page, position, kind) {
+ await page.getByTestId(`dock-toggle-${position}`).click();
+ await page.getByTestId(`dock-pick-${kind}`).click();
+}
+
+/** A terminal tab's × asks first (an easy mis-click); confirm through the dialog. */
+async function killTabConfirmed(page, tabLocator) {
+ await tabLocator.getByTestId("dock-tab-close").click();
+ await page.getByRole("dialog").getByRole("button", { name: "关闭此终端" }).click();
+}
+
+async function runInTerminal(page, command) {
+ await terminalBody(page).locator(".xterm-screen").click();
+ await page.keyboard.type(command);
+ await page.keyboard.press("Enter");
+}
+
+/**
+ * Waits until the shown terminal 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 waitForShell(page, tag) {
+ await expect(page.locator('[data-testid="dock-terminal-body"][data-status="ready"]')).toBeVisible(
+ { timeout: 20000 },
+ );
+ await runInTerminal(page, `echo ${tag.slice(0, 2)}''${tag.slice(2)}`);
+ await expect.poll(() => screenText(page), { timeout: 30000 }).toMatch(new RegExp(`${tag}$`, "m"));
+}
+
+test("Ctrl+` opens a shell in the bottom dock; hiding keeps it running, reopening reattaches", 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. The docks render on the draft page too.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible({ timeout: 10000 });
+ await waitForShell(page, "DOCK_UP_1");
+ await runInTerminal(page, "echo DOCK_KEEPS_RUNNING");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("DOCK_KEEPS_RUNNING");
+
+ // Hide via the dock's ×: the surface goes away, the tab and the shell do not.
+ await dockAt(page, "bottom").getByTestId("dock-close").click();
+ await expect(anyDock(page)).toHaveCount(0);
+ await expect
+ .poll(async () => {
+ const res = await (await page.request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+ })
+ .toBe(1);
+
+ // Ctrl+` restores the same shell — the marker typed before the hide is still on screen.
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible();
+ await expect.poll(() => screenText(page), { timeout: 20000 }).toContain("DOCK_KEEPS_RUNNING");
+
+ // A terminal tab's × (always visible) asks first — killing ends the shell for real —
+ // and confirming kills it; the last tab gone puts the dock away.
+ await killTabConfirmed(
+ page,
+ dockAt(page, "bottom").locator('[data-testid="dock-tab"][data-terminal-id]'),
+ );
+ await expect(anyDock(page)).toHaveCount(0);
+ await expect
+ .poll(
+ async () => {
+ const res = await (await page.request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+ },
+ { timeout: 10000 },
+ )
+ .toBe(0);
+});
+
+test("two toolbar toggles: an opened empty dock shows the picker; hiding keeps tabs", 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}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ // Exactly two dock buttons, both reading closed; no per-element toolbar icons.
+ await expect(page.getByTestId("dock-toggle-bottom")).toHaveAttribute("aria-expanded", "false");
+ await expect(page.getByTestId("dock-toggle-right")).toHaveAttribute("aria-expanded", "false");
+ await expect(page.getByTestId("panels-toolbar").locator("button")).toHaveCount(2);
+
+ // Pull open the right dock: the picker lists every element; picking Trace opens its tab.
+ await page.getByTestId("dock-toggle-right").click();
+ const right = dockAt(page, "right");
+ await expect(right.getByTestId("dock-picker")).toBeVisible();
+ for (const kind of ["agents", "terminal", "workspace", "memory", "trace"]) {
+ await expect(right.getByTestId(`dock-pick-${kind}`)).toBeVisible();
+ }
+ await right.getByTestId("dock-pick-trace").click();
+ await expect(right.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();
+ await expect(page.getByTestId("dock-toggle-right")).toHaveAttribute("aria-expanded", "true");
+
+ // The bottom dock opens independently — both docks on screen at once.
+ await openViaPicker(page, "bottom", "memory");
+ await expect(
+ dockAt(page, "bottom").locator('[data-tab-id="memory"][data-active="true"]'),
+ ).toBeVisible();
+ await expect(anyDock(page)).toHaveCount(2);
+
+ // Toggling the right dock hides it (tab kept); reopening comes back on the tab, not the picker.
+ await page.getByTestId("dock-toggle-right").click();
+ await expect(dockAt(page, "right")).toHaveCount(0);
+ await page.getByTestId("dock-toggle-right").click();
+ await expect(right.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();
+ await expect(right.getByTestId("dock-picker")).toHaveCount(0);
+
+ // A panel tab's × closes it; the last tab closing puts the dock away entirely.
+ await right.locator('[data-tab-id="trace"]').getByTestId("dock-tab-close").click();
+ await expect(dockAt(page, "right")).toHaveCount(0);
+ await expect(page.getByTestId("dock-toggle-right")).toHaveAttribute("aria-expanded", "false");
+});
+
+test("tabs of every kind share a dock: switch, close a panel tab, terminals numbered", 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}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ await openViaPicker(page, "right", "workspace");
+ const right = dockAt(page, "right");
+ await expect(right.locator('[data-tab-id="workspace"][data-active="true"]')).toBeVisible();
+
+ // A shell into the SAME dock through its own "+" menu.
+ await right.getByTestId("dock-add").click();
+ await page.getByTestId("dock-add-terminal").click();
+ await expect(
+ right.locator('[data-testid="dock-tab"][data-terminal-id][data-active="true"]'),
+ ).toBeVisible({ timeout: 20000 });
+ await waitForShell(page, "MIXED_DOCK");
+ // The strip lists both kinds; the terminal label carries its stable `N:` seq prefix.
+ await expect(right.locator('[data-testid="dock-tab"]')).toHaveCount(2);
+ await expect(right.locator('[data-testid="dock-tab"][data-terminal-id]').first()).toContainText(
+ /^\d+:/,
+ );
+
+ // Tab click switches; the terminal's view survives being covered (still attached below).
+ await right.locator('[data-tab-id="workspace"]').click();
+ await expect(right.locator('[data-tab-id="workspace"][data-active="true"]')).toBeVisible();
+ await expect(right.getByText("根目录")).toBeVisible();
+ await right.locator('[data-testid="dock-tab"][data-terminal-id]').click();
+ await expect.poll(() => screenText(page), { timeout: 20000 }).toContain("MIXED_DOCK");
+
+ // A panel tab's × closes just the panel; the terminal tab remains, dock stays.
+ await right.locator('[data-tab-id="workspace"]').getByTestId("dock-tab-close").click();
+ await expect(right.locator('[data-testid="dock-tab"]')).toHaveCount(1);
+ await expect(right).toBeVisible();
+ await killAllTerminals(page.request);
+});
+
+test("a whole dock moves to the other edge; a single tab moves by drag onto the drop target", 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}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ await openViaPicker(page, "right", "workspace");
+ const right = dockAt(page, "right");
+ await right.getByTestId("dock-add").click();
+ await page.getByTestId("dock-add-trace").click();
+ await expect(right.locator('[data-testid="dock-tab"]')).toHaveCount(2);
+ await expect(right.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();
+
+ // Header button: the whole dock (both tabs) onto the bottom edge.
+ await right.getByTestId("dock-move").click();
+ await expect(dockAt(page, "right")).toHaveCount(0);
+ const bottom = dockAt(page, "bottom");
+ await expect(bottom.locator('[data-testid="dock-tab"]')).toHaveCount(2);
+ // The shown tab (trace, active before the move) stays the shown tab after it.
+ await expect(bottom.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();
+
+ // Drag the workspace tab out of the strip: the edge overlay appears; dropping on the
+ // RIGHT target splits it back out into its own right dock.
+ const wsTab = bottom.locator('[data-tab-id="workspace"]');
+ const wb = await wsTab.boundingBox();
+ await page.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(wb.x + wb.width / 2 + 10, wb.y - 120, { steps: 5 });
+ await expect(page.getByTestId("dock-layout-widget")).toBeVisible();
+ const target = page.locator('[data-testid="dock-layout-target"][data-dock-pos="right"]');
+ const tb = await target.boundingBox();
+ await page.mouse.move(tb.x + tb.width / 2, tb.y + tb.height / 2, { steps: 4 });
+ await expect(page.locator('[data-testid="dock-layout-preview"][data-pos="right"]')).toBeVisible();
+ await page.mouse.up();
+ await expect(
+ dockAt(page, "right").locator('[data-tab-id="workspace"][data-active="true"]'),
+ ).toBeVisible();
+ await expect(bottom.locator('[data-tab-id="trace"]')).toBeVisible();
+});
+
+test("sizes and the arrangement survive a reload; hidden stays hidden", 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}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ await openViaPicker(page, "bottom", "trace");
+ await openViaPicker(page, "right", "workspace");
+ const bottom = dockAt(page, "bottom");
+ await expect(bottom.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();
+
+ // Drag the bottom boundary up ~120px: the height ratio grows and persists.
+ const before = (await bottom.boundingBox()).height;
+ const resizer = bottom.getByTestId("dock-resizer");
+ const rb = await resizer.boundingBox();
+ await page.mouse.move(rb.x + rb.width / 2, rb.y + rb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(rb.x + rb.width / 2, rb.y - 120, { steps: 6 });
+ await page.mouse.up();
+ const after = (await bottom.boundingBox()).height;
+ expect(after - before).toBeGreaterThan(80);
+
+ // The RIGHT dock's boundary drags too (its handle is a layout sibling of the dock —
+ // the regression where it could not reach the box it resizes).
+ const right = dockAt(page, "right");
+ const wBefore = (await right.boundingBox()).width;
+ const vHandle = page.locator('[data-testid="dock-resizer"][aria-orientation="vertical"]');
+ const vb = await vHandle.boundingBox();
+ await page.mouse.move(vb.x + vb.width / 2, vb.y + vb.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(vb.x - 100, vb.y + vb.height / 2, { steps: 6 });
+ await page.mouse.up();
+ const wAfter = (await right.boundingBox()).width;
+ expect(wAfter - wBefore).toBeGreaterThan(60);
+
+ // Hide the right dock (its tab stays behind), then reload: the bottom dock comes back
+ // at its size, the right dock stays hidden, and reopening restores its tab.
+ await page.getByTestId("dock-toggle-right").click();
+ await expect(dockAt(page, "right")).toHaveCount(0);
+ await page.reload();
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await expect(
+ dockAt(page, "bottom").locator('[data-tab-id="trace"][data-active="true"]'),
+ ).toBeVisible();
+ await expect(dockAt(page, "right")).toHaveCount(0);
+ // Polled: the initial restore slides the dock in, so a one-shot measure can catch the
+ // entrance transition mid-flight.
+ await expect
+ .poll(async () => Math.abs((await dockAt(page, "bottom").boundingBox()).height - after))
+ .toBeLessThan(24);
+ await page.getByTestId("dock-toggle-right").click();
+ await expect(
+ dockAt(page, "right").locator('[data-tab-id="workspace"][data-active="true"]'),
+ ).toBeVisible();
+});
+
+test("each conversation manages its own tabs: nothing leaks, and each side survives the round trip", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const sidA = await createSession(page.request, projectId);
+ const sidB = await createSession(page.request, projectId);
+
+ await page.goto(`${BASE}/chat/${sidA}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await openViaPicker(page, "right", "workspace");
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible({ timeout: 20000 });
+ await waitForShell(page, "SCOPED_SHELL");
+ const shellId = await page
+ .locator('[data-testid="dock-tab"][data-terminal-id]')
+ .getAttribute("data-terminal-id");
+
+ // B starts with no docks of its own — A's tabs (terminal included) never leak in.
+ await page.goto(`${BASE}/chat/${sidB}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await expect(anyDock(page)).toHaveCount(0);
+ await openViaPicker(page, "bottom", "memory");
+ await expect(
+ dockAt(page, "bottom").locator('[data-tab-id="memory"][data-active="true"]'),
+ ).toBeVisible();
+
+ // Back to A: its arrangement returns — the same shell tab in the bottom dock, live
+ // (identity via the tab id plus a fresh probe; scrollback replay has a known
+ // load-sensitive flake that predates the docks). B's memory tab did not follow.
+ await page.goto(`${BASE}/chat/${sidA}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await expect(dockAt(page, "right").locator('[data-tab-id="workspace"]')).toBeVisible();
+ await expect(
+ page.locator(`[data-testid="dock-tab"][data-terminal-id="${shellId}"][data-active="true"]`),
+ ).toBeVisible();
+ await waitForShell(page, "STILL_SAME_SHELL");
+ await expect(page.locator('[data-tab-id="memory"]')).toHaveCount(0);
+ await killAllTerminals(page.request);
+});
+
+test("a new shell starts in the conversation's Workspace, not at home", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ const res = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { provider: "custom", modelId: "claude-4-8" } },
+ );
+ expect(res.ok(), "create session").toBeTruthy();
+ const session = (await res.json()).session;
+ // The Workspace directory exists from session creation (a temp one is mkdir'd then),
+ // so the shell can really start there. Compared by directory NAME: the server resolves
+ // the path's realpath, which can differ from the reported one by a symlinked prefix.
+ const dirName = session.workspace.split(/[/\\]/).filter(Boolean).pop();
+
+ await page.goto(`${BASE}/chat/${session.sessionId}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible({ timeout: 20000 });
+ await waitForShell(page, "WS_CWD");
+
+ await runInTerminal(page, "pwd");
+ await expect.poll(() => screenText(page), { timeout: 20000 }).toContain(dirName);
+ // The server names the shell after its directory, so the tab says where it opened.
+ const { terminals } = await (await page.request.get(`${BASE}/api/terminals`)).json();
+ expect(terminals.filter((t) => t.alive).map((t) => t.cwd.split(/[/\\]/).pop())).toContain(
+ dirName,
+ );
+ await killAllTerminals(page.request);
+});
+
+test("Detach hands the terminal to /terminal?id=… and its tab leaves the strip", async ({
+ page,
+ context,
+}) => {
+ 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}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible({ timeout: 20000 });
+ await waitForShell(page, "DETACH_ME");
+
+ const popupPromise = context.waitForEvent("page");
+ await dockAt(page, "bottom").getByTestId("dock-detach").click();
+ const popup = await popupPromise;
+ await popup.waitForURL(/\/terminal\?id=/);
+ // Same shell, same screen: the marker typed in the dock shows in the window.
+ await expect
+ .poll(() => popup.locator(".xterm-rows").innerText(), { timeout: 20000 })
+ .toContain("DETACH_ME");
+ // The dock let go: no terminal tab left (the dock hid with its last tab gone).
+ await expect(anyDock(page)).toHaveCount(0);
+ // Closing the window hands the shell BACK: its tab returns to the dock it left.
+ await popup.close();
+ await expect(
+ dockAt(page, "bottom").locator(
+ '[data-testid="dock-tab"][data-terminal-id][data-active="true"]',
+ ),
+ ).toBeVisible({ timeout: 10000 });
+ await expect.poll(() => screenText(page), { timeout: 20000 }).toContain("DETACH_ME");
+ await killAllTerminals(page.request);
+});
+
+test("a failed shell create surfaces as a toast, and a later attempt recovers", 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);
+
+ // 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/${sessionId}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await page.keyboard.press("Control+Backquote");
+
+ // The failure says WHY instead of doing nothing — the server's message included.
+ await expect(page.getByText("posix_spawn failed (mock)")).toBeVisible({ timeout: 10000 });
+ await expect(anyDock(page)).toHaveCount(0);
+
+ // Server recovers (unroute) → the next attempt starts a real shell.
+ await page.unroute("**/api/terminals");
+ await page.keyboard.press("Control+Backquote");
+ await expect(dockAt(page, "bottom")).toBeVisible({ timeout: 20000 });
+ await waitForShell(page, "RECOVERED");
+ await killAllTerminals(page.request);
+});
diff --git a/packages/web/e2e/files-switch.spec.mjs b/packages/web/e2e/files-switch.spec.mjs
index d87075d2..a6d95e9e 100644
--- a/packages/web/e2e/files-switch.spec.mjs
+++ b/packages/web/e2e/files-switch.spec.mjs
@@ -1,14 +1,12 @@
/**
* Regression: switching conversations while a Files-panel HTML preview is open must
- * return the panel to the NEW session's file list — not resurrect the old session's
- * preview against the new session.
+ * never resurrect the old session's preview against the new session.
*
- * The trap this guards: the panel stays mounted across a sidebar switch (client-side
- * navigation, `session` prop flips), and the openRequest locate effect also re-runs when
- * previewPath's identity changes with session.sessionId. The parent clears openRequest
- * only after child effects, so without a handled-once guard the old request replays
- * against the new session — with the isolated iframe that committed a preview-redirect
- * URL for a file the new Workspace doesn't have, i.e. a raw 404 page in the panel.
+ * Under per-conversation docks the guard is structural: B has no workspace tab of its
+ * own, so switching shows NO dock at all — nothing to replay A's preview into — and B's
+ * own workspace (opened via the toolbar toggle and the picker) starts on B's empty list.
+ * Switching back to A remounts A's workspace tab fresh, on A's file list (the preview
+ * state does not survive the scope switch — the tab's body unmounted with it).
*/
import { test, expect } from "@playwright/test";
import { provisionAndLogin } from "./auth.mjs";
@@ -70,21 +68,25 @@ test("switching conversations closes the old session's HTML preview and shows th
await cardRow.click();
await expect(page.frameLocator("iframe").getByText("Session A page")).toBeVisible();
- // --- switch to B via the sidebar (client-side navigation, the panel stays mounted) ---
+ // --- switch to B via the sidebar (client-side navigation) ---
const sidebar = page.getByRole("complementary");
// Wait for A's generated title so "新对话" uniquely identifies B.
- await expect(sidebar.getByText("Configure Tailwind theme")).toBeVisible();
+ await expect(sidebar.getByText("Configure Tailwind theme").first()).toBeVisible();
await sidebar.getByText("新对话").first().click();
await expect(page).toHaveURL(new RegExp(sidB));
- // The panel must be back on the (empty) list of B: no preview header, no iframe kept
- // or re-created for A's demo.html.
- await expect(page.getByRole("button", { name: "返回列表" })).toHaveCount(0);
+ // B manages its own tabs: no dock carried over, no iframe kept or re-created for A's
+ // demo.html. B's own workspace then opens on B's (empty) list.
+ await expect(page.locator('[data-testid="dock"]')).toHaveCount(0);
await expect(page.locator("iframe")).toHaveCount(0);
+ await page.getByTestId("dock-toggle-right").click();
+ await page.getByTestId("dock-pick-workspace").click();
+ await expect(page.getByRole("button", { name: "返回列表" })).toHaveCount(0);
await expect(page.getByText("空目录")).toBeVisible();
- // --- switching back to A keeps the panel usable: the list shows A's file again ---
+ // --- switching back to A restores A's own workspace tab, fresh on A's file list ---
await sidebar.getByText("Configure Tailwind theme").first().click();
await expect(page).toHaveURL(new RegExp(sidA));
await expect(page.getByText("demo.html").first()).toBeVisible();
+ await expect(page.locator("iframe")).toHaveCount(0);
});
diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjs
index 87ff6bf6..10ec145e 100644
--- a/packages/web/e2e/layout.spec.mjs
+++ b/packages/web/e2e/layout.spec.mjs
@@ -27,7 +27,7 @@
* chrome used to stop fitting below ~412px;
* - the sidebar's "New chat" button has no background fill (same gray-scale style as nav items);
* - the collapsed rail shows, in product-specified order, last conversation / new chat /
- * Agents / Skills / Models / Cost Center / Trajectories / Evaluation Center with localized
+ * Agents / Skills / Models / Cost Center / Evaluation Center with localized
* (en + zh) hover
* tooltips; "last conversation" targets the newest non-archived session and is disabled
* while none exists; expanding from the rail restores the pinned sidebar;
@@ -403,16 +403,17 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",
});
expect(put.ok(), "put models").toBeTruthy();
- // --- No sessions yet: the rail renders all 8 entries, "last conversation" disabled ---
+ // --- No sessions yet: the rail renders all 7 entries, "last conversation" disabled ---
await page.setViewportSize({ width: 1280, height: 720 });
await page.goto(`${BASE}/chat`);
await page.getByRole("button", { name: "Collapse sidebar" }).click();
const rail = page.locator("aside nav");
const entries = rail.locator("a, button");
- await expect(entries).toHaveCount(8);
+ await expect(entries).toHaveCount(7);
await expect(rail.getByRole("button", { name: "Last conversation" })).toBeDisabled();
- // --- Order and tooltips (en): aria-label defines the order, title carries the same copy ---
+ // --- Order and tooltips (en): aria-label defines the order, title carries the same copy.
+ // Traces has no rail entry — the Trace panel lives in the chat toolbar's panel switcher. ---
const EN = [
"Last conversation",
"New chat",
@@ -420,7 +421,6 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",
"Skills",
"Models",
"Cost Center",
- "Trajectories",
"Evaluation Center",
];
const attrs = (name) =>
@@ -479,17 +479,8 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",
// --- zh: tooltips follow the product-specified wording ---
await page.addInitScript(() => localStorage.setItem("penguin.lang", "zh"));
await page.reload();
- await expect(entries).toHaveCount(8);
- const ZH = [
- "最近一次对话",
- "新建对话",
- "智能体",
- "技能库",
- "模型库",
- "成本中心",
- "轨迹观测",
- "评估中心",
- ];
+ await expect(entries).toHaveCount(7);
+ const ZH = ["最近一次对话", "新建对话", "智能体", "技能库", "模型库", "成本中心", "评估中心"];
expect(await attrs("aria-label"), "rail order (zh)").toEqual(ZH);
expect(await attrs("title"), "rail tooltips (zh)").toEqual(ZH);
diff --git a/packages/web/e2e/mobile-dock.spec.mjs b/packages/web/e2e/mobile-dock.spec.mjs
new file mode 100644
index 00000000..e178ca8a
--- /dev/null
+++ b/packages/web/e2e/mobile-dock.spec.mjs
@@ -0,0 +1,76 @@
+/**
+ * Narrow viewport (<1024px, the dock store's merge breakpoint): the right and bottom
+ * docks render as ONE merged bottom surface — a 320px-minimum right panel does not fit a
+ * phone. Pulling open a dock lands on the merged surface's picker; picking the Workspace
+ * opens its tab there; drilling into a directory and opening a Markdown file renders the
+ * preview; the dock's × puts the whole surface away.
+ * Upload uses a nested path (notes/demo.md): also covers the server's sandbox
+ * auto-creating a missing parent directory.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+
+test.use({ viewport: { width: 412, height: 915 } });
+
+test("mobile merged dock: workspace opens at the bottom → nested dir → md rendered preview → × hides", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, "sheetuser", "password123");
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+
+ const put = await page.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();
+
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8" },
+ })
+ ).json();
+ const sessionId = sess.session.sessionId;
+
+ const md = Buffer.from("# Sheet Heading\n\nBody paragraph.").toString("base64");
+ const up = await page.request.put(
+ `${BASE}/api/sessions/${sessionId}/files/content?path=notes/demo.md`,
+ { data: { dataBase64: md } },
+ );
+ expect(up.ok(), "upload nested md").toBeTruthy();
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ // Pull open the right dock: at this width it renders as the merged bottom surface,
+ // whose picker then opens the Workspace (the tab still records its right-dock home).
+ await page.getByTestId("dock-toggle-right").click();
+
+ // One merged bottom surface, never a right dock at this width.
+ const dock = page.locator('[data-testid="dock"][data-position="bottom"]');
+ await expect(dock).toBeVisible();
+ await expect(page.locator('[data-testid="dock"][data-position="right"]')).toHaveCount(0);
+ await dock.getByTestId("dock-pick-workspace").click();
+ await expect(dock.locator('[data-tab-id="workspace"][data-active="true"]')).toBeVisible();
+
+ // Drill into the directory → open the md → default rendered view (h1 shown, not source).
+ await dock.getByText("notes").first().click();
+ await dock.getByText("demo.md").first().click();
+ await expect(dock.getByRole("heading", { name: "Sheet Heading" })).toBeVisible();
+
+ // The dock's × puts the surface away; the toolbar toggle reads closed again.
+ await dock.getByTestId("dock-close").click();
+ await expect(dock).toBeHidden();
+ await expect(page.getByTestId("dock-toggle-right")).toHaveAttribute("aria-expanded", "false");
+});
diff --git a/packages/web/e2e/outline.spec.mjs b/packages/web/e2e/outline.spec.mjs
index d1d0b6e2..6508fdf9 100644
--- a/packages/web/e2e/outline.spec.mjs
+++ b/packages/web/e2e/outline.spec.mjs
@@ -95,7 +95,8 @@ test("minimap ticks + hover preview + jump, five-turn gate, sticky group header,
// …and no toolbar fallback either while a docked panel eats the gutter. Wait until the
// stream really is too narrow for the rail (the exact condition the fallback keys on)
// plus a paint, so the button's absence proves the gate — not a panel still opening.
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
+ await page.getByTestId("dock-pick-workspace").click();
await page.waitForFunction(() => {
const c = document.querySelector("[data-outline-anchor]")?.closest(".overflow-y-auto");
return c ? (c.clientWidth - 768) / 2 < 56 : false;
@@ -104,7 +105,7 @@ test("minimap ticks + hover preview + jump, five-turn gate, sticky group header,
() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))),
);
await expect(menuButton).toHaveCount(0);
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
// The fifth exchange crosses the gate: one tick per exchange in the gutter minimap;
// auto-follow parked the stream at the bottom, so the newest exchange is the active
@@ -150,7 +151,7 @@ test("minimap ticks + hover preview + jump, five-turn gate, sticky group header,
// the index moves to the toolbar dropdown (navigation stays reachable, and the dropdown
// lists ALL entries — no windowing there); closing the panel restores the rail (live
// measurement, not a breakpoint).
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
await expect(ticks).toHaveCount(0);
await menuButton.click();
const menuEntries = page.locator("[data-outline-menu-entry]");
@@ -158,7 +159,7 @@ test("minimap ticks + hover preview + jump, five-turn gate, sticky group header,
await expect(menuEntries.first()).toContainText("第一问:项目结构");
await menuEntries.nth(2).click(); // jump and close
await expect(menuEntries).toHaveCount(0);
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
await expect(ticks).toHaveCount(5);
await expect(menuButton).toHaveCount(0);
@@ -297,7 +298,7 @@ test("the tick rail windows to the turns around the reading position on long con
// The toolbar dropdown (shown once the docked panel hides the rail) still lists EVERY
// turn — the window is rail-only; the dropdown list scrolls instead.
- await page.getByRole("button", { name: "打开工作区" }).click();
+ await page.getByTestId("dock-toggle-right").click();
await expect(ticks).toHaveCount(0);
await page.getByRole("button", { name: "对话索引" }).click();
await expect(page.locator("[data-outline-menu-entry]")).toHaveCount(TURNS);
diff --git a/packages/web/e2e/sheet.spec.mjs b/packages/web/e2e/sheet.spec.mjs
deleted file mode 100644
index e1571236..00000000
--- a/packages/web/e2e/sheet.spec.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Narrow viewport (<1024px, below use-files-panel's isDocked breakpoint): the Files panel
- * uses a bottom Sheet: open → drill into a directory → Markdown renders by default → Esc
- * closes and unmounts.
- * Upload uses a nested path (notes/demo.md): also covers the server's sandbox auto-creating
- * a missing parent directory.
- */
-import { test, expect } from "@playwright/test";
-import { provisionAndLogin } from "./auth.mjs";
-
-const BASE = process.env.BASE_URL;
-const MOCK = process.env.MOCK_URL;
-
-test.use({ viewport: { width: 412, height: 915 } });
-
-test("mobile Files sheet: open → nested dir → md rendered preview → esc close", async ({
- page,
-}) => {
- await provisionAndLogin(page.request, "sheetuser", "password123");
- const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
- const projectId = projects.projects[0].projectId;
-
- const put = await page.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();
-
- const sess = await (
- await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
- data: { provider: "custom", modelId: "claude-4-8" },
- })
- ).json();
- const sessionId = sess.session.sessionId;
-
- const md = Buffer.from("# Sheet Heading\n\nBody paragraph.").toString("base64");
- const up = await page.request.put(
- `${BASE}/api/sessions/${sessionId}/files/content?path=notes/demo.md`,
- { data: { dataBase64: md } },
- );
- expect(up.ok(), "upload nested md").toBeTruthy();
-
- await page.goto(`${BASE}/chat/${sessionId}`);
- await page.getByRole("button", { name: "打开工作区" }).click();
- const sheet = page.getByRole("dialog");
- await expect(sheet).toBeVisible();
-
- // Drill into the directory → open the md → default rendered view (h1 shown, not source).
- await sheet.getByText("notes").first().click();
- await sheet.getByText("demo.md").first().click();
- await expect(sheet.getByRole("heading", { name: "Sheet Heading" })).toBeVisible();
-
- // Esc closes: unmounts entirely once the exit animation finishes.
- await page.keyboard.press("Escape");
- await expect(sheet).toBeHidden();
-});
diff --git a/packages/web/e2e/subagent.spec.mjs b/packages/web/e2e/subagent.spec.mjs
index 47bafb65..8cf6e97c 100644
--- a/packages/web/e2e/subagent.spec.mjs
+++ b/packages/web/e2e/subagent.spec.mjs
@@ -1,22 +1,22 @@
/**
- * Subagents side panel: a spawned child session leaves only a full-width shortcut row in the
- * main stream; clicking it opens the right-hand panel with that Task's call graph (root +
- * children, clickable nodes, per-node elapsed time) above the selected child's live
+ * Subagents panel as a dock tab: a spawned child session leaves only a full-width shortcut
+ * row in the main stream; clicking it brings the agents tab up with that Task's call graph
+ * (root + children, clickable nodes, per-node elapsed time) above the selected child's live
* conversation. Verifies the row/panel flow live, across a mid-run reload and an
* after-completion reload (the parent Trace stores only a session_meta pointer for the child;
- * the server expands the child Trace and the frontend reattaches it), the agents/files panel
- * exclusivity (opening either closes the other, from any path), the TASK-SCOPED visibility (a
- * new Task closes the panel at its boundary; only a manual open or the current task's own
- * spawn brings it back, the auto-open re-armed per task and a mid-task manual close
- * respected), the historical topology (the old turn's row pins its Task back; a toolbar reopen
- * returns to the latest), the child-session title generated from the child's own conversation,
- * the sidebar "Subagents" folder, and — in a second always-ask session — that an approval
- * INSIDE the child stays discoverable (row badge) and actionable from the panel.
- * A dedicated reload-free test drives the full task-scoped lifecycle (auto-open, boundary
- * close from an open panel, per-task re-arm, manual close held for the rest of the task), and
- * a draft-flow test covers /chat/new: the panel auto-opens on the session's first live spawn,
- * and the child conversation shows its own user prompt both live (forwarded by run_subagent)
- * and after a reload (child-Trace expansion).
+ * the server expands the child Trace and the frontend reattaches it), the agents and
+ * Workspace tabs COEXISTING in one dock (activating one covers, never closes, the other),
+ * the historical topology (the old turn's row pins its Task back; closing the tab and
+ * reopening from the toolbar returns to the latest), the child-session title generated from
+ * the child's own conversation, the sidebar "Subagents" folder, the identity strip's
+ * jump-to-session button, and — in a second always-ask session — that an approval INSIDE
+ * the child stays discoverable (row badge) and actionable from the panel.
+ * A dedicated reload-free test drives the auto-open lifecycle (auto-open on the current
+ * task's first live spawn, re-armed per task, a mid-task manual close respected, an open
+ * tab surviving a plain follow-up task), and a draft-flow test covers /chat/new: the panel
+ * auto-opens on the session's first live spawn, and the child conversation shows its own
+ * user prompt both live (forwarded by run_subagent) and after a reload (child-Trace
+ * expansion).
*
* Standalone spec: shares one server with chat.spec.mjs, so it registers its own users here
* (registration auto-provisions a `project-<8hex>`), independent of chat.spec's execution order.
@@ -82,11 +82,14 @@ async function revealChip(page) {
}).toPass({ timeout: 15_000 });
}
+/** The agents dock tab, shown (its dock visible, the tab active). */
+const agentsTabActive = (page) =>
+ page.locator('[data-testid="dock-tab"][data-tab-id="agents"][data-active="true"]');
+
/**
- * Click the chip and wait for the docked panel (its title is a heading; the toolbar toggle
- * with the same text is a button). The reveal + click runs as one polled block: the turn can
- * finish between the two steps and collapse the group over the chip, so a failed click retries
- * from the reveal.
+ * Click the chip and wait for the agents tab to come up shown. The reveal + click runs as
+ * one polled block: the turn can finish between the two steps and collapse the group over
+ * the chip, so a failed click retries from the reveal.
*/
async function openPanelViaChip(page) {
const chip = chipOf(page);
@@ -97,7 +100,7 @@ async function openPanelViaChip(page) {
}
await chip.click({ timeout: 2000 });
}).toPass({ timeout: 15_000 });
- await expect(page.getByRole("heading", { name: "智能体面板" })).toBeVisible();
+ await expect(agentsTabActive(page)).toBeVisible();
}
test("subagent renders as a chip; the panel shows the call graph and child conversation, and survives reloads", async ({
@@ -160,41 +163,26 @@ test("subagent renders as a chip; the panel shows the call graph and child conve
"one done-node duration in the graph",
).toHaveCount(1);
- // --- Panel exclusivity: the agents panel and the Workspace files panel never show together —
- // opening either one (from any path; the toolbar toggles here) closes the other. A closed
- // docked panel keeps its content MOUNTED at fixed width inside a zero-width clipping window
- // (see files-panel.tsx), sliding past the viewport's right edge — so "not shown" is asserted
- // as out-of-viewport, not as hidden.
- const agentsToggle = page.getByRole("button", { name: "智能体面板" });
- const filesToggle = page.getByRole("button", { name: "打开工作区" });
- const agentsHeading = page.getByRole("heading", { name: "智能体面板" });
- const filesHeading = page.getByRole("heading", { name: "文件" });
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true"); // open from the chip click above
- await filesToggle.click(); // open files -> agents must close
- await expect(filesToggle).toHaveAttribute("aria-expanded", "true");
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false");
- await expect(filesHeading).toBeInViewport();
- await expect(agentsHeading).not.toBeInViewport();
- await agentsToggle.click(); // and the reverse: open agents -> files must close
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true");
- await expect(filesToggle).toHaveAttribute("aria-expanded", "false");
- await expect(agentsHeading).toBeInViewport();
- await expect(filesHeading).not.toBeInViewport();
- // The closed panel must leave NOTHING behind: its clipping window is zero-width, and with
- // border-box sizing a divider there would still paint its 1px right beside the open panel —
- // a hairline, the resize gutter, then the real divider, which reads as a second, empty panel.
- // Polled: the width transition is still running right after the toggle click.
- const shellWidth = (heading) =>
- heading.evaluate((el) => el.closest(".overflow-hidden").getBoundingClientRect().width);
- await expect
- .poll(() => shellWidth(filesHeading), {
- message: "closed panel occupies no width, divider included",
- })
- .toBe(0);
- expect(
- await shellWidth(agentsHeading),
- "open panel is the only one taking width",
- ).toBeGreaterThan(0);
+ // --- Tabs coexist: the agents tab and the Workspace tab share the right dock — opening
+ // one COVERS the other (it stays in the strip, inactive) instead of closing it, which is
+ // exactly what the old drawer exclusivity forbade. The workspace joins through the
+ // dock's own "+" menu.
+ const rightDock = page.locator('[data-testid="dock"][data-position="right"]');
+ await expect(agentsTabActive(page)).toBeVisible(); // shown from the chip click above
+ await rightDock.getByTestId("dock-add").click();
+ await page.getByTestId("dock-add-workspace").click(); // workspace up -> agents covered, not closed
+ await expect(rightDock.locator('[data-tab-id="workspace"][data-active="true"]')).toBeVisible();
+ await expect(rightDock.locator('[data-tab-id="agents"][data-active="false"]')).toBeVisible();
+ await rightDock.locator('[data-tab-id="agents"]').click(); // and back: agents up front, workspace stays tabbed
+ await expect(rightDock.locator('[data-tab-id="agents"][data-active="true"]')).toBeVisible();
+ await expect(rightDock.locator('[data-tab-id="workspace"][data-active="false"]')).toBeVisible();
+ // The covered tab's body renders nothing on screen (display:none, not a stray strip).
+ await expect(page.getByText("根目录")).toBeHidden();
+ // Put the workspace tab away for the blocks below via its always-visible ×; the dock
+ // stays on the agents tab.
+ await rightDock.locator('[data-tab-id="workspace"]').getByTestId("dock-tab-close").click();
+ await expect(rightDock.locator('[data-tab-id="workspace"]')).toHaveCount(0);
+ await expect(agentsTabActive(page)).toBeVisible();
// --- Historical topology: a plain follow-up Task makes the first turn's graph historical
// (the boundary itself — the panel closing on a new Task — is covered by the reload-free
@@ -216,9 +204,17 @@ test("subagent renders as a chip; the panel shows the call graph and child conve
"true",
);
await expect(page.getByText("Subagent report: 3 TODOs")).toBeVisible();
- await agentsToggle.click(); // close
- await agentsToggle.click(); // reopen from the toolbar -> back to the DEFAULT latest-Task scope
- await expect(page.getByText("本次任务尚未派生子智能体")).toBeVisible();
+ // Close the tab (its × — the last tab, so the dock goes away with it, dropping the
+ // pinned scope), then reopen through the toolbar toggle and the picker -> back to the
+ // DEFAULT latest-Task scope.
+ await rightDock.locator('[data-tab-id="agents"]').getByTestId("dock-tab-close").click();
+ await expect(rightDock).toHaveCount(0);
+ await page.getByTestId("dock-toggle-right").click();
+ await page.getByTestId("dock-pick-agents").click();
+ await expect(agentsTabActive(page)).toBeVisible();
+ // Two renders of the note (the graph section and the selection empty state) are fine —
+ // both say the same thing about the latest Task.
+ await expect(page.getByText("本次任务尚未派生子智能体").first()).toBeVisible();
// --- Child session title: generated by the model from the run_subagent prompt that spawned it (async, poll until persisted). ---
const childOf = async () => {
@@ -258,7 +254,7 @@ test("subagent renders as a chip; the panel shows the call graph and child conve
await expect(sidebar.getByText("Subagent TODO summary")).toBeVisible();
});
-test("task-scoped panel lifecycle: boundary close, per-task auto-open re-arm, manual close respected", async ({
+test("auto-open lifecycle: spawn opens the tab, a plain task keeps it, manual close is respected per task", async ({
page,
}) => {
// A dedicated fresh session with NO reloads: every send happens on a live, never-reloaded
@@ -268,37 +264,35 @@ test("task-scoped panel lifecycle: boundary close, per-task auto-open re-arm, ma
await page.goto(`${BASE}/chat/${sessionId}`);
const ta = page.getByPlaceholder(/输入消息/);
await ta.waitFor();
- const agentsToggle = page.getByRole("button", { name: "智能体面板" });
+ const closeAgentsTab = () =>
+ page.locator('[data-tab-id="agents"]').getByTestId("dock-tab-close").click();
- // Task 1 spawns: the panel opens ITSELF once the spawn goes live (no clicks).
+ // Task 1 spawns: the tab comes up ITSELF once the spawn goes live (no clicks).
await ta.fill("run a subagent");
await page.getByRole("button", { name: "发送" }).click();
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true");
+ await expect(agentsTabActive(page)).toBeVisible();
await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible();
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true"); // stays open after the task
+ await expect(agentsTabActive(page)).toBeVisible(); // stays up after the task
- // Task 2 (plain): the boundary closes the panel by default — an unrelated task must not
- // inherit it — and with no spawn it STAYS closed.
+ // Task 2 (plain): an open tab SURVIVES the boundary — the arrangement is the user's, and
+ // a task that spawns nothing neither opens nor closes anything.
await ta.fill("hello again");
await page.getByRole("button", { name: "发送" }).click();
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false"); // closed at the boundary
await expect(page.getByText("Command finished; the result looks as expected.")).toHaveCount(2);
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false"); // no spawn: stays closed
-
- // Task 3 spawns again: the auto-open is RE-ARMED per task. Open the panel manually first so
- // the boundary demonstrably closes an OPEN panel before the spawn reopens it (the mock
- // delays this spawn ~800ms, keeping boundary-close -> auto-open observable in order); a
- // manual close mid-task is then respected until the next boundary.
- await agentsToggle.click();
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true");
+ await expect(agentsTabActive(page)).toBeVisible();
+
+ // Task 3 spawns again after a manual close: the auto-open is RE-ARMED per task (the mock
+ // delays this spawn ~800ms, keeping close -> auto-open observable in order); a manual
+ // close mid-task is then respected until the next boundary.
+ await closeAgentsTab(); // manual close between tasks (the tab's ×)
+ await expect(agentsTabActive(page)).toHaveCount(0);
await ta.fill("run another subagent");
await page.getByRole("button", { name: "发送" }).click();
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false"); // boundary close first
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true"); // spawn -> auto-open again
- await agentsToggle.click(); // manual close mid-task: the task's one attempt is consumed
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false");
+ await expect(agentsTabActive(page)).toBeVisible(); // spawn -> auto-open again
+ await closeAgentsTab(); // manual close mid-task: the task's one attempt is consumed
+ await expect(agentsTabActive(page)).toHaveCount(0);
await expect(page.getByText("Command finished; the result looks as expected.")).toHaveCount(3);
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "false"); // stayed closed for the task
+ await expect(agentsTabActive(page)).toHaveCount(0); // stayed closed for the task
});
test("an approval inside the subagent stays discoverable via the chip badge and actionable from the panel", async ({
@@ -318,15 +312,15 @@ test("an approval inside the subagent stays discoverable via the chip badge and
await page.getByRole("button", { name: "允许" }).click();
// The child's exec_command approval surfaces on the chip (待审批 joins its accessible name)
- // and as an amber dot on the toolbar toggle — discoverable with the panel closed.
+ // and as an amber dot on the right-dock toggle — discoverable with the panel closed.
const pendingChip = page.getByRole("button", { name: /子会话.*待审批/ });
await expect(pendingChip).toBeVisible();
- const toolbarToggle = page.getByRole("button", { name: "智能体面板" });
- await expect(toolbarToggle.locator("span.bg-amber-500")).toBeVisible();
+ const rightToggle = page.getByTestId("dock-toggle-right");
+ await expect(rightToggle.locator("span.bg-amber-500")).toBeVisible();
// Open the panel from the chip and approve the child's tool call from inside it.
await pendingChip.click();
- await expect(page.getByRole("heading", { name: "智能体面板" })).toBeVisible();
+ await expect(page.locator('[data-tab-id="agents"][data-active="true"]')).toBeVisible();
await expect(page.getByText("exec_command").first()).toBeVisible();
await page.getByRole("button", { name: "允许" }).click();
@@ -335,7 +329,7 @@ test("an approval inside the subagent stays discoverable via the chip badge and
await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible();
// The pending badge is gone once the approval is decided (asserted on the always-visible
// toolbar toggle — the chip itself collapses with its group when the turn ends).
- await expect(toolbarToggle.locator("span.bg-amber-500")).toHaveCount(0);
+ await expect(rightToggle.locator("span.bg-amber-500")).toHaveCount(0);
});
test("draft flow: the panel auto-opens on the first live spawn and the child conversation shows its user prompt", async ({
@@ -373,9 +367,7 @@ test("draft flow: the panel auto-opens on the first live spawn and the child con
// The panel auto-opens as soon as the spawn goes live — no clicks (the child's exec_command
// sleeps ~1s, so the Task reliably outlives the draft navigation and the client attaches
// while the spawn is still running).
- const agentsToggle = page.getByRole("button", { name: "智能体面板" });
- await expect(agentsToggle).toHaveAttribute("aria-expanded", "true");
- await expect(page.getByRole("heading", { name: "智能体面板" })).toBeVisible();
+ await expect(page.locator('[data-tab-id="agents"][data-active="true"]')).toBeVisible();
// The child conversation INCLUDES its user side while LIVE: run_subagent forwards the child's
// input message itself (origin-tagged), not just the model's output.
await expect(page.getByText(CHILD_PROMPT)).toBeVisible();
diff --git a/packages/web/e2e/terminal-dock.spec.mjs b/packages/web/e2e/terminal-dock.spec.mjs
deleted file mode 100644
index 7d324f05..00000000
--- a/packages/web/e2e/terminal-dock.spec.mjs
+++ /dev/null
@@ -1,1082 +0,0 @@
-/**
- * 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();
- // The pane closes rather than parking behind the panel; it lingers just long enough to
- // collapse (useLingeringSlot) and then unmounts, so there is no steady state to assert
- // here beyond its absence — the shell it was showing is checked below.
-
- // 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 the panel leaves the slot EMPTY. Opening the panel is what the user saw close
- // the terminal, so closing the panel must not conjure it back.
- await workspace.click();
- await expect(workspace).toHaveAttribute("aria-expanded", "false");
- await expect(dock(page)).toBeHidden();
-
- // Asking for it again brings it back on the edge it was on, with its screen intact — the
- // arrangement survived, only the showing of it did not.
- await page.keyboard.press("Control+Backquote");
- 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 an open 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");
-});
-
-test("the dock stays with its conversation, not with the user's browsing", 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}`);
- await expect(page.locator('[data-testid="panels-toolbar"]')).toBeVisible({ timeout: 20000 });
- await page.keyboard.press("Control+Backquote");
- await expect(dock(page)).toBeVisible({ timeout: 10000 });
- await waitForDockShell(page, "AWAY_SHELL_UP");
- await runInDock(page, "echo AWAY_MARKER");
- await expect.poll(() => dockScreenText(page), { timeout: 15000 }).toContain("AWAY_MARKER");
-
- // A page with no conversation of its own: a shell has no business beside it. The shell
- // keeps running — this is about where it is shown, not whether it lives.
- await page.locator('aside a[href="/agents"]').first().click();
- await expect(page).toHaveURL(/\/agents$/);
- 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 on the conversation, it is there again with its screen intact.
- await page.goBack();
- await expect(page).toHaveURL(new RegExp(`/chat/${sessionId}$`));
- 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("AWAY_MARKER");
-});
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index ab7b674a..daa93c29 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -4,8 +4,7 @@
* - <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, useLayoutEffect, useMemo, useState, useSyncExternalStore } from "react";
-import { createPortal } from "react-dom";
+import { useEffect, useLayoutEffect, useMemo, useState } from "react";
import { NavLink, Outlet, useMatch, useNavigate } from "react-router";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
@@ -22,22 +21,8 @@ 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";
+import { setDockScope } from "../../features/dock/dock-state";
import { toneStrip } from "../../lib/tone";
/** "Last conversation" glyph (chat lines + resume arrow), used only by the rail. */
@@ -53,7 +38,7 @@ const railItemClass = (active: boolean) =>
/**
* Collapsed narrow rail: expand button on top; below it, in product-specified order, last
- * conversation / new chat / Agents / Skills / Models / Costs / Traces / Benchmark (every entry
+ * conversation / new chat / Agents / Skills / Models / Costs / Benchmark (every entry
* carries a localized title + aria-label, so hover tooltips follow the UI language); user
* avatar at the bottom. No Logo shown.
*/
@@ -92,13 +77,14 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
navigate(`/chat/${DRAFT_SESSION_ID}`, agentId ? { state: { agentId } } : undefined);
};
- /** Page entries (rail positions 3-8): same routes, same labels as the pinned nav. */
+ /** Page entries (rail positions 3-7): same routes, same labels as the pinned nav.
+ Traces is not among them: the Trace panel lives in the chat toolbar's panel switcher
+ now, and the /traces browsing page stays reachable through its deep links. */
const pages: ReadonlyArray<{ to: string; label: string; icon: string }> = [
{ to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },
{ to: "/skills", label: S.nav.skills, icon: NAV_ICONS.skills },
{ to: "/models", label: S.nav.models, icon: NAV_ICONS.models },
{ to: "/usage", label: S.nav.usage, icon: NAV_ICONS.usage },
- { to: "/traces", label: S.nav.traces, icon: NAV_ICONS.traces },
{ to: "/benchmark", label: S.nav.benchmark, icon: NAV_ICONS.benchmark },
];
@@ -115,7 +101,7 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
</button>
{/* The entries scroll as one block, like the pinned sidebar's nav + session list: the rail
keeps only the expand control and the account avatar at fixed height, so a window too
- short for eight icons scrolls them here instead of pushing them out of the rail and
+ short for the icons scrolls them here instead of pushing them out of the rail and
growing the document. Scrollbar hidden — at 48px wide it would cost a third of the
rail's width. */}
<nav className="no-scrollbar mt-1 flex min-h-0 flex-1 flex-col items-center gap-1 overflow-y-auto">
@@ -187,65 +173,18 @@ 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.
+ // The docks belong to the conversation they were arranged in, so switching Sessions
+ // switches the arrangement with it (dock-state.ts). The draft page's route id ("new" /
+ // a parked draft id) is a scope of its own, handed to the Session the first send
+ // creates; pages with no Session scope to a placeholder. Layout effect, not a plain
+ // one: it has to land before the chat page's docks paint, or the outgoing
+ // conversation's docks flash on the incoming one.
const dockScope = useMatch("/chat/:sessionId")?.params.sessionId ?? null;
useLayoutEffect(() => {
- // null off a conversation, which is a scope with no arrangement — so the dock is not on
- // screen there. A terminal belongs to the conversation it was opened in; carrying it
- // into Agents or user management puts a shell beside a page that has nothing to do with
- // it. Coming back to the conversation restores it, because only the scope changed.
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();
@@ -305,9 +244,7 @@ export function AppLayout() {
)}
</aside>
- {/* 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">
+ <div 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
@@ -366,20 +303,12 @@ export function AppLayout() {
</div>
)}
- {/* 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" />}
+ <main className="min-h-0 min-w-0 flex-1 overflow-hidden">
+ <Outlet />
+ </main>
+ {/* The docks themselves render inside the chat page (features/dock); the xterm
+ views live in this pool and are adopted into dock tab bodies by DOM handoff,
+ so navigating between pages never reconnects a terminal. */}
<TerminalDockRuntime />
</div>
diff --git a/packages/web/src/features/chat/agent-topology.ts b/packages/web/src/features/chat/agent-topology.ts
index e6066b02..e519cb01 100644
--- a/packages/web/src/features/chat/agent-topology.ts
+++ b/packages/web/src/features/chat/agent-topology.ts
@@ -99,7 +99,7 @@ export function modelTaskStartCount(items: readonly ChatItem[]): number {
* Count of Task-starting user items (the reducer's startTask predicate: user_text/user_image —
* steering chips and internal injections such as compaction summaries never become such items,
* so they never count). The subagents panel's task-boundary signal: an INCREASE means the user
- * started a new Task in this session (see advancePanelTaskScope in use-subagents-panel.ts).
+ * started a new Task in this session (see advancePanelTaskScope in panel-task-scope.ts).
*/
export function taskStartCount(items: readonly ChatItem[]): number {
let n = 0;
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index c6dc9620..bae01b8e 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -1,14 +1,14 @@
/**
- * Chat page (refactored version):
- * a thin top toolbar (Session title / status / iconized stats / Agents + Files toggles /
- * details popup) + the message stream and input area (input box vertically centered when there
- * are no messages).
- * Files is no longer a mutually exclusive tab — it's a persistent, closable, resizable docked
- * panel on the right (use-files-panel.ts), and each message's trailing file summary card jumps to
- * and locates the file in the tree via onOpenFile. The subagents panel docks the same way
- * (use-subagents-panel.ts): subagent chips in the stream open it focused via onOpenSubagent,
- * and the three docked panels — files, subagents and Memory (use-memory-panel.ts) — are
- * mutually exclusive (coordinated here, not in the hooks).
+ * Chat page:
+ * a thin top toolbar (Session title / status / iconized stats / panel switcher / details
+ * popup) + the message stream and input area (input box vertically centered when there
+ * are no messages), with the dock surfaces beside and below (features/dock): every side
+ * element — subagents, Workspace files, Memory, Trace, terminals — is a tab in the right
+ * or bottom dock, arranged by the user and persisted globally. This page contributes the
+ * panel BODIES (they need its session/stream state) through DockPanel's renderPanel, and
+ * the stream's jump commands: a message file card opens the Workspace tab on that file
+ * (onOpenFile), a subagent chip opens the agents tab focused (onOpenSubagent), a
+ * memory-change row opens the Memory tab located (onLocateMemoryChange).
* Approval mode and Model/context usage live in the input area's toolbar; context is compacted
* via the /compact slash command.
* Draft state (/chat/new) is carried by DraftView: Agent / Workspace / approval mode / Model are
@@ -33,15 +33,6 @@ 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";
@@ -63,6 +54,7 @@ import {
} from "../../lib/omni/stream-model";
import type { StreamModel } from "../../lib/omni/stream-model";
import { aggregateMemoryChanges, sameMemoryChanges } from "../../lib/omni/memory-changes";
+import type { MemoryLocateTarget } from "../../lib/omni/memory-changes";
import { bucketCostUsd, liveSessionElapsedMs } from "../../lib/omni/task-stats";
import type { TaskStatsTracker } from "../../lib/omni/task-stats";
import { useAuth } from "../../state/auth";
@@ -108,22 +100,29 @@ import { GoalStatusBanner } from "./goal-banner";
import { handoffMessage, modelSwitchMessage } from "./agent-handoff";
import { hasConfiguredKey, sameModelRef } from "../models/model-grouping";
import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
-import { FilesPanel } from "./files-panel";
-import { useFilesPanel } from "./use-files-panel";
-import type { FilesPanelState } from "./use-files-panel";
-import { MemoryPanel } from "./memory-panel";
-import { useMemoryPanel } from "./use-memory-panel";
-import type { MemoryPanelState } from "./use-memory-panel";
+import { WorkspaceBrowser } from "./workspace-browser";
+import { ChatMemoryView } from "./memory-view";
import { useMemoryListing } from "./use-memory-listing";
import { deletedChangeKeys } from "./memory-nav";
-import { SubagentsPanel } from "./subagents-panel";
-import { TerminalDockSlot } from "../terminal/terminal-dock-slot";
+import { SubagentsView } from "./subagents-view";
+import { TracePanel } from "../traces/trace-panel";
+import { DockPanel } from "../dock/dock-panel";
+import { useDockMount } from "../dock/use-dock-mount";
+import { panelLabel } from "../dock/panel-meta";
+import { adoptDockScope } from "../dock/dock-state";
+import { setDockCwd } from "../dock/dock-terminal";
import {
- advancePanelTaskScope,
- createPanelTaskScope,
- useSubagentsPanel,
-} from "./use-subagents-panel";
-import type { SubagentsPanelState } from "./use-subagents-panel";
+ dockViews,
+ dockVersion,
+ isTabShown,
+ openPanel,
+ panelDock,
+ subscribeDock,
+ type PanelKind,
+} from "../dock/dock-state";
+import "../dock/dock-terminal"; // registers the global Ctrl+` hotkey with the app bundle
+import { terminalApiSupported, subscribeTerminals } from "../terminal/terminal-list";
+import { advancePanelTaskScope, createPanelTaskScope } from "./panel-task-scope";
import { useSessionDraft } from "./use-session-draft";
import { useSessionStream } from "./use-session-stream";
import { PanelsToolbar } from "./panels-toolbar";
@@ -136,13 +135,6 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
/** How often the background-process list refreshes while it can still change (a run may promote a command at any time; a running process can exit on its own). */
const PROCESS_POLL_MS = 15_000;
-/**
- * Docked panel swap sequencing: how long the outgoing panel gets to retract before the
- * incoming one slides in. Matches the panels' own `transition-[width] duration-200`
- * (files-panel.tsx / subagents-panel.tsx) — shorter would cut the retract off, longer
- * would leave a dead gap.
- */
-
/** 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 }) {
return (
@@ -320,144 +312,76 @@ export function ChatPage() {
const [thinkingSwitch, setThinkingSwitch] = useState<StagedThinkingSwitch | null>(null);
const routeSessionId = params.sessionId ?? null;
- const filesPanelRaw = useFilesPanel(routeSessionId);
- const memoryPanelRaw = useMemoryPanel(routeSessionId);
- const subagentsPanelRaw = useSubagentsPanel(routeSessionId);
- // The three docked panels are MUTUALLY EXCLUSIVE — side by side they'd crush the chat column at
- // the 1024px breakpoint (and stacked Sheets on mobile would be worse). Exclusivity is
- // enforced here, on the panel objects every consumer receives, rather than at each call site:
- // ANY path that opens one panel (toolbar toggles, message file cards via onOpenFile, subagent
- // chips via onOpenSubagent, memory-changes card rows via onLocateMemoryChange, or a future
- // caller) closes the other two as a side effect of setOpen(true). Closing never cascades. The
- // hooks stay uncoordinated on purpose — they don't know about each other; only this page,
- // which owns all three, does.
- //
- // Docked swaps are SEQUENCED, not simultaneous: with both width transitions running at
- // once the total width is constant, so the closing panel's left-anchored content never
- // moves — the incoming panel just wipes over it, which reads as "the old panel never
- // retracted". Closing the old one fully first (its width animates while the chat column
- // takes the space back), then sliding the new one in, makes both motions legible. A new
- // swap/toggle cancels the pending open; mobile Sheets keep the instant switch — they
- // overlay rather than share width, so the sequencing would only add dead time.
- const panelSwapTimer = useRef<number | null>(null);
- const cancelPanelSwap = () => {
- if (panelSwapTimer.current !== null) {
- window.clearTimeout(panelSwapTimer.current);
- panelSwapTimer.current = null;
- }
- };
- useEffect(() => cancelPanelSwap, []);
- /**
- * 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) || retractingPane) {
- panelSwapTimer.current = window.setTimeout(() => {
- panelSwapTimer.current = null;
- open(true);
- }, 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");
+ // The docks' arrangement lives in the dock store (features/dock) — tabs, active tab,
+ // sizes, all global and persisted. This page re-renders on any dock change and owns only
+ // the stream-driven JUMP COMMANDS the panel bodies consume: each is a fresh object per
+ // call (identity-compared, so repeating the same jump still re-triggers the view's
+ // effect), and each resets on a Session switch because it pointed into the old session's
+ // stream. The tabs themselves deliberately survive the switch — the panels re-bind to
+ // the conversation on screen.
+ useSyncExternalStore(subscribeDock, dockVersion);
+ useSyncExternalStore(subscribeTerminals, terminalApiSupported);
+ /** Workspace tab: locate this file in the tree (a message file card's click). */
+ const [fileOpenRequest, setFileOpenRequest] = useState<{ path: string } | null>(null);
+ /** Memory tab: land on this memory's detail (a card row), or the list (null target). */
+ const [memoryRequest, setMemoryRequest] = useState<{
+ target: MemoryLocateTarget | null;
+ } | null>(null);
+ /** Agents tab: select this child conversation (a subagent chip's click; the chain ends with the child's own id). */
+ const [subagentFocus, setSubagentFocus] = useState<{
+ sessionId: string;
+ origin: string[];
+ } | null>(null);
/**
- * Tri-panel exclusivity: at most one of the three docked panels is open, so opening one
- * hard-closes the sibling that is already closed (a no-op) and hands the OPEN sibling to
- * swapPanels for the sequenced close→open (the collapse-transition dance above). Closing
- * asks the two siblings whether the side is still held — this panel's own `open` is the
- * render-time value and still reads true here.
+ * Which Task's topology the agents tab displays. Null = the LATEST Task; a chip click
+ * pins the graph to the Task containing that chip instead — `anchorSessionId` is the
+ * clicked child's TOP-LEVEL ancestor, which the view resolves to its Task slice.
*/
- const exclusiveOpen = (
- self: { setOpen: (v: boolean) => void },
- siblings: [
- { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
- { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
- ],
- ) => {
- const retracting = sidePaneShowing();
- setChatSidePanelOpen(true);
- const [a, b] = siblings;
- const openSibling = a.open ? a : b;
- const otherSibling = openSibling === a ? b : a;
- otherSibling.setOpen(false);
- swapPanels(openSibling, self.setOpen, retracting);
- };
- const filesPanel: FilesPanelState = {
- ...filesPanelRaw,
- setOpen: (next: boolean) => {
- cancelPanelSwap();
- if (next) {
- exclusiveOpen(filesPanelRaw, [subagentsPanelRaw, memoryPanelRaw]);
- } else {
- filesPanelRaw.setOpen(false);
- setChatSidePanelOpen(subagentsPanelRaw.open || memoryPanelRaw.open);
- }
- },
- };
- const subagentsPanel: SubagentsPanelState = {
- ...subagentsPanelRaw,
- setOpen: (next: boolean) => {
- cancelPanelSwap();
- if (next) {
- exclusiveOpen(subagentsPanelRaw, [filesPanelRaw, memoryPanelRaw]);
- } else {
- subagentsPanelRaw.setOpen(false);
- setChatSidePanelOpen(filesPanelRaw.open || memoryPanelRaw.open);
- }
- },
- };
- const memoryPanel: MemoryPanelState = {
- ...memoryPanelRaw,
- setOpen: (next: boolean) => {
- cancelPanelSwap();
- if (next) {
- exclusiveOpen(memoryPanelRaw, [filesPanelRaw, subagentsPanelRaw]);
- } else {
- memoryPanelRaw.setOpen(false);
- setChatSidePanelOpen(filesPanelRaw.open || subagentsPanelRaw.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 every panel
- // 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();
+ const [subagentTaskScope, setSubagentTaskScope] = useState<{
+ anchorSessionId: string;
+ } | null>(null);
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);
- memoryPanelRaw.setOpen(false);
- // Panel objects are recreated every render; the raw hooks' setters are stable.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [terminalHasTheSide]);
+ setFileOpenRequest(null);
+ setMemoryRequest(null);
+ setSubagentFocus(null);
+ setSubagentTaskScope(null);
+ }, [routeSessionId]);
+ // A command also resets when its panel's TAB closes: the tab body unmounts with the tab,
+ // so a re-added tab is a fresh mount that would otherwise replay the stale command —
+ // reopening the Workspace would re-locate a long-clicked file, and reopening the agents
+ // tab would come back pinned to an old Task instead of the latest.
+ const workspaceTabExists = panelDock("workspace") !== null;
+ const memoryTabExists = panelDock("memory") !== null;
+ const agentsTabExists = panelDock("agents") !== null;
+ useEffect(() => {
+ if (!workspaceTabExists) setFileOpenRequest(null);
+ }, [workspaceTabExists]);
+ useEffect(() => {
+ if (!memoryTabExists) setMemoryRequest(null);
+ }, [memoryTabExists]);
+ useEffect(() => {
+ if (!agentsTabExists) {
+ setSubagentFocus(null);
+ setSubagentTaskScope(null);
+ }
+ }, [agentsTabExists]);
// 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.
const parkedDraftId = parkedDraftIdOf(routeSessionId);
const draft = routeSessionId === DRAFT_SESSION_ID || parkedDraftId !== null;
const selected = draft ? null : (sessions.find((s) => s.sessionId === routeSessionId) ?? null);
+ // New shells start in this conversation's Workspace — its files are what a terminal
+ // opened here is for. While drafting, the Workspace is the one picked in the draft and
+ // DraftView publishes it instead (a child effect runs before this one, so this must
+ // yield rather than clobber it with null). Leaving the chat for another page keeps the
+ // last conversation's Workspace: it is a better default than home for the hotkey,
+ // which stays live everywhere.
+ useEffect(() => {
+ if (draft) return;
+ setDockCwd(selected?.workspace ?? null);
+ }, [draft, selected?.workspace]);
+
// Currently effective model (session state, the model reference comes from the Session DTO): model selection in draft state is handled internally by DraftView.
const activeModelRef = selected
? { provider: selected.provider, modelId: selected.modelId }
@@ -551,12 +475,13 @@ export function ChatPage() {
memoryChangesRef.current = rawMemoryChanges;
}
const sessionMemoryChanges = memoryChangesRef.current;
- // The Agent's memory listing, fetched once memory is on screen or this conversation has
- // changes to mark; shared by the Memory panel and the card's deleted-row marking.
+ // The Agent's memory listing, fetched once the Memory tab exists (its body is mounted
+ // even behind another tab) or this conversation has changes to mark; shared by the
+ // Memory panel and the card's deleted-row marking.
const memoryListing = useMemoryListing(
projectId,
selected?.agentId ?? null,
- memoryPanelRaw.open || sessionMemoryChanges.length > 0,
+ panelDock("memory") !== null || sessionMemoryChanges.length > 0,
sessionMemoryChanges,
);
// Changed files the loaded listing no longer carries: the card drops those rows
@@ -595,31 +520,10 @@ export function ChatPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedSessionId, selectedAgentId, setCurrentAgentId]);
- // A NEW chat starts with every panel closed: a panel opened for an earlier conversation must
- // not carry into a freshly created one. The draft is the reset point — it renders no panels
- // itself, so the Session created from it (first send navigates to /chat/:id) begins closed,
- // while a plain conversation switch keeps whatever the user had open. This effect owns the
- // ONLY automatic close of any of them.
- useEffect(() => {
- if (!draft) return;
- // A swap's pending delayed open must not fire into the fresh draft after this reset.
- cancelPanelSwap();
- filesPanelRaw.setOpen(false);
- subagentsPanelRaw.setOpen(false);
- memoryPanelRaw.setOpen(false);
- setChatSidePanelOpen(false); // nothing holds the side any more: side panes come back
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [draft]);
-
- // Subagents panel AUTO-OPEN (the one visibility rule this panel has beyond the Files panel's):
- // the pure tracker (advancePanelTaskScope, unit-tested) opens it on the CURRENT task's first
- // live spawn, re-armed at every task boundary so a manual close is respected until the next
- // one. Boundaries themselves no longer close anything — an open panel now survives Session
- // switches and new Tasks alike, matching the Files panel.
- // The auto-open applies only when docked (a mobile Sheet sliding over the conversation
- // uninvited would be worse than staying discoverable via the row), never over an open Files
- // panel (an automatic open must not steal an explicit one — the row and the toolbar's amber
- // dot still signal), and never re-triggers an already-open panel (that would yank a pinned
+ // Agents tab AUTO-OPEN (the one automatic tab action): the pure tracker
+ // (advancePanelTaskScope, unit-tested) brings the agents tab to the front on the CURRENT
+ // task's first live spawn, re-armed at every task boundary so a manual close is respected
+ // until the next one. It never re-triggers an already-shown tab (that would yank a pinned
// historical graph back to the latest Task); the tracker consumes the attempt regardless.
const panelTaskScopeRef = useRef(createPanelTaskScope());
// Deliberately the LIVE model's items only (never the backfilled prefix): the tracker
@@ -634,18 +538,8 @@ export function ChatPage() {
taskCount,
liveSpawn,
});
- if (
- action === "autoOpen" &&
- subagentsPanelRaw.isDocked &&
- !subagentsPanelRaw.open &&
- !filesPanelRaw.open &&
- !memoryPanelRaw.open
- ) {
- setChatSidePanelOpen(true);
- subagentsPanelRaw.setOpen(true);
- }
- // The panel objects are rebuilt every render; the tracker only acts on real transitions of
- // these three observed values.
+ if (action === "autoOpen" && !isTabShown("agents")) openPanel("agents");
+ // The tracker only acts on real transitions of these three observed values.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedSessionId, taskCount, liveSpawn]);
@@ -796,9 +690,8 @@ export function ChatPage() {
// thinking-level switch staged behind its dialog (per-session UI state — a compaction
// that self-heals to a new session id routes through here too and drops the held pick),
// and the popover's per-session data (process list / token buckets / trace path),
- // avoiding stale data from the previous Session (Files panel state resets itself keyed
- // on sessionId inside use-files-panel, and the cost hold re-keys itself inside
- // advanceCostStat). The thinking level itself needs no reset — it is read off the
+ // avoiding stale data from the previous Session (the panel jump commands reset in their
+ // own effect above, and the cost hold re-keys itself inside advanceCostStat). The thinking level itself needs no reset — it is read off the
// selected Session row, so it changes with the session by construction.
useEffect(() => {
usageAppliedRef.current = null;
@@ -1058,7 +951,7 @@ 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
+ // Same conversation under a new id: its docks follow, or they are stranded under
// an id nothing routes to again.
adoptDockScope(respondedId);
navigate(`/chat/${respondedId}`, { replace: true });
@@ -1520,30 +1413,31 @@ export function ChatPage() {
},
onOpenFile: (path) => {
// The file card has already normalized the text path to a Workspace-relative path
- // (toWorkspaceRelative, including stripping absolute-path prefixes and converting Windows
- // separators), so this just opens the panel and navigates to it directly (the wrapped
- // setOpen already closes the sibling panels — see the exclusivity block above).
- filesPanel.setOpen(true);
- filesPanel.browsePath(path);
+ // (toWorkspaceRelative, including stripping absolute-path prefixes and converting
+ // Windows separators), so this just brings the Workspace tab up and navigates to it.
+ openPanel("workspace");
+ setFileOpenRequest({ path });
},
onOpenSubagent: (sessionId, origin) => {
- // Chip click: open the panel focused on that child (the focus chain ends with the child's
- // own id; the wrapped setOpen closes the sibling panels). focusSubagent after setOpen: the
- // open resets the Task scope to "latest", and the focus then pins it to this chip's Task.
- subagentsPanel.setOpen(true);
- subagentsPanel.focusSubagent(sessionId, [...origin, sessionId]);
+ // Chip click: the agents tab focused on that child (the focus chain ends with the
+ // child's own id), with the graph pinned to this chip's Task.
+ openPanel("agents");
+ setSubagentTaskScope({ anchorSessionId: origin[0] ?? sessionId });
+ setSubagentFocus({ sessionId, origin: [...origin, sessionId] });
},
onOpenMemory: () => {
- // The Memory panel on its list (the wrapped setOpen closes the sibling panels).
- memoryPanel.setOpen(true);
- memoryPanelRaw.openMemory(null);
+ // The Memory tab on its list.
+ openPanel("memory");
+ setMemoryRequest({ target: null });
},
onLocateMemoryChange: (row) => {
- memoryPanel.setOpen(true);
- memoryPanelRaw.openMemory({
- scope: row.scope,
- ...(row.scopeKey !== undefined ? { scopeKey: row.scopeKey } : {}),
- file: row.file,
+ openPanel("memory");
+ setMemoryRequest({
+ target: {
+ scope: row.scope,
+ ...(row.scopeKey !== undefined ? { scopeKey: row.scopeKey } : {}),
+ file: row.file,
+ },
});
},
...(deletedMemoryKeys !== undefined ? { deletedMemoryKeys } : {}),
@@ -1557,6 +1451,63 @@ export function ChatPage() {
// nested approval stays discoverable while the panel is closed.
const anySubagentPending = [...stream.pendingApprovals.keys()].some((k) => !k.startsWith(" "));
+ // The docks to render: right beside the chat row, bottom below it (the narrow merged
+ // view arrives as a bottom view). They render on the draft page too — the arrangement is
+ // the user's workbench, and a terminal opened while drafting must be visible — with the
+ // session-bound panels showing a placeholder until the first send creates the Session.
+ // useDockMount keeps a closing dock mounted through its collapse transition and skips
+ // the animation for instant changes (scope switches, cross-dock moves).
+ const views = dockViews();
+ const rightMount = useDockMount(views.find((view) => view.position === "right") ?? null);
+ const bottomMount = useDockMount(views.find((view) => view.position === "bottom") ?? null);
+ const terminalSupported = terminalApiSupported();
+
+ /**
+ * The panel tabs' bodies. Keyed by Session where the view starts over per conversation
+ * (agents / memory / trace); the Workspace browser instead re-binds through its props —
+ * its own handled-once request guard is what the conversation-switch e2e covers.
+ */
+ const renderPanel = (kind: PanelKind, active: boolean): ReactNode => {
+ if (!selected) return <EmptyState title={panelLabel(kind)} description={S.dock.draftEmpty} />;
+ switch (kind) {
+ case "agents":
+ return (
+ <SubagentsView
+ key={selected.sessionId}
+ session={selected}
+ // The merged view (backfilled windows included): a chip on an older turn keeps
+ // its historical graph and child conversation reachable after pagination.
+ model={panelModel}
+ version={stream.version}
+ taskRunning={stream.taskState !== "idle"}
+ ctx={ctx}
+ focusRequest={subagentFocus}
+ taskScope={subagentTaskScope}
+ />
+ );
+ case "workspace":
+ return (
+ <WorkspaceBrowser session={selected} openRequest={fileOpenRequest} active={active} />
+ );
+ case "memory":
+ return (
+ <ChatMemoryView
+ key={selected.sessionId}
+ session={selected}
+ changes={sessionMemoryChanges}
+ scopes={memoryListing.scopes}
+ listingError={memoryListing.error}
+ request={memoryRequest}
+ active={active}
+ // Management (add / edit / delete) lives on the agent-settings memory tab.
+ onOpenSettings={() => navigate(`/agents/${selected.agentId}?tab=memory`)}
+ />
+ );
+ case "trace":
+ return <TracePanel key={selected.sessionId} session={selected} active={active} />;
+ }
+ };
+
if (!projectId || !agentId) {
return (
<div className="p-6">
@@ -1698,7 +1649,9 @@ export function ChatPage() {
selected === null ? null : sessionActivity(stream.taskState, selected.hasTrace, false);
return (
- <div className="flex h-full flex-col bg-white dark:bg-gray-950">
+ // data-dock-host: the docks' edge bands, drop preview and the bottom dock's height
+ // ratio all measure this column (dock-drag.tsx / dock-panel.tsx).
+ <div data-dock-host className="flex h-full flex-col bg-white dark:bg-gray-950">
{/* Thin top toolbar */}
{selected && (
<div className="flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800">
@@ -1722,29 +1675,11 @@ export function ChatPage() {
)}
</div>
- {/* 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),
- Memory docks the two-level memory view (use-memory-panel.ts) — opening any of the
- three closes the other two (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)}
- memoryOpen={memoryPanel.open}
- onToggleMemory={() => {
- if (memoryPanel.open) {
- memoryPanel.setOpen(false);
- } else {
- // Toolbar entry lands on the list level (memory-nav entry routing).
- memoryPanel.setOpen(true);
- memoryPanelRaw.openMemory(null);
- }
- }}
- />
+ {/* Panel switcher (icon-only): pinned triggers + the "create" dropdown with
+ placement actions and pin toggles. Every entry is a dock tab (features/dock)
+ — the toolbar reads and drives the dock store directly; this page only feeds
+ the pending-approval dot. */}
+ <PanelsToolbar agentsPending={anySubagentPending} />
{/* 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
@@ -2020,13 +1955,11 @@ 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), 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" />
+ {/* Body: chat column + the right dock on this row (below the toolbar — a dock
+ beside the whole page would squeeze the header), with the bottom dock after the
+ row spanning the full page width. data-dock-row is what the drag preview
+ measures for a right landing. */}
+ <div data-dock-row className="flex min-h-0 flex-1">
{/* 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
@@ -2139,33 +2072,29 @@ export function ChatPage() {
)}
</ChatDropRegion>
- {selected && (
- <SubagentsPanel
- session={selected}
- panel={subagentsPanel}
- // The merged view (backfilled windows included): a chip on an older turn keeps
- // its historical graph and child conversation reachable after pagination.
- model={panelModel}
- version={stream.version}
- taskRunning={stream.taskState !== "idle"}
- ctx={ctx}
+ {rightMount.view && (
+ <DockPanel
+ view={rightMount.view}
+ open={rightMount.open}
+ animateEntrance={rightMount.animateEntrance}
+ renderPanel={renderPanel}
+ panelBadges={{ agents: anySubagentPending }}
+ terminalSupported={terminalSupported}
/>
)}
- {selected && <FilesPanel session={selected} panel={filesPanel} />}
- {selected && (
- <MemoryPanel
- session={selected}
- panel={memoryPanel}
- memoryChanges={sessionMemoryChanges}
- scopes={memoryListing.scopes}
- listingError={memoryListing.error}
- // Management (add / edit / delete) lives on the agent-settings memory tab.
- onOpenMemorySettings={() => navigate(`/agents/${selected.agentId}?tab=memory`)}
- />
- )}
- <TerminalDockSlot position="right" />
</div>
+ {bottomMount.view && (
+ <DockPanel
+ view={bottomMount.view}
+ open={bottomMount.open}
+ animateEntrance={bottomMount.animateEntrance}
+ renderPanel={renderPanel}
+ panelBadges={{ agents: anySubagentPending }}
+ terminalSupported={terminalSupported}
+ />
+ )}
+
<Modal
open={credentialGuide}
title={S.project.noCredentialTitle}
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 59a0d6a6..7c5009a8 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -48,7 +48,6 @@ 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";
@@ -63,6 +62,8 @@ import { PenguinLogo } from "../../components/ui/penguin-logo";
import { toastError } from "../../components/ui/toast";
import { useVersionInfo } from "../../lib/use-version-info";
import { ChatInput } from "./chat-input";
+import { adoptDockScope } from "../dock/dock-state";
+import { setDockCwd } from "../dock/dock-terminal";
import { buildSkillsMessage } from "./skill-use";
import { EXAMPLE_FOLDERS } from "./example-tasks";
import type { ExampleFolderId, ExampleTask, ExampleTaskId } from "./example-tasks";
@@ -177,6 +178,12 @@ export function DraftView({
cached.agentId ?? currentAgent?.agentId ?? null,
);
const [workspace, setWorkspace] = useState(cached.workspace ?? "");
+ // A terminal opened while drafting starts in the Workspace chosen here; "" is the
+ // temporary Workspace, whose directory the server only creates with the Session, so
+ // that case falls back to home (setDockCwd's null).
+ useEffect(() => {
+ setDockCwd(workspace || null);
+ }, [workspace]);
const [approvalMode, setApprovalMode] = useState<ApprovalMode>(
cached.approvalMode ?? "allow-all",
);
@@ -634,9 +641,9 @@ export function DraftView({
const fresh = await api.getSession(res.sessionId).catch(() => null);
add(fresh?.session ?? 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).
+ // The draft now has an id of its own, so its docks move with it: anything left
+ // behind under the draft's scope would surface in the NEXT new conversation
+ // instead (dock-state.ts).
adoptDockScope(res.sessionId);
navigate(`/chat/${res.sessionId}`, { replace: true });
return true;
diff --git a/packages/web/src/features/chat/files-panel.tsx b/packages/web/src/features/chat/files-panel.tsx
deleted file mode 100644
index 52080bcc..00000000
--- a/packages/web/src/features/chat/files-panel.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Files panel: on desktop (≥1024px, see isDocked in use-files-panel.ts) it docks to the right
- * of the chat with a drag-to-resize edge; on narrower viewports it becomes a bottom Sheet
- * (snaps to half for browsing / full for preview, gesture-draggable) so the vertical layout
- * keeps the chat transcript above it visible. Content is a single WorkspaceBrowser directory-tree
- * view; clicking a file chip in a message navigates the tree via openRequest (use-files-panel.ts).
- */
-import type { SessionInfo } from "@prismshadow/penguin-server/api";
-import { S } from "../../lib/strings";
-import { Sheet } from "../../components/ui/sheet";
-import { CloseIcon } from "../../components/ui/icons";
-import { WorkspaceBrowser } from "./workspace-browser";
-import type { FilesPanelState } from "./use-files-panel";
-
-export function FilesPanel({ session, panel }: { session: SessionInfo; panel: FilesPanelState }) {
- if (!panel.isDocked) {
- return (
- <Sheet
- open={panel.open}
- snap={panel.sheetSnap}
- onSnapChange={panel.setSheetSnap}
- onClose={() => panel.setOpen(false)}
- title={S.files.title}
- >
- <div className="flex h-full min-h-0 flex-col">
- <div className="min-h-0 flex-1">
- <WorkspaceBrowser
- session={session}
- openRequest={panel.openRequest}
- active={panel.open}
- // Entering preview from list view: bump the snap point up to full (preview needs the space)
- onPreviewOpen={() => panel.setSheetSnap("full")}
- />
- </div>
- </div>
- </Sheet>
- );
- }
-
- return (
- <>
- {panel.open && (
- <div
- data-testid="files-panel-resizer"
- onMouseDown={panel.startResize}
- onDoubleClick={panel.resetWidth}
- title={S.files.resizeHandle}
- className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 hover:bg-brand-300/50 dark:hover:bg-brand-700/40 ${
- panel.resizing ? "bg-brand-400/60" : "bg-transparent"
- }`}
- />
- )}
- <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
- // stay mounted, and inert removes content collapsed to 0 width from the tab order and
- // accessibility tree, so keyboard users can't Tab into a close button that's visually gone.
- inert={!panel.open}
- // Freeze the panel's pointer events while dragging to resize: a preview iframe
- // (HTML/PDF) is a separate document, and mousemove over it gets swallowed instead of
- // reaching us, so the width stops tracking the cursor; pointer-events-none lets events
- // pass through.
- //
- // relative: the clipping window acts as its own containing block. Content is fixed at
- // the target width (see below), and when closed the whole block sits outside the
- // viewport's right edge — if an absolute descendant (e.g. the upload button's sr-only
- // input) anchored to the nearest initial containing block instead, it would bypass this
- // overflow-hidden and stretch the **document** wide, making a horizontal scrollbar
- // appear out of nowhere.
- //
- // The divider belongs to the OPEN state only: with border-box sizing a closed panel's
- // border still paints its 1px even at width 0, and since both docked panels stay
- // mounted, the closed one left a stray line beside the open one — a hairline, a gap
- // (the open panel's resize handle) and then the real divider, which reads as an extra
- // empty panel wedged in. Both closed, the two leftover lines stacked at the window edge.
- className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden ${
- panel.open ? "border-l border-gray-200 dark:border-gray-800" : ""
- } ${panel.resizing ? "pointer-events-none" : "transition-[width] duration-200"}`}
- >
- {/* Content is fixed at the target width; the outer element is only a clipping window:
- during the open/close animation the outer element passes through intermediate
- widths, and if the content resized along with it, the text would get squeezed into
- a column frame-by-frame before expanding back out. With a fixed width, the content
- behaves as a rigid body that slides in and out past the clipping edge with zero
- reflow. While dragging to resize, both values stay in sync, so this isn't affected. */}
- <div style={{ width: panel.width }} className="flex h-full min-h-0 flex-col">
- {/* Title row for docked state (the Sheet state has its own title bar via Sheet, no duplication needed) */}
- <div className="flex shrink-0 items-center gap-1 px-3 pt-2">
- <h4 className="min-w-0 flex-1 truncate text-sm font-semibold">{S.files.title}</h4>
- <button
- type="button"
- onClick={() => panel.setOpen(false)}
- title={S.common.close}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <CloseIcon />
- </button>
- </div>
- <div className="min-h-0 flex-1">
- <WorkspaceBrowser
- session={session}
- openRequest={panel.openRequest}
- active={panel.open}
- />
- </div>
- </div>
- </div>
- </>
- );
-}
diff --git a/packages/web/src/features/chat/memory-panel.tsx b/packages/web/src/features/chat/memory-panel.tsx
deleted file mode 100644
index 7263386c..00000000
--- a/packages/web/src/features/chat/memory-panel.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * Memory panel — a peer of the subagents and files panels, same shell behavior: docked to
- * the right with a drag-to-resize edge on desktop (≥1024px, see isDocked in
- * use-memory-panel.ts), a bottom Sheet on narrower viewports. Content is the two-level
- * Memory view (memory-view.tsx); the panel itself only provides the frame, mirroring
- * files-panel.tsx — including the inert width-collapse (see that file's notes on why the
- * node stays mounted and why the divider belongs to the open state only).
- */
-import type { SessionInfo } from "@prismshadow/penguin-server/api";
-import { S } from "../../lib/strings";
-import { Sheet } from "../../components/ui/sheet";
-import { CloseIcon } from "../../components/ui/icons";
-import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
-import { ChatMemoryView } from "./memory-view";
-import type { ScopeFiles } from "./memory-nav";
-import type { MemoryPanelState } from "./use-memory-panel";
-
-interface MemoryPanelProps {
- session: SessionInfo;
- panel: MemoryPanelState;
- /** This conversation's aggregated memory changes (identity-stable across streaming ticks — see chat-page's stabilization). */
- memoryChanges: MemoryChangeRow[];
- /** The server listing (loaded by chat-page's use-memory-listing) and its error, shared with the card's deleted-row marking. */
- scopes: ScopeFiles[] | null;
- listingError: string | null;
- /** Opens the agent-settings memory tab (the view's management link). */
- onOpenMemorySettings?: (() => void) | undefined;
-}
-
-export function MemoryPanel({
- session,
- panel,
- memoryChanges,
- scopes,
- listingError,
- onOpenMemorySettings,
-}: MemoryPanelProps) {
- const view = (
- // Keyed by session: a new conversation starts back at the list level.
- <ChatMemoryView
- key={session.sessionId}
- session={session}
- changes={memoryChanges}
- scopes={scopes}
- listingError={listingError}
- request={panel.memoryRequest}
- active={panel.open}
- {...(onOpenMemorySettings ? { onOpenSettings: onOpenMemorySettings } : {})}
- />
- );
-
- if (!panel.isDocked) {
- return (
- <Sheet
- open={panel.open}
- snap={panel.sheetSnap}
- onSnapChange={panel.setSheetSnap}
- onClose={() => panel.setOpen(false)}
- title={S.chat.memoryViewTitle}
- >
- <div className="flex h-full min-h-0 flex-col">
- <div className="min-h-0 flex-1">{view}</div>
- </div>
- </Sheet>
- );
- }
-
- return (
- <>
- {panel.open && (
- <div
- data-testid="memory-panel-resizer"
- onMouseDown={panel.startResize}
- onDoubleClick={panel.resetWidth}
- title={S.files.resizeHandle}
- className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 hover:bg-brand-300/50 dark:hover:bg-brand-700/40 ${
- panel.resizing ? "bg-brand-400/60" : "bg-transparent"
- }`}
- />
- )}
- <div
- data-testid="memory-panel"
- ref={panel.panelRef}
- style={{ width: panel.open ? panel.width : 0 }}
- inert={!panel.open}
- className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden ${
- panel.open ? "border-l border-gray-200 dark:border-gray-800" : ""
- } ${panel.resizing ? "pointer-events-none" : "transition-[width] duration-200"}`}
- >
- <div style={{ width: panel.width }} className="flex h-full min-h-0 flex-col">
- <div className="flex shrink-0 items-center gap-1 px-3 pt-2">
- <h4 className="min-w-0 flex-1 truncate text-sm font-semibold">
- {S.chat.memoryViewTitle}
- </h4>
- <button
- type="button"
- onClick={() => panel.setOpen(false)}
- title={S.common.close}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <CloseIcon />
- </button>
- </div>
- <div className="min-h-0 flex-1">{view}</div>
- </div>
- </div>
- </>
- );
-}
diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsx
index f5e2e7e3..21521b40 100644
--- a/packages/web/src/features/chat/memory-view.tsx
+++ b/packages/web/src/features/chat/memory-view.tsx
@@ -1,5 +1,5 @@
/**
- * The Memory side panel's content (see memory-panel.tsx for the shell): two levels, modeled
+ * The Memory tab's content (the dock provides the shell — features/dock): two levels, modeled
* by memory-nav.ts. The list shows both scopes' topic lists — the same server routes the
* agent-settings memory tab reads — with a marker on topics this conversation changed; a
* topic's detail is the memory's content rendered like the file viewer (Markdown,
diff --git a/packages/web/src/features/chat/panel-task-scope.ts b/packages/web/src/features/chat/panel-task-scope.ts
new file mode 100644
index 00000000..7f398b5a
--- /dev/null
+++ b/packages/web/src/features/chat/panel-task-scope.ts
@@ -0,0 +1,57 @@
+/**
+ * The subagents panel's auto-open tracker (pure — unit-tested in
+ * test/panel-task-scope.test.ts): the current Task's first live spawn opens the panel
+ * once, re-armed at each task boundary, so a manual close mid-task is respected. The chat
+ * page observes the stream and applies the decision through the dock store.
+ */
+
+/**
+ * Mutable tracker state, held in a ref by the chat page. `taskCount` is the number of
+ * Task-starting user items observed in the session's stream (taskStartCount in
+ * agent-topology.ts); an increase IS the "user started a new Task" boundary.
+ */
+export interface PanelTaskScope {
+ sessionId: string | null;
+ taskCount: number;
+ /** Task ordinal (the taskCount value) whose one auto-open attempt was already consumed; null = armed. */
+ autoOpenedAt: number | null;
+}
+
+export function createPanelTaskScope(): PanelTaskScope {
+ return { sessionId: null, taskCount: 0, autoOpenedAt: null };
+}
+
+/**
+ * Advance the tracker with one observation of the current session's stream and return whether
+ * the panel should auto-open:
+ * - a live spawn in the current task → "autoOpen", at most once per task, so a manual close
+ * afterwards is respected until the next boundary;
+ * - a boundary (a Session switch, or a new Task within the session) RE-ARMS that one attempt
+ * but is never itself an action — an open panel is not closed here. Entering a
+ * session mid-run therefore auto-opens on the spawn that is already live, which reads as
+ * that spawn introducing itself;
+ * - anything else (steering, compaction, more messages in the same task) → null.
+ * A taskCount DECREASE is a defensive re-baseline (a resync swapped in a smaller model):
+ * adopted silently, with the auto-open attempt marked consumed so a rebuild can never
+ * surprise-open a panel the user closed mid-task.
+ * The caller applies "autoOpen" under its own guards (not already shown); the attempt is
+ * consumed here regardless, so a suppressed attempt never retriggers within the same task.
+ */
+export function advancePanelTaskScope(
+ state: PanelTaskScope,
+ obs: { sessionId: string | null; taskCount: number; liveSpawn: boolean },
+): "autoOpen" | null {
+ const switched = obs.sessionId !== state.sessionId;
+ const rebaseline = !switched && obs.taskCount < state.taskCount;
+ if (switched || obs.taskCount !== state.taskCount) {
+ state.sessionId = obs.sessionId;
+ state.taskCount = obs.taskCount;
+ // A real boundary re-arms the auto-open; the defensive re-baseline marks it consumed.
+ state.autoOpenedAt = rebaseline ? obs.taskCount : null;
+ }
+ if (obs.liveSpawn && state.autoOpenedAt !== state.taskCount) {
+ state.autoOpenedAt = state.taskCount;
+ return "autoOpen";
+ }
+ return null;
+}
diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsx
index 60300b6f..b0cc566a 100644
--- a/packages/web/src/features/chat/panels-toolbar.tsx
+++ b/packages/web/src/features/chat/panels-toolbar.tsx
@@ -1,106 +1,35 @@
/**
- * 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.
+ * Top-right dock switcher of the chat toolbar (Codex-style): exactly two icon buttons —
+ * pull open the bottom dock, pull open the right dock. Opening a dock that has no tabs
+ * yet lands on its picker (choose what to open there); everything element-specific — the
+ * tab strips, each dock's "+" menu, the pickers — lives on the dock surfaces themselves
+ * (features/dock), so this component stays two toggles.
*
- * Four panels exist: the subagents panel, the terminal dock, the Workspace files panel and
- * the Memory 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 and Memory reachable through the dropdown
- * (the terminal also via 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.
+ * The pending-approval amber dot rides the button of the dock that holds the agents tab
+ * (the right one while the panel is closed — the default edge panels open on), keeping a
+ * nested approval discoverable while the panel is off screen.
*/
-import { useEffect, useRef, useState, useSyncExternalStore } from "react";
-import type { ReactNode } from "react";
+import { useSyncExternalStore } from "react";
import { S } from "../../lib/strings";
-import { Dropdown } from "../../components/ui/dropdown";
-import { NAV_ICONS } from "../../components/ui/icons";
import { GlyphIcon } from "../../components/ui/glyph-icon";
-import { FOLDER_ICON } from "../../components/ui/group-list";
import { ICON_SIZE } from "../../lib/icon-scale";
-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";
import { toneDot } from "../../lib/tone";
-
-export type PanelKey = "agents" | "terminal" | "workspace" | "memory";
-
-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", "memory"];
-
-/** Open book: the Memory panel's mark (same glyph as the memory-changes card header). */
-const MEMORY_ICON =
- "M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 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 = ICON_SIZE.iconButton }: { 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
- >
- <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>
- );
-}
+import {
+ dockVersion,
+ isDockVisible,
+ panelDock,
+ subscribeDock,
+ toggleDock,
+ type DockPosition,
+} from "../dock/dock-state";
+
+/** Window with a bottom pane / a right pane: the two pull-open buttons. */
+const PANEL_BOTTOM_ICON = "M4 5h16v14H4zM4 14h16";
+const PANEL_RIGHT_ICON = "M4 5h16v14H4zM14 5v14";
export interface PanelsToolbarProps {
- agentsOpen: boolean;
- onToggleAgents: () => void;
- /** A pending approval inside a subagent: amber dot on the agents trigger. */
+ /** A pending approval inside a subagent: amber dot beside the agents tab's dock button. */
agentsPending: boolean;
- workspaceOpen: boolean;
- onToggleWorkspace: () => void;
- memoryOpen: boolean;
- onToggleMemory: () => 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) =>
@@ -110,323 +39,36 @@ const triggerClass = (active: boolean) =>
: "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>
- );
-}
+export function PanelsToolbar({ agentsPending }: PanelsToolbarProps) {
+ useSyncExternalStore(subscribeDock, dockVersion);
+ // The dot follows the agents tab's dock; with the panel closed it sits on the right
+ // button — the edge the panel opens on.
+ const pendingDock: DockPosition = panelDock("agents") ?? "right";
-/**
- * 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,
- };
-}
+ const toggles: Array<{ position: DockPosition; label: string; icon: string }> = [
+ { position: "bottom", label: S.dock.bottomDock, icon: PANEL_BOTTOM_ICON },
+ { position: "right", label: S.dock.rightDock, icon: PANEL_RIGHT_ICON },
+ ];
-/**
- * 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) => (
+ <div className="flex shrink-0 items-center gap-1" data-testid="panels-toolbar">
+ {toggles.map(({ position, label, icon }) => (
<button
- key={terminal.id}
+ key={position}
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-xs 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"
+ aria-expanded={isDockVisible(position)}
+ onClick={() => toggleDock(position)}
+ title={label}
+ aria-label={label}
+ data-testid={`dock-toggle-${position}`}
+ className={triggerClass(isDockVisible(position))}
>
- <span className="shrink-0 text-gray-500 dark:text-gray-400">
- <GlyphIcon d={NAV_ICONS.terminal} />
- </span>
- <span className="min-w-0 truncate">
- {terminal.seq ?? index + 1}: {displayTitle(terminal.title) || terminal.name}
- </span>
+ <GlyphIcon d={icon} size={ICON_SIZE.iconButton} />
+ {agentsPending && pendingDock === position && (
+ <span aria-hidden className={`h-1.5 w-1.5 rounded-full ${toneDot.attention}`} />
+ )}
</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: () => <GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.iconButton} />,
- 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: () => <GlyphIcon d={FOLDER_ICON} size={ICON_SIZE.iconButton} />,
- open: props.workspaceOpen,
- toggle: props.onToggleWorkspace,
- },
- {
- key: "memory",
- label: S.chat.memoryViewTitle,
- buttonLabel: S.chat.openMemoryPanel,
- glyph: () => <GlyphIcon d={MEMORY_ICON} size={ICON_SIZE.iconButton} />,
- open: props.memoryOpen,
- toggle: props.onToggleMemory,
- },
- ];
-
- 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 ${toneDot.attention}`} />
- )}
- {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)}
- >
- <GlyphIcon d={CREATE_ICON} size={ICON_SIZE.iconButton} />
- {!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 ${toneDot.attention}`}
- />
- )}
- </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"
- }`}
- >
- <GlyphIcon d={PIN_ICON} filled={pinned} />
- </button>
- </div>
- );
- })}
- </Dropdown>
- </div>
</div>
);
}
diff --git a/packages/web/src/features/chat/subagents-panel.tsx b/packages/web/src/features/chat/subagents-panel.tsx
deleted file mode 100644
index 1d014b02..00000000
--- a/packages/web/src/features/chat/subagents-panel.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * Subagents panel shell (same docked/Sheet split as files-panel.tsx, which documents the
- * clipping-window and inert rationale in detail): on desktop (≥1024px) it docks to the right of
- * the chat with a drag-to-resize edge; on narrower viewports it becomes a bottom Sheet. Content
- * is SubagentsView (latest-Task call graph + the selected child conversation), keyed by session
- * so node selection resets on session switch.
- */
-import type { SessionInfo } from "@prismshadow/penguin-server/api";
-import { S } from "../../lib/strings";
-import type { StreamModel } from "../../lib/omni/stream-model";
-import { Sheet } from "../../components/ui/sheet";
-import { CloseIcon } from "../../components/ui/icons";
-import { SubagentsView } from "./subagents-view";
-import type { StreamRenderContext } from "./message-stream";
-import type { SubagentsPanelState } from "./use-subagents-panel";
-
-export function SubagentsPanel({
- session,
- panel,
- model,
- version,
- taskRunning,
- ctx,
-}: {
- session: SessionInfo;
- panel: SubagentsPanelState;
- model: StreamModel;
- version: number;
- taskRunning: boolean;
- ctx: StreamRenderContext;
-}) {
- const view = (
- <SubagentsView
- key={session.sessionId}
- session={session}
- model={model}
- version={version}
- taskRunning={taskRunning}
- ctx={ctx}
- focusRequest={panel.focusRequest}
- taskScope={panel.taskScope}
- />
- );
-
- if (!panel.isDocked) {
- return (
- <Sheet
- open={panel.open}
- snap={panel.sheetSnap}
- onSnapChange={panel.setSheetSnap}
- onClose={() => panel.setOpen(false)}
- title={S.subagentPanel.title}
- >
- <div className="flex h-full min-h-0 flex-col">
- <div className="min-h-0 flex-1">{view}</div>
- </div>
- </Sheet>
- );
- }
-
- return (
- <>
- {panel.open && (
- <div
- onMouseDown={panel.startResize}
- onDoubleClick={panel.resetWidth}
- title={S.files.resizeHandle}
- className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 hover:bg-brand-300/50 dark:hover:bg-brand-700/40 ${
- panel.resizing ? "bg-brand-400/60" : "bg-transparent"
- }`}
- />
- )}
- <div
- ref={panel.panelRef}
- style={{ width: panel.open ? panel.width : 0 }}
- // Same inert + clipping-window handling as the Files panel, and the same open-only
- // divider (a closed panel's 1px border would otherwise paint next to the open one —
- // see files-panel.tsx).
- inert={!panel.open}
- className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden ${
- panel.open ? "border-l border-gray-200 dark:border-gray-800" : ""
- } ${panel.resizing ? "pointer-events-none" : "transition-[width] duration-200"}`}
- >
- <div style={{ width: panel.width }} className="flex h-full min-h-0 flex-col">
- <div className="flex shrink-0 items-center gap-1 px-3 pt-2">
- <h4 className="min-w-0 flex-1 truncate text-sm font-semibold">
- {S.subagentPanel.title}
- </h4>
- <button
- type="button"
- onClick={() => panel.setOpen(false)}
- title={S.common.close}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <CloseIcon />
- </button>
- </div>
- <div className="min-h-0 flex-1">{view}</div>
- </div>
- </div>
- </>
- );
-}
diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsx
index 425d7028..ddae9709 100644
--- a/packages/web/src/features/chat/subagents-view.tsx
+++ b/packages/web/src/features/chat/subagents-view.tsx
@@ -8,7 +8,7 @@
*
* Which Task: the LATEST by default (toolbar open / session switch — a new Task then resets
* the graph to its own agents as it streams); a chip click pins `taskScope` to that chip's
- * Task instead (use-subagents-panel.ts), so a chip on an older turn shows that turn's
+ * Task instead (the chat page's subagentTaskScope), so a chip on an older turn shows that turn's
* HISTORICAL graph via extractTopologyForChild — falling back to the latest Task when the
* anchor is no longer referenced (e.g. a resync swapped the model).
*
@@ -20,12 +20,16 @@
* highlighted node.
*/
import { useEffect, useMemo, useState } from "react";
+import { useNavigate } from "react-router";
import type { SessionInfo } from "@prismshadow/penguin-server/api";
import { S } from "../../lib/strings";
import type { StreamModel } from "../../lib/omni/stream-model";
import { AgentAvatar } from "../../components/ui/agent-avatar";
import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
import { StatusIcon } from "../../components/ui/status-icon";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { noteSessionSeen } from "../../lib/session-seen";
import { useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
import {
@@ -63,11 +67,12 @@ export function SubagentsView({
/** Main-session render context (origin []): the child conversation derives its own from it. */
ctx: StreamRenderContext;
focusRequest: Selection | null;
- /** Displayed Task scope (see use-subagents-panel.ts): null = latest; an anchor pins the historical Task containing that child. */
+ /** Displayed Task scope (the chat page's subagentTaskScope): null = latest; an anchor pins the historical Task containing that child. */
taskScope: { anchorSessionId: string } | null;
}) {
- const { agents } = useProject();
+ const { agents, setCurrentAgentId } = useProject();
const { sessions } = useSessions();
+ const navigate = useNavigate();
const [selected, setSelected] = useState<Selection | null>(null);
// A chip click focuses that child (fresh-object identity: re-clicking the same chip re-fires).
@@ -125,6 +130,21 @@ export function SubagentsView({
? { ...ctx, origin: active.origin, taskRunning: activeRunning }
: null;
+ /**
+ * Jump to the selected subagent's own Session in the chat area. Subagent runs register
+ * as Sessions (session_created over the parent's channel), so the child opens with the
+ * full chat surface — its own composer, panels and history. Mirrors the sidebar's
+ * openSession: the seen marker is stamped and the current Agent follows the child's.
+ */
+ const openAsSession = (): void => {
+ if (!active) return;
+ const row = sessions.find((s) => s.sessionId === active.sessionId);
+ if (row) noteSessionSeen(row.projectId, row.sessionId, row.lastActiveAt);
+ const agentId = row?.agentId ?? activeModel?.meta?.agentId ?? null;
+ if (agentId !== null) setCurrentAgentId(agentId);
+ navigate(`/chat/${active.sessionId}`);
+ };
+
return (
<div className="flex h-full min-h-0 flex-col">
{/* Call graph of the displayed Task — latest by default, a chip's Task when pinned (capped height; scrolls both ways for deep/wide trees). */}
@@ -184,6 +204,21 @@ export function SubagentsView({
{activeRunning && (
<StatusIcon state="running" size={10} label={S.chat.subagentRunning} />
)}
+ <span className="min-w-0 flex-1" />
+ {/* Jump out of the panel: the child conversation as a full Session. */}
+ <button
+ type="button"
+ title={S.subagentPanel.openAsSession}
+ aria-label={S.subagentPanel.openAsSession}
+ data-testid="subagent-open-session"
+ onClick={openAsSession}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon
+ 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"
+ size={ICON_SIZE.rowLead}
+ />
+ </button>
</div>
<div className="min-h-0 flex-1">
{/* Keyed by child: switching nodes resets scroll-follow instead of carrying the old position over. */}
diff --git a/packages/web/src/features/chat/use-files-panel.ts b/packages/web/src/features/chat/use-files-panel.ts
deleted file mode 100644
index dbcfda2f..00000000
--- a/packages/web/src/features/chat/use-files-panel.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * Files panel state machine: panel open/close, the responsive breakpoint for desktop docking
- * vs. falling back to a mobile drawer, and the "locate a file in the directory tree" navigation
- * command (driven by clicking a file chip inside a message). Drag-to-resize and the width live
- * in use-panel-width.ts, shared with the Agents and Memory panels so they all open at the
- * same width.
- *
- * The panel's content is just WorkspaceBrowser's single directory-tree view — the protocol has no
- * structured file-write signal at all (file writes can happen inside the opaque exec_command shell),
- * so there's no "Agent output" list to maintain; a file clicked in a message jumps straight to
- * locating it in the tree.
- *
- * Only the navigation command resets when sessionId changes; the open/closed state persists
- * across Sessions (once opened, it stays open — a panel the user opened is part of their
- * browsing environment, and switching conversations shouldn't collapse it). Starting a NEW chat
- * is the one reset point, and it belongs to the chat page, which owns every docked panel: see
- * the draft effect in chat-page.tsx.
- */
-import { useCallback, useEffect, useState } from "react";
-import type { SheetSnap } from "../../components/ui/sheet";
-import { usePanelWidth } from "./use-panel-width";
-import type { PanelWidthState } from "./use-panel-width";
-
-export interface FilesPanelState extends PanelWidthState {
- open: boolean;
- setOpen: (open: boolean) => void;
- /** Snap point for the mobile bottom Sheet (half = browsing / full = preview); unused in the desktop docked state. */
- sheetSnap: SheetSnap;
- setSheetSnap: (snap: SheetSnap) => void;
- /** Clicking a file chip in a message: commands WorkspaceBrowser to navigate to and locate that file. */
- browsePath: (path: string) => void;
- /** The external navigation command produced by browsePath; each call creates a new object
- * reference, ensuring that clicking the same file again still re-triggers WorkspaceBrowser's
- * locate effect (compared by object identity, not by path value). */
- openRequest: { path: string } | null;
- /** Docked at >=1024px (lg); otherwise falls back to a Drawer overlay. Responsive, updates live
- * as the window width changes — docked and Drawer are mounted mutually exclusively; mounting
- * both at once would cause WorkspaceBrowser's own data requests to fire twice. */
- isDocked: boolean;
-}
-
-const DOCK_QUERY = "(min-width: 1024px)";
-
-export function useFilesPanel(sessionId: string | null): FilesPanelState {
- const [open, setOpenRaw] = useState(false);
- const [sheetSnap, setSheetSnap] = useState<SheetSnap>("half");
- const [openRequest, setOpenRequest] = useState<{ path: string } | null>(null);
-
- /** Opening the panel defaults to browsing intent (Sheet snaps to half); browsePath's preview
- * intent overrides it to full within the same batch, without flickering. Closing doesn't
- * change the snap point. In the desktop docked state, sheetSnap is unused by anything, so this has no side effect there. */
- const setOpen = useCallback((next: boolean) => {
- if (next) setSheetSnap("half");
- setOpenRaw(next);
- }, []);
- const widthState = usePanelWidth();
- const [isDocked, setIsDocked] = useState(() => window.matchMedia(DOCK_QUERY).matches);
-
- // Switching Session/Agent only resets the navigation command (which pointed at a file in the
- // old session); the open/closed state deliberately survives — see the header note.
- useEffect(() => {
- setOpenRequest(null);
- }, [sessionId]);
-
- useEffect(() => {
- const mq = window.matchMedia(DOCK_QUERY);
- const onChange = (e: MediaQueryListEvent) => setIsDocked(e.matches);
- mq.addEventListener("change", onChange);
- return () => mq.removeEventListener("change", onChange);
- }, []);
-
- const browsePath = useCallback((path: string) => {
- setSheetSnap("full"); // Preview intent: opens the mobile Sheet fully
- setOpenRequest({ path });
- }, []);
-
- return {
- open,
- setOpen,
- sheetSnap,
- setSheetSnap,
- browsePath,
- openRequest,
- isDocked,
- ...widthState,
- };
-}
diff --git a/packages/web/src/features/chat/use-memory-panel.ts b/packages/web/src/features/chat/use-memory-panel.ts
deleted file mode 100644
index 2df6d6a7..00000000
--- a/packages/web/src/features/chat/use-memory-panel.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Memory panel state machine — the Memory side panel is a peer of the subagents and files
- * panels (chat-page wraps all three setOpens with the same exclusivity choreography) and
- * mirrors use-files-panel.ts: open/close, the responsive docked-vs-Sheet breakpoint, and
- * one navigation command. The command (`openMemory`) carries the Memory view's entry
- * routing (memory-nav.ts): a locate target lands on that memory's detail, null lands on
- * the list — so every entry point (toolbar toggle, card header, card row) goes through it
- * and the view never needs to guess where the user came from.
- *
- * Only the navigation command resets when sessionId changes; the open/closed state
- * persists across Sessions, matching the other two panels.
- */
-import { useCallback, useEffect, useState } from "react";
-import type { SheetSnap } from "../../components/ui/sheet";
-import type { MemoryLocateTarget } from "../../lib/omni/memory-changes";
-import { usePanelWidth } from "./use-panel-width";
-import type { PanelWidthState } from "./use-panel-width";
-
-export interface MemoryPanelState extends PanelWidthState {
- open: boolean;
- setOpen: (open: boolean) => void;
- /** Snap point for the mobile bottom Sheet; unused in the desktop docked state. */
- sheetSnap: SheetSnap;
- setSheetSnap: (snap: SheetSnap) => void;
- /** Navigation command: a target lands on that memory's detail (card row), null on the list (toolbar / card header). */
- openMemory: (target: MemoryLocateTarget | null) => void;
- /** The command produced by openMemory; a new object per call so repeating the same target still re-triggers the view's routing effect (compared by identity, like the files panel's openRequest). */
- memoryRequest: { target: MemoryLocateTarget | null } | null;
- /** Docked at >=1024px (lg); otherwise falls back to the bottom Sheet — same breakpoint as the sibling panels. */
- isDocked: boolean;
-}
-
-const DOCK_QUERY = "(min-width: 1024px)";
-
-export function useMemoryPanel(sessionId: string | null): MemoryPanelState {
- const [open, setOpenRaw] = useState(false);
- const [sheetSnap, setSheetSnap] = useState<SheetSnap>("half");
- const [memoryRequest, setMemoryRequest] = useState<{
- target: MemoryLocateTarget | null;
- } | null>(null);
-
- /** Opening defaults to browsing intent (Sheet at half); openMemory's locate overrides to full in the same batch. */
- const setOpen = useCallback((next: boolean) => {
- if (next) setSheetSnap("half");
- setOpenRaw(next);
- }, []);
- const widthState = usePanelWidth();
- const [isDocked, setIsDocked] = useState(() => window.matchMedia(DOCK_QUERY).matches);
-
- // Switching Session/Agent only resets the navigation command (which pointed at the old
- // session's changes); the open/closed state deliberately survives.
- useEffect(() => {
- setMemoryRequest(null);
- }, [sessionId]);
-
- useEffect(() => {
- const mq = window.matchMedia(DOCK_QUERY);
- const onChange = (e: MediaQueryListEvent) => setIsDocked(e.matches);
- mq.addEventListener("change", onChange);
- return () => mq.removeEventListener("change", onChange);
- }, []);
-
- const openMemory = useCallback((target: MemoryLocateTarget | null) => {
- if (target !== null) setSheetSnap("full"); // A located memory's content needs the space, like file preview
- setMemoryRequest({ target });
- }, []);
-
- return {
- open,
- setOpen,
- sheetSnap,
- setSheetSnap,
- openMemory,
- memoryRequest,
- isDocked,
- ...widthState,
- };
-}
diff --git a/packages/web/src/features/chat/use-subagents-panel.ts b/packages/web/src/features/chat/use-subagents-panel.ts
deleted file mode 100644
index 04568e72..00000000
--- a/packages/web/src/features/chat/use-subagents-panel.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * Subagents panel state machine (a sibling of use-files-panel.ts, which documents the shared
- * mechanics): panel open/close, the desktop-dock vs. mobile-Sheet breakpoint, the "focus this
- * child conversation" command driven by clicking a subagent chip inside a message, and the
- * displayed Task scope (latest vs. the historical Task a chip was clicked on — see taskScope).
- * Width and drag-to-resize live in use-panel-width.ts, shared with the Files and Memory panels
- * so the mutually exclusive panels always open at the same width.
- *
- * Visibility now follows the Files panel: an open panel survives a Session switch, and only a
- * NEW chat resets them all to closed (the chat page owns that reset — it owns every docked
- * panel). What
- * stays specific to this panel is the AUTO-OPEN: the current Task's first live spawn opens it
- * once, re-armed at each task boundary, so a manual close mid-task is respected. The pure
- * tracker below (createPanelTaskScope/advancePanelTaskScope) owns that decision; the chat page
- * observes the stream and applies it under its own layout guards.
- *
- * The focus command uses the fresh-object idiom so clicking the same chip again still
- * re-triggers the panel's focus effect.
- */
-import { useCallback, useEffect, useState } from "react";
-import type { SheetSnap } from "../../components/ui/sheet";
-import { usePanelWidth } from "./use-panel-width";
-import type { PanelWidthState } from "./use-panel-width";
-
-export interface SubagentsPanelState extends PanelWidthState {
- open: boolean;
- setOpen: (open: boolean) => void;
- /** Snap point for the mobile bottom Sheet; unused in the desktop docked state. */
- sheetSnap: SheetSnap;
- setSheetSnap: (snap: SheetSnap) => void;
- /** Clicking a subagent chip: commands the panel to select this child conversation. `origin` is the full chain ending with the child's own session id. */
- focusSubagent: (sessionId: string, origin: string[]) => void;
- /** The external focus command produced by focusSubagent; a fresh object per call (identity-compared, so re-clicking the same chip re-triggers the effect). */
- focusRequest: { sessionId: string; origin: string[] } | null;
- /**
- * Which Task's topology the panel displays. Null = the LATEST Task (the default: opening via
- * the toolbar resets to it, and so does switching Sessions). A chip click pins the graph to
- * the Task containing that chip instead — `anchorSessionId` is the clicked child's TOP-LEVEL
- * ancestor (the first origin hop; for deeper chips inside the panel the referencing main-
- * stream item belongs to that ancestor), which the view resolves to its Task slice via
- * extractTopologyForChild, so a chip on an older turn shows that turn's historical graph.
- */
- taskScope: { anchorSessionId: string } | null;
- /** Docked at >=1024px (lg); otherwise a bottom Sheet — mounted mutually exclusively. */
- isDocked: boolean;
-}
-
-const DOCK_QUERY = "(min-width: 1024px)";
-
-// ---------------------------------------------------------------------------
-// Auto-open tracker (pure — unit-tested in test/panel-task-scope.test.ts)
-// ---------------------------------------------------------------------------
-
-/**
- * Mutable tracker state, held in a ref by the chat page. `taskCount` is the number of
- * Task-starting user items observed in the session's stream (taskStartCount in
- * agent-topology.ts); an increase IS the "user started a new Task" boundary.
- */
-export interface PanelTaskScope {
- sessionId: string | null;
- taskCount: number;
- /** Task ordinal (the taskCount value) whose one auto-open attempt was already consumed; null = armed. */
- autoOpenedAt: number | null;
-}
-
-export function createPanelTaskScope(): PanelTaskScope {
- return { sessionId: null, taskCount: 0, autoOpenedAt: null };
-}
-
-/**
- * Advance the tracker with one observation of the current session's stream and return whether
- * the panel should auto-open:
- * - a live spawn in the current task → "autoOpen", at most once per task, so a manual close
- * afterwards is respected until the next boundary;
- * - a boundary (a Session switch, or a new Task within the session) RE-ARMS that one attempt
- * but is never itself an action — an open panel is not closed here any more. Entering a
- * session mid-run therefore auto-opens on the spawn that is already live, which reads as
- * that spawn introducing itself;
- * - anything else (steering, compaction, more messages in the same task) → null.
- * A taskCount DECREASE is a defensive re-baseline (a resync swapped in a smaller model):
- * adopted silently, with the auto-open attempt marked consumed so a rebuild can never
- * surprise-open a panel the user closed mid-task.
- * The caller applies "autoOpen" under its own layout guards (docked, Files panel closed, not
- * already open); the attempt is consumed here regardless, so a suppressed attempt never
- * retriggers within the same task.
- */
-export function advancePanelTaskScope(
- state: PanelTaskScope,
- obs: { sessionId: string | null; taskCount: number; liveSpawn: boolean },
-): "autoOpen" | null {
- const switched = obs.sessionId !== state.sessionId;
- const rebaseline = !switched && obs.taskCount < state.taskCount;
- if (switched || obs.taskCount !== state.taskCount) {
- state.sessionId = obs.sessionId;
- state.taskCount = obs.taskCount;
- // A real boundary re-arms the auto-open; the defensive re-baseline marks it consumed.
- state.autoOpenedAt = rebaseline ? obs.taskCount : null;
- }
- if (obs.liveSpawn && state.autoOpenedAt !== state.taskCount) {
- state.autoOpenedAt = state.taskCount;
- return "autoOpen";
- }
- return null;
-}
-
-export function useSubagentsPanel(sessionId: string | null): SubagentsPanelState {
- const [open, setOpenRaw] = useState(false);
- const [sheetSnap, setSheetSnap] = useState<SheetSnap>("half");
- const [focusRequest, setFocusRequest] = useState<{
- sessionId: string;
- origin: string[];
- } | null>(null);
- const [taskScope, setTaskScope] = useState<{ anchorSessionId: string } | null>(null);
-
- /**
- * Opening defaults to browsing intent (Sheet at half) on the LATEST Task's graph;
- * focusSubagent's conversation intent — queued in the same batch on the chip path — then
- * promotes the snap to full and pins the scope to the chip's Task.
- */
- const setOpen = useCallback((next: boolean) => {
- if (next) {
- setSheetSnap("half");
- setTaskScope(null);
- }
- setOpenRaw(next);
- }, []);
- const widthState = usePanelWidth();
- const [isDocked, setIsDocked] = useState(() => window.matchMedia(DOCK_QUERY).matches);
-
- // Switching Session resets the focus command and any pinned historical Task scope (both
- // pointed into the old session's stream — the new session opens on its latest topology).
- // The open/closed state is NOT touched: like the Files panel, an open panel survives the
- // switch, and only a new chat closes it (chat-page.tsx).
- useEffect(() => {
- setFocusRequest(null);
- setTaskScope(null);
- }, [sessionId]);
-
- useEffect(() => {
- const mq = window.matchMedia(DOCK_QUERY);
- const onChange = (e: MediaQueryListEvent) => setIsDocked(e.matches);
- mq.addEventListener("change", onChange);
- return () => mq.removeEventListener("change", onChange);
- }, []);
-
- const focusSubagent = useCallback((sid: string, origin: string[]) => {
- setSheetSnap("full"); // Conversation intent: the child transcript needs the space on mobile
- // Pin the graph to this chip's Task (the top-level ancestor anchors the slice lookup) —
- // ordered after the setOpen(true) of the same click, so the pin wins the batch.
- setTaskScope({ anchorSessionId: origin[0] ?? sid });
- setFocusRequest({ sessionId: sid, origin });
- }, []);
-
- return {
- open,
- setOpen,
- sheetSnap,
- setSheetSnap,
- focusSubagent,
- focusRequest,
- taskScope,
- isDocked,
- ...widthState,
- };
-}
diff --git a/packages/web/src/features/dock/dock-drag.tsx b/packages/web/src/features/dock/dock-drag.tsx
new file mode 100644
index 00000000..1a57e58c
--- /dev/null
+++ b/packages/web/src/features/dock/dock-drag.tsx
@@ -0,0 +1,130 @@
+/**
+ * Drag-to-dock: the overlay UI and hit-testing behind dragging a tab (or a whole dock's
+ * header) onto the other edge of the chat page.
+ *
+ * Two ways to pick an edge while dragging, both live-previewing before anything moves:
+ * 1. drag straight into an edge band of the chat column (`[data-dock-host]`) — the nearer
+ * of the right/bottom edges within the band is the candidate;
+ * 2. drop targets: a small widget near the bottom-right with one rectangle per edge —
+ * 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
+ * strip owns the pointer), so CSS hover never fires on the overlay.
+ */
+import { createPortal } from "react-dom";
+import type { CSSProperties } from "react";
+import { panelWidth } from "../chat/use-panel-width";
+import { DOCK_MIN_HEIGHT_PX, DOCK_RATIO_MAX, bottomRatio, type DockPosition } from "./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;
+}
+
+/** 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]> = [
+ ["right", (rect.right - x) / rect.width],
+ ["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 dock at `position` would occupy after the drop — measured from the
+ * live layout, not assumed: an already-open dock contributes its rendered rect; otherwise
+ * the stored sizes apply, clamped exactly like the docks' own CSS. The right region's top
+ * is the main row (`[data-dock-row]`, below the chat toolbar), the row the right dock
+ * really renders in.
+ */
+function previewStyle(host: DOMRect, position: DockPosition): CSSProperties {
+ const existing =
+ document
+ .querySelector<HTMLElement>(`[data-testid='dock'][data-position='${position}']`)
+ ?.getBoundingClientRect() ?? null;
+ if (position === "bottom") {
+ const height = Math.min(
+ existing?.height ??
+ Math.max(
+ DOCK_MIN_HEIGHT_PX,
+ Math.min(DOCK_RATIO_MAX * host.height, bottomRatio() * host.height),
+ ),
+ host.height,
+ );
+ return { left: host.left, top: host.bottom - height, width: host.width, height };
+ }
+ const row = document.querySelector("[data-dock-row]")?.getBoundingClientRect() ?? host;
+ const top = Math.max(host.top, row.top);
+ const width = Math.min(existing?.width ?? panelWidth(), host.width);
+ return { left: host.right - width, top, width, height: row.bottom - top };
+}
+
+/** 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 tab/header drag is in flight. `candidate`
+ * is what the drag currently points at; `null` means "release changes nothing".
+ */
+export function DockDragOverlay({ candidate }: { candidate: DockPosition | null }) {
+ const host = dockHostRect();
+ if (!host) return null;
+
+ 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(host, candidate)}
+ />
+ )}
+
+ {/* Drop-target widget, kept a comfortable margin off the host's corner. */}
+ <div
+ data-testid="dock-layout-widget"
+ className="fixed z-[70] 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"
+ style={{ left: host.right - 108, top: host.bottom - 96 }}
+ >
+ <DropTarget position="bottom" candidate={candidate} shape="h-4 w-9" />
+ <DropTarget position="right" candidate={candidate} shape="h-9 w-4.5" />
+ </div>
+ </>,
+ document.body,
+ );
+}
diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsx
new file mode 100644
index 00000000..b1f45501
--- /dev/null
+++ b/packages/web/src/features/dock/dock-panel.tsx
@@ -0,0 +1,841 @@
+/**
+ * One dock surface (dock-state.ts owns the arrangement): a tab strip across the top and
+ * the active tab's body below — or, while the open dock has no tabs, a centered picker
+ * choosing what to open here. The chat page renders one per open dock — right and/or
+ * bottom — or a single merged bottom surface below the desktop breakpoint.
+ *
+ * Panel tabs' bodies come from the page through `renderPanel` (they need the page's
+ * session/stream state); terminal tabs' bodies are the pooled xterm views
+ * (terminal-view-pool.tsx), adopted by DOM handoff so tab churn never reconnects a shell.
+ * Every tab's body stays mounted while its tab is in the strip — switching tabs hides and
+ * shows, so a panel keeps its scroll and drill-down state — except terminal views, which
+ * the pool keeps only for shown terminals (an off-screen shell reattaches on return).
+ *
+ * The header carries the strip, a "+" menu (panels, a fresh shell, and any live shell no
+ * conversation holds), a detach button while a terminal is shown, a move-to-other-edge
+ * button, and the dock's × (hide — tabs stay; each tab's own always-visible × is what
+ * removes). Tabs drag sideways to reorder; dragging a tab out of the strip brings up the
+ * edge overlay (dock-drag.tsx) and dropping on the other edge moves that tab there.
+ * Dragging the header itself moves the whole dock the same way. The boundary with the
+ * chat content resizes the dock — the right dock through the shared side-panel width,
+ * the bottom dock through its height ratio.
+ */
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import type { ReactNode } from "react";
+import { S } from "../../lib/strings";
+import { CloseIcon, NAV_ICONS } from "../../components/ui/icons";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { Dropdown } from "../../components/ui/dropdown";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneDot } from "../../lib/tone";
+import { useTerminalChrome } from "../terminal/terminal-appearance";
+import {
+ displayTitle,
+ killTerminal,
+ liveTerminals,
+ subscribeTerminals,
+} from "../terminal/terminal-list";
+import {
+ subscribeTerminalViewStates,
+ terminalViewContainer,
+ terminalViewState,
+} from "../terminal/terminal-view-pool";
+import type { TerminalInfo } from "../terminal/terminal-view";
+import { createShellInDock, detachTerminal, openTerminalInDock } from "./dock-terminal";
+import { DockDragOverlay, dockDropCandidate } from "./dock-drag";
+import { panelGlyph, panelLabel } from "./panel-meta";
+import {
+ DOCK_MIN_HEIGHT_PX,
+ DOCK_RATIO_MAX,
+ PANEL_KINDS,
+ activateTab,
+ addTerminalTab,
+ bottomRatio,
+ dockVersion,
+ hideView,
+ moveDock,
+ moveTab,
+ openPanel,
+ removeTab,
+ reorderDock,
+ resetBottomRatio,
+ setBottomRatio,
+ subscribeDock,
+ tabHome,
+ tabKey,
+ unownedTerminals,
+ type DockPosition,
+ type DockTab,
+ type DockView,
+ type PanelKind,
+} from "./dock-state";
+import {
+ persistPanelWidth,
+ resetPanelWidth,
+ setPanelWidth,
+ usePanelWidthValue,
+} from "../chat/use-panel-width";
+import { usePointerDrag } from "./use-pointer-drag";
+
+/** Plus: the add-tab trigger. */
+const ADD_ICON = "M12 5v14M5 12h14";
+/** Window with a bottom pane / a right pane: the move-dock buttons. */
+const PANEL_BOTTOM_ICON = "M4 5h16v14H4zM4 14h16";
+const PANEL_RIGHT_ICON = "M4 5h16v14H4zM14 5v14";
+/** Box with an arrow escaping to the top right: detach to its own window. */
+const DETACH_ICON = "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";
+
+/** Small icon-sized header button shared by the dock's controls. */
+function DockButton(props: {
+ label: string;
+ testId: string;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ 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 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ {props.children}
+ </button>
+ );
+}
+
+/**
+ * One tab in the strip: glyph + name + an always-visible ×. Two sibling buttons, not
+ * nested — a button inside a button is invalid and unclickable. The × has a reserved
+ * slot of its own after the label, never overlapping it: crowded tabs shrink by
+ * truncating the label (ellipsis) while the glyph and the × keep their width, so the
+ * close target stays where the pointer expects it.
+ */
+function DockTabButton(props: {
+ tabId: string;
+ label: string;
+ title: string;
+ glyph: ReactNode;
+ active: boolean;
+ /** Attention dot (e.g. a pending approval inside a subagent) shown beside the name. */
+ badge: boolean;
+ closeLabel: string;
+ onSelect: () => void;
+ onClose: () => void;
+ /** Terminal tabs keep their id on the node for tests and the strip's drag targeting. */
+ terminalId?: string;
+}) {
+ return (
+ <div
+ data-testid="dock-tab"
+ data-tab-id={props.tabId}
+ {...(props.terminalId !== undefined ? { "data-terminal-id": props.terminalId } : {})}
+ data-active={props.active}
+ className={`flex h-6 max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${
+ props.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-700 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"
+ }`}
+ >
+ <button
+ type="button"
+ title={props.title}
+ onClick={props.onSelect}
+ className="flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs"
+ >
+ <span aria-hidden className="shrink-0">
+ {props.glyph}
+ </span>
+ <span className="min-w-0 truncate">{props.label}</span>
+ {props.badge && (
+ <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot.attention}`} />
+ )}
+ </button>
+ <button
+ type="button"
+ title={props.closeLabel}
+ aria-label={`${props.closeLabel}: ${props.label}`}
+ data-testid="dock-tab-close"
+ onClick={props.onClose}
+ className="flex h-4 w-4 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200"
+ >
+ <CloseIcon size={10} />
+ </button>
+ </div>
+ );
+}
+
+/**
+ * A terminal tab's body: adopts the shown terminal's pooled container. Only while shown —
+ * the pool keeps views for shown terminals alone, so adopting an inactive tab's container
+ * would hold an empty node.
+ */
+function TerminalBody({ id, active }: { id: string; active: boolean }) {
+ const chrome = useTerminalChrome();
+ // Machine-readable connection state on the body root, for tests and tooling — the
+ // screen itself is the visible status.
+ const viewState = useSyncExternalStore(subscribeTerminalViewStates, () =>
+ terminalViewState(active ? id : null),
+ );
+ const bodyRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const body = bodyRef.current;
+ if (!body || !active) return;
+ const container = terminalViewContainer(id);
+ body.appendChild(container);
+ return () => {
+ if (container.parentElement === body) body.removeChild(container);
+ };
+ }, [id, active]);
+ return (
+ <div
+ ref={bodyRef}
+ data-testid="dock-terminal-body"
+ data-status={viewState.status}
+ className={`flex min-h-0 flex-1 flex-col overflow-hidden px-2 py-1 ${chrome.surface}`}
+ />
+ );
+}
+
+/** The strip label of a terminal tab: stable seq + live title, like a tmux status line. */
+function terminalLabel(info: TerminalInfo | undefined, id: string, ordinal: number): string {
+ if (!info) return `${ordinal}: ${id.slice(0, 6)}`;
+ return `${info.seq ?? ordinal}: ${displayTitle(info.title) || info.name}`;
+}
+
+/**
+ * The body of an open dock with no tabs: a centered choice list (Codex-style) — pick what
+ * to open here. Every side element is a row; the terminal row adopts the newest shell no
+ * conversation holds, or starts a fresh one, and names its hotkey.
+ */
+function DockPicker({
+ choose,
+ chooseTerminal,
+ terminalSupported,
+ horizontal,
+}: {
+ choose: (kind: PanelKind) => void;
+ chooseTerminal: () => void;
+ terminalSupported: boolean;
+ /** The bottom (and merged) surface lays its choices out in a row, the right one as a list. */
+ horizontal: boolean;
+}) {
+ const rowClass =
+ "flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";
+ const row = (kind: PanelKind) => (
+ <button
+ key={kind}
+ type="button"
+ data-testid={`dock-pick-${kind}`}
+ onClick={() => choose(kind)}
+ className={rowClass}
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">{panelGlyph(kind)}</span>
+ <span className="min-w-0 truncate">{panelLabel(kind)}</span>
+ </button>
+ );
+ return (
+ <div
+ data-testid="dock-picker"
+ className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto p-4"
+ >
+ <div
+ className={
+ horizontal
+ ? "flex max-w-full flex-wrap items-center justify-center gap-1"
+ : "flex w-60 flex-col gap-0.5"
+ }
+ >
+ {row("agents")}
+ {terminalSupported && (
+ <button
+ type="button"
+ data-testid="dock-pick-terminal"
+ onClick={chooseTerminal}
+ className={rowClass}
+ >
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">
+ <GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.iconButton} />
+ </span>
+ <span className="min-w-0 flex-1 truncate">{S.terminal.title}</span>
+ <kbd className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">
+ Ctrl+`
+ </kbd>
+ </button>
+ )}
+ {row("workspace")}
+ {row("memory")}
+ {row("trace")}
+ </div>
+ </div>
+ );
+}
+
+export interface DockPanelProps {
+ view: DockView;
+ /** The page's panel bodies (they need its session/stream state); null hides that kind from the add menu too. */
+ renderPanel: (kind: PanelKind, active: boolean) => ReactNode;
+ /** Attention dots per panel kind (the agents tab's pending-approval amber dot). */
+ panelBadges?: Partial<Record<PanelKind, boolean>>;
+ /** Whether the server serves the terminal API at all (an older runtime does not). */
+ terminalSupported: boolean;
+ /** False only while the dock collapses on its way out (use-dock-mount keeps it mounted). */
+ open?: boolean;
+ /** Whether mounting plays the expand transition (false for instant changes — scope switches, moves). */
+ animateEntrance?: boolean;
+}
+
+export function DockPanel({
+ view,
+ renderPanel,
+ panelBadges,
+ terminalSupported,
+ open = true,
+ animateEntrance = true,
+}: DockPanelProps) {
+ useSyncExternalStore(subscribeDock, dockVersion);
+ const terminals = useSyncExternalStore(subscribeTerminals, liveTerminals);
+ const terminalById = new Map(terminals.map((t) => [t.id, t]));
+ const { position, merged, tabs, activeKey } = view;
+ const horizontal = position === "bottom";
+ const other: DockPosition = position === "right" ? "bottom" : "right";
+ const [addOpen, setAddOpen] = useState(false);
+
+ const activeTab = tabs.find((tab) => tabKey(tab) === activeKey) ?? null;
+
+ // ---------------------------------------------------------------------------- selection
+
+ // A terminal tab's × ends the shell itself (server-side) — an easy mis-click next to
+ // the tab, so it confirms first. Panel tabs close directly: nothing is lost.
+ const [confirmKill, setConfirmKill] = useState<{ id: string; label: string } | null>(null);
+ const closeTab = useCallback((tab: DockTab, label: string) => {
+ if (tab.kind === "terminal") {
+ setConfirmKill({ id: tab.terminalId, label });
+ return;
+ }
+ removeTab(tabKey(tab));
+ }, []);
+ const killConfirmed = useCallback(() => {
+ if (!confirmKill) return;
+ void killTerminal(confirmKill.id);
+ removeTab(`terminal:${confirmKill.id}`);
+ setConfirmKill(null);
+ }, [confirmKill]);
+
+ /**
+ * Detach the shown terminal to its own /terminal window. The shell stays live (and
+ * listed — multi-client attach); its tab leaves the strip, and closing the window puts
+ * it back where it was (dock-terminal.ts owns the round trip).
+ */
+ const detach = useCallback(() => {
+ if (activeTab?.kind !== "terminal") return;
+ const home = merged ? (tabHome(tabKey(activeTab)) ?? "bottom") : position;
+ detachTerminal(activeTab.terminalId, home);
+ }, [activeTab, merged, position]);
+
+ // 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 (activeKey === null) return;
+ stripRef.current
+ ?.querySelector(`[data-tab-id="${CSS.escape(activeKey)}"]`)
+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [activeKey, tabs]);
+
+ // 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);
+ }, []);
+
+ // ------------------------------------------------------------------ header drag: move dock
+ const [headerDrag, setHeaderDrag] = useState<{
+ active: boolean;
+ candidate: DockPosition | null;
+ }>({ active: false, candidate: null });
+ const clearHeaderDrag = () => setHeaderDrag({ active: false, candidate: null });
+
+ const headerDragProps = usePointerDrag<object>({
+ begin: (event) =>
+ // The merged view spans both docks, so "move the dock" has no target of its own.
+ merged || (event.target as HTMLElement).closest("button, [data-testid='dock-tab']")
+ ? null
+ : {},
+ onMove: (event) =>
+ setHeaderDrag({ active: true, candidate: dockDropCandidate(event.clientX, event.clientY) }),
+ onEnd: (_payload, dragged) => {
+ const candidate = headerDrag.candidate;
+ clearHeaderDrag();
+ if (dragged && candidate && candidate !== position) moveDock(position, candidate);
+ },
+ onCancel: clearHeaderDrag,
+ });
+
+ // --------------------------------------------------- tab drag: reorder or move to the other edge
+ const [tabDrag, setTabDrag] = useState<{ active: boolean; candidate: DockPosition | null }>({
+ active: false,
+ candidate: null,
+ });
+ const clearTabDrag = () => setTabDrag({ active: false, candidate: null });
+
+ const stripDragProps = usePointerDrag<{ id: string }>({
+ threshold: 6,
+ begin: (event) => {
+ // Merged strips span both docks: a cross-dock reorder would silently move tabs
+ // between docks, so the merged view keeps taps only (the buttons' own clicks).
+ if (merged) return null;
+ const target = event.target as HTMLElement;
+ if (target.closest("[data-testid='dock-tab-close']")) return null;
+ const id = target.closest<HTMLElement>("[data-tab-id]")?.dataset.tabId;
+ return id ? { id } : null;
+ },
+ onMove: (event, { id }) => {
+ // Out of the strip (with a little slack): the gesture becomes "move to the other
+ // edge" — the same overlay as moving a dock, with the preview showing the landing.
+ const strip = event.currentTarget.getBoundingClientRect();
+ if (event.clientY < strip.top - 20 || event.clientY > strip.bottom + 20) {
+ setTabDrag({ active: true, candidate: dockDropCandidate(event.clientX, event.clientY) });
+ return;
+ }
+ setTabDrag({ active: false, candidate: null });
+
+ // Within the strip: live reorder against the other tabs' midpoints.
+ const tabEls = [...event.currentTarget.querySelectorAll<HTMLElement>("[data-tab-id]")];
+ const currentIds = tabEls.map((el) => el.dataset.tabId as string);
+ const others = tabEls.filter((el) => el.dataset.tabId !== 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.tabId as string);
+ nextIds.splice(insertAt, 0, id);
+ if (nextIds.some((nextId, index) => nextId !== currentIds[index]))
+ reorderDock(position, nextIds);
+ },
+ onEnd: ({ id }, dragged) => {
+ const { active, candidate } = tabDrag;
+ 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) {
+ activateTab(id);
+ return;
+ }
+ if (!active || !candidate || candidate === tabHome(id)) return;
+ moveTab(id, candidate);
+ },
+ onCancel: clearTabDrag,
+ });
+
+ // ------------------------------------------------------------------------ boundary resize
+ const [resizing, setResizing] = useState(false);
+ const sideWidth = usePanelWidthValue();
+ // The dock's own root node. The RIGHT dock's resize handle is a layout SIBLING of it
+ // (it must cost real width), so the handle's events cannot `closest()` their way to the
+ // dock — the ref is how both handles reach the box they resize.
+ const rootRef = useRef<HTMLDivElement | null>(null);
+
+ const resizerDragProps = usePointerDrag<object>({
+ threshold: 0,
+ begin: (event) => {
+ event.preventDefault(); // no text selection while dragging the boundary
+ setResizing(true);
+ return {};
+ },
+ onMove: (event) => {
+ const pane = rootRef.current?.getBoundingClientRect();
+ if (!pane) return;
+ if (horizontal) {
+ // The ratio's basis is the chat page column ([data-dock-host]), the same box the
+ // rendered height is computed from below.
+ const host = document.querySelector("[data-dock-host]")?.getBoundingClientRect();
+ if (!host || host.height === 0) return;
+ setBottomRatio((pane.bottom - event.clientY) / host.height);
+ } else {
+ setPanelWidth(pane.right - event.clientX);
+ }
+ },
+ onEnd: () => {
+ setResizing(false);
+ if (!horizontal) persistPanelWidth(); // once per drag, not per frame
+ },
+ onCancel: () => setResizing(false),
+ });
+
+ // The bottom dock's height in PIXELS: ratio × the measured chat column, with the same
+ // clamps the drag applies. Pixels rather than a CSS percentage so the expand/collapse
+ // transition interpolates cleanly to 0 and the INNER content can sit at the settled
+ // height while the outer box animates past it (no reflow mid-transition; xterm would
+ // refit its grid on every intermediate height).
+ // Lazy initial measurement: on every mount but the app's very first commit the host is
+ // already in the DOM, so the first paint uses the real height — a 0 start would make
+ // the height jump 0→target one commit later, which the transition class turns into an
+ // unasked-for slide (and an instant mount is exactly the case that must not slide).
+ // On the first commit the host is not attached yet; that mount is the animated initial
+ // restore, whose entrance starts at 0 by design.
+ const [hostHeight, setHostHeight] = useState(() => {
+ const host = document.querySelector("[data-dock-host]");
+ return host instanceof HTMLElement ? host.getBoundingClientRect().height : 0;
+ });
+ useLayoutEffect(() => {
+ if (!horizontal) return;
+ const host = document.querySelector("[data-dock-host]");
+ if (!(host instanceof HTMLElement)) return;
+ const measure = () => setHostHeight(host.getBoundingClientRect().height);
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(host);
+ return () => observer.disconnect();
+ }, [horizontal]);
+ const bottomHeight = Math.round(
+ Math.min(DOCK_RATIO_MAX * hostHeight, Math.max(DOCK_MIN_HEIGHT_PX, bottomRatio() * hostHeight)),
+ );
+
+ const onResizerDoubleClick = useCallback(
+ () => (horizontal ? resetBottomRatio() : resetPanelWidth()),
+ [horizontal],
+ );
+
+ // ------------------------------------------------------------------------------ add menu
+
+ const openPanelHere = (kind: PanelKind): void => {
+ setAddOpen(false);
+ // The merged view has no edge of its own to insist on — the panel's existing tab (or
+ // the right-dock default) decides, which is also where it lands when the window
+ // widens back out.
+ openPanel(kind, merged ? undefined : position);
+ };
+
+ /** Live shells no conversation holds: offer to pull them into this dock. */
+ const adoptableIds = new Set(unownedTerminals(terminals.map((t) => t.id)));
+ const adoptable = terminals.filter((t) => adoptableIds.has(t.id));
+
+ const addMenu = (
+ <Dropdown
+ open={addOpen}
+ setOpen={setAddOpen}
+ portal={{ direction: "down", align: "right" }}
+ menuClass="w-56"
+ button={
+ <DockButton label={S.dock.addTab} testId="dock-add" onClick={() => setAddOpen(!addOpen)}>
+ <GlyphIcon d={ADD_ICON} size={ICON_SIZE.iconButton} />
+ </DockButton>
+ }
+ >
+ {PANEL_KINDS.map((kind) => (
+ <button
+ key={kind}
+ type="button"
+ data-testid={`dock-add-${kind}`}
+ onClick={() => openPanelHere(kind)}
+ 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">{panelGlyph(kind)}</span>
+ <span className="min-w-0 truncate">{panelLabel(kind)}</span>
+ </button>
+ ))}
+ {terminalSupported && (
+ <>
+ <div className="mx-2 my-1 border-t border-gray-100 dark:border-gray-800" />
+ <button
+ type="button"
+ data-testid="dock-add-terminal"
+ onClick={() => {
+ setAddOpen(false);
+ void createShellInDock(merged ? undefined : position);
+ }}
+ 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">
+ <GlyphIcon d={ADD_ICON} size={ICON_SIZE.iconButton} />
+ </span>
+ <span className="min-w-0 truncate">{S.terminal.newShell}</span>
+ </button>
+ {adoptable.map((terminal, index) => (
+ <button
+ key={terminal.id}
+ type="button"
+ data-testid="dock-add-shell"
+ data-terminal-id={terminal.id}
+ onClick={() => {
+ setAddOpen(false);
+ addTerminalTab(terminal.id, merged ? undefined : position);
+ }}
+ className="mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs 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="min-w-0 truncate">
+ {terminalLabel(terminal, terminal.id, index + 1)}
+ </span>
+ </button>
+ ))}
+ </>
+ )}
+ </Dropdown>
+ );
+
+ // ------------------------------------------------------------------------------- render
+
+ // First paint happens at size 0; `entered` flips a frame later so the expand really
+ // transitions — a node that MOUNTS at its target size has no transition to run. Double
+ // rAF: the first can land in the same frame as the initial paint, and a 0→size set
+ // within one frame is not a transition either. An instant mount (scope switch, a moved
+ // tab's target dock) starts entered instead and paints at full size straight away.
+ const [entered, setEntered] = useState(!animateEntrance);
+ useEffect(() => {
+ if (entered) return;
+ let inner = 0;
+ const outer = requestAnimationFrame(() => {
+ inner = requestAnimationFrame(() => setEntered(true));
+ });
+ return () => {
+ cancelAnimationFrame(outer);
+ cancelAnimationFrame(inner);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const overlayActive = headerDrag.active || tabDrag.active;
+ const overlayCandidate = headerDrag.active ? headerDrag.candidate : tabDrag.candidate;
+
+ const terminalOrdinals = new Map<string, number>();
+ tabs.forEach((tab) => {
+ if (tab.kind === "terminal") terminalOrdinals.set(tab.terminalId, terminalOrdinals.size + 1);
+ });
+
+ const header = (
+ <header
+ data-testid="dock-header"
+ {...headerDragProps}
+ className={`flex shrink-0 items-center gap-2 border-b border-gray-200 px-2 py-1.5 text-xs dark:border-gray-800 ${
+ merged ? "" : "cursor-grab select-none"
+ }`}
+ >
+ {/* Tab strip: this dock's tabs, current one highlighted; drag sideways to reorder,
+ drag out to move onto the other edge. Scrolls when the tabs outgrow the header. */}
+ <div
+ ref={stripRef}
+ data-testid="dock-tab-strip"
+ {...stripDragProps}
+ className="no-scrollbar flex min-w-0 items-center gap-1 overflow-x-auto"
+ >
+ {tabs.map((tab) => {
+ const key = tabKey(tab);
+ if (tab.kind === "panel") {
+ return (
+ <DockTabButton
+ key={key}
+ tabId={key}
+ label={panelLabel(tab.panel)}
+ title={panelLabel(tab.panel)}
+ glyph={panelGlyph(tab.panel, ICON_SIZE.inlineGlyph)}
+ active={key === activeKey}
+ badge={panelBadges?.[tab.panel] === true}
+ closeLabel={S.dock.closeTab}
+ onSelect={() => activateTab(key)}
+ onClose={() => closeTab(tab, panelLabel(tab.panel))}
+ />
+ );
+ }
+ const info = terminalById.get(tab.terminalId);
+ const label = terminalLabel(
+ info,
+ tab.terminalId,
+ terminalOrdinals.get(tab.terminalId) ?? 1,
+ );
+ return (
+ <DockTabButton
+ key={key}
+ tabId={key}
+ terminalId={tab.terminalId}
+ label={label}
+ title={info ? `${info.name} — ${info.cwd}` : label}
+ glyph={<GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.inlineGlyph} />}
+ active={key === activeKey}
+ badge={false}
+ closeLabel={S.terminal.killShell}
+ onSelect={() => activateTab(key)}
+ onClose={() => closeTab(tab, label)}
+ />
+ );
+ })}
+ </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">
+ {activeTab?.kind === "terminal" && (
+ <DockButton label={S.terminal.detach} testId="dock-detach" onClick={detach}>
+ <GlyphIcon d={DETACH_ICON} size={ICON_SIZE.rowLead} />
+ </DockButton>
+ )}
+ {addMenu}
+ {!merged && tabs.length > 0 && (
+ <DockButton
+ label={position === "right" ? S.dock.moveToBottom : S.dock.moveToRight}
+ testId="dock-move"
+ onClick={() => moveDock(position, other)}
+ >
+ <GlyphIcon
+ d={position === "right" ? PANEL_BOTTOM_ICON : PANEL_RIGHT_ICON}
+ size={ICON_SIZE.rowLead}
+ />
+ </DockButton>
+ )}
+ <DockButton label={S.dock.hideDock} testId="dock-close" onClick={() => hideView(view)}>
+ <CloseIcon size={12} />
+ </DockButton>
+ </div>
+ </header>
+ );
+
+ const bodies =
+ tabs.length === 0 ? (
+ // An open dock with nothing in it yet: the picker chooses what this dock opens.
+ <DockPicker
+ choose={(kind) => openPanel(kind, merged ? undefined : position)}
+ chooseTerminal={() => void openTerminalInDock(merged ? undefined : position)}
+ terminalSupported={terminalSupported}
+ horizontal={horizontal}
+ />
+ ) : (
+ <div className="relative min-h-0 flex-1">
+ {tabs.map((tab) => {
+ const key = tabKey(tab);
+ const active = key === activeKey;
+ return (
+ <div key={key} className={active ? "flex h-full min-h-0 flex-col" : "hidden"}>
+ {tab.kind === "panel" ? (
+ renderPanel(tab.panel, active)
+ ) : (
+ <TerminalBody id={tab.terminalId} active={active} />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+
+ const killConfirm = (
+ <ConfirmModal
+ open={confirmKill !== null}
+ title={S.dock.killConfirmTitle}
+ onClose={() => setConfirmKill(null)}
+ onConfirm={killConfirmed}
+ confirmLabel={S.terminal.killShell}
+ >
+ {confirmKill !== null && <p>{S.dock.killConfirmBody(confirmKill.label)}</p>}
+ </ConfirmModal>
+ );
+
+ if (horizontal) {
+ return (
+ <div
+ ref={rootRef}
+ data-testid="dock"
+ data-position="bottom"
+ // Collapsed to 0 while closing/entering; the border belongs to the open state
+ // only — with border-box sizing a collapsed dock would still paint its 1px,
+ // leaving a hairline where nothing is.
+ style={{ height: open && entered ? bottomHeight : 0 }}
+ inert={!open}
+ className={`relative flex w-full shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${
+ open ? "border-t border-gray-200 dark:border-gray-800" : ""
+ } ${resizing ? "" : "transition-[height] duration-200"}`}
+ >
+ {/* The handle straddles the boundary as an overlay, costing no height. Only while
+ open — a collapsing dock must not keep a grabbable edge behind. */}
+ {open && (
+ <div
+ data-testid="dock-resizer"
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label={S.dock.resize}
+ title={S.dock.resize}
+ {...resizerDragProps}
+ onDoubleClick={onResizerDoubleClick}
+ className={`absolute -top-[3px] left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${
+ resizing ? "bg-sky-500/60" : "bg-transparent hover:bg-sky-500/40"
+ }`}
+ />
+ )}
+ {/* Content fixed at the settled height inside the clipping window: while the
+ outer box animates through intermediate heights, nothing reflows — xterm
+ keeps its grid, panels keep their layout — the surface just slides. */}
+ <div style={{ height: bottomHeight }} className="flex min-h-0 shrink-0 flex-col">
+ {header}
+ {bodies}
+ </div>
+ {overlayActive && <DockDragOverlay candidate={overlayCandidate} />}
+ {killConfirm}
+ </div>
+ );
+ }
+
+ return (
+ <>
+ {/* A layout-sibling handle, not an overlay: it must cost real width so the chat
+ column measures the same under every surface. Only while open — a collapsing
+ dock must not leave a bare strip behind. */}
+ {open && (
+ <div
+ data-testid="dock-resizer"
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={S.dock.resize}
+ title={S.dock.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"
+ }`}
+ />
+ )}
+ <div
+ ref={rootRef}
+ data-testid="dock"
+ data-position="right"
+ // The border belongs to the open state only (see the bottom branch's note).
+ style={{ width: open && entered ? sideWidth : 0 }}
+ inert={!open}
+ className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${
+ open ? "border-l border-gray-200 dark:border-gray-800" : ""
+ } ${resizing ? "" : "transition-[width] duration-200"}`}
+ >
+ {/* Fixed-width content inside the clipping window: while the outer element
+ animates through intermediate widths, the content must not reflow frame by
+ frame — text would squeeze, and xterm would refit its grid on every one. */}
+ <div style={{ width: sideWidth }} className="flex min-h-0 flex-1 flex-col">
+ {header}
+ {bodies}
+ </div>
+ {overlayActive && <DockDragOverlay candidate={overlayCandidate} />}
+ {killConfirm}
+ </div>
+ </>
+ );
+}
diff --git a/packages/web/src/features/dock/dock-state.ts b/packages/web/src/features/dock/dock-state.ts
new file mode 100644
index 00000000..543ce40f
--- /dev/null
+++ b/packages/web/src/features/dock/dock-state.ts
@@ -0,0 +1,716 @@
+/**
+ * State of the dock system, as a tiny module-level store.
+ *
+ * The dock is TWO surfaces — one on the right edge, one at the bottom of the chat page —
+ * and every side element is a TAB in one of them: the subagents panel, the Workspace
+ * files panel, the Memory panel, the Trace panel, and any number of terminals. A dock
+ * shows its tabs in a strip and renders the active one; an OPEN dock with no tabs shows a
+ * picker instead (choose what to open here), which is what the toolbar's two pull-open
+ * buttons land on. Both docks can be open at once, and any tab can live in either dock
+ * (the panel kinds are singletons — one tab per kind within a conversation — while
+ * terminals are one tab per shell).
+ *
+ * The arrangement is SCOPED to the conversation it was made in, like each browser window
+ * managing its own tabs: switching Sessions switches the whole arrangement, and no
+ * conversation's tabs depend on another's. The shells behind terminal tabs are per-user
+ * and keep running regardless; a scope only decides which of them are on screen here.
+ * The draft page and pages with no Session use placeholder scopes; an arrangement made
+ * while drafting is handed to the Session the first send creates (adoptDockScope).
+ * Everything persists (one localStorage entry, least-recently-used scopes aging out), so
+ * a reload restores each conversation's docks. Sizes are the exception: how wide/tall the
+ * user likes a dock is one preference, not one per conversation.
+ *
+ * Closing a TAB removes it (the last tab closing also puts the dock away); a dock's ×
+ * hides the surface keeping its tabs for the next open. Below the desktop breakpoint the
+ * two docks render as ONE merged bottom surface (a 320px-minimum right panel does not fit
+ * a phone); the stored arrangement splits back apart when the window widens.
+ *
+ * A store (rather than component state) because the consumers live far apart: the chat
+ * toolbar toggles the docks, the global hotkey flips the terminal, AppLayout points the
+ * scope at the route's conversation, the chat page renders the docks, and the terminal
+ * list prunes dead shells' tabs on refresh.
+ */
+
+const LAYOUT_KEY = "penguin.dock.layout";
+/** Scopes kept in storage; past that, the least recently touched conversations age out. */
+const MAX_SCOPES = 40;
+
+export type DockPosition = "right" | "bottom";
+
+/** The singleton panel kinds. Terminals are the one multi-instance tab kind. */
+export type PanelKind = "agents" | "workspace" | "memory" | "trace";
+
+export const PANEL_KINDS: readonly PanelKind[] = ["agents", "workspace", "memory", "trace"];
+
+export type DockTab =
+ { kind: "panel"; panel: PanelKind } | { kind: "terminal"; terminalId: string };
+
+/** Stable identity of a tab ("agents", …, "terminal:<id>") — the stored form. */
+export function tabKey(tab: DockTab): string {
+ return tab.kind === "panel" ? tab.panel : `terminal:${tab.terminalId}`;
+}
+
+function parseTabKey(key: string): DockTab | null {
+ if ((PANEL_KINDS as readonly string[]).includes(key))
+ return { kind: "panel", panel: key as PanelKind };
+ if (key.startsWith("terminal:") && key.length > "terminal:".length)
+ return { kind: "terminal", terminalId: key.slice("terminal:".length) };
+ return null;
+}
+
+/**
+ * The bottom dock's HEIGHT is a ratio of the chat page column. The px minimum (and the
+ * ratio ceiling, which also leaves the chat room) are enforced both by the dock's CSS and
+ * by the resize drag. The right dock's WIDTH is not here: it is the shared side-panel
+ * width (use-panel-width.ts), unchanged from the pre-dock panels.
+ */
+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;
+
+function clampRatio(value: number): number {
+ if (!Number.isFinite(value)) return DEFAULT_DOCK_HEIGHT_RATIO;
+ return Math.min(DOCK_RATIO_MAX, Math.max(DOCK_RATIO_MIN, value));
+}
+
+interface DockAreaState {
+ tabs: DockTab[];
+ /** tabKey of the shown tab; kept pointing at a member (or null when empty). */
+ active: string | null;
+ /** An open dock is on screen — with tabs it shows the active one, without it shows the picker. */
+ open: boolean;
+}
+
+function emptyArea(): DockAreaState {
+ return { tabs: [], active: null, open: false };
+}
+
+/** One conversation's arrangement — everything setDockScope swaps. */
+interface ScopeLayout {
+ right: DockAreaState;
+ bottom: DockAreaState;
+ /** The dock touched last: the merged view's active tab follows it, and Ctrl+` targets it. */
+ focus: DockPosition;
+}
+
+function emptyScope(): ScopeLayout {
+ return { right: emptyArea(), bottom: emptyArea(), focus: "bottom" };
+}
+
+/**
+ * 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. The
+ * draft page instead scopes to its route id ("new" / a parked draft id), whose
+ * arrangement adoptDockScope hands to the Session the first send creates.
+ */
+const NO_SCOPE = "~none";
+
+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);
+ return typeof parsed === "object" && parsed !== null ? (parsed as T) : fallback;
+ } catch {
+ return fallback; // node env / private mode / malformed entry: start from the default
+ }
+}
+
+function writeJson(key: string, value: unknown): void {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // Private-mode storage failures only cost persistence.
+ }
+}
+
+/**
+ * One stored dock, 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 sanitizeArea(raw: unknown): DockAreaState {
+ const area = (raw ?? {}) as Partial<{ tabs: unknown; active: unknown; open: unknown }>;
+ const tabs = (Array.isArray(area.tabs) ? area.tabs : [])
+ .map((key) => (typeof key === "string" ? parseTabKey(key) : null))
+ .filter((tab): tab is DockTab => tab !== null);
+ // One tab per key: a duplicated stored entry would render two strips fighting over one active.
+ const seen = new Set<string>();
+ const unique = tabs.filter((tab) => {
+ const key = tabKey(tab);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ const active =
+ typeof area.active === "string" && unique.some((tab) => tabKey(tab) === area.active)
+ ? area.active
+ : unique.length > 0
+ ? tabKey(unique[unique.length - 1]!)
+ : null;
+ return { tabs: unique, active, open: area.open === true };
+}
+
+function sanitizeScope(raw: unknown): ScopeLayout {
+ const scope = (raw ?? {}) as Partial<Record<string, unknown>>;
+ const right = sanitizeArea(scope.right);
+ const bottom = sanitizeArea(scope.bottom);
+ // A panel key present in both docks keeps the right copy (sanitizeArea dedupes only within a dock).
+ const rightKeys = new Set(right.tabs.map(tabKey));
+ bottom.tabs = bottom.tabs.filter((tab) => !rightKeys.has(tabKey(tab)));
+ if (bottom.active !== null && !bottom.tabs.some((tab) => tabKey(tab) === bottom.active))
+ bottom.active = bottom.tabs.length > 0 ? tabKey(bottom.tabs[bottom.tabs.length - 1]!) : null;
+ return { right, bottom, focus: scope.focus === "right" ? "right" : "bottom" };
+}
+
+interface StoredLayout {
+ scopes: Record<string, unknown>;
+ bottomRatio: unknown;
+}
+
+function loadStored(): { scopes: Record<string, ScopeLayout>; bottomRatio: number } {
+ const raw = readJson<Partial<StoredLayout>>(LAYOUT_KEY, {});
+ const scopes: Record<string, ScopeLayout> = {};
+ if (typeof raw.scopes === "object" && raw.scopes !== null) {
+ for (const [key, value] of Object.entries(raw.scopes)) scopes[key] = sanitizeScope(value);
+ }
+ return {
+ scopes,
+ bottomRatio: clampRatio(typeof raw.bottomRatio === "number" ? raw.bottomRatio : NaN),
+ };
+}
+
+let { scopes, bottomRatio: ratio } = loadStored();
+let scope = NO_SCOPE;
+// Unpacked into a local rather than read through `scopes[scope]` everywhere: the reads
+// are on every render path, and one live object per scope keeps switching cheap.
+let layout: ScopeLayout = scopes[scope] ?? emptyScope();
+
+/** Whether a scope's arrangement is worth a storage entry at all. */
+function scopeIsEmpty(s: ScopeLayout): boolean {
+ return s.right.tabs.length === 0 && s.bottom.tabs.length === 0 && !s.right.open && !s.bottom.open;
+}
+
+/** Writes the live layout back into the scope map and persists it. */
+function persist(): void {
+ // An untouched scope is not worth a storage entry: visiting a conversation without ever
+ // opening a dock would otherwise leave one behind for every conversation visited.
+ if (scopeIsEmpty(layout)) {
+ 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]: layout };
+ }
+ 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(LAYOUT_KEY, {
+ scopes: Object.fromEntries(
+ Object.entries(scopes).map(([key, s]) => [
+ key,
+ {
+ right: { ...s.right, tabs: s.right.tabs.map(tabKey) },
+ bottom: { ...s.bottom, tabs: s.bottom.tabs.map(tabKey) },
+ focus: s.focus,
+ },
+ ]),
+ ),
+ bottomRatio: ratio,
+ });
+}
+
+const listeners = new Set<() => void>();
+let version = 0;
+let instant = 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 dockVersion(): number {
+ return version;
+}
+
+/**
+ * Counter of changes that must NOT animate: scope switches (a context swap, not a
+ * collapse gesture) and cross-dock moves (the tab jumps to the other edge — animating
+ * the source's collapse and the target's expansion would read as two motions for one
+ * action). The renderer compares it across updates: bumped together with the change ⇒
+ * apply the new layout instantly; otherwise play the expand/collapse transition.
+ */
+export function instantVersion(): number {
+ return instant;
+}
+
+export function subscribeDock(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+// -------------------------------------------------------------------------------- scope
+
+/**
+ * Points the dock at a conversation (or a placeholder off one). Everything on screen
+ * changes with it; the shells behind terminal tabs are untouched, so switching away and
+ * back costs nothing. A dock arranged before a conversation was chosen (the `~none`
+ * placeholder — /chat resolves to a Session a moment after it loads) is handed to the
+ * conversation that is chosen, never clobbering one that has an arrangement of its own.
+ */
+export function setDockScope(next: string | null): void {
+ switchScope(next ?? NO_SCOPE, scope === NO_SCOPE);
+}
+
+/**
+ * The draft this scope was holding has become a real Session: its arrangement moves to
+ * the new id. Called at the points that turn a draft into a Session (its send paths, and
+ * a self-heal renaming a session id), not on any navigation away from the draft.
+ */
+export function adoptDockScope(sessionId: string): void {
+ switchScope(sessionId, true);
+}
+
+function switchScope(target: string, mayHandOver: boolean): void {
+ if (target === scope) return;
+ instant += 1;
+ 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 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(LAYOUT_KEY, {
+ scopes: Object.fromEntries(
+ Object.entries(scopes).map(([key, s]) => [
+ key,
+ {
+ right: { ...s.right, tabs: s.right.tabs.map(tabKey) },
+ bottom: { ...s.bottom, tabs: s.bottom.tabs.map(tabKey) },
+ focus: s.focus,
+ },
+ ]),
+ ),
+ bottomRatio: ratio,
+ });
+ }
+ scope = target;
+ layout = scopes[scope] ?? emptyScope();
+ notify();
+}
+
+/** The scope on screen (tests and diagnostics; components never need it). */
+export function currentDockScope(): string {
+ return scope;
+}
+
+// ------------------------------------------------------------------------------- narrow
+
+/**
+ * Below 1024px (the breakpoint the pre-dock panels used) the docks merge into one bottom
+ * surface. The store owns the media query so every narrow-aware decision (merged active,
+ * toggle semantics, the view models) lives in one place; components just render dockViews().
+ */
+let narrow = false;
+if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
+ const query = window.matchMedia("(max-width: 1023.98px)");
+ narrow = query.matches;
+ query.addEventListener("change", (event) => {
+ narrow = event.matches;
+ notify();
+ });
+}
+
+export function isNarrow(): boolean {
+ return narrow;
+}
+
+// ------------------------------------------------------------------------------ getters
+
+function area(position: DockPosition): DockAreaState {
+ return layout[position];
+}
+
+function findTab(key: string): { position: DockPosition; index: number } | null {
+ for (const position of ["right", "bottom"] as const) {
+ const index = layout[position].tabs.findIndex((tab) => tabKey(tab) === key);
+ if (index !== -1) return { position, index };
+ }
+ return null;
+}
+
+/** The dock a tab lives in (open or not), or null when no dock holds it. */
+export function tabHome(key: string): DockPosition | null {
+ return findTab(key)?.position ?? null;
+}
+
+/** Whether a dock occupies its edge. An open dock with no tabs shows the picker. */
+export function isDockVisible(position: DockPosition): boolean {
+ return area(position).open;
+}
+
+export function dockTabs(position: DockPosition): DockTab[] {
+ return area(position).tabs;
+}
+
+export function dockActiveKey(position: DockPosition): string | null {
+ return area(position).active;
+}
+
+/**
+ * The merged view's active tab: the focused dock's active when that dock is on screen,
+ * else the other visible dock's. What "the shown tab" means below the breakpoint.
+ */
+function mergedActiveKey(): string | null {
+ const first = layout.focus;
+ const second: DockPosition = first === "right" ? "bottom" : "right";
+ if (isDockVisible(first) && area(first).active !== null) return area(first).active;
+ if (isDockVisible(second)) return area(second).active;
+ return null;
+}
+
+/** One renderable dock: where it sits, what its strip lists, which tab shows. */
+export interface DockView {
+ position: DockPosition;
+ /** True for the narrow merged view (its strip spans both docks; its × hides both). */
+ merged: boolean;
+ tabs: DockTab[];
+ activeKey: string | null;
+}
+
+/**
+ * The docks to render right now. Wide: one view per open dock. Narrow: a single merged
+ * bottom view listing every open dock's tabs (bottom's first — it is the surface the
+ * merged view inherits). An open dock with no tabs renders its picker.
+ */
+export function dockViews(): DockView[] {
+ if (!narrow) {
+ return (["right", "bottom"] as const).filter(isDockVisible).map((position) => ({
+ position,
+ merged: false,
+ tabs: area(position).tabs,
+ activeKey: area(position).active,
+ }));
+ }
+ if (!isDockVisible("right") && !isDockVisible("bottom")) return [];
+ const tabs = [
+ ...(isDockVisible("bottom") ? layout.bottom.tabs : []),
+ ...(isDockVisible("right") ? layout.right.tabs : []),
+ ];
+ return [{ position: "bottom", merged: true, tabs, activeKey: mergedActiveKey() }];
+}
+
+/** Whether a tab is the one actually on screen (narrow-aware — what a toggle closes). */
+export function isTabShown(key: string): boolean {
+ const home = tabHome(key);
+ if (home === null || !isDockVisible(home)) return false;
+ return narrow ? mergedActiveKey() === key : area(home).active === key;
+}
+
+/** Whether a tab sits in a visible dock at all (shown or behind another tab). */
+export function isTabOnScreen(key: string): boolean {
+ const home = tabHome(key);
+ return home !== null && isDockVisible(home);
+}
+
+// ------------------------------------------------------------------------------ actions
+
+function activate(position: DockPosition, key: string): void {
+ const state = area(position);
+ state.active = key;
+ state.open = true;
+ layout.focus = position;
+}
+
+/** Brings an existing tab on screen: opens its dock, makes it active, focuses its dock. */
+export function activateTab(key: string): void {
+ const found = findTab(key);
+ if (!found) return;
+ activate(found.position, key);
+ persist();
+ notify();
+}
+
+function insertTab(tab: DockTab, position: DockPosition): void {
+ const key = tabKey(tab);
+ const existing = findTab(key);
+ if (existing && existing.position !== position) {
+ layout[existing.position].tabs = layout[existing.position].tabs.filter(
+ (t) => tabKey(t) !== key,
+ );
+ if (layout[existing.position].active === key) {
+ const rest = layout[existing.position].tabs;
+ layout[existing.position].active = rest.length > 0 ? tabKey(rest[rest.length - 1]!) : null;
+ }
+ }
+ if (!existing || existing.position !== position) {
+ layout[position].tabs = [...layout[position].tabs, tab];
+ }
+ activate(position, key);
+}
+
+/**
+ * Removes a tab wherever it lives; the dock falls back to its last remaining tab, and
+ * removing the LAST tab puts the dock away — from the user's seat the × closed the
+ * content, so no empty surface (nor a surprise picker) should linger.
+ */
+export function removeTab(key: string): void {
+ const found = findTab(key);
+ if (!found) return;
+ const state = area(found.position);
+ state.tabs = state.tabs.filter((tab) => tabKey(tab) !== key);
+ if (state.active === key)
+ state.active = state.tabs.length > 0 ? tabKey(state.tabs[state.tabs.length - 1]!) : null;
+ if (state.tabs.length === 0) state.open = false;
+ persist();
+ notify();
+}
+
+/** Moves one tab to the other dock (drag / the dock pickers), activating it there. */
+export function moveTab(key: string, to: DockPosition): void {
+ const found = findTab(key);
+ if (!found) return;
+ instant += 1;
+ const tab = layout[found.position].tabs[found.index]!;
+ insertTab(tab, to);
+ if (layout[found.position].tabs.length === 0) layout[found.position].open = false;
+ persist();
+ notify();
+}
+
+/** Moves a whole dock's tabs onto the other edge, after any tabs already there. */
+export function moveDock(from: DockPosition, to: DockPosition): void {
+ if (from === to) return;
+ const source = area(from);
+ if (source.tabs.length === 0) return;
+ instant += 1;
+ const shown = source.active;
+ const target = area(to);
+ target.tabs = [...target.tabs, ...source.tabs];
+ source.tabs = [];
+ source.active = null;
+ source.open = false;
+ if (shown !== null) activate(to, shown);
+ else layout.focus = to;
+ target.open = true;
+ persist();
+ notify();
+}
+
+/** Reorders one dock's strip; `keys` is the full new order of that dock's tabs. */
+export function reorderDock(position: DockPosition, keys: readonly string[]): void {
+ const state = area(position);
+ const byKey = new Map(state.tabs.map((tab) => [tabKey(tab), tab]));
+ const next = keys.map((key) => byKey.get(key)).filter((tab): tab is DockTab => tab !== undefined);
+ if (next.length !== state.tabs.length) return; // a stale drag; keep the strip consistent
+ if (next.every((tab, index) => tab === state.tabs[index])) return;
+ state.tabs = next;
+ persist();
+ notify();
+}
+
+/**
+ * The toolbar's two pull-open buttons: an open dock goes away (its tabs stay for the next
+ * open); a closed one comes on screen — showing its tabs, or the picker when it has none.
+ */
+export function toggleDock(position: DockPosition): void {
+ const state = area(position);
+ state.open = !state.open;
+ if (state.open) layout.focus = position;
+ persist();
+ notify();
+}
+
+/** The merged view's ×: both docks away (wide views pass their own position instead). */
+export function hideView(view: DockView): void {
+ if (view.merged) {
+ layout.right.open = false;
+ layout.bottom.open = false;
+ } else {
+ area(view.position).open = false;
+ }
+ persist();
+ notify();
+}
+
+// ------------------------------------------------------------------------------- panels
+
+/** The dock a panel's tab lives in (open or not), or null when the panel is closed. */
+export function panelDock(kind: PanelKind): DockPosition | null {
+ return tabHome(kind);
+}
+
+/**
+ * Puts a panel on screen: adds its tab (to `position`, or where it already lives, or the
+ * right dock — the default edge for panels opened from the conversation) and activates
+ * it. Idempotent when already shown.
+ */
+export function openPanel(kind: PanelKind, position?: DockPosition): void {
+ const target = position ?? panelDock(kind) ?? "right";
+ insertTab({ kind: "panel", panel: kind }, target);
+ persist();
+ notify();
+}
+
+export function closePanel(kind: PanelKind): void {
+ removeTab(kind);
+}
+
+// ---------------------------------------------------------------------------- terminals
+
+function terminalKey(id: string): string {
+ return `terminal:${id}`;
+}
+
+/** The dock a terminal's tab lives in within THIS scope, or null when it has no tab here. */
+export function terminalTabDock(id: string): DockPosition | null {
+ return tabHome(terminalKey(id));
+}
+
+/** This scope's terminal tabs, in strip order (bottom dock first). */
+export function terminalTabIds(): string[] {
+ return [...layout.bottom.tabs, ...layout.right.tabs]
+ .filter((tab): tab is Extract<DockTab, { kind: "terminal" }> => tab.kind === "terminal")
+ .map((tab) => tab.terminalId);
+}
+
+/**
+ * Of `ids`, the ones no conversation holds — created through the API or the CLI, or whose
+ * tab was closed. A dock picker's terminal row 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>();
+ for (const s of [layout, ...Object.values(scopes)]) {
+ for (const tab of [...s.right.tabs, ...s.bottom.tabs]) {
+ if (tab.kind === "terminal") owned.add(tab.terminalId);
+ }
+ }
+ return ids.filter((id) => !owned.has(id));
+}
+
+/** New terminals land at the bottom dock unless a dock asked for them explicitly. */
+export function addTerminalTab(id: string, position?: DockPosition): void {
+ insertTab({ kind: "terminal", terminalId: id }, position ?? terminalTabDock(id) ?? "bottom");
+ persist();
+ notify();
+}
+
+/**
+ * Brings a terminal on screen in this conversation: its tab activates where it lives, or
+ * a new tab joins the bottom dock.
+ */
+export function showTerminal(id: string): void {
+ addTerminalTab(id);
+}
+
+/**
+ * Puts a terminal tab back into a NAMED conversation's dock — the detach round trip: the
+ * tab left scope X when its shell moved to a window, and closing that window must return
+ * it to X even when another conversation is on screen by then. No-op when any scope
+ * already holds the shell (the user re-tabbed it meanwhile).
+ */
+export function restoreTerminalTab(scopeId: string, id: string, position: DockPosition): void {
+ if (unownedTerminals([id]).length === 0) return;
+ if (scopeId === scope) {
+ addTerminalTab(id, position);
+ return;
+ }
+ const target = scopes[scopeId] ?? emptyScope();
+ const state = target[position];
+ state.tabs = [...state.tabs, { kind: "terminal", terminalId: id }];
+ state.active = terminalKey(id);
+ state.open = true;
+ const { [scopeId]: _previous, ...rest } = scopes;
+ scopes = { ...rest, [scopeId]: target };
+ persist();
+ notify();
+}
+
+/**
+ * Drops tabs of 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 pruneTerminalTabs(liveIds: ReadonlySet<string>): void {
+ let changed = false;
+ const pruneArea = (state: DockAreaState): boolean => {
+ const kept = state.tabs.filter((tab) => tab.kind !== "terminal" || liveIds.has(tab.terminalId));
+ if (kept.length === state.tabs.length) return false;
+ state.tabs = kept;
+ if (state.active !== null && !kept.some((tab) => tabKey(tab) === state.active))
+ state.active = kept.length > 0 ? tabKey(kept[kept.length - 1]!) : null;
+ if (kept.length === 0) state.open = false;
+ return true;
+ };
+ for (const s of Object.values(scopes)) {
+ if (s === layout) continue; // the live scope is pruned below
+ if (pruneArea(s.right)) changed = true;
+ if (pruneArea(s.bottom)) changed = true;
+ }
+ if (pruneArea(layout.right)) changed = true;
+ if (pruneArea(layout.bottom)) changed = true;
+ if (!changed) return;
+ persist();
+ notify();
+}
+
+/**
+ * Ctrl+`'s toggle, on the store's synchronous half: hides the docks that hold this
+ * conversation's terminal tabs when one is shown; restores/activates the newest terminal
+ * tab when there are tabs but none on screen. Returns false when this scope has no
+ * terminal tab at all — the caller (dock-terminal.ts) then adopts or creates a shell,
+ * which is async.
+ */
+export function toggleTerminalDocks(): boolean {
+ const ids = terminalTabIds();
+ if (ids.length === 0) return false;
+ const holders = (["right", "bottom"] as const).filter((position) =>
+ area(position).tabs.some((tab) => tab.kind === "terminal"),
+ );
+ const anyShown = holders.some(
+ (position) =>
+ isDockVisible(position) &&
+ (narrow
+ ? mergedActiveKey()?.startsWith("terminal:") === true
+ : area(position).active?.startsWith("terminal:") === true),
+ );
+ if (anyShown) {
+ for (const position of holders) area(position).open = false;
+ persist();
+ notify();
+ return true;
+ }
+ showTerminal(ids[ids.length - 1]!);
+ return true;
+}
+
+// -------------------------------------------------------------------------------- sizes
+
+/** The bottom dock's height, as a ratio of the chat page column (a global preference). */
+export function bottomRatio(): number {
+ return ratio;
+}
+
+export function setBottomRatio(next: number): void {
+ const clamped = clampRatio(next);
+ if (clamped === ratio) return;
+ ratio = clamped;
+ persist();
+ notify();
+}
+
+export function resetBottomRatio(): void {
+ ratio = DEFAULT_DOCK_HEIGHT_RATIO;
+ persist();
+ notify();
+}
diff --git a/packages/web/src/features/dock/dock-terminal.ts b/packages/web/src/features/dock/dock-terminal.ts
new file mode 100644
index 00000000..e1b51034
--- /dev/null
+++ b/packages/web/src/features/dock/dock-terminal.ts
@@ -0,0 +1,158 @@
+/**
+ * The dock's terminal-side helpers: creating/adopting shells for terminal tabs, and the
+ * global Ctrl+` hotkey. Split from dock-state.ts so the store stays pure (unit-testable
+ * without fetch); this module owns every server round-trip a terminal tab needs.
+ */
+import { S } from "../../lib/strings";
+import { toastError } from "../../components/ui/toast";
+import {
+ HttpStatusError,
+ fetchJson,
+ probeJson,
+ type TerminalInfo,
+} from "../terminal/terminal-view";
+import { liveTerminals, noteTerminalCreated, refreshTerminals } from "../terminal/terminal-list";
+import {
+ addTerminalTab,
+ currentDockScope,
+ removeTab,
+ restoreTerminalTab,
+ showTerminal,
+ toggleTerminalDocks,
+ unownedTerminals,
+ type DockPosition,
+} from "./dock-state";
+
+/** Where a new shell starts when no Workspace is known: the user's home directory. */
+const HOME_CWD = "~";
+
+/**
+ * The Workspace a new shell should start in — the conversation's own directory, which is
+ * where its files are and what the agent has been working in. Published by the surface
+ * that knows it (the chat page for a Session, the draft page for the Workspace picked
+ * there) rather than read from a store, because the Ctrl+` hotkey creates shells from a
+ * module-scope listener with no React context to consult. Null = none known; the shell
+ * falls back to home.
+ */
+let workspaceCwd: string | null = null;
+
+/** Points new shells at this absolute Workspace path; null restores the home default. */
+export function setDockCwd(path: string | null): void {
+ workspaceCwd = path !== null && path.trim() !== "" ? path : null;
+}
+
+/** A rejected working directory (gone, replaced by a file, relative) — see resolveCwd server-side. */
+function isBadCwd(err: unknown): boolean {
+ return err instanceof HttpStatusError && err.status === 400 && err.message.includes("cwd_not_");
+}
+
+/**
+ * Creates a fresh shell and tabs it into `position` (the bottom dock by default). The
+ * shell starts in the current Workspace; a Workspace the server rejects (deleted since,
+ * or a path this server cannot see) falls back to home rather than leaving the user with
+ * no terminal at all.
+ * Failures surface as a toast — with no tab created there is no surface of its own to
+ * carry the error, and a swallowed create looks like nothing happened, which is exactly
+ * how a server-side spawn failure used to present.
+ */
+export async function createShellInDock(position?: DockPosition): Promise<void> {
+ const create = (cwd: string): Promise<TerminalInfo> =>
+ fetchJson<TerminalInfo>("/api/terminals", { method: "POST", body: JSON.stringify({ cwd }) });
+ try {
+ let created: TerminalInfo;
+ try {
+ created = await create(workspaceCwd ?? HOME_CWD);
+ } catch (err) {
+ if (workspaceCwd === null || !isBadCwd(err)) throw err;
+ console.warn(`[terminal] Workspace unusable as cwd, opening in ${HOME_CWD}:`, err);
+ created = await create(HOME_CWD);
+ }
+ noteTerminalCreated(created);
+ addTerminalTab(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:", detail);
+ toastError(`${S.terminal.createFailed}: ${detail}`);
+ } finally {
+ void refreshTerminals();
+ }
+}
+
+/**
+ * Puts a terminal on screen in `position` (or the bottom dock): the newest live shell no
+ * conversation holds is adopted — one started through the API or the CLI, or whose tab
+ * was closed — rather than answered with a second shell running beside it; only when
+ * every live shell is already tabbed somewhere (or none exists) is a new one created.
+ */
+export async function openTerminalInDock(position?: DockPosition): Promise<void> {
+ const listed = await fetchJson<{ terminals: TerminalInfo[] }>("/api/terminals").catch(() => null);
+ const live = (listed?.terminals ?? liveTerminals()).filter((t) => t.alive);
+ const adoptable = unownedTerminals(live.map((t) => t.id)).at(-1);
+ if (adoptable !== undefined) {
+ addTerminalTab(adoptable, position);
+ void refreshTerminals();
+ return;
+ }
+ await createShellInDock(position);
+}
+
+/**
+ * Detach a terminal to its own /terminal window, and RETURN it when that window closes:
+ * the tab leaves the strip while the shell lives in the window, and closing the window
+ * puts the tab back into the conversation and dock it left — even if the user is looking
+ * at another conversation by then. There is no cross-window close event, so a slow poll
+ * on the handle's `closed` flag watches for it; the restore is skipped when the shell
+ * ended inside the window or the user already pulled it back in through a "+" menu.
+ * (The handle is why the window is NOT opened with "noopener" — window.open would then
+ * return null; the target is this same app's own page.)
+ */
+export function detachTerminal(id: string, position: DockPosition): void {
+ const fromScope = currentDockScope();
+ const popup = window.open(`/terminal?id=${encodeURIComponent(id)}`, "_blank");
+ removeTab(`terminal:${id}`);
+ if (!popup) return; // blocked popup: the shell stays reachable from the "+" menus
+ const timer = window.setInterval(() => {
+ if (!popup.closed) return;
+ window.clearInterval(timer);
+ void (async () => {
+ const info = await probeJson<TerminalInfo>(`/api/terminals/${encodeURIComponent(id)}`).catch(
+ () => null,
+ );
+ if (info?.alive !== true) return; // the shell ended in the window: nothing to restore
+ restoreTerminalTab(fromScope, id, position);
+ void refreshTerminals();
+ })();
+ }, 600);
+}
+
+/**
+ * Ctrl+`: hide the shown terminals, or bring them back — and with no terminal tab in
+ * this conversation, adopt or create a shell (the async tail the store's synchronous
+ * toggle hands off).
+ */
+export function toggleTerminal(): void {
+ if (!toggleTerminalDocks()) void openTerminalInDock();
+}
+
+/** Re-exported for callers that already know which shell they want on screen. */
+export { showTerminal };
+
+// 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 docks (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();
+ toggleTerminal();
+ });
+}
diff --git a/packages/web/src/features/dock/panel-meta.tsx b/packages/web/src/features/dock/panel-meta.tsx
new file mode 100644
index 00000000..438a6464
--- /dev/null
+++ b/packages/web/src/features/dock/panel-meta.tsx
@@ -0,0 +1,65 @@
+/**
+ * The panel kinds' display identity — label and glyph — shared by every surface that names
+ * them: the toolbar's triggers and menu rows, the docks' tab strips, and the docks' add
+ * menus. One table, so a panel never has two names or two marks.
+ */
+import type { ReactNode } from "react";
+import { S } from "../../lib/strings";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { FOLDER_ICON } from "../../components/ui/group-list";
+import { NAV_ICONS } from "../../components/ui/icons";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import type { PanelKind } from "./dock-state";
+
+/** Open book: the Memory panel's mark (same glyph as the memory-changes card header). */
+const MEMORY_ICON =
+ "M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";
+
+/** The subagents spawn-tree glyph is multi-element (circles + edges), so it is a component. */
+export function AgentsGlyph({ size = ICON_SIZE.iconButton }: { 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
+ >
+ <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>
+ );
+}
+
+/** The panel's short display name (read at call time — `S` is a live locale binding). */
+export function panelLabel(kind: PanelKind): string {
+ switch (kind) {
+ case "agents":
+ return S.chat.openAgents;
+ case "workspace":
+ return S.chat.workspacePanel;
+ case "memory":
+ return S.chat.memoryViewTitle;
+ case "trace":
+ return S.nav.traces;
+ }
+}
+
+export function panelGlyph(kind: PanelKind, size: number = ICON_SIZE.iconButton): ReactNode {
+ switch (kind) {
+ case "agents":
+ return <AgentsGlyph size={size} />;
+ case "workspace":
+ return <GlyphIcon d={FOLDER_ICON} size={size} />;
+ case "memory":
+ return <GlyphIcon d={MEMORY_ICON} size={size} />;
+ case "trace":
+ return <GlyphIcon d={NAV_ICONS.traces} size={size} />;
+ }
+}
diff --git a/packages/web/src/features/dock/use-dock-mount.ts b/packages/web/src/features/dock/use-dock-mount.ts
new file mode 100644
index 00000000..75b79e77
--- /dev/null
+++ b/packages/web/src/features/dock/use-dock-mount.ts
@@ -0,0 +1,71 @@
+/**
+ * Mount state of one dock position, giving open/close its animation without giving one to
+ * changes that must be instant.
+ *
+ * The store's dockViews() only lists OPEN docks, but a collapse transition needs the node
+ * on both ends of it — so this hook keeps the last view mounted (open=false, sliding to
+ * zero) for the transition's duration before unmounting for real. Changes the store marks
+ * instant (scope switches, cross-dock moves — see instantVersion) skip both directions:
+ * a closing dock unmounts immediately, an opening one mounts at full size.
+ *
+ * The animate/linger decision is frozen AT RENDER TIME of the open/close flip (a ref
+ * adjusted during render — deterministic for a given store state, so a re-render replays
+ * it identically): an effect would decide only after the flip already painted, which for
+ * a close means the node is gone before the transition could start.
+ */
+import { useEffect, useRef, useState } from "react";
+import type { DockView } from "./dock-state";
+import { instantVersion } from "./dock-state";
+
+/**
+ * The one duration of the dock choreography: the expand and collapse transitions and the
+ * exit linger all use it. The `duration-200` Tailwind classes in dock-panel.tsx must
+ * match it; CSS cannot read a JS constant.
+ */
+export const DOCK_TRANSITION_MS = 200;
+
+export interface DockMount {
+ /** The view to render, kept through the exit transition; null = nothing mounted. */
+ view: DockView | null;
+ /** False only while the mounted view is collapsing on its way out. */
+ open: boolean;
+ /** Whether an opening dock plays the expand transition (false for instant changes). */
+ animateEntrance: boolean;
+}
+
+export function useDockMount(view: DockView | null): DockMount {
+ const open = view !== null;
+ const instant = instantVersion();
+ // The most recent open view — what a collapse keeps on screen while it slides out.
+ const lastView = useRef<DockView | null>(null);
+ if (open) lastView.current = view;
+ /** The current open/close episode and its frozen animate decision. */
+ const episode = useRef({ open, instant, animate: true });
+ /** True while a closed dock lingers for its collapse; a timer ends it. */
+ const lingering = useRef(false);
+ const [, bumpTick] = useState(0);
+
+ if (open !== episode.current.open) {
+ const animate = instant === episode.current.instant;
+ episode.current = { open, instant, animate };
+ lingering.current = !open && animate && lastView.current !== null;
+ } else if (instant !== episode.current.instant) {
+ // An instant bump without an open flip here (e.g. the other dock moved): track it so
+ // it cannot retroactively mark a LATER flip instant.
+ episode.current.instant = instant;
+ }
+
+ useEffect(() => {
+ if (open || !lingering.current) return;
+ const timer = window.setTimeout(() => {
+ lingering.current = false;
+ bumpTick((t) => t + 1); // unmount the lingering node now that the collapse ended
+ }, DOCK_TRANSITION_MS);
+ return () => window.clearTimeout(timer);
+ }, [open]);
+
+ if (open) return { view, open: true, animateEntrance: episode.current.animate };
+ if (lingering.current && lastView.current !== null)
+ return { view: lastView.current, open: false, animateEntrance: true };
+ return { view: null, open: false, animateEntrance: true };
+}
diff --git a/packages/web/src/features/dock/use-pointer-drag.ts b/packages/web/src/features/dock/use-pointer-drag.ts
new file mode 100644
index 00000000..6c18c4f4
--- /dev/null
+++ b/packages/web/src/features/dock/use-pointer-drag.ts
@@ -0,0 +1,56 @@
+/**
+ * Shared pointer-drag state machine for the dock'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.
+ */
+import { useMemo, useRef } from "react";
+
+export 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?.();
+ },
+ }),
+ [],
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-dock-layout.tsx b/packages/web/src/features/terminal/terminal-dock-layout.tsx
deleted file mode 100644
index 03088b45..00000000
--- a/packages/web/src/features/terminal/terminal-dock-layout.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 3ce65f3a..00000000
--- a/packages/web/src/features/terminal/terminal-dock-slot.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * 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
deleted file mode 100644
index b962f710..00000000
--- a/packages/web/src/features/terminal/terminal-dock-state.ts
+++ /dev/null
@@ -1,602 +0,0 @@
-/**
- * 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, …) scope to a placeholder
- * that holds no arrangement, so the dock is not on screen there — a terminal belongs to a
- * conversation, not beside a settings page — and returning to the conversation restores it.
- * A dock opened while on that placeholder is handed to the first conversation chosen
- * afterwards (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) holds the side. Not persisted: it mirrors panel
- * state that is itself per-visit.
- *
- * Taking the side CLOSES a side pane rather than parking it behind the panel. The pane
- * stays in the arrangement, so reopening the dock brings it back on the edge it was on —
- * but closing the panel leaves the slot empty, because from where the user sits, opening
- * the panel is what closed the terminal, and closing the panel should not conjure it back.
- */
-let sidePanelHoldsTheSide = false;
-
-/** Whether a chat side panel currently holds the side. */
-export function chatSidePanelOpen(): boolean {
- return sidePanelHoldsTheSide;
-}
-
-export function setChatSidePanelOpen(open: boolean): void {
- if (open) {
- cancelHandover(); // the panel is back: nothing left to hand over
- // Only a side pane competes for this space; a top/bottom one costs height and stays.
- if (visible && panes.some((p) => !isHorizontal(p))) {
- visible = false;
- persist();
- }
- }
- if (sidePanelHoldsTheSide === open) return;
- sidePanelHoldsTheSide = 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 (!sidePanelHoldsTheSide) return;
- sidePanelHoldsTheSide = 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 a side pane still waiting out an
- * outgoing panel's retraction (see handingOver). Nothing else is ever filtered — a panel
- * taking the side closes the pane outright rather than parking it.
- */
-export function visiblePanes(): DockPosition[] {
- const next = 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
deleted file mode 100644
index d5e38fe6..00000000
--- a/packages/web/src/features/terminal/terminal-dock.tsx
+++ /dev/null
@@ -1,796 +0,0 @@
-/**
- * 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";
-import { CloseIcon } from "../../components/ui/icons";
-
-/** 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}`}
- >
- <CloseIcon size={10} />
- </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-list.ts b/packages/web/src/features/terminal/terminal-list.ts
index ae46a10a..862bcdce 100644
--- a/packages/web/src/features/terminal/terminal-list.ts
+++ b/packages/web/src/features/terminal/terminal-list.ts
@@ -1,8 +1,8 @@
/**
* 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.
+ * here, tabbed into a dock or not: the docks' strips show the tabbed ones (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:
@@ -12,15 +12,29 @@
* 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";
+import { pruneTerminalTabs } from "../dock/dock-state";
-const POLL_MS = 30_000;
+/**
+ * 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();
+}
-const ORDER_KEY = "penguin.terminal.tabOrder";
+const POLL_MS = 30_000;
/** Raw live list as the server reports it (creation order). */
let raw: TerminalInfo[] = [];
-/** Stable sorted snapshot (same reference until contents change) for useSyncExternalStore. */
+/** Stable snapshot (same reference until contents change) for useSyncExternalStore. */
let terminals: TerminalInfo[] = [];
let fingerprint = "";
let inflight: Promise<void> | null = null;
@@ -29,27 +43,6 @@ 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
@@ -70,35 +63,13 @@ function isPendingKill(id: string): boolean {
function commit(next: TerminalInfo[]): void {
raw = next;
- const sorted = applyOrder(next);
- const nextFingerprint = JSON.stringify(sorted);
+ const nextFingerprint = JSON.stringify(next);
if (nextFingerprint === fingerprint) return;
- terminals = sorted;
+ terminals = next;
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;
@@ -137,7 +108,7 @@ export function refreshTerminals(): Promise<void> {
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)));
+ pruneTerminalTabs(new Set(live.map((t) => t.id)));
commit(live);
} catch {
// Network hiccup: the next poll/focus refresh will catch up.
diff --git a/packages/web/src/features/terminal/terminal-view-pool.tsx b/packages/web/src/features/terminal/terminal-view-pool.tsx
index d5b43cbe..c06ccccd 100644
--- a/packages/web/src/features/terminal/terminal-view-pool.tsx
+++ b/packages/web/src/features/terminal/terminal-view-pool.tsx
@@ -1,27 +1,20 @@
/**
- * The dock's live terminal views, pooled OUTSIDE the pane components.
+ * The docks' live terminal views, pooled OUTSIDE the dock 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
+ * Dock tab bodies adopt the container with a plain appendChild. Because both the
+ * React element (keyed by terminal id) and the DOM subtree survive any dock change,
+ * moving a terminal tab between docks — or moving a whole dock to the other edge — never
+ * remounts xterm and never drops the WebSocket; the dock 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).
+ * The pool also owns the per-terminal view state (status/info) consumers display.
*/
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 { dockActiveKey, isDockVisible, subscribeDock } from "../dock/dock-state";
import { noteTerminalTitle, refreshTerminals } from "./terminal-list";
export interface TerminalViewState {
@@ -75,21 +68,21 @@ function attachById(id: string) {
}
/**
- * 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.
+ * The set of terminal ids that should have a live view right now: each visible dock's
+ * active tab, when it is a terminal. An inactive terminal tab has no view — switching to
+ * it reattaches (server-side restore) — and hiding a dock disposes its shown view the
+ * same way. Both docks are always consulted: below the desktop breakpoint the merged
+ * surface shows one dock's active tab, and keeping the other's view alive through the
+ * merge costs one idle attach while saving a reconnect flash on every width change.
*/
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);
+ for (const position of ["right", "bottom"] as const) {
+ if (!isDockVisible(position)) continue;
+ const key = dockActiveKey(position);
+ if (key === null || !key.startsWith("terminal:")) continue;
+ const id = key.slice("terminal:".length);
+ if (!ids.includes(id)) ids.push(id);
}
return ids;
}
@@ -105,9 +98,9 @@ function shownIdsSnapshot(): string[] {
}
export function TerminalDockRuntime() {
- const ids = useSyncExternalStore(subscribeTerminalDock, shownIdsSnapshot);
+ const ids = useSyncExternalStore(subscribeDock, shownIdsSnapshot);
- // (The Ctrl+` hotkey is a module-scope listener in terminal-dock-state.ts — binding it
+ // (The Ctrl+` hotkey is a module-scope listener in dock-terminal.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
diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsx
new file mode 100644
index 00000000..2dacd101
--- /dev/null
+++ b/packages/web/src/features/traces/trace-panel.tsx
@@ -0,0 +1,161 @@
+/**
+ * Trace panel — the current conversation's Trace files as a dock tab, reusing the traces
+ * page's file view (performance timeline + event list) scoped to one Session. The file
+ * pills page newest-first; the export link downloads the selected file raw. Cross-Session
+ * browsing stays on the /traces page (deep-linked from the Agents page and the details
+ * popover) — this panel is the "what did this conversation do" view.
+ *
+ * Loading is gated on `active` (the dock keeps inactive tabs mounted): the listing is
+ * fetched on the first show and re-fetched on every re-show, so a Task that finished while
+ * the tab was hidden appears on return without a manual refresh.
+ */
+import { useEffect, useRef, useState } from "react";
+import type { SessionInfo } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatBytes } from "../../lib/format";
+import { DownloadIcon } from "../../components/ui/icons";
+import { EmptyState } from "../../components/ui/empty-state";
+import { Skeleton } from "../../components/ui/skeleton";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { TraceFileView } from "./trace-file-view";
+import type { TraceHighlight } from "./timeline-chart";
+
+/** File pills rendered before the "+N" overflow control expands them (a long Session can hold dozens of compaction shards). */
+const FILE_PILL_CAP = 6;
+
+interface FileRef {
+ index: number;
+ date: string;
+ sizeBytes: number;
+}
+
+export function TracePanel({ session, active }: { session: SessionInfo; active: boolean }) {
+ const [files, setFiles] = useState<FileRef[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [fileIndex, setFileIndex] = useState<number | null>(null);
+ const [showAllFiles, setShowAllFiles] = useState(false);
+ const [highlight, setHighlight] = useState<TraceHighlight | null>(null);
+
+ // Fetch on show: the first activation loads, later re-activations re-list (a Task may
+ // have written a new file while the tab was hidden). Split into a rising-edge tick and
+ // a fetch effect keyed on it — a single edge-detecting fetch effect would lose the
+ // FIRST load under StrictMode's dev-mode double-invoke (the ref flips on the first run,
+ // whose fetch the cleanup cancels; the second run then sees no edge and never refetches,
+ // leaving the skeleton up forever). The selected pill survives a re-list while its file
+ // still exists; a vanished selection falls back to the newest file.
+ const [listTick, setListTick] = useState(0);
+ const prevActive = useRef(active);
+ useEffect(() => {
+ if (active && !prevActive.current) setListTick((t) => t + 1);
+ prevActive.current = active;
+ }, [active]);
+ useEffect(() => {
+ if (!active) return;
+ let cancelled = false;
+ void api
+ .getSessionTraces(session.sessionId)
+ .then((res) => {
+ if (cancelled) return;
+ // Newest first: the pill row and the default selection both read left-to-right
+ // from the most recent context.
+ setFiles([...res.files].sort((a, b) => b.index - a.index));
+ setError(null);
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ setFiles([]);
+ setError(apiErrorText(err));
+ });
+ return () => {
+ cancelled = true;
+ };
+ // listTick re-runs the fetch on every re-show; `active` alone would only load once.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [active, listTick, session.sessionId]);
+
+ if (files === null) {
+ return (
+ <div className="space-y-3 p-4">
+ <Skeleton className="h-5 w-2/3" />
+ <Skeleton className="h-5 w-1/2" />
+ </div>
+ );
+ }
+
+ if (error !== null) {
+ return <EmptyState title={S.tracePanel.loadFailed} description={error} />;
+ }
+
+ if (files.length === 0) {
+ return <EmptyState title={S.tracePanel.empty} description={S.tracePanel.emptyHint} />;
+ }
+
+ const activeFile = files.find((f) => f.index === fileIndex) ?? files[0]!;
+ const visibleFiles = showAllFiles ? files : files.slice(0, FILE_PILL_CAP);
+
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto p-3">
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="mr-1 text-xs text-gray-400">{S.traces.filesTitle}</span>
+ {visibleFiles.map((f) => (
+ <button
+ key={f.index}
+ type="button"
+ onClick={() => setFileIndex(f.index)}
+ title={`${f.date} · ${formatBytes(f.sizeBytes)}`}
+ className={`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${
+ f.index === activeFile.index
+ ? "border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
+ : "border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
+ }`}
+ >
+ #{String(f.index).padStart(3, "0")}
+ </button>
+ ))}
+ {!showAllFiles && files.length > FILE_PILL_CAP && (
+ <button
+ type="button"
+ title={S.chat.loadMore}
+ aria-label={S.chat.loadMore}
+ onClick={() => setShowAllFiles(true)}
+ className="rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
+ >
+ +{files.length - FILE_PILL_CAP}
+ </button>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="min-w-0 flex-1 truncate font-mono text-xs text-gray-400">
+ {activeFile.date} · {formatBytes(activeFile.sizeBytes)}
+ </p>
+ {/* Raw-file download for the selected Trace file (same styling as the inactive pills). */}
+ <a
+ href={api.agentTraceDownloadUrl(
+ session.projectId,
+ session.agentId,
+ session.sessionId,
+ activeFile.index,
+ )}
+ download
+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
+ >
+ <DownloadIcon size={ICON_SIZE.rowLead} />
+ {S.traces.exportFile}
+ </a>
+ </div>
+
+ <TraceFileView
+ projectId={session.projectId}
+ agentId={session.agentId}
+ sessionId={session.sessionId}
+ index={activeFile.index}
+ highlight={highlight}
+ onHighlight={setHighlight}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.ts
index 16040707..9fca3634 100644
--- a/packages/web/src/lib/nav-group-collapse.ts
+++ b/packages/web/src/lib/nav-group-collapse.ts
@@ -17,16 +17,11 @@
* Page entries of the collapsible nav group, in rendered order. Each key names its
* route (`/<key>`), its S.nav label, and its NAV_ICONS glyph — the sidebar derives
* its nav rows from this manifest, so the covered range is pinned here (and in the
- * unit tests) rather than duplicated.
+ * unit tests) rather than duplicated. Traces is deliberately absent: the Trace panel
+ * lives in the chat toolbar's panel switcher, and the /traces browsing page stays
+ * reachable through its deep links (Agents page, session details).
*/
-export const NAV_GROUP_KEYS = [
- "agents",
- "skills",
- "models",
- "usage",
- "traces",
- "benchmark",
-] as const;
+export const NAV_GROUP_KEYS = ["agents", "skills", "models", "usage", "benchmark"] as const;
export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];
/**
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 27fea25b..043f3208 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -36,9 +36,7 @@ export const en: Strings = {
/** 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). */
@@ -46,7 +44,6 @@ export const en: Strings = {
"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",
@@ -57,6 +54,27 @@ export const en: Strings = {
exitedWithCode: (code: string): string => `exit code ${code}`,
},
+ dock: {
+ addTab: "Add panel",
+ closeTab: "Close panel",
+ hideDock: "Hide sidebar",
+ moveToRight: "Move to the right",
+ moveToBottom: "Move to the bottom",
+ resize: "Resize panel",
+ rightDock: "Right sidebar",
+ bottomDock: "Bottom panel",
+ draftEmpty: "Available once the conversation starts",
+ killConfirmTitle: "Close this terminal?",
+ killConfirmBody: (name: string): string =>
+ `This ends the shell "${name}" — it cannot be restored.`,
+ },
+
+ tracePanel: {
+ empty: "No traces yet",
+ emptyHint: "This session has not produced a Trace file yet",
+ loadFailed: "Failed to load traces",
+ },
+
settings: {
language: "Language",
languageInfo: "Interface language; can follow the browser.",
@@ -205,12 +223,12 @@ export const en: Strings = {
common: {
save: "Save",
cancel: "Cancel",
+ close: "Close",
create: "Create",
delete: "Delete",
edit: "Edit",
settings: "Settings",
confirm: "Confirm",
- close: "Close",
loading: "Loading…",
saved: "Saved",
saving: "Saving…",
@@ -1425,13 +1443,9 @@ Scenarios:
historyLoadFailed: "Failed to load history",
statsLabel: "Stats",
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",
@@ -1444,7 +1458,6 @@ Scenarios:
memoryViewTitle: "Memory",
memoryChangedMark: "Changed in this conversation",
memoryContentUnavailable: "Content unavailable (the file may have been moved or deleted)",
- openMemoryPanel: "Open memory",
memoryRowOpen: "View content",
memoryBack: "Back to the list",
memoryEmptyAll: "No memory yet — say “remember …” in a chat to have the agent save one",
@@ -1604,12 +1617,12 @@ Scenarios:
/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */
subagentPanel: {
- title: "Agents panel",
topologyLabel: "Call graph",
mainSessionNote: "The main conversation stays in the chat area",
empty: "No subagents in the current task yet",
nodeRunning: "running",
nodeDone: "done",
+ openAsSession: "Jump to this session",
},
files: {
@@ -1635,7 +1648,6 @@ Scenarios:
htmlRendered: "Rendered",
htmlSource: "Source",
backToList: "Back to list",
- resizeHandle: "Drag to resize, double-click to reset",
},
usage: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 8f6f17d6..9cf60fab 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -37,10 +37,6 @@ export const zh = {
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). */
@@ -48,7 +44,6 @@ export const zh = {
"该服务端没有终端接口:运行中的 runtime 早于该功能。热更新只替换平台与前端,终端接口属于 runtime,需更新 runtime 本身(重启无效)",
/** Codex-style handoff: opens /terminal?id=… in a new window, the dock lets go. */
detach: "在新窗口打开",
- close: "关闭",
status: {
connecting: "连接中",
ready: "已连接",
@@ -59,6 +54,35 @@ export const zh = {
exitedWithCode: (code: string): string => `退出码 ${code}`,
},
+ /** The dock surfaces (right / bottom) every side element renders in as a tab. */
+ dock: {
+ /** The dock header's "+" menu: panels and shells this dock can take a tab for. */
+ addTab: "添加面板",
+ /** A panel tab's × (its content closes; terminal tabs use terminal.killShell instead). */
+ closeTab: "关闭面板",
+ /** The dock header's ×: the dock hides, its tabs stay for the next open. */
+ hideDock: "收起侧边栏",
+ moveToRight: "移到右侧",
+ moveToBottom: "移到下方",
+ /** Boundary drag handle between a dock and the chat content (double-click resets). */
+ resize: "调整面板大小",
+ /** The toolbar's two pull-open buttons (aria-expanded carries the open state). */
+ rightDock: "右侧栏",
+ bottomDock: "下侧栏",
+ /** A session-bound panel's body on the draft page, where no Session exists yet. */
+ draftEmpty: "发送第一条消息后可用",
+ /** Terminal tab ×: ends the shell for real, so it asks first. `name` is the tab label. */
+ killConfirmTitle: "关闭此终端?",
+ killConfirmBody: (name: string): string => `将结束 Shell「${name}」的进程,无法恢复。`,
+ },
+
+ /** The Trace dock panel (the current conversation's Trace files). */
+ tracePanel: {
+ empty: "暂无轨迹",
+ emptyHint: "该会话还没有产生 Trace 文件",
+ loadFailed: "轨迹加载失败",
+ },
+
settings: {
language: "语言",
languageInfo: "界面语言,可跟随浏览器设置。",
@@ -198,12 +222,12 @@ export const zh = {
common: {
save: "保存",
cancel: "取消",
+ close: "关闭",
create: "创建",
delete: "删除",
edit: "编辑",
settings: "设置",
confirm: "确认",
- close: "关闭",
loading: "加载中…",
saved: "已保存",
saving: "保存中…",
@@ -1377,13 +1401,8 @@ Benchmark:
historyLoadFailed: "历史消息加载失败",
statsLabel: "统计信息",
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} 张图片`,
@@ -1398,7 +1417,6 @@ Benchmark:
memoryViewTitle: "记忆",
memoryChangedMark: "本次对话已更改",
memoryContentUnavailable: "无法加载内容(文件可能已被移动或删除)",
- openMemoryPanel: "打开记忆",
memoryRowOpen: "查看内容",
memoryBack: "返回列表",
memoryEmptyAll: "还没有任何记忆——在对话里说「记住……」即可让 agent 保存",
@@ -1557,12 +1575,13 @@ Benchmark:
/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */
subagentPanel: {
- title: "智能体面板",
topologyLabel: "调用关系",
mainSessionNote: "主会话请在对话区查看",
empty: "本次任务尚未派生子智能体",
nodeRunning: "运行中",
nodeDone: "已完成",
+ /** Identity-strip jump: opens the selected subagent's own Session in the chat area. */
+ openAsSession: "跳转到该会话",
},
files: {
@@ -1587,7 +1606,6 @@ Benchmark:
htmlRendered: "渲染视图",
htmlSource: "源码",
backToList: "返回列表",
- resizeHandle: "拖拽调整宽度,双击恢复默认",
},
usage: {
diff --git a/packages/web/test/dock-state.test.ts b/packages/web/test/dock-state.test.ts
new file mode 100644
index 00000000..c2145c63
--- /dev/null
+++ b/packages/web/test/dock-state.test.ts
@@ -0,0 +1,356 @@
+/**
+ * The dock store (features/dock/dock-state.ts): two docks (right/bottom) of uniform tabs
+ * — singleton panels plus per-shell terminal tabs — SCOPED per conversation like browser
+ * windows managing their own tabs: switching Sessions switches the whole arrangement, and
+ * no conversation's tabs depend on another's. An open dock with no tabs is still visible
+ * (it shows the picker); closing a tab removes it, and the last tab closing puts the dock
+ * away; a dock's own toggle hides it keeping its tabs.
+ *
+ * The module reads localStorage at import time, so the stub is installed first and the
+ * module imported dynamically.
+ */
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+let dock: typeof import("../src/features/dock/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/dock/dock-state");
+});
+
+let scopeSeq = 0;
+/** A fresh, never-used conversation scope per test — scopes are the isolation boundary. */
+beforeEach(() => {
+ scopeSeq += 1;
+ dock.setDockScope(`test-session-${scopeSeq}`);
+});
+
+describe("panel tabs", () => {
+ it("opens a panel as a right-dock tab by default and shows it", () => {
+ dock.openPanel("workspace");
+ expect(dock.panelDock("workspace")).toBe("right");
+ expect(dock.isDockVisible("right")).toBe(true);
+ expect(dock.dockActiveKey("right")).toBe("workspace");
+ expect(dock.isTabShown("workspace")).toBe(true);
+ });
+
+ it("keeps panels singletons: opening in the other dock MOVES the tab", () => {
+ dock.openPanel("memory", "right");
+ dock.openPanel("memory", "bottom");
+ expect(dock.panelDock("memory")).toBe("bottom");
+ expect(dock.dockTabs("right")).toHaveLength(0);
+ expect(dock.dockTabs("bottom")).toHaveLength(1);
+ });
+
+ it("reopens a panel where its tab already lives instead of moving it home", () => {
+ dock.openPanel("agents", "bottom");
+ dock.openPanel("workspace", "bottom");
+ dock.openPanel("agents"); // no position: the existing bottom tab activates
+ expect(dock.panelDock("agents")).toBe("bottom");
+ expect(dock.dockActiveKey("bottom")).toBe("agents");
+ });
+
+ it("closing a panel tab removes it; closing the last one puts the dock away", () => {
+ dock.openPanel("workspace", "right");
+ dock.openPanel("memory", "right");
+ dock.closePanel("memory");
+ expect(dock.panelDock("memory")).toBeNull();
+ expect(dock.dockActiveKey("right")).toBe("workspace");
+ expect(dock.isDockVisible("right")).toBe(true);
+ dock.closePanel("workspace");
+ expect(dock.isDockVisible("right")).toBe(false);
+ });
+});
+
+describe("the toolbar's dock toggles and the picker", () => {
+ it("an open dock with no tabs is visible (the picker state)", () => {
+ expect(dock.isDockVisible("right")).toBe(false);
+ dock.toggleDock("right");
+ expect(dock.isDockVisible("right")).toBe(true);
+ expect(dock.dockTabs("right")).toHaveLength(0);
+ expect(dock.dockViews()).toEqual([
+ { position: "right", merged: false, tabs: [], activeKey: null },
+ ]);
+ dock.toggleDock("right");
+ expect(dock.isDockVisible("right")).toBe(false);
+ });
+
+ it("toggling a dock closed keeps its tabs for the next open", () => {
+ dock.openPanel("workspace", "bottom");
+ dock.toggleDock("bottom");
+ expect(dock.isDockVisible("bottom")).toBe(false);
+ expect(dock.dockTabs("bottom")).toHaveLength(1);
+ dock.toggleDock("bottom");
+ expect(dock.dockActiveKey("bottom")).toBe("workspace");
+ });
+});
+
+describe("terminal tabs", () => {
+ it("adds one tab per shell, defaulting to the bottom dock", () => {
+ dock.addTerminalTab("term-a");
+ dock.addTerminalTab("term-b");
+ expect(dock.terminalTabDock("term-a")).toBe("bottom");
+ expect(dock.terminalTabIds()).toEqual(["term-a", "term-b"]);
+ expect(dock.dockActiveKey("bottom")).toBe("terminal:term-b");
+ });
+
+ it("shows an existing tab where it lives instead of duplicating it", () => {
+ dock.addTerminalTab("term-a", "right");
+ dock.addTerminalTab("term-b", "right");
+ dock.showTerminal("term-a");
+ expect(dock.terminalTabIds()).toEqual(["term-a", "term-b"]);
+ expect(dock.dockActiveKey("right")).toBe("terminal:term-a");
+ });
+
+ it("mixes freely with panel tabs in one dock", () => {
+ dock.openPanel("workspace", "bottom");
+ dock.addTerminalTab("term-a", "bottom");
+ expect(dock.dockTabs("bottom").map(dock.tabKey)).toEqual(["workspace", "terminal:term-a"]);
+ dock.activateTab("workspace");
+ expect(dock.isTabShown("workspace")).toBe(true);
+ expect(dock.isTabShown("terminal:term-a")).toBe(false);
+ });
+});
+
+describe("conversation scopes (each window manages its own tabs)", () => {
+ it("switches the whole arrangement with the Session, and restores it on return", () => {
+ const a = `scope-a-${scopeSeq}`;
+ const b = `scope-b-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.openPanel("workspace", "right");
+ dock.addTerminalTab("term-a", "bottom");
+
+ // A conversation that never arranged anything shows nothing.
+ dock.setDockScope(b);
+ expect(dock.isDockVisible("right")).toBe(false);
+ expect(dock.isDockVisible("bottom")).toBe(false);
+ expect(dock.terminalTabIds()).toEqual([]);
+
+ // B's own arrangement never leaks into A's, and A's comes back intact.
+ dock.openPanel("memory", "bottom");
+ dock.setDockScope(a);
+ expect(dock.panelDock("workspace")).toBe("right");
+ expect(dock.panelDock("memory")).toBeNull();
+ expect(dock.terminalTabIds()).toEqual(["term-a"]);
+ });
+
+ it("does not lend one Session's terminals to another's docks", () => {
+ const a = `scope-c-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.addTerminalTab("term-owned", "bottom");
+ dock.setDockScope(`scope-d-${scopeSeq}`);
+ expect(dock.terminalTabDock("term-owned")).toBeNull();
+ // …and cross-scope ownership still counts: the shell is not adoptable here.
+ expect(dock.unownedTerminals(["term-owned", "term-free"])).toEqual(["term-free"]);
+ });
+
+ it("hands a placeholder-scope arrangement to the first Session chosen", () => {
+ dock.setDockScope(null); // ~none: /chat before it resolves to a conversation
+ dock.addTerminalTab("term-staged", "bottom");
+ dock.setDockScope(`scope-resolved-${scopeSeq}`);
+ expect(dock.terminalTabDock("term-staged")).toBe("bottom");
+ // Moved, not copied: going back off-conversation shows nothing.
+ dock.setDockScope(null);
+ expect(dock.terminalTabIds()).toEqual([]);
+ });
+
+ it("adoptDockScope moves a draft's arrangement to the born Session, never clobbering", () => {
+ const draft = `new-${scopeSeq}`;
+ const born = `scope-born-${scopeSeq}`;
+ dock.setDockScope(draft);
+ dock.openPanel("workspace", "right");
+ dock.adoptDockScope(born);
+ expect(dock.currentDockScope()).toBe(born);
+ expect(dock.panelDock("workspace")).toBe("right");
+ // The next draft starts clean rather than inheriting it.
+ dock.setDockScope(draft);
+ expect(dock.panelDock("workspace")).toBeNull();
+
+ // Never clobbers a Session that already has an arrangement of its own.
+ const owner = `scope-owner-${scopeSeq}`;
+ dock.setDockScope(owner);
+ dock.openPanel("memory", "bottom");
+ dock.setDockScope(draft);
+ dock.openPanel("trace", "right");
+ dock.adoptDockScope(owner);
+ expect(dock.panelDock("memory")).toBe("bottom");
+ expect(dock.panelDock("trace")).toBeNull();
+ });
+
+ it("prunes dead shells' tabs across every scope, not just the one on screen", () => {
+ const a = `scope-e-${scopeSeq}`;
+ const b = `scope-f-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.addTerminalTab("term-dead", "bottom");
+ dock.setDockScope(b);
+ dock.addTerminalTab("term-live", "bottom");
+ dock.pruneTerminalTabs(new Set(["term-live"]));
+ expect(dock.terminalTabIds()).toEqual(["term-live"]);
+ dock.setDockScope(a);
+ expect(dock.terminalTabIds()).toEqual([]);
+ expect(dock.isDockVisible("bottom")).toBe(false); // its only tab died: the dock went away
+ });
+});
+
+describe("moving", () => {
+ it("moves a single tab to the other dock and activates it there", () => {
+ dock.openPanel("workspace", "right");
+ dock.openPanel("memory", "right");
+ dock.moveTab("workspace", "bottom");
+ expect(dock.panelDock("workspace")).toBe("bottom");
+ expect(dock.dockActiveKey("bottom")).toBe("workspace");
+ // The source dock moved on to its remaining tab.
+ expect(dock.dockActiveKey("right")).toBe("memory");
+ });
+
+ it("moving the only tab closes its source dock instead of leaving an empty surface", () => {
+ dock.openPanel("workspace", "right");
+ dock.moveTab("workspace", "bottom");
+ expect(dock.isDockVisible("right")).toBe(false);
+ expect(dock.isDockVisible("bottom")).toBe(true);
+ });
+
+ it("moves a whole dock, merging after the target's own tabs and keeping the shown tab", () => {
+ dock.openPanel("workspace", "right");
+ dock.openPanel("memory", "bottom");
+ dock.moveDock("right", "bottom");
+ expect(dock.isDockVisible("right")).toBe(false);
+ expect(dock.dockTabs("bottom").map(dock.tabKey)).toEqual(["memory", "workspace"]);
+ expect(dock.dockActiveKey("bottom")).toBe("workspace");
+ });
+
+ it("reorders a dock's strip only with a complete, matching key list", () => {
+ dock.openPanel("workspace", "right");
+ dock.openPanel("memory", "right");
+ dock.reorderDock("right", ["memory", "workspace"]);
+ expect(dock.dockTabs("right").map(dock.tabKey)).toEqual(["memory", "workspace"]);
+ // A stale drag (a key that no longer exists) changes nothing.
+ dock.reorderDock("right", ["memory", "trace"]);
+ expect(dock.dockTabs("right").map(dock.tabKey)).toEqual(["memory", "workspace"]);
+ });
+});
+
+describe("the terminal toggle (Ctrl+`)", () => {
+ it("reports no tab so the caller adopts/creates, then hides and restores", () => {
+ expect(dock.toggleTerminalDocks()).toBe(false); // nothing to toggle: async path takes over
+ dock.addTerminalTab("term-a");
+ expect(dock.toggleTerminalDocks()).toBe(true); // shown → hidden
+ expect(dock.isDockVisible("bottom")).toBe(false);
+ expect(dock.toggleTerminalDocks()).toBe(true); // hidden → shown again
+ expect(dock.isDockVisible("bottom")).toBe(true);
+ expect(dock.dockActiveKey("bottom")).toBe("terminal:term-a");
+ });
+
+ it("brings the terminal to the front when a panel covers it, instead of hiding", () => {
+ dock.addTerminalTab("term-a", "bottom");
+ dock.openPanel("workspace", "bottom"); // workspace now shown, terminal behind it
+ expect(dock.toggleTerminalDocks()).toBe(true);
+ expect(dock.dockActiveKey("bottom")).toBe("terminal:term-a");
+ });
+});
+
+describe("persistence", () => {
+ it("round-trips each scope's arrangement — tabs, active, open flags — across a reload", async () => {
+ const a = `scope-persist-a-${scopeSeq}`;
+ const b = `scope-persist-b-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.openPanel("workspace", "right");
+ dock.addTerminalTab("term-a", "bottom");
+ dock.toggleDock("bottom"); // hidden, tabs kept
+ dock.setBottomRatio(0.5);
+ dock.setDockScope(b);
+ dock.openPanel("memory", "bottom");
+
+ // Reload: a second module instance reading the same storage back from scratch.
+ vi.resetModules();
+ const reloaded = await import("../src/features/dock/dock-state");
+ reloaded.setDockScope(a);
+ expect(reloaded.panelDock("workspace")).toBe("right");
+ expect(reloaded.isDockVisible("right")).toBe(true);
+ expect(reloaded.isDockVisible("bottom")).toBe(false); // hidden stays hidden
+ expect(reloaded.terminalTabIds()).toEqual(["term-a"]);
+ expect(reloaded.bottomRatio()).toBe(0.5); // sizes are one preference, not per scope
+ reloaded.setDockScope(b);
+ expect(reloaded.dockActiveKey("bottom")).toBe("memory");
+ });
+
+ it("degrades a malformed stored entry to empty docks", async () => {
+ store.set(
+ "penguin.dock.layout",
+ '{"scopes": {"s": {"right": {"tabs": [42]}}}, "bottomRatio": "x"}',
+ );
+ vi.resetModules();
+ const reloaded = await import("../src/features/dock/dock-state");
+ reloaded.setDockScope("s");
+ expect(reloaded.dockTabs("right")).toHaveLength(0);
+ expect(reloaded.isDockVisible("right")).toBe(false);
+ expect(reloaded.bottomRatio()).toBeCloseTo(0.4);
+ });
+});
+
+describe("instant changes (no animation)", () => {
+ it("bumps instantVersion for scope switches and moves, not for toggles", () => {
+ const before = dock.instantVersion();
+ dock.openPanel("workspace", "right");
+ dock.toggleDock("bottom");
+ dock.removeTab("workspace");
+ expect(dock.instantVersion()).toBe(before); // animated changes leave it alone
+ dock.openPanel("workspace", "right");
+ dock.moveTab("workspace", "bottom");
+ expect(dock.instantVersion()).toBe(before + 1);
+ dock.openPanel("memory", "bottom");
+ dock.moveDock("bottom", "right");
+ expect(dock.instantVersion()).toBe(before + 2);
+ dock.setDockScope(`scope-instant-${scopeSeq}`);
+ expect(dock.instantVersion()).toBe(before + 3);
+ });
+});
+
+describe("the detach round trip", () => {
+ it("restores a terminal tab into the scope it left, even while another is on screen", () => {
+ const a = `scope-detach-a-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.addTerminalTab("term-win", "bottom");
+ dock.removeTab("terminal:term-win"); // the detach: tab leaves while the shell moves out
+ expect(dock.isDockVisible("bottom")).toBe(false);
+
+ dock.setDockScope(`scope-detach-b-${scopeSeq}`); // the user wandered off meanwhile
+ dock.restoreTerminalTab(a, "term-win", "bottom");
+ expect(dock.terminalTabIds()).toEqual([]); // not into the scope on screen
+ dock.setDockScope(a);
+ expect(dock.terminalTabIds()).toEqual(["term-win"]);
+ expect(dock.isDockVisible("bottom")).toBe(true);
+ expect(dock.dockActiveKey("bottom")).toBe("terminal:term-win");
+ });
+
+ it("does nothing when some conversation already holds the shell again", () => {
+ const a = `scope-detach-c-${scopeSeq}`;
+ dock.setDockScope(a);
+ dock.addTerminalTab("term-back", "bottom"); // the user re-tabbed it before the window closed
+ dock.restoreTerminalTab(`scope-detach-d-${scopeSeq}`, "term-back", "right");
+ dock.setDockScope(`scope-detach-d-${scopeSeq}`);
+ expect(dock.terminalTabIds()).toEqual([]);
+ });
+});
+
+describe("view models", () => {
+ it("renders one view per open dock", () => {
+ dock.openPanel("workspace", "right");
+ dock.addTerminalTab("term-a", "bottom");
+ const views = dock.dockViews();
+ expect(views.map((v) => v.position)).toEqual(["right", "bottom"]);
+ expect(views[0]?.merged).toBe(false);
+ expect(views[0]?.activeKey).toBe("workspace");
+ expect(views[1]?.activeKey).toBe("terminal:term-a");
+ });
+});
diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.ts
index 427c0bd4..deceda63 100644
--- a/packages/web/test/nav-group-collapse.test.ts
+++ b/packages/web/test/nav-group-collapse.test.ts
@@ -35,14 +35,9 @@ function memStorage(): NavCollapseStorage & { map: Map<string, string> } {
describe("NAV_GROUP_KEYS", () => {
it("covers exactly the 智能体 → 评估中心 range, in rendered order", () => {
- expect([...NAV_GROUP_KEYS]).toEqual([
- "agents",
- "skills",
- "models",
- "usage",
- "traces",
- "benchmark",
- ]);
+ // Traces is deliberately absent: the Trace panel moved into the chat toolbar's panel
+ // switcher (features/dock), and /traces stays reachable through its deep links only.
+ expect([...NAV_GROUP_KEYS]).toEqual(["agents", "skills", "models", "usage", "benchmark"]);
// Pin the endpoints by label: a manifest edit that shifts the range shows up here.
expect(zh.nav[NAV_GROUP_KEYS[0]]).toBe("智能体");
expect(zh.nav[NAV_GROUP_KEYS[NAV_GROUP_KEYS.length - 1]!]).toBe("评估中心");
diff --git a/packages/web/test/panel-task-scope.test.ts b/packages/web/test/panel-task-scope.test.ts
index 6302ce0c..9545b0fd 100644
--- a/packages/web/test/panel-task-scope.test.ts
+++ b/packages/web/test/panel-task-scope.test.ts
@@ -8,10 +8,7 @@
* returned action under its own layout guards.
*/
import { describe, expect, it } from "vitest";
-import {
- advancePanelTaskScope,
- createPanelTaskScope,
-} from "../src/features/chat/use-subagents-panel";
+import { advancePanelTaskScope, createPanelTaskScope } from "../src/features/chat/panel-task-scope";
const obs = (sessionId: string | null, taskCount: number, liveSpawn = false) => ({
sessionId,
diff --git a/packages/web/test/terminal-dock-scope.test.ts b/packages/web/test/terminal-dock-scope.test.ts
deleted file mode 100644
index 2a381706..00000000
--- a/packages/web/test/terminal-dock-scope.test.ts
+++ /dev/null
@@ -1,335 +0,0 @@
-/**
- * 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("closes a side pane when a panel takes the side, and closing the panel leaves it closed", () => {
- dock.setDockScope("session-side");
- dock.assignTerminalToPane("term-right", "right");
- expect(dock.isTerminalDockOpen()).toBe(true);
-
- dock.setChatSidePanelOpen(true);
- expect(dock.isTerminalDockOpen()).toBe(false);
- // Closed, not parked behind the panel: closing the panel must not conjure it back,
- // because opening the panel is what the user saw close the terminal.
- dock.setChatSidePanelOpen(false);
- expect(dock.isTerminalDockOpen()).toBe(false);
-
- // The arrangement survives, so reopening returns it to the edge it was on.
- expect(dock.openPanes()).toEqual(["right"]);
- expect(dock.paneOfTerminal("term-right")).toBe("right");
- dock.setTerminalDockOpen(true);
- 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.isTerminalDockOpen()).toBe(true);
- expect(dock.visiblePanes()).toEqual(["bottom"]);
- });
-
- it("is not on screen away from a conversation, and comes back on return", () => {
- dock.setChatSidePanelOpen(false); // no panel holding the side, so no handover to wait out
- dock.setDockScope("session-away");
- dock.assignTerminalToPane("term-away", "right");
- expect(dock.isTerminalDockOpen()).toBe(true);
-
- // Agents, user management, settings: no Session, so the placeholder scope. Asserted on
- // this conversation's pane rather than on the dock as a whole — the placeholder can hold
- // an arrangement of its own (a terminal opened while on one of those pages), and what
- // matters is that the conversation's does not follow the user there.
- dock.setDockScope(null);
- expect(dock.paneOfTerminal("term-away")).toBeNull();
- expect(dock.openPanes()).not.toContain("right");
-
- dock.setDockScope("session-away");
- expect(dock.isTerminalDockOpen()).toBe(true);
- expect(dock.paneOfTerminal("term-away")).toBe("right");
- });
-
- 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,
- // which closed the pane again on its way in.
- expect(dock.isTerminalDockOpen()).toBe(false);
- 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
- });
-});