From d5be4d2adbcd8d81d26f99402c4f9705e41b1257 Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:58:22 -0700 Subject: [PATCH 1/7] fix(workspaces): share the phone workspace terminal on desktop Offer the same base terminal as a Workspace tab in standalone local workspaces, including when runtime discovery is pending or unavailable. Keep launched sessions preferred and preserve saved splits across detail visits, without adding a runtime session or changing remote workspaces. Allow concurrent base-terminal attachments while keeping idle-stop exclusive. Each connection retains ownership of its own transport so a phone and desktop can share the running process. Add admission, layout, discovery and cross-device regressions. Local browser and live terminal integration tests remain unrun. Refs #1954. Co-authored-by: GPT-6 Astra --- context/workspace-runtime-lifecycle.md | 6 +- frontend/src/lib/api/workspace-runtime.ts | 4 + .../mobile/MobileWorkspaceTerminal.svelte | 8 +- .../terminal/PooledSessionTerminal.svelte | 4 +- .../terminal/WorkspaceTerminalView.svelte | 66 +++- .../terminal/WorkspaceTerminalView.test.ts | 365 +++++++++++++++--- .../WorkspaceTerminalViewPane.test.ts | 3 +- .../src/lib/stores/session-host.svelte.ts | 2 + .../00-inline-workspace-continuity.spec.ts | 2 +- .../00-workspace-create-and-launch.spec.ts | 97 +++-- .../e2e-full/00-workspace-launcher.spec.ts | 4 +- frontend/tests/e2e/workspace-sidebar.spec.ts | 105 +++-- internal/terminal/handler.go | 45 ++- internal/terminal/handler_test.go | 88 ++++- 14 files changed, 619 insertions(+), 180 deletions(-) diff --git a/context/workspace-runtime-lifecycle.md b/context/workspace-runtime-lifecycle.md index 81f5f12438..c187937909 100644 --- a/context/workspace-runtime-lifecycle.md +++ b/context/workspace-runtime-lifecycle.md @@ -278,9 +278,9 @@ Processes on the execution host: ### Terminal sessions -- The base workspace tmux session is durable backend state, but production terminal panes are - pooled runtime sessions; the primary terminal endpoint is not a mounted SPA workflow - (`frontend/src/lib/components/terminal/PooledSessionTerminal.svelte`). +- The local base workspace terminal is durable backend state, shared by phone’s Workspace + choice and the standalone desktop Workspace workflow tab. It stays available while runtime + discovery is pending or fails; embedded detail panes and remote hosts remain session-only. - Launched agent and shell sessions are not durable after natural exit. - The shell drawer is a singleton per workspace; a tmux-backed shell survives server restarts until it exits or the workspace is deleted. diff --git a/frontend/src/lib/api/workspace-runtime.ts b/frontend/src/lib/api/workspace-runtime.ts index 65f488b25c..e61371f90e 100644 --- a/frontend/src/lib/api/workspace-runtime.ts +++ b/frontend/src/lib/api/workspace-runtime.ts @@ -30,3 +30,7 @@ export function workspaceSessionWebSocketPath(workspaceId: string, sessionKey: s export function workspaceTmuxWebSocketPath(workspaceId: string, hostKey?: string): string { return `${wsBaseUrl()}${executionHostPrefix(hostKey)}/workspaces/${encodeURIComponent(workspaceId)}` + "/terminal"; } + +export function workspaceBaseSessionKey(workspaceId: string): string { + return `${workspaceId}:@workspace`; +} diff --git a/frontend/src/lib/components/mobile/MobileWorkspaceTerminal.svelte b/frontend/src/lib/components/mobile/MobileWorkspaceTerminal.svelte index 1e792f4bcc..66472edafa 100644 --- a/frontend/src/lib/components/mobile/MobileWorkspaceTerminal.svelte +++ b/frontend/src/lib/components/mobile/MobileWorkspaceTerminal.svelte @@ -27,6 +27,7 @@ import { workspaceSessionWebSocketPath, workspaceTmuxWebSocketPath, + workspaceBaseSessionKey, type WorkspaceRuntimeState, } from "../../api/workspace-runtime.js"; import { getAppRuntime } from "../../app/runtime-context.js"; @@ -183,10 +184,6 @@ return { workspaceId, ...(hostKey === undefined ? {} : { hostKey }) }; } - function baseSessionKey(id: string): string { - return `${id}:@workspace`; - } - function mobileTerminalSessions( runtimeState: WorkspaceRuntimeState | null, detail: WorkspaceDetail | null, @@ -204,7 +201,7 @@ return [ ...launched, { - key: baseSessionKey(detail.id), + key: workspaceBaseSessionKey(detail.id), label: "Workspace", status: "running", generation: detail.created_at, @@ -248,6 +245,7 @@ kind: session.runtimeSession?.kind, label: session.label, cursorWheelInput: session.cursorWheelInput, + reconnectOnExit: session.runtimeSession === null, }); } for (const key of ownedHostKeys) { diff --git a/frontend/src/lib/components/terminal/PooledSessionTerminal.svelte b/frontend/src/lib/components/terminal/PooledSessionTerminal.svelte index 005dff2339..eaf888201e 100644 --- a/frontend/src/lib/components/terminal/PooledSessionTerminal.svelte +++ b/frontend/src/lib/components/terminal/PooledSessionTerminal.svelte @@ -244,14 +244,14 @@ bind:this={terminalPane} websocketPath={session.websocketPath} fleetHostKey={session.fleetHostKey} - reconnectOnExit={false} + reconnectOnExit={session.reconnectOnExit ?? false} disabled={session.disabled ?? false} active={active && attached} renderingEnabled={!retained} autoFocus={false} cursorWheelInput={session.cursorWheelInput ?? false} initialStatus={stoppedShell ? undefined : session.status} - onExit={(code) => onExit(code)} + onExit={session.reconnectOnExit ? undefined : onExit} onConnectionChange={(connected) => onConnectionChange(connected)} /> {/key} diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte index 4b04f6d5ef..9e7596f4b4 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte @@ -47,6 +47,8 @@ } from "../../api/types.js"; import { workspaceSessionWebSocketPath, + workspaceTmuxWebSocketPath, + workspaceBaseSessionKey, type WorkspaceRuntimeState, } from "../../api/workspace-runtime.js"; import { @@ -711,9 +713,29 @@ const workspaceLive = $derived( workspace?.id === workspaceId && selectedWorkspaceHostKey(workspace) === workspaceHostKey, ); + const embeddedWorkspace = $derived(paneSurface !== undefined); const runtimeLive = $derived( runtime !== null && runtimeForId === workspaceId && runtimeForHostKey === workspaceHostKey && workspaceLive, ); + // The standalone Workspaces view exposes the same durable terminal as phone. + // Detail panes keep their compact session-only layout and promotion behavior. + const baseTerminalHostKey = $derived( + workspaceLive && workspace?.status === "ready" && workspaceHostKey === undefined && !embeddedWorkspace + ? sessionHostKey(workspaceId, undefined, workspaceBaseSessionKey(workspaceId), workspace.created_at) + : null, + ); + const workflowLive = $derived(runtimeLive || baseTerminalHostKey !== null); + $effect(() => { + if (baseTerminalHostKey === null) return; + untrack(() => { + terminalLayout = { + ...terminalLayout, + workflowTree: normalizeWorkflowTree(terminalLayout.workflowTree, [ + ...collectWorkflowTabKeys(terminalLayout.workflowTree), "home", + ]), + }; + }); + }); // A workspace counts on its own visible page or when something launches in it; // automatic display beside a PR or issue does not. function reportWorkspaceLaunch(): void { @@ -799,7 +821,7 @@ ); const renderedWorkspaceInputRegion = $derived.by(() => { if (!hostVisible) return null; - if (workspaceInputRegion === "workflow" && !runtimeLive) return null; + if (workspaceInputRegion === "workflow" && !workflowLive) return null; if ( workspaceInputRegion === "details" && (!workspaceDetailsReady || hideRightSidebar || !sidebarOpen) @@ -813,7 +835,7 @@ }); $effect.pre(() => { - const workflowVisible = hostVisible && runtimeLive; + const workflowVisible = hostVisible && workflowLive; const detailsVisible = hostVisible && workspaceDetailsReady && !hideRightSidebar && sidebarOpen; const terminalVisible = hostVisible && terminalLayout.dock === "bottom"; @@ -990,7 +1012,6 @@ untrack(() => publishHostedSessions(key, sessions)); }); - const embeddedWorkspace = $derived(paneSurface !== undefined); const workspaceErrorVisible = $derived(hostVisible && (!embeddedWorkspace || pendingWorkspaceLaunch(workspaceId, workspaceHostKey) !== null)); // `auto` records who opened it: an overlay the view raised over an empty pane is @@ -1147,7 +1168,8 @@ return; } const tabs = workflowTabDescriptors; - const activeMissing = !tabs.some((tab) => tab.key === activeTabKey) && + const activeMissing = (activeTabKey === "home" && lastRequestedTabKey === null && restoredTabKey === null && runtimeSessions.length > 0 && tabs[0]?.key !== "home") || + !tabs.some((tab) => tab.key === activeTabKey) && !promotedSessionKeys.has(sessionKeyFromWorkflowTab(activeTabKey) ?? "") && !(activeTabKey === "terminal" && runtimeSessions.some((session) => sessionRegion(session) === "terminal")); const workspaceKey = viewWorkspaceKey; @@ -1161,7 +1183,7 @@ if (tabs.length > 0 && activeMissing) selectWorkspaceTab(tabs[0]!.key, false); // A docked terminal is not a workflow tab but is very much on screen, so an // empty strip alone does not mean the workspace has nothing to show. - if (tabs.length > 0 || anySession) { + if (tabs.some((tab) => tab.key !== "home") || anySession) { // Take back what the view opened, and only that: a reconnect, a relaunch, // or a first runtime load that lands before its sessions do all report zero // sessions for a moment, and an auto-opened launcher left over that gap @@ -1218,7 +1240,8 @@ // is looking at reported as inactive, which took the promote command away from // the only session there was to promote. soleEmbeddedSession?.key ?? - sessionKeyFromWorkflowTab(activeTabKey) ?? + (activeTabKey === "home" && baseTerminalHostKey !== null + ? workspaceBaseSessionKey(workspaceId) : sessionKeyFromWorkflowTab(activeTabKey)) ?? (terminalLayout.open ? terminalLayout.activeSessionKey : null), ); @@ -1462,6 +1485,9 @@ closable: true, }); } + if (baseTerminalHostKey !== null) { + tabs.push({ key: "home", label: "Workspace", kind: "plain_shell" }); + } return tabs; }); const renderedWorkflowTree = $derived( @@ -1607,7 +1633,8 @@ function activeWorkflowSessionKeys(node: WorkflowNode | null): string[] { if (node === null) return []; if (node.type === "leaf") { - const sessionKey = sessionKeyFromWorkflowTab(node.activeTabKey); + const sessionKey = node.activeTabKey === "home" && baseTerminalHostKey !== null + ? workspaceBaseSessionKey(workspaceId) : sessionKeyFromWorkflowTab(node.activeTabKey); return sessionKey === null ? [] : [sessionKey]; } return [...activeWorkflowSessionKeys(node.first), ...activeWorkflowSessionKeys(node.second)]; @@ -1623,8 +1650,9 @@ * one, and any interaction that re-selected the tab fixed it by accident. */ $effect(() => { - if (!runtimeLive) return; + if (!workflowLive) return; const live = new Set(runtimeSessions.map((session) => session.key)); + if (baseTerminalHostKey !== null) live.add(workspaceBaseSessionKey(workspaceId)); const showing = activeWorkflowSessionKeys(renderedWorkflowTree).filter((key) => live.has(key)); // Untracked: mountSessionTerminal writes the mounted list that the tree's own // descriptors read, and it is a no-op for a session already mounted, so this @@ -1931,6 +1959,17 @@ $effect(() => { const prefix = sessionHostPrefix(workspaceId, workspaceHostKey); const desired = new Map(); + if (baseTerminalHostKey !== null && mountedSessionKeys.includes(workspaceBaseSessionKey(workspaceId))) { + desired.set(baseTerminalHostKey, { + hostKey: baseTerminalHostKey, + websocketPath: workspaceTmuxWebSocketPath(workspaceId), + status: "running", + label: "Workspace", + reconnectOnExit: true, + cursorWheelInput: false, + disabled: actionsBlocked, + }); + } for (const session of runtimeSessions) { // A promoted session is on screen in a detail pane, which renders its slot // but cannot mount it: only this view knows the websocket path, the @@ -1966,6 +2005,7 @@ const liveGenerationKeys = runtimeLive && runtimeSnapshotAuthoritative ? new Set(runtimeSessions.map(sessionHostKeyFor)) : null; + if (baseTerminalHostKey !== null) liveGenerationKeys?.add(baseTerminalHostKey); untrack(() => { releaseOwnedSessions(prefix); if (desired.size > 0) ownedSessionPrefixes.add(prefix); @@ -2172,6 +2212,8 @@ keys.push(workflowTabKeyForSession(session.key)); } } + // Keep local placement while details load or embedded rendering temporarily hides it. + if (workspaceHostKey === undefined) keys.push("home"); return keys; } @@ -2672,7 +2714,7 @@ else if (sessionRegion(selected) === "terminal") restoreWorkspaceTabSelection(activeTabKey); } mountedSessionKeys = mountedSessionKeys.filter( - (key) => data.sessions.some((session) => session.key === key), + (key) => key === workspaceBaseSessionKey(id) || data.sessions.some((session) => session.key === key), ); if (admission !== undefined) reconcileQueuedWorkspaceLaunch(data); return data; @@ -5129,7 +5171,7 @@ ondragover={handleWorkflowDragOver} ondrop={handleWorkflowDrop} > - {#if !runtimeLive} + {#if !workflowLive}
Loading workspace runtime... @@ -5202,7 +5244,9 @@
{/snippet} {#snippet renderTab(tabKey, active)} - {#if tabKey === "terminal"} + {#if tabKey === "home" && baseTerminalHostKey !== null} + + {:else if tabKey === "terminal"} ({ let sockets: MockWebSocket[] = []; +function runtimeSockets(): MockWebSocket[] { + return sockets.filter((socket) => socket.url.includes("/runtime/sessions/")); +} + class MockWebSocket extends EventTarget { static OPEN = 1; readyState = 1; @@ -277,7 +281,8 @@ vi.mock("../../api/generated-api.js", async (importOriginal) => { }; }); -vi.mock("../../api/workspace-runtime.js", () => ({ +vi.mock("../../api/workspace-runtime.js", async (importOriginal) => ({ + ...(await importOriginal()), workspaceSessionWebSocketPath: (workspaceId: string, sessionKey: string) => `/ws/v1/workspaces/${workspaceId}/runtime/sessions/${sessionKey}/terminal`, workspaceTmuxWebSocketPath: (workspaceId: string) => `/ws/v1/workspaces/${workspaceId}/terminal`, @@ -315,6 +320,7 @@ import { mountedSessions, resetSessionHostForTest, sessionHostPrefix, + sessionHostKey, } from "../../stores/session-host.svelte.ts"; import { activeHostedSession, @@ -860,6 +866,224 @@ describe("WorkspaceTerminalView", () => { vi.unstubAllGlobals(); }); + it("uses terminal zoom after focusing Workspace beside a docked chat", async () => { + const chat = { ...reviewerSession, kind: "acp", display_region: "terminal" }; + mocks.getWorkspaceRuntime.mockResolvedValue({ launch_targets: [], sessions: [chat] }); + localStorage.setItem("kenn-forge-workspace-active-tab:ws-1", "home"); + localStorage.setItem( + "kenn-forge-workspace-terminal-layout:ws-1", + JSON.stringify({ + ...JSON.parse(persistedTerminalLayout("tabs")), + open: true, + }), + ); + render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + await screen.findByRole("tab", { name: "Workspace", exact: true }); + const dock = await screen.findByRole("group", { name: "Reviewer split drop targets" }); + await fireEvent.focusIn(dock); + expect(screen.getByRole("button", { name: "Increase ACP font size" })).toBeTruthy(); + const basePane = document.querySelector('[data-pane-key="home"]')!; + expect(basePane).not.toBeNull(); + await fireEvent.focusIn(basePane); + const increase = screen.getByRole("button", { name: "Increase terminal font size" }); + await fireEvent.focusOut(basePane, { relatedTarget: increase }); + increase.focus(); + await fireEvent.click(increase); + await waitFor(() => + expect(mocks.mockUpdateSettings).toHaveBeenCalledWith({ + terminal: expect.objectContaining({ font_size: 15 }), + }), + ); + expect(mocks.mockSetACPSettings).not.toHaveBeenCalled(); + }); + + it("restores Workspace split when runtime arrives before workspace details", async () => { + const detail = deferred(); + const originalFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: Request | URL | string, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + return new URL(url, "http://localhost").pathname === "/api/v1/workspaces/ws-1" + ? detail.promise + : originalFetch(input, init); + }); + localStorage.setItem("kenn-forge-workspace-active-tab:ws-1", "home"); + localStorage.setItem("kenn-forge-workspace-terminal-layout:ws-1", persistedSplitWorkflowLayout(runningSession.key)); + const view = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + await waitFor(() => expect(mocks.getWorkspaceRuntime).toHaveBeenCalled()); + await waitFor(() => + expect(localStorage.getItem("kenn-forge-workspace-terminal-layout:ws-1")).toContain("session:ws-1:helper"), + ); + // Release details after the independently fetched runtime has settled. + await new Promise((resolve) => setTimeout(resolve, 0)); + detail.resolve(Response.json(workspaceResponse)); + await screen.findByRole("tab", { name: "Workspace", exact: true }); + await screen.findByRole("tab", { name: "Helper" }); + await waitFor(() => + expect(JSON.parse(localStorage.getItem("kenn-forge-workspace-terminal-layout:ws-1")!).workflowTree).toMatchObject( + { type: "split" }, + ), + ); + await waitFor(() => expect(sockets).toHaveLength(2)); + const base = sockets.find((socket) => new URL(socket.url).pathname === "/ws/v1/workspaces/ws-1/terminal")!; + expect(base).toBeDefined(); + base.onopen(); + await fireEvent.click(screen.getByRole("tab", { name: "Helper" })); + await fireEvent.click(screen.getByRole("tab", { name: "Workspace", exact: true })); + await view.rerender({ workspaceId: "" }); + await view.rerender({ workspaceId: "ws-1" }); + await screen.findByRole("tab", { name: "Workspace", exact: true }); + expect(sockets.filter((socket) => new URL(socket.url).pathname === "/ws/v1/workspaces/ws-1/terminal")).toHaveLength( + 1, + ); + expect(base.close).not.toHaveBeenCalled(); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }); + + it("preserves the Workspace split through a changed runtime in an embedded detail", async () => { + const storageKey = "kenn-forge-workspace-terminal-layout:ws-1"; + const saved = JSON.parse(persistedSplitWorkflowLayout(runningSession.key)); + saved.workflowTree.ratio = 0.37; + localStorage.setItem(storageKey, JSON.stringify(saved)); + localStorage.setItem("kenn-forge-workspace-active-tab:ws-1", "home"); + const eventSources = installEventSourceRecorder(); + const view = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + await screen.findByRole("tab", { name: "Workspace", exact: true }); + await screen.findByRole("tab", { name: "Helper" }); + const storedTree = () => JSON.parse(localStorage.getItem(storageKey)!).workflowTree; + const expectedPlacement = { + type: "split", + id: "wf-split", + direction: "horizontal", + ratio: 0.37, + first: { type: "leaf", id: "wf-home", tabs: expect.arrayContaining(["home"]) }, + second: { type: "leaf", id: "wf-session", tabs: expect.arrayContaining([`session:${runningSession.key}`]) }, + }; + await waitFor(() => expect(storedTree()).toMatchObject(expectedPlacement)); + + claimForPrs(); + noteWorkspacePaneRendered("prs"); + await view.rerender({ workspaceId: "ws-1", paneSurface: "prs" }); + await waitFor(() => expect(screen.queryByRole("tab", { name: "Workspace", exact: true })).toBeNull()); + mocks.getWorkspaceRuntime.mockResolvedValue(runtimeWithTwoWorkflowSessions()); + const priorReads = mocks.getWorkspaceRuntime.mock.calls.length; + await waitFor(() => expect(latestWorkspaceEventListeners(eventSources)["reconnect.stale"]).toBeTypeOf("function")); + latestWorkspaceEventListeners(eventSources)["reconnect.stale"]?.(); + await waitFor(() => expect(mocks.getWorkspaceRuntime.mock.calls.length).toBeGreaterThan(priorReads)); + // Prove the changed snapshot was applied, while allowing the new session's normal insertion. + await waitFor(() => expect(localStorage.getItem(storageKey)).toContain(`session:${reviewerSession.key}`)); + expect(screen.queryByRole("tab", { name: "Workspace", exact: true })).toBeNull(); + expect(storedTree()).toMatchObject(expectedPlacement); + + await view.rerender({ workspaceId: "ws-1", paneSurface: undefined }); + await waitFor(() => + expect(screen.getByRole("tab", { name: "Workspace", exact: true }).getAttribute("aria-selected")).toBe("true"), + ); + expect(screen.getByRole("tab", { name: "Helper" }).getAttribute("aria-selected")).toBe("true"); + expect(screen.getAllByRole("tablist", { name: "Workflow group tabs" })).toHaveLength(2); + expect(storedTree()).toMatchObject(expectedPlacement); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }); + + it.each(["pending", "failed"] as const)( + "keeps the shared Workspace base terminal available when discovery is %s", + async (discovery) => { + if (discovery === "pending") { + mocks.getWorkspaceRuntime.mockReturnValue(new Promise(() => undefined)); + } else { + mocks.getWorkspaceRuntime.mockImplementation(async () => + Response.json( + { + status: 503, + code: "serviceUnavailable", + detail: "Runtime discovery unavailable", + }, + { status: 503 }, + ), + ); + } + localStorage.setItem("kenn-forge-workspace-active-tab:ws-1", "home"); + render(WorkspaceTerminalView, { props: { workspaceId: "ws-1", hideWorkspaceList: true } }); + + const tab = await screen.findByRole("tab", { name: "Workspace", exact: true }); + expect(tab.getAttribute("aria-selected")).toBe("true"); + await waitFor(() => + expect(mountedSessions()).toContainEqual( + expect.objectContaining({ + hostKey: sessionHostKey("ws-1", undefined, "ws-1:@workspace", workspaceResponse.created_at), + websocketPath: "/ws/v1/workspaces/ws-1/terminal", + label: "Workspace", + reconnectOnExit: true, + }), + ), + ); + expect(screen.queryByRole("button", { name: "Rename Workspace" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Close Workspace" })).toBeNull(); + await waitFor(() => + expect(sockets.some((socket) => new URL(socket.url).pathname.endsWith("/workspaces/ws-1/terminal"))).toBe(true), + ); + if (discovery === "failed") { + await waitFor(() => + expect(document.querySelector(".runtime-error")?.textContent).toContain("Runtime discovery unavailable"), + ); + } else { + await waitFor(() => expect(sockets[0]?.runListenersAttached).toBe(true)); + sockets[0]!.onopen(); + sockets[0]!.onmessage(new MessageEvent("message", { data: JSON.stringify({ type: "exited", code: 0 }) })); + await waitFor(() => expect(sockets).toHaveLength(2), { timeout: 4_000 }); + expect(mountedSessions()).toHaveLength(1); + expect(tab.getAttribute("aria-selected")).toBe("true"); + } + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }, + ); + + it("keeps launched sessions first and reuses Workspace across switching, polling, and reopening", async () => { + localStorage.removeItem("kenn-forge-workspace-active-tab:ws-1"); + const intervalCallbacks: Array<{ callback: () => void; delay: number | undefined }> = []; + capturePollingIntervals(intervalCallbacks); + const view = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + await waitFor(() => expect(screen.getByRole("tab", { name: "Helper" }).getAttribute("aria-selected")).toBe("true")); + await fireEvent.click(screen.getByRole("tab", { name: "Workspace", exact: true })); + await waitFor(() => + expect( + sockets.filter((socket) => new URL(socket.url).pathname.endsWith("/workspaces/ws-1/terminal")), + ).toHaveLength(1), + ); + const base = sockets.find((socket) => new URL(socket.url).pathname.endsWith("/workspaces/ws-1/terminal"))!; + base.onopen(); + await fireEvent.click(screen.getByRole("tab", { name: "Helper" })); + await fireEvent.click(screen.getByRole("tab", { name: "Workspace", exact: true })); + await fireEvent.keyDown(window, { key: "Escape" }); + intervalCallbacks[0]!.callback(); + await waitFor(() => expect(mocks.getWorkspaceRuntime).toHaveBeenCalledTimes(2)); + await view.rerender({ workspaceId: "" }); + await waitFor(() => expect(screen.queryByRole("tab", { name: "Workspace", exact: true })).toBeNull()); + await view.rerender({ workspaceId: "ws-1" }); + await waitFor(() => + expect(screen.getByRole("tab", { name: "Workspace", exact: true }).getAttribute("aria-selected")).toBe("true"), + ); + expect(base.close).not.toHaveBeenCalled(); + expect(sockets.filter((socket) => new URL(socket.url).pathname.endsWith("/workspaces/ws-1/terminal"))).toHaveLength( + 1, + ); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }); + + it.each(["member", "devbox:remote"])("does not offer a local Workspace terminal on %s", async (host) => { + const originalFetch = globalThis.fetch; + vi.stubGlobal("fetch", async (input: Request | URL | string, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + if (new URL(url, "http://localhost").pathname.endsWith("/workspaces/ws-1/runtime")) { + return Response.json(runtimeWithStaleSession()); + } + return originalFetch(input, init); + }); + render(WorkspaceTerminalView, { props: { workspaceId: "ws-1", workspaceHostKey: host } }); + await screen.findByRole("tab", { name: "Helper" }); + expect(screen.queryByRole("tab", { name: "Workspace", exact: true })).toBeNull(); + expect(mountedSessions().some((session) => session.hostKey.includes("@workspace"))).toBe(false); + }); + it.each([ { itemType: "pr", @@ -1727,27 +1951,36 @@ describe("WorkspaceTerminalView", () => { expect(screen.getByLabelText(label).classList.contains(className)).toBe(true); }); - it("keeps the remaining agent visible when the selected terminal exits", async () => { - mocks.getWorkspaceRuntime.mockResolvedValue(runtimeWithTwoWorkflowSessions()); - render(WorkspaceTerminalView, { - props: { - workspaceId: "ws-1", - }, - }); - - await screen.findByRole("region", { name: "Workflow panes" }); - await waitFor(() => expect(sockets).toHaveLength(1)); - - sockets[0]!.onmessage?.( - new MessageEvent("message", { - data: JSON.stringify({ type: "exited", code: 0 }), - }), - ); - - await waitFor(() => expect(screen.queryByRole("tab", { name: /Helper/ })).toBeNull()); - expect(screen.getByRole("tab", { name: /Reviewer/ }).getAttribute("aria-selected")).toBe("true"); - expect(localStorage.getItem("kenn-forge-workspace-active-tab:ws-1")).toBe("session:ws-1:reviewer"); - }); + it.each([0, 1])( + "selects the fallback with %s remaining agents when the selected terminal exits", + async (remaining) => { + mocks.getWorkspaceRuntime.mockResolvedValue( + remaining ? runtimeWithTwoWorkflowSessions() : runtimeWithStaleSession(), + ); + render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + await screen.findByRole("region", { name: "Workflow panes" }); + await screen.findByRole("tab", { name: "Helper" }); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); + if (remaining === 0) mocks.getWorkspaceRuntime.mockResolvedValue(runtimeWithLaunchTargetsOnly()); + runtimeSockets()[0]!.onmessage( + new MessageEvent("message", { + data: JSON.stringify({ type: "exited", code: 0 }), + }), + ); + await waitFor(() => expect(screen.queryByRole("tab", { name: /Helper/ })).toBeNull()); + await waitFor(() => + expect( + screen + .getByRole("tab", { name: remaining ? "Reviewer" : "Workspace", exact: true }) + .getAttribute("aria-selected"), + ).toBe("true"), + ); + expect(localStorage.getItem("kenn-forge-workspace-active-tab:ws-1")).toBe( + remaining ? "session:ws-1:reviewer" : "home", + ); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }, + ); it("hides pane workspace info until the selected workspace loads", async () => { serveAnyWorkspace(); @@ -2764,24 +2997,30 @@ describe("WorkspaceTerminalView", () => { ); const { rerender } = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); await screen.findByRole("tab", { name: /Helper/ }); - await waitFor(() => expect(sockets).toHaveLength(1)); - sockets[0]!.onopen(); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); + runtimeSockets()[0]!.onopen(); await rerender({ workspaceId: "ws-2" }); await screen.findByRole("button", { name: "Workspace info" }); - sockets[0]!.onclose(new CloseEvent("close")); - await waitFor(() => expect(mountedSessions()).toHaveLength(0)); + runtimeSockets()[0]!.onclose(new CloseEvent("close")); + await waitFor(() => + expect(mountedSessions().filter((session) => session.websocketPath.includes("/runtime/sessions/"))).toHaveLength( + 0, + ), + ); const refreshedRuntime = deferred>(); mocks.getWorkspaceRuntime.mockReturnValue(refreshedRuntime.promise); await rerender({ workspaceId: "ws-1" }); await screen.findByRole("tab", { name: /Helper/ }); - expect(mountedSessions()).toHaveLength(0); - expect(sockets).toHaveLength(1); + expect(mountedSessions().filter((session) => session.websocketPath.includes("/runtime/sessions/"))).toHaveLength(0); + expect(runtimeSockets()).toHaveLength(1); refreshedRuntime.resolve(runtimeWithSession("2026-04-29T00:05:00Z")); - await waitFor(() => expect(sockets).toHaveLength(2)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(2)); expect(screen.getByRole("tab", { name: /Helper/ }).getAttribute("aria-selected")).toBe("true"); - expect(mountedSessions()[0]?.hostKey).toContain("00%3A05%3A00Z"); + expect( + mountedSessions().filter((session) => session.websocketPath.includes("/runtime/sessions/"))[0]?.hostKey, + ).toContain("00%3A05%3A00Z"); }); it("forgets a restored workspace when the refresh reports it deleted", async () => { @@ -2852,9 +3091,9 @@ describe("WorkspaceTerminalView", () => { await screen.findByRole("button", { name: "Refresh workspace details" }); initialRuntime.resolve(runtimeWithStaleSession()); await screen.findByRole("tab", { name: /Helper/ }); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); - sockets[0]!.onmessage?.( + runtimeSockets()[0]!.onmessage?.( new MessageEvent("message", { data: JSON.stringify({ type: "exited", code: 0 }), }), @@ -3277,10 +3516,10 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }); await fireEvent.click(terminalButton); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); expect(screen.queryByLabelText("Terminal selector")).toBeNull(); - sockets[0]!.onmessage?.( + runtimeSockets()[0]!.onmessage?.( new MessageEvent("message", { data: JSON.stringify({ type: "exited", code: 0 }), }), @@ -3309,7 +3548,7 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }), ); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); await fireEvent.click(screen.getByRole("button", { name: "Close Shell" })); @@ -3338,7 +3577,7 @@ describe("WorkspaceTerminalView", () => { }); await fireEvent.click(await screen.findByRole("button", { name: "Open terminal panel" })); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); await fireEvent.click(screen.getByRole("button", { name: "Close Shell" })); const confirm = await screen.findByRole("dialog", { name: "Stop Shell?" }); const stalledRefresh = deferred>(); @@ -3450,15 +3689,15 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }); await fireEvent.click(terminalButton); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); - sockets[0]!.onmessage?.( + runtimeSockets()[0]!.onmessage?.( new MessageEvent("message", { data: JSON.stringify({ type: "exited", code: 0 }), }), ); await screen.findByRole("button", { name: "Open terminal panel" }); - expect(sockets).toHaveLength(1); + expect(runtimeSockets()).toHaveLength(1); }); // A chat whose agent dies is parked under the same session, and its next @@ -3769,9 +4008,9 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }); await fireEvent.click(terminalButton); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); - sockets[0]!.onmessage?.( + runtimeSockets()[0]!.onmessage?.( new MessageEvent("message", { data: JSON.stringify({ type: "exited", code: 0 }), }), @@ -3780,13 +4019,13 @@ describe("WorkspaceTerminalView", () => { await fireEvent.click(screen.getAllByRole("button", { name: "New terminal" })[0]!); freshRefresh.resolve(runtimeWithTerminalSession(relaunchedShellSession)); - await waitFor(() => expect(sockets.some((socket) => socket.url.includes("ws-1_shell_b"))).toBe(true)); + await waitFor(() => expect(runtimeSockets().some((socket) => socket.url.includes("ws-1_shell_b"))).toBe(true)); staleRefresh.resolve(runtimeWithTerminalSession()); await new Promise((resolve) => setTimeout(resolve, 0)); - expect(sockets.filter((socket) => socket.url.includes("ws-1_shell_a"))).toHaveLength(1); - expect(sockets.filter((socket) => socket.url.includes("ws-1_shell_b"))).toHaveLength(1); + expect(runtimeSockets().filter((socket) => socket.url.includes("ws-1_shell_a"))).toHaveLength(1); + expect(runtimeSockets().filter((socket) => socket.url.includes("ws-1_shell_b"))).toHaveLength(1); }); it("moves a workflow shell back into the terminal panel", async () => { @@ -3804,7 +4043,7 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }), ); - await waitFor(() => expect(sockets).toHaveLength(1)); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); expect(screen.getByRole("button", { name: "Focus Shell" }).getAttribute("draggable")).toBe("true"); await fireEvent.click(screen.getByRole("button", { name: "Move Shell to workflow" })); @@ -3830,8 +4069,8 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }), ); - await waitFor(() => expect(sockets).toHaveLength(1)); - const socket = sockets[0]!; + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); + const socket = runtimeSockets()[0]!; expect(socket.url).toContain("ws-1_shell_a"); await fireEvent.click(screen.getByRole("button", { name: "Move Shell to workflow" })); @@ -3842,7 +4081,7 @@ describe("WorkspaceTerminalView", () => { // One tmux attachment from start to finish. Both regions render the same // pooled terminal, so moving between them reparents it instead of tearing // the shell down and reattaching to a scrollback-less new one. - expect(sockets.filter((candidate) => candidate.url.includes("ws-1_shell_a"))).toHaveLength(1); + expect(runtimeSockets().filter((candidate) => candidate.url.includes("ws-1_shell_a"))).toHaveLength(1); expect(socket.close).not.toHaveBeenCalled(); }); @@ -3861,15 +4100,20 @@ describe("WorkspaceTerminalView", () => { name: "Open terminal panel", }), ); - await waitFor(() => expect(sockets).toHaveLength(1)); - sockets[0]!.onopen(); - const hostKey = mountedSessions()[0]!.hostKey; + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); + runtimeSockets()[0]!.onopen(); + const hostKey = mountedSessions().filter((session) => session.websocketPath.includes("/runtime/sessions/"))[0]! + .hostKey; await fireEvent.click(screen.getAllByRole("button", { name: "Close terminal panel" })[0]!); await waitFor(() => expect(isSessionClaimed(hostKey)).toBe(false)); - expect(mountedSessions().some((session) => session.hostKey === hostKey)).toBe(true); - expect(sockets[0]!.close).not.toHaveBeenCalled(); + expect( + mountedSessions() + .filter((session) => session.websocketPath.includes("/runtime/sessions/")) + .some((session) => session.hostKey === hostKey), + ).toBe(true); + expect(runtimeSockets()[0]!.close).not.toHaveBeenCalled(); }); it("shows a workspace sidebar collapse button", async () => { @@ -6627,7 +6871,18 @@ describe("WorkspaceTerminalView", () => { .map(([data]) => (typeof data === "string" ? data : new TextDecoder().decode(data as Uint8Array))) .join(""), ).not.toContain("Review this change"); - expect(within(strip).getAllByRole("tab")).toHaveLength(1); + expect( + within(strip) + .getAllByRole("tab") + .map((tab) => tab.textContent?.trim()) + .sort(), + ).toEqual(["Helper", "Workspace"]); + expect( + within(strip) + .getByRole("tab", { name: /Helper/ }) + .getAttribute("aria-selected"), + ).toBe("true"); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); }); it("focuses the terminal once the prompt is delivered, unless the user is typing elsewhere", async () => { @@ -7149,7 +7404,7 @@ describe("WorkspaceTerminalView", () => { }); const execution = runCommand.mock.results.at(-1)!.value; const firstView = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); - await screen.findByText("Loading workspace runtime..."); + await screen.findByText("Launching helper..."); const placed = JSON.parse(localStorage.getItem(storageKey)!); expect(placed.workflowMode).toBe("grid"); firstView.unmount(); diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalViewPane.test.ts b/frontend/src/lib/components/terminal/WorkspaceTerminalViewPane.test.ts index 0996f2db75..da8bb5167e 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalViewPane.test.ts +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalViewPane.test.ts @@ -56,7 +56,8 @@ vi.mock("../../stores/flash.svelte.js", () => ({ showFlash: mocks.showFlash, })); -vi.mock("../../api/workspace-runtime.js", () => ({ +vi.mock("../../api/workspace-runtime.js", async (importOriginal) => ({ + ...(await importOriginal()), workspaceSessionWebSocketPath: () => "", workspaceTmuxWebSocketPath: () => "", })); diff --git a/frontend/src/lib/stores/session-host.svelte.ts b/frontend/src/lib/stores/session-host.svelte.ts index 3cdcc9c48d..e1931a4de9 100644 --- a/frontend/src/lib/stores/session-host.svelte.ts +++ b/frontend/src/lib/stores/session-host.svelte.ts @@ -54,6 +54,7 @@ export interface MountedSession { websocketPath: string; status: string; cursorWheelInput?: boolean; + reconnectOnExit?: boolean; disabled?: boolean; } @@ -197,6 +198,7 @@ export function noteSessionMounted(session: MountedSession): void { existing.status === session.status && existing.kind === session.kind && existing.label === session.label && + (existing.reconnectOnExit ?? false) === (session.reconnectOnExit ?? false) && (existing.cursorWheelInput ?? false) === (session.cursorWheelInput ?? false) && (existing.disabled ?? false) === (session.disabled ?? false) ) { diff --git a/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts b/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts index 9334a00868..501a8d0997 100644 --- a/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts +++ b/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts @@ -1937,7 +1937,7 @@ test.describe("inline workspace pane continuity", () => { await selectTopBarTab(page, "Workspaces"); await expect(page).toHaveURL(new RegExp(`/terminal/${workspace.id}$`)); - const backInTab = page.locator(".workspace-tab-slot .terminal-container"); + const backInTab = page.locator(".workspace-tab-slot .terminal-panel.open .terminal-container"); await expect(witness).toBeVisible(); await expect(backInTab).toHaveAttribute("data-continuity", "witness"); // The same session must still accept input after the second diff --git a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts index 57f578460c..3d2467dd93 100644 --- a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts @@ -946,7 +946,10 @@ test.describe("workspace create-and-launch full stack", () => { } }); - test("phone local base terminal survives pending and failed runtime discovery", async ({ page, browser }) => { + test("phone and desktop share the base terminal through pending and failed runtime discovery", async ({ + page, + browser, + }) => { test.skip( !hasCommand("git") || !hasCommand("tmux", ["-V"]) || !hasCommand("sh", ["-c", ":"]), "git, tmux, and sh are required for the real workspace runtime flow", @@ -965,29 +968,37 @@ test.describe("workspace create-and-launch full stack", () => { phoneContext = await browser.newContext({ ...devices["Pixel 7"] }); const phonePage = await phoneContext.newPage(); await trackSessionWebSockets(phonePage); + await trackSessionWebSockets(page); + let phoneOutput = ""; + let desktopOutput = ""; + phonePage.on("websocket", (socket) => + socket.on("framereceived", ({ payload }) => { + phoneOutput += payload.toString(); + }), + ); + page.on("websocket", (socket) => + socket.on("framereceived", ({ payload }) => { + desktopOutput += payload.toString(); + }), + ); const runtimeGate = new Promise((resolve) => { releaseRuntime = resolve; }); // Match the path alone: the showing page adds ?viewing=true. - await phonePage.route( - (url) => /^\/api\/v1\/workspaces\/[^/]+\/runtime$/.test(url.pathname), - async (route) => { - if (route.request().method() !== "GET") { - await route.continue(); - return; - } - await runtimeGate; - await route.fulfill({ - status: 503, - contentType: "application/problem+json", - body: JSON.stringify({ - status: 503, - code: "serviceUnavailable", - detail: "runtime discovery unavailable", - }), - }); - }, - ); + const runtimeRoute = async (route: import("@playwright/test").Route) => { + if (route.request().method() !== "GET") { + await route.continue(); + return; + } + await runtimeGate; + await route.fulfill({ + status: 503, + contentType: "application/problem+json", + body: JSON.stringify({ status: 503, code: "serviceUnavailable", detail: "runtime discovery unavailable" }), + }); + }; + await page.route((url) => /^\/api\/v1\/workspaces\/[^/]+\/runtime$/.test(url.pathname), runtimeRoute); + await phonePage.route((url) => /^\/api\/v1\/workspaces\/[^/]+\/runtime$/.test(url.pathname), runtimeRoute); const createResponsePromise = phonePage.waitForResponse( (response) => @@ -1016,28 +1027,50 @@ test.describe("workspace create-and-launch full stack", () => { const input = phonePage.getByRole("textbox", { name: "Terminal command" }); await phonePage.getByRole("button", { name: "Open terminal composer" }).tap(); - await input.fill("printf 'base-before-runtime\\n'"); + await input.fill( + `sh -c 'printf "shared-base-process:%s\\n" "$$"; while read line; do printf "shared-base-reply:%s:%s\\n" "$$" "$line"; done'`, + ); await phonePage.getByRole("button", { name: "Send terminal input" }).tap(); - await expect - .poll(async () => - (await workspaceBaseWebSockets(phonePage, created.id)) - .flatMap((socket) => socket.sent) - .some((frame) => frame.includes("base-before-runtime")), - ) - .toBe(true); + await expect.poll(() => phoneOutput).toMatch(/shared-base-process:\d+/); + const processId = /shared-base-process:(\d+)/.exec(phoneOutput)![1]!; + await page.goto(`${server.info.base_url}/terminal/${created.id}`); + const workspaceTab = page.getByRole("tab", { name: "Workspace", exact: true }); + await expect(workspaceTab).toHaveAttribute("aria-selected", "true"); + await expect.poll(() => desktopOutput).toContain(`shared-base-process:${processId}`); + const desktopInput = page.locator(".workspace-stage .xterm-helper-textarea"); + await desktopInput.focus(); + await page.keyboard.type("desktop-joined"); + await page.keyboard.press("Enter"); + await expect.poll(() => desktopOutput).toContain(`shared-base-reply:${processId}:desktop-joined`); + await expect.poll(() => phoneOutput).toContain(`shared-base-reply:${processId}:desktop-joined`); + expect(await runtimeTargets(api, created.id)).toEqual([]); + expect(await persistedRuntimeTargets(api, created.id)).toEqual([]); + await page.screenshot({ path: test.info().outputPath("workspace-base-desktop.png") }); releaseRuntime(); runtimeReleased = true; await expect(phonePage.getByText("Runtime sessions unavailable")).toBeVisible(); - await input.fill("printf 'base-after-runtime-failure\\n'"); + await expect(page.getByText("runtime discovery unavailable", { exact: true })).toBeVisible(); + await input.fill("phone-after-failure"); await phonePage.getByRole("button", { name: "Send terminal input" }).tap(); + await expect.poll(() => desktopOutput).toContain(`shared-base-reply:${processId}:phone-after-failure`); + await page.reload(); + await expect(workspaceTab).toHaveAttribute("aria-selected", "true"); + await page.keyboard.press("Escape"); + await desktopInput.focus(); + // The init-script log starts fresh on reload, unlike the accumulated output buffer. await expect .poll(async () => - (await workspaceBaseWebSockets(phonePage, created.id)) - .flatMap((socket) => socket.sent) - .some((frame) => frame.includes("base-after-runtime-failure")), + (await workspaceBaseWebSockets(page, created.id)).some( + (entry) => + !entry.closed && entry.sent.some((frame) => /"type":"(?:claim_resize|resize|refresh)"/.test(frame)), + ), ) .toBe(true); + await page.keyboard.type("desktop-reopened"); + await page.keyboard.press("Enter"); + await expect.poll(() => phoneOutput).toContain(`shared-base-reply:${processId}:desktop-reopened`); + expect(await runtimeTargets(api, created.id)).toEqual([]); } finally { if (!runtimeReleased) releaseRuntime(); await phoneContext?.close(); diff --git a/frontend/tests/e2e-full/00-workspace-launcher.spec.ts b/frontend/tests/e2e-full/00-workspace-launcher.spec.ts index 3ca11a9c27..e902474327 100644 --- a/frontend/tests/e2e-full/00-workspace-launcher.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-launcher.spec.ts @@ -264,7 +264,9 @@ test.describe("embedded workspace launcher", () => { await page.goto(`${isolatedServer.info.base_url}/terminal/${workspace.id}`); await page.getByRole("region", { name: "Session launcher" }).getByRole("button", { name: "Shell" }).click(); - const terminal = page.locator(".workspace-tab-slot .terminal-container"); + const terminal = page.locator( + '.workspace-tab-slot [data-pane-key^="session:"] .terminal-container, .workspace-tab-slot [data-pane-key="terminal"] .terminal-container', + ); await expect(terminal).toBeVisible(); await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); await expect diff --git a/frontend/tests/e2e/workspace-sidebar.spec.ts b/frontend/tests/e2e/workspace-sidebar.spec.ts index 83d66c053e..0c8c499108 100644 --- a/frontend/tests/e2e/workspace-sidebar.spec.ts +++ b/frontend/tests/e2e/workspace-sidebar.spec.ts @@ -2825,7 +2825,9 @@ test.describe("workspace launcher", () => { release(); await expect(panel).toBeHidden(); - await expect(page.locator(".terminal-container .xterm-helper-textarea")).toBeFocused(); + await expect( + page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container .xterm-helper-textarea'), + ).toBeFocused(); }); test("a failed launch reports its error and leaves the launching card usable", async ({ page }) => { @@ -2854,8 +2856,17 @@ test.describe("workspace launcher", () => { ).toBeVisible(); }); - test("shows launch choices without attaching a terminal in an empty workspace", async ({ page }) => { + test("shows launch choices without launching a runtime session in an empty workspace", async ({ page }) => { const terminalSockets: string[] = []; + const sessionLaunches: string[] = []; + page.on("request", (request) => { + if ( + request.method() === "POST" && + new URL(request.url()).pathname === "/api/v1/workspaces/ws-123/runtime/sessions" + ) { + sessionLaunches.push(request.url()); + } + }); page.on("websocket", (socket) => { const url = socket.url(); if (url.includes("/terminal")) { @@ -2875,7 +2886,11 @@ test.describe("workspace launcher", () => { }), ).toBeVisible(); await expect(page.getByText("Plain shell")).toHaveCount(0); - await expect.poll(() => terminalSockets.length).toBe(0); + await expect + .poll(() => terminalSockets.map((url) => new URL(url).pathname)) + .toContain("/ws/v1/workspaces/ws-123/terminal"); + expect(terminalSockets.filter((url) => url.includes("/runtime/sessions/"))).toHaveLength(0); + expect(sessionLaunches).toHaveLength(0); }); test("shows a restored runtime session immediately", async ({ page }) => { @@ -2918,7 +2933,7 @@ test.describe("workspace launcher", () => { const tabs = page.getByRole("region", { name: "Workflow panes" }); await expect(tabs.getByRole("tab", { name: "Codex" })).toBeVisible(); - await expect(page.locator(".terminal-container")).toBeVisible(); + await expect(page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container')).toBeVisible(); await expect .poll(async () => { const urls = await page.evaluate(() => @@ -2968,7 +2983,7 @@ test.describe("workspace launcher", () => { await workflow.getByRole("button", { name: "Move Codex to terminal" }).click(); await expect(workflow.getByRole("tab", { name: "Terminal" })).toHaveAttribute("aria-selected", "true"); - await expect(page.locator(".tabbed-panel-leaf .terminal-container")).toBeVisible(); + await expect(workflow.locator('[data-pane-key="terminal"] .terminal-container')).toBeVisible(); }); test("keeps a closed top-docked terminal reachable when terminal sessions exist", async ({ page }) => { @@ -3001,14 +3016,20 @@ test.describe("workspace launcher", () => { const terminalTab = workflow.getByRole("tab", { name: "Terminal", }); + const workspaceTab = workflow.getByRole("tab", { name: "Workspace", exact: true }); + const terminalPane = workflow.locator('[data-pane-key="terminal"]'); + await expect(workspaceTab).toHaveAttribute("aria-selected", "true"); + await expect(workflow.locator('[data-pane-key="home"] .terminal-container')).toBeVisible(); await expect(terminalTab).toBeVisible(); - await expect(terminalTab).toHaveAttribute("aria-selected", "true"); - await expect(page.locator(".tabbed-panel-leaf .terminal-container")).toHaveCount(0); + await expect(terminalTab).toHaveAttribute("aria-selected", "false"); + await expect(terminalPane.locator(".terminal-container")).toHaveCount(0); - await workflow.getByRole("button", { name: "Open terminal panel", exact: true }).click(); + await terminalTab.click(); + await expect(workspaceTab).toHaveAttribute("aria-selected", "false"); await expect(terminalTab).toHaveAttribute("aria-selected", "true"); - await expect(page.locator(".tabbed-panel-leaf .terminal-container")).toBeVisible(); + await expect(terminalPane.getByRole("button", { name: "Close terminal panel", exact: true }).first()).toBeVisible(); + await expect(terminalPane.locator(".terminal-container")).toBeVisible(); }); test("applies a workflow preset that restores the Shell workflow tab", async ({ page }) => { @@ -3031,7 +3052,7 @@ test.describe("workspace launcher", () => { name: "Workflow panes", }); await expect(workflow.getByRole("tab", { name: "Shell" })).toHaveAttribute("aria-selected", "true"); - await expect(page.locator(".tabbed-panel-leaf .terminal-container")).toBeVisible(); + await expect(workflow.locator('[data-pane-key="session:ws-123:plain_shell"] .terminal-container')).toBeVisible(); }); test("renders workflow panes flush with the workspace stage", async ({ page }) => { @@ -3364,7 +3385,7 @@ test.describe("workspace launcher", () => { const tabs = page.getByRole("region", { name: "Workflow panes" }); await expect(tabs.getByRole("tab", { name: "Codex" })).toBeVisible(); - await expect(page.locator(".terminal-container")).toBeVisible(); + await expect(page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container')).toBeVisible(); }); test("xterm workspace terminal sends resize frames after viewport changes", async ({ page }) => { @@ -3450,7 +3471,7 @@ test.describe("workspace launcher", () => { await expect(launchTarget).toBeVisible(); await launchTarget.click(); - await expect(page.locator(".terminal-container .xterm")).toBeVisible(); + await expect(page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container .xterm')).toBeVisible(); await page.evaluate(() => { for (const socket of ( window as unknown as { @@ -3470,18 +3491,21 @@ test.describe("workspace launcher", () => { window as unknown as { __kenn_forgeRecordedTerminalSockets: Array<{ sent: unknown[]; + url: string; }>; } - ).__kenn_forgeRecordedTerminalSockets.some((socket) => - socket.sent.some((frame) => { - if (typeof frame !== "string") return false; - try { - return JSON.parse(frame).type === "claim_resize"; - } catch { - return false; - } - }), - ), + ).__kenn_forgeRecordedTerminalSockets + .filter((socket) => socket.url.includes("/runtime/sessions/ws-123%3Acodex/terminal")) + .some((socket) => + socket.sent.some((frame) => { + if (typeof frame !== "string") return false; + try { + return JSON.parse(frame).type === "claim_resize"; + } catch { + return false; + } + }), + ), ), ) .toBe(true); @@ -3507,19 +3531,22 @@ test.describe("workspace launcher", () => { window as unknown as { __kenn_forgeRecordedTerminalSockets: Array<{ sent: unknown[]; + url: string; }>; } - ).__kenn_forgeRecordedTerminalSockets.some((socket) => - socket.sent.some((frame) => { - if (typeof frame !== "string") return false; - try { - const type = JSON.parse(frame).type; - return type === "resize" || type === "claim_resize"; - } catch { - return false; - } - }), - ), + ).__kenn_forgeRecordedTerminalSockets + .filter((socket) => socket.url.includes("/runtime/sessions/ws-123%3Acodex/terminal")) + .some((socket) => + socket.sent.some((frame) => { + if (typeof frame !== "string") return false; + try { + const type = JSON.parse(frame).type; + return type === "resize" || type === "claim_resize"; + } catch { + return false; + } + }), + ), ), ) .toBe(true); @@ -3596,7 +3623,7 @@ test.describe("workspace launcher", () => { }); await page.getByRole("button", { name: "Codex" }).click(); - await expect(page.locator(".terminal-container .xterm")).toBeVisible(); + await expect(page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container .xterm')).toBeVisible(); await expect .poll(() => page.evaluate(() => @@ -3606,7 +3633,9 @@ test.describe("workspace launcher", () => { ), ) .toBe(true); - await expect(page.locator(".terminal-container .xterm-screen canvas")).toHaveCount(0); + await expect( + page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container .xterm-screen canvas'), + ).toHaveCount(0); }); test("xterm workspace terminal normalizes Windows multiline paste as one payload", async ({ page }) => { @@ -3684,7 +3713,7 @@ test.describe("workspace launcher", () => { await expect(launchTarget).toBeVisible(); await launchTarget.click(); - await expect(page.locator(".terminal-container .xterm")).toBeVisible(); + await expect(page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container .xterm')).toBeVisible(); await page.evaluate(() => { for (const socket of ( window as unknown as { @@ -3697,7 +3726,7 @@ test.describe("workspace launcher", () => { } }); - const terminal = page.locator(".terminal-container").first(); + const terminal = page.locator('[data-pane-key="session:ws-123:codex"] .terminal-container'); await terminal.evaluate((element) => { const event = new Event("paste", { bubbles: true, @@ -3719,9 +3748,11 @@ test.describe("workspace launcher", () => { window as unknown as { __kenn_forgeRecordedTerminalSockets: Array<{ sent: unknown[]; + url: string; }>; } ).__kenn_forgeRecordedTerminalSockets + .filter((socket) => socket.url.includes("/runtime/sessions/ws-123%3Acodex/terminal")) .flatMap((socket) => socket.sent) .map((frame) => (Array.isArray(frame) ? decoder.decode(new Uint8Array(frame)) : frame)); }), diff --git a/internal/terminal/handler.go b/internal/terminal/handler.go index 9b46bbca13..49dca5b1df 100644 --- a/internal/terminal/handler.go +++ b/internal/terminal/handler.go @@ -35,7 +35,13 @@ type Handler struct { Typed func(workspaceID string) mu sync.Mutex - active map[string]int + active map[string]*terminalSlot +} + +// Attachments share the running process; idle stop must exclude every attachment. +type terminalSlot struct { + attachments int + stopping bool } func (h *Handler) ServeHTTP( @@ -106,7 +112,7 @@ func (h *Handler) ServeHTTP( "rows", rows, ) - releaseTerminal, err := h.claimTerminalSlot(id) + releaseTerminal, err := h.claimTerminalSlot(id, false) if err != nil { logWebsocketDebug( "workspace terminal rejected: slot unavailable", @@ -454,7 +460,7 @@ func writeTerminalExit(conn *websocket.Conn, exitCode int) { // StopUnattachedTerminal claims the workspace slot so an attach cannot restart it mid-pass. func (h *Handler) StopUnattachedTerminal(ctx context.Context, ws *db.Workspace) error { - release, err := h.claimTerminalSlot(ws.ID) + release, err := h.claimTerminalSlot(ws.ID, true) if err != nil { return nil } @@ -463,38 +469,49 @@ func (h *Handler) StopUnattachedTerminal(ctx context.Context, ws *db.Workspace) } func (h *Handler) claimTerminalSlot( - id string, + id string, stopping bool, ) (func(), error) { h.mu.Lock() defer h.mu.Unlock() if h.active == nil { - h.active = make(map[string]int) + h.active = make(map[string]*terminalSlot) + } + slot := h.active[id] + if slot == nil { + slot = &terminalSlot{} } - if h.active[id] > 0 { + if slot.stopping || (stopping && slot.attachments > 0) { return nil, errors.New("workspace terminal already active") } - h.active[id]++ - active := h.active[id] + slot.stopping = stopping + if !stopping { + slot.attachments++ + } + h.active[id] = slot logWebsocketDebug( "workspace terminal slot claimed", "workspace_id", id, - "active", active, + "active", slot.attachments, + "stopping", slot.stopping, ) var once sync.Once return func() { once.Do(func() { h.mu.Lock() defer h.mu.Unlock() - h.active[id]-- - active := h.active[id] - if active <= 0 { + if stopping { + slot.stopping = false + } else { + slot.attachments-- + } + if slot.attachments == 0 && !slot.stopping { delete(h.active, id) - active = 0 } logWebsocketDebug( "workspace terminal slot released", "workspace_id", id, - "active", active, + "active", slot.attachments, + "stopping", slot.stopping, ) }) }, nil diff --git a/internal/terminal/handler_test.go b/internal/terminal/handler_test.go index d6f6cb0092..5fa78ce0c2 100644 --- a/internal/terminal/handler_test.go +++ b/internal/terminal/handler_test.go @@ -79,25 +79,39 @@ func TestHandlerWorkspaceNotReady(t *testing.T) { assert.Contains(rec.Body.String(), "not ready") } -func TestHandlerRejectsConcurrentWorkspaceTerminals(t *testing.T) { +func TestHandlerSharesAttachmentsAndExcludesIdleStop(t *testing.T) { assert := assert.New(t) require := require.New(t) - h := &Handler{} - release, err := h.claimTerminalSlot("ws-1") + phone, err := h.claimTerminalSlot("ws-1", false) + require.NoError(err) + desktop, err := h.claimTerminalSlot("ws-1", false) require.NoError(err) - assert.NotNil(release) + assert.Equal(2, h.active["ws-1"].attachments) - release2, err := h.claimTerminalSlot("ws-1") + stop, err := h.claimTerminalSlot("ws-1", true) require.Error(err) - assert.Nil(release2) - - release() - - release3, err := h.claimTerminalSlot("ws-1") + assert.Nil(stop) + phone() + phone() + assert.Equal(1, h.active["ws-1"].attachments, "release is idempotent") + stop, err = h.claimTerminalSlot("ws-1", true) + require.Error(err) + assert.Nil(stop, "one remaining attachment still prevents idle stop") + desktop() + assert.Empty(h.active) + stop, err = h.claimTerminalSlot("ws-1", true) + require.NoError(err) + attach, err := h.claimTerminalSlot("ws-1", false) + require.Error(err) + assert.Nil(attach) + stop() + stop() + assert.Empty(h.active) + reattach, err := h.claimTerminalSlot("ws-1", false) require.NoError(err) - assert.NotNil(release3) - release3() + reattach() + assert.Empty(h.active) } type blockingStopPtyOwnerClient struct { @@ -138,17 +152,17 @@ func TestStopUnattachedTerminalReservesOnlyWorkspaceSlot(t *testing.T) { require.True(h.mu.TryLock(), "stopping a terminal must release the shared admission lock") h.mu.Unlock() - release, err := h.claimTerminalSlot(ws.ID) + release, err := h.claimTerminalSlot(ws.ID, false) require.Error(err) require.Nil(release) - releaseOther, err := h.claimTerminalSlot("ws-2") + releaseOther, err := h.claimTerminalSlot("ws-2", false) require.NoError(err) releaseOther() require.NoError(h.StopUnattachedTerminal(t.Context(), ws)) unblock() require.NoError(<-done) - release, err = h.claimTerminalSlot(ws.ID) + release, err = h.claimTerminalSlot(ws.ID, false) require.NoError(err) release() } @@ -222,10 +236,10 @@ func TestHandlerAttachesPtyOwnerTerminal(t *testing.T) { server := httptest.NewServer(mux) t.Cleanup(server.Close) + terminalURL := "ws" + strings.TrimPrefix(server.URL, "http") + + "/api/v1/workspaces/" + ws.ID + "/terminal" conn, resp, err := websocket.Dial( - t.Context(), - "ws"+strings.TrimPrefix(server.URL, "http")+ - "/api/v1/workspaces/"+ws.ID+"/terminal", + t.Context(), terminalURL, &websocket.DialOptions{ CompressionMode: websocket.CompressionContextTakeover, }, @@ -241,6 +255,10 @@ func TestHandlerAttachesPtyOwnerTerminal(t *testing.T) { ) require.Contains(readWebSocketUntil(t, conn, "ready"), "ready") + second, _, err := websocket.Dial(t.Context(), terminalURL, nil) + require.NoError(err) + defer second.Close(websocket.StatusNormalClosure, "done") + require.Contains(readWebSocketUntil(t, second, "ready"), "ready") require.NoError(conn.Write( t.Context(), websocket.MessageText, []byte(terminalwebsocket.HeartbeatMessage), @@ -264,6 +282,11 @@ func TestHandlerAttachesPtyOwnerTerminal(t *testing.T) { []byte("printf 'got:hello size:'; stty size\n"), )) require.Contains(readWebSocketUntil(t, conn, "got:hello size:33 101"), "got:hello size:33 101") + require.Contains(readWebSocketUntil(t, second, "got:hello size:33 101"), "got:hello size:33 101") + require.NoError(conn.Close(websocket.StatusNormalClosure, "phone detached")) + require.NoError(second.Write(t.Context(), websocket.MessageBinary, + []byte("printf 'after:%s\\n' first-close\n"))) + require.Contains(readWebSocketUntil(t, second, "after:first-close"), "after:first-close") } func TestHandleControlAppliesResizeClaim(t *testing.T) { @@ -379,3 +402,32 @@ func readWebSocketUntil( } } } + +func TestHandlerDesktopCanAttachWhilePhoneOwnsWorkspace(t *testing.T) { + require := require.New(t) + d := openTestDB(t) + mgr := workspacetest.NewManager(t, d, t.TempDir()) + ws := &workspace.Workspace{ + ID: "shared-workspace", Platform: "github", PlatformHost: "github.com", + RepoOwner: "acme", RepoName: "widget", + ItemType: db.WorkspaceItemTypePullRequest, ItemNumber: 42, + GitHeadRef: "feature/test", WorktreePath: t.TempDir(), + TmuxSession: "forge-shared-workspace", Status: "ready", TerminalBackend: workspace.TerminalBackendTmux, + } + require.NoError(d.InsertWorkspace(t.Context(), ws)) + handler := &Handler{Workspaces: mgr} + // The phone already owns a claim. Exercise desktop admission without + // needing a websocket or subprocess; rejection precedes both backend paths. + releasePhone, err := handler.claimTerminalSlot(ws.ID, false) + require.NoError(err) + defer releasePhone() + request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, + "/ws/v1/workspaces/"+ws.ID+"/terminal", nil) + request.SetPathValue("id", ws.ID) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + require.Equal(http.StatusUpgradeRequired, recorder.Code, + "desktop must reach websocket upgrade while phone remains attached: %s", recorder.Body.String()) + require.Contains(recorder.Body.String(), `Connection header "" does not contain Upgrade`) + require.Equal(1, handler.active[ws.ID].attachments, "the rejected handshake releases only its own claim") +} From cbc93ad2a8ebcc43ac442b4dea924a35c84d3487 Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:49:51 -0700 Subject: [PATCH 2/7] fix(workspaces): preserve shared terminals during navigation Avoid a workflow-slot teardown error when switching workspaces. Start a new base terminal only while its workspace is visible, while retaining an already mounted connection across navigation. Preserve the shared PTY owner's size when an inactive client attaches without dimensions. Keep initial size defaults for new tmux clients. Update existing terminal tests and fixtures for the separate Workspace tab, retaining their input, clipboard, focus and geometry assertions. Live browser and terminal integration checks were not run locally. Refs #1954. Co-authored-by: GPT-6 Astra --- ...erminalView.host-visible.browser.svelte.ts | 7 ++ ...TerminalView.layout-flip.browser.svelte.ts | 16 +++-- .../terminal/WorkspaceTerminalView.svelte | 7 +- .../terminal/WorkspaceTerminalView.test.ts | 69 +++++++++++++++++++ .../00-inline-workspace-continuity.spec.ts | 8 ++- .../00-settings-terminal-font.spec.ts | 21 +++--- .../00-tmux-browser-clipboard.spec.ts | 3 +- .../00-workspace-tab-persistence.spec.ts | 4 +- .../e2e-full/workspace-compact-header.spec.ts | 8 ++- frontend/tests/e2e/workspace-sidebar.spec.ts | 21 +++--- .../workspacetest/pty_owner_e2e_test.go | 34 ++++++--- internal/terminal/bridge.go | 4 +- internal/terminal/handler.go | 8 +++ internal/terminal/handler_test.go | 26 ++++--- 14 files changed, 185 insertions(+), 51 deletions(-) diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.host-visible.browser.svelte.ts b/frontend/src/lib/components/terminal/WorkspaceTerminalView.host-visible.browser.svelte.ts index 62f80500f6..d83ad3bfc7 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.host-visible.browser.svelte.ts +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.host-visible.browser.svelte.ts @@ -552,6 +552,7 @@ describe("WorkspaceTerminalView hostVisible", () => { // reads settingsStore.getTerminalSettings() at initialization, so the // main subtree cannot mount without a settings store on STORES_KEY. const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, @@ -626,6 +627,7 @@ describe("WorkspaceTerminalView hostVisible", () => { globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, @@ -724,6 +726,7 @@ describe("WorkspaceTerminalView hostVisible", () => { globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, @@ -795,6 +798,7 @@ describe("WorkspaceTerminalView hostVisible", () => { // (inside the options popover) with livePreview, which writes settings // back through the store — so the stub needs a setter too. const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, @@ -888,6 +892,7 @@ describe("WorkspaceTerminalView hostVisible", () => { globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => terminalSettings.font_size, getQuickActions: () => [], getTerminalSettings: () => terminalSettings, @@ -956,6 +961,7 @@ describe("WorkspaceTerminalView hostVisible", () => { globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => terminalSettings.font_size, getQuickActions: () => [], getTerminalSettings: () => terminalSettings, @@ -1009,6 +1015,7 @@ describe("WorkspaceTerminalView hostVisible", () => { globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.layout-flip.browser.svelte.ts b/frontend/src/lib/components/terminal/WorkspaceTerminalView.layout-flip.browser.svelte.ts index 27dc57c11e..b364129e10 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.layout-flip.browser.svelte.ts +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.layout-flip.browser.svelte.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { Effect } from "effect"; import { DEFAULT_TERMINAL_SETTINGS } from "../../api/types.js"; import { makeAppRuntime } from "../../app/runtime.js"; +import { createSettingsStore } from "../../stores/settings.svelte.js"; import { STORES_KEY } from "../../context.js"; import { createMockApiFetch, jsonResponse, type MockRouteOverride } from "../../../test/mockApiFetch.js"; @@ -90,10 +91,10 @@ describe("WorkspaceTerminalView layout flip", () => { globalThis.fetch = api.fetch; globalThis.EventSource = NoopEventSource as unknown as typeof EventSource; - // TerminalOptionsMenu (always present in the ready-workspace toolbar) - // reads settingsStore.getTerminalSettings() at initialization, so the - // main subtree cannot mount without a settings store on STORES_KEY. + // Include the terminal settings read by the shared base terminal as well + // as the toolbar's fixture-specific actions. const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [{ label: "Review", agent: "codex", prompt: "Review this change" }], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, @@ -107,14 +108,19 @@ describe("WorkspaceTerminalView layout flip", () => { }); try { + const workspaceTab = screen.getByRole("tab", { name: "Workspace", exact: true }); + await expect.element(workspaceTab).toBeVisible(); + const launcher = page.getByRole("dialog", { name: "Launch a session", exact: true }); + await expect.element(launcher).toBeVisible(); + await launcher.getByRole("button", { name: "Close", exact: true }).click(); const info = screen.getByRole("button", { name: "Workspace info", exact: true }); const launch = screen.getByRole("button", { name: "Launch", exact: true }); const quickActions = screen.getByRole("button", { name: "Quick actions", exact: true }); const presets = screen.getByRole("button", { name: "Workflow presets", exact: true }); await expect.element(info).toBeVisible(); for (const [control, anchor] of [ - [launch, info], - [quickActions, info], + [launch, workspaceTab], + [quickActions, workspaceTab], [presets, screen.getByRole("button", { name: "Delete", exact: true })], ]) { const titleRow = anchor!.element().getBoundingClientRect(); diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte index 9e7596f4b4..b5e5c9874b 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte @@ -1652,7 +1652,7 @@ $effect(() => { if (!workflowLive) return; const live = new Set(runtimeSessions.map((session) => session.key)); - if (baseTerminalHostKey !== null) live.add(workspaceBaseSessionKey(workspaceId)); + if (baseTerminalHostKey !== null && hostVisible) live.add(workspaceBaseSessionKey(workspaceId)); const showing = activeWorkflowSessionKeys(renderedWorkflowTree).filter((key) => live.has(key)); // Untracked: mountSessionTerminal writes the mounted list that the tree's own // descriptors read, and it is a no-op for a session already mounted, so this @@ -5290,9 +5290,10 @@ {@const session = runtimeSessions.find( (candidate) => candidate.key === sessionKey, )} - {#if session && isSessionTerminalMounted(session.key)} + {@const hostKey = session ? sessionHostKeyFor(session) : null} + {#if session && hostKey !== null && isSessionTerminalMounted(session.key)} {/if} diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts b/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts index 493adb5b07..b14d677bb0 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts @@ -866,6 +866,75 @@ describe("WorkspaceTerminalView", () => { vi.unstubAllGlobals(); }); + it("does not start a base terminal while an unused embedded workspace is parked", async () => { + mocks.getWorkspaceRuntime.mockResolvedValue({ launch_targets: [], sessions: [] }); + claimForPrs(); + noteWorkspacePaneRendered("prs"); + const view = render(WorkspaceTerminalView, { + props: { workspaceId: "ws-1", paneSurface: "prs", hostVisible: true }, + }); + await waitFor(() => expect(mocks.getWorkspaceRuntime).toHaveBeenCalled()); + await waitFor(() => expect(hostedWorkspaceControls()?.workspaceKey).toContain("ws-1")); + expect(sockets).toHaveLength(0); + + await view.rerender({ workspaceId: "ws-1", paneSurface: undefined, hostVisible: false }); + await screen.findByRole("tab", { name: "Workspace", exact: true }); + await tick(); + expect(sockets).toHaveLength(0); + expect(mountedSessions()).toHaveLength(0); + + await view.rerender({ workspaceId: "ws-1", hostVisible: true }); + await waitFor(() => expect(sockets).toHaveLength(1)); + const base = sockets[0]!; + expect(new URL(base.url).pathname).toBe("/ws/v1/workspaces/ws-1/terminal"); + base.onopen(); + await view.rerender({ workspaceId: "ws-1", hostVisible: false }); + await view.rerender({ workspaceId: "ws-1", hostVisible: true }); + expect(sockets).toHaveLength(1); + expect(base.close).not.toHaveBeenCalled(); + await view.rerender({ workspaceId: "ws-1", paneSurface: "prs", hostVisible: true }); + await waitFor(() => expect(mountedSessions()).toHaveLength(0)); + await view.rerender({ workspaceId: "ws-1", paneSurface: undefined, hostVisible: false }); + await tick(); + expect(mountedSessions()).toHaveLength(0); + expect(sockets).toHaveLength(1); + expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); + }); + + it("keeps workflow slots renderable through repeated workspace switches", async () => { + serveAnyWorkspace(); + claimForPrs(); + noteWorkspacePaneRendered("prs"); + mocks.getWorkspaceRuntime.mockImplementation(async (id: string) => ({ + launch_targets: [], + sessions: [runningSession, reviewerSession].map((session) => ({ + ...session, + key: `${id}:${session.target_key}`, + workspace_id: id, + })), + })); + const view = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1", paneSurface: "prs" } }); + const expectSession = async (id: string) => { + await waitFor(() => + expect(screen.getByRole("tab", { name: "Helper" }).getAttribute("aria-selected")).toBe("true"), + ); + await waitFor(() => + expect(document.querySelector(`[data-pane-key="session:${id}:helper"] [data-session-host]`)).not.toBeNull(), + ); + }; + await expectSession("ws-1"); + await waitFor(() => expect(runtimeSockets()).toHaveLength(1)); + await view.rerender({ workspaceId: "ws-1", paneSurface: undefined, hostVisible: false }); + await view.rerender({ workspaceId: "ws-2", paneSurface: "prs", hostVisible: true }); + await expectSession("ws-2"); + await waitFor(() => expect(runtimeSockets()).toHaveLength(2)); + await view.rerender({ workspaceId: "ws-2", paneSurface: undefined, hostVisible: false }); + await view.rerender({ workspaceId: "ws-1", paneSurface: "prs", hostVisible: true }); + await expectSession("ws-1"); + expect(runtimeSockets()).toHaveLength(2); + expect(runtimeSockets().every((socket) => socket.close.mock.calls.length === 0)).toBe(true); + }); + it("uses terminal zoom after focusing Workspace beside a docked chat", async () => { const chat = { ...reviewerSession, kind: "acp", display_region: "terminal" }; mocks.getWorkspaceRuntime.mockResolvedValue({ launch_targets: [], sessions: [chat] }); diff --git a/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts b/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts index 501a8d0997..883ed03b3a 100644 --- a/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts +++ b/frontend/tests/e2e-full/00-inline-workspace-continuity.spec.ts @@ -93,6 +93,8 @@ function hasCommand(command: string, args: string[] = ["--version"]): boolean { function observeTerminalControlFrames(page: Page): TerminalControlFrame[] { const frames: TerminalControlFrame[] = []; page.on("websocket", (socket) => { + const pathname = new URL(socket.url()).pathname; + if (!pathname.includes("/runtime/sessions/") || !pathname.endsWith("/terminal")) return; socket.on("framesent", ({ payload }) => { if (typeof payload !== "string") return; try { @@ -977,7 +979,11 @@ test.describe("inline workspace pane continuity", () => { ).length; await workflow.getByRole("button", { name: "Close Terminal", exact: true }).click(); - await expect(workflow.getByRole("button", { name: "Open terminal panel", exact: true })).toBeVisible(); + await expect(terminalTab).toHaveAttribute("aria-selected", "false"); + await expect(workflow.getByRole("tab", { name: "Workspace", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ); await expect .poll(() => controlFrames.filter((frame) => frame.type === "resize_active" && frame.active === false).length, { timeout: 15_000, diff --git a/frontend/tests/e2e-full/00-settings-terminal-font.spec.ts b/frontend/tests/e2e-full/00-settings-terminal-font.spec.ts index 46c8572021..a933175991 100644 --- a/frontend/tests/e2e-full/00-settings-terminal-font.spec.ts +++ b/frontend/tests/e2e-full/00-settings-terminal-font.spec.ts @@ -3,7 +3,7 @@ // that start near the end of the run stretch the suite tail. import { execFileSync } from "node:child_process"; -import { expect, request as playwrightRequest, test, type APIRequestContext, type Page } from "@playwright/test"; +import { expect, request as playwrightRequest, test, type APIRequestContext, type Locator } from "@playwright/test"; import { startIsolatedE2EServer, startIsolatedWorkspaceE2EServer, type IsolatedE2EServer } from "./support/e2eServer"; import { openSettingsPanel } from "./support/settingsPanel"; @@ -49,8 +49,8 @@ async function waitForWorkspaceReady( throw new Error(`workspace ${workspaceId} did not become ready`); } -async function terminalScreenSizeKey(page: Page): Promise { - return await page.locator(".terminal-container .xterm-screen").evaluate((element) => { +async function terminalScreenSizeKey(terminal: Locator): Promise { + return await terminal.locator(".xterm-screen").evaluate((element) => { const style = getComputedStyle(element); return `${style.width}x${style.height}`; }); @@ -231,9 +231,10 @@ test.describe("terminal options popover", () => { await page.goto(`${workspaceServer.info.base_url}/terminal/${workspace.id}`); await page.getByRole("button", { name: "Open terminal panel" }).click(); - await expect(page.locator(".terminal-container .xterm-screen")).toBeVisible(); - await expect.poll(() => terminalScreenSizeKey(page)).not.toBe("0pxx0px"); - const initialScreenSize = await terminalScreenSizeKey(page); + const terminal = page.getByRole("region", { name: "Terminal panel" }).locator(".terminal-container"); + await expect(terminal.locator(".xterm-screen")).toBeVisible(); + await expect.poll(() => terminalScreenSizeKey(terminal)).not.toBe("0pxx0px"); + const initialScreenSize = await terminalScreenSizeKey(terminal); await page.getByRole("button", { name: "Terminal options" }).click(); const terminalOptionsDialog = page.getByRole("dialog", { name: "Terminal options" }); @@ -242,15 +243,15 @@ test.describe("terminal options popover", () => { await expect(terminalOptionsDialog.getByRole("button", { name: "Save visible modes" })).toHaveCount(0); await terminalOptionsDialog.getByRole("spinbutton", { name: "Font size", exact: true }).fill("20"); await expect(page.getByRole("button", { name: "Reset terminal font size" })).toHaveText("20px"); - await expect.poll(() => terminalScreenSizeKey(page)).not.toBe(initialScreenSize); + await expect.poll(() => terminalScreenSizeKey(terminal)).not.toBe(initialScreenSize); await page.keyboard.press("Escape"); await expect(page.getByRole("dialog", { name: "Terminal options" })).toBeHidden(); - await expect.poll(() => terminalScreenSizeKey(page)).toBe(initialScreenSize); + await expect.poll(() => terminalScreenSizeKey(terminal)).toBe(initialScreenSize); await page.getByRole("button", { name: "Terminal options" }).click(); await terminalOptionsDialog.getByRole("spinbutton", { name: "Font size", exact: true }).fill("18"); - await expect.poll(() => terminalScreenSizeKey(page)).not.toBe(initialScreenSize); + await expect.poll(() => terminalScreenSizeKey(terminal)).not.toBe(initialScreenSize); let releaseSettingsSave: (() => void) | undefined; await page.route("**/api/v1/settings", async (route) => { if (route.request().method() === "PUT" && releaseSettingsSave === undefined) { @@ -283,7 +284,7 @@ test.describe("terminal options popover", () => { .toBe(18); await page.keyboard.press("Escape"); - await expect.poll(() => terminalScreenSizeKey(page)).not.toBe(initialScreenSize); + await expect.poll(() => terminalScreenSizeKey(terminal)).not.toBe(initialScreenSize); } finally { await workspaceApi?.dispose(); await workspaceServer?.stop(); diff --git a/frontend/tests/e2e-full/00-tmux-browser-clipboard.spec.ts b/frontend/tests/e2e-full/00-tmux-browser-clipboard.spec.ts index b2ffda029b..6058bbceac 100644 --- a/frontend/tests/e2e-full/00-tmux-browser-clipboard.spec.ts +++ b/frontend/tests/e2e-full/00-tmux-browser-clipboard.spec.ts @@ -300,6 +300,8 @@ function observeTerminalOutput(page: Page): { closed: boolean; }> = []; page.on("websocket", (socket) => { + const socketUrl = new URL(socket.url()); + if (!socketUrl.pathname.includes("/runtime/sessions/") || !socketUrl.pathname.endsWith("/terminal")) return; const stream = { output: "", input: "", @@ -309,7 +311,6 @@ function observeTerminalOutput(page: Page): { closed: false, }; streams.push(stream); - const socketUrl = new URL(socket.url()); const initialColumns = Number.parseInt(socketUrl.searchParams.get("cols") ?? "", 10); const initialRows = Number.parseInt(socketUrl.searchParams.get("rows") ?? "", 10); if (Number.isFinite(initialColumns) && initialColumns > 0) { diff --git a/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts b/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts index e389bba96b..86cd9591d4 100644 --- a/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts @@ -155,14 +155,14 @@ test.describe("workspace tab persistence", () => { await page.goto(`${isolatedServer.info.base_url}/terminal/${createdWorkspace.id}`); const workflow = page.getByRole("region", { name: "Workflow panes" }); - const panes = workflow.locator(".tabbed-panel-tab-panel"); + const panes = workflow.locator('[data-pane-key="terminal"]'); const terminalTab = workflow.getByRole("tab", { name: "Terminal" }); await expect(page.getByRole("region", { name: "Session launcher" })).toBeVisible(); await openTerminalWorkflowTab(page); await expect(panes).toHaveCount(1); await expect(terminalTab).toHaveAttribute("aria-selected", "true"); - const terminalPane = workflow.locator(".tabbed-panel-tab-panel.active"); + const terminalPane = panes; await terminalPane.evaluate((el) => el.setAttribute("data-test-terminal-id", "preserved")); await page.getByRole("button", { name: "Workspace info", exact: true }).click(); diff --git a/frontend/tests/e2e-full/workspace-compact-header.spec.ts b/frontend/tests/e2e-full/workspace-compact-header.spec.ts index 4829feef63..81dc747da4 100644 --- a/frontend/tests/e2e-full/workspace-compact-header.spec.ts +++ b/frontend/tests/e2e-full/workspace-compact-header.spec.ts @@ -21,7 +21,13 @@ test("narrow workspace headers leave room for the terminal and keep controls rea const bounds = await header.boundingBox(); expect(bounds!.height).toBeLessThanOrEqual(56); expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(600); - await expect(header.getByRole("button", { name: "Launch", exact: true })).toBeVisible(); + await expect( + page.getByRole("tablist", { name: "Workflow group tabs" }).getByRole("button", { name: "Launch", exact: true }), + ).toBeVisible(); + await page + .getByRole("dialog", { name: "Launch a session" }) + .getByRole("button", { name: "Close", exact: true }) + .click(); await page.screenshot({ path: test.info().outputPath("compact-workspace-header.png") }); await controls.click(); const menu = page.getByRole("dialog", { name: "Workspace controls" }); diff --git a/frontend/tests/e2e/workspace-sidebar.spec.ts b/frontend/tests/e2e/workspace-sidebar.spec.ts index 0c8c499108..55583cf1c0 100644 --- a/frontend/tests/e2e/workspace-sidebar.spec.ts +++ b/frontend/tests/e2e/workspace-sidebar.spec.ts @@ -6382,7 +6382,7 @@ test.describe("delayed-response navigation", () => { await page.goto(`/terminal/${wsA.id}`); // A's session tab should be visible. - await expect(page.locator(".workspace-stage .tabbed-panel-tab-panel")).not.toHaveCount(0); + await expect(page.getByRole("tab", { name: sessionA.label, exact: true })).toBeVisible(); await page .locator(".workspace-list-sidebar .ws-row", { @@ -6390,17 +6390,22 @@ test.describe("delayed-response navigation", () => { }) .click(); - // The header should have moved to B as soon as wsB's - // workspace GET resolves. But because B's runtime fetch is - // still in flight, the workspace stage must show the - // "Loading workspace runtime..." state, not A's session - // panes. + // B's own base terminal remains available while its runtime request + // is held, without exposing A's session tabs or panes. await expect(page.locator(".terminal-main .header-name")).toContainText(wsB.mr_title); - await expect(page.locator(".workspace-stage .state-message")).toContainText("Loading workspace runtime"); + await expect(page.getByRole("tab", { name: "Workspace", exact: true })).toHaveAttribute("aria-selected", "true"); + await expect(page.getByRole("tab", { name: sessionA.label, exact: true })).toHaveCount(0); + await expect(page.locator(`.workspace-stage [data-pane-key="session:${sessionA.key}"]`)).toHaveCount(0); + const runtimeResponse = page.waitForResponse( + (response) => new URL(response.url()).pathname === `/api/v1/workspaces/${wsB.id}/runtime`, + ); releaseBRuntime(); + await runtimeResponse; - // Once B's runtime resolves, the loading state goes away. + // B stays usable after discovery resolves without resurrecting A. + await expect(page.getByRole("tab", { name: "Workspace", exact: true })).toHaveAttribute("aria-selected", "true"); + await expect(page.getByRole("tab", { name: sessionA.label, exact: true })).toHaveCount(0); await expect(page.locator(".workspace-stage .state-message")).toHaveCount(0); }); diff --git a/internal/server/workspacetest/pty_owner_e2e_test.go b/internal/server/workspacetest/pty_owner_e2e_test.go index ccbdea797d..26ebbadfa0 100644 --- a/internal/server/workspacetest/pty_owner_e2e_test.go +++ b/internal/server/workspacetest/pty_owner_e2e_test.go @@ -668,11 +668,10 @@ func TestRustPtyManagerRejectsConcurrentAttachmentsE2E(t *testing.T) { ) } -func TestWorkspacePtyOwnerTerminalRejectsConcurrentAttachmentsE2E(t *testing.T) { +func TestWorkspacePtyOwnerTerminalSharesConcurrentAttachmentsE2E(t *testing.T) { runParallelWorkspacePTYTest(t) require := require.New(t) - assert := assert.New(t) dir := t.TempDir() ptyOwnerDir := filepath.Join(dir, "pty-owner") @@ -693,22 +692,37 @@ func TestWorkspacePtyOwnerTerminalRejectsConcurrentAttachmentsE2E(t *testing.T) ts := httptest.NewServer(fixture.server) t.Cleanup(ts.Close) - first, _, err := workspaceTerminalDialWithQuery(ctx, ts.URL, ws.ID, "") + first, _, err := workspaceTerminalDialWithQuery(ctx, ts.URL, ws.ID, "cols=91&rows=27") require.NoError(err) defer first.Close(websocket.StatusNormalClosure, "done") + workspaceTerminalConnWriteRead( + t, ctx, first, "shared_owner=phone; printf 'owner:%s\\n' \"$shared_owner\"\n", "owner:phone", + ) - second, status, err := workspaceTerminalDialWithQuery(ctx, ts.URL, ws.ID, "") - require.Error(err) - if second != nil { - second.Close(websocket.StatusNormalClosure, "done") - } - assert.Equal(http.StatusConflict, status) + second, _, err := workspaceTerminalDialWithQuery(ctx, ts.URL, ws.ID, "") + require.NoError(err) + defer second.Close(websocket.StatusNormalClosure, "done") + workspaceTerminalConnWriteRead( + t, ctx, second, "printf 'shared:%s\\n' \"$shared_owner\"\n", "shared:phone", + ) + + workspaceTerminalConnWriteRead( + t, ctx, second, "size=$(stty size); printf 'shared-size:%s\\n' \"$size\"\n", "shared-size:27 91", + ) + require.NoError(second.Write(ctx, websocket.MessageText, []byte(`{"type":"claim_resize","cols":100,"rows":32}`))) + workspaceTerminalConnWriteRead( + t, ctx, second, "size=$(stty size); printf 'visible-size:%s\\n' \"$size\"\n", "visible-size:32 100", + ) require.NoError(first.Close(websocket.StatusNormalClosure, "done")) + workspaceTerminalConnWriteRead( + t, ctx, second, "printf 'remaining:%s\\n' \"$shared_owner\"\n", "remaining:phone", + ) + require.NoError(second.Close(websocket.StatusNormalClosure, "done")) third := workspaceTerminalDialEventually(t, ctx, ts.URL, ws.ID) defer third.Close(websocket.StatusNormalClosure, "done") workspaceTerminalConnWriteRead( - t, ctx, third, "printf 'owner-after-close\n'\n", "owner-after-close", + t, ctx, third, "printf 'reopened:%s\\n' \"$shared_owner\"\n", "reopened:phone", ) } diff --git a/internal/terminal/bridge.go b/internal/terminal/bridge.go index 6e4187bf9b..e26b908aaf 100644 --- a/internal/terminal/bridge.go +++ b/internal/terminal/bridge.go @@ -119,8 +119,8 @@ func handleControl(ptmx *os.File, msg *controlMsg) { func parseGeometry(r *http.Request) ptysize.Geometry { return ptysize.Normalize(ptysize.Geometry{ - Cols: parseIntParam(r, "cols", 120), - Rows: parseIntParam(r, "rows", 30), + Cols: parseIntParam(r, "cols", 0), + Rows: parseIntParam(r, "rows", 0), PixelWidth: parseIntParam(r, "pixel_width", 0), PixelHeight: parseIntParam(r, "pixel_height", 0), }) diff --git a/internal/terminal/handler.go b/internal/terminal/handler.go index 49dca5b1df..76d2867420 100644 --- a/internal/terminal/handler.go +++ b/internal/terminal/handler.go @@ -226,6 +226,14 @@ func (h *Handler) ServeHTTP( } defer releaseProc() + // A new tmux client needs a size. A shared PTY owner instead preserves its + // current size when an inactive browser attaches without resize authority. + if geometry.Cols == 0 { + geometry.Cols = 120 + } + if geometry.Rows == 0 { + geometry.Rows = 30 + } winSize := ptysize.Winsize(geometry) ptmx, err := pty.StartWithSize(cmd, winSize) if err != nil { diff --git a/internal/terminal/handler_test.go b/internal/terminal/handler_test.go index 5fa78ce0c2..5741149669 100644 --- a/internal/terminal/handler_test.go +++ b/internal/terminal/handler_test.go @@ -364,14 +364,24 @@ func TestProcessExitCode(t *testing.T) { assert.Equal(-1, processExitCode(errors.New("wait failed"))) } -func TestParseGeometryFallsBack(t *testing.T) { - req := httptest.NewRequestWithContext(t.Context(), - http.MethodGet, "/?cols=bad&rows=0", nil, - ) - geometry := parseGeometry(req) - assert := assert.New(t) - assert.Equal(120, geometry.Cols) - assert.Equal(30, geometry.Rows) +func TestParseGeometryPreservesResizeAuthority(t *testing.T) { + for _, tc := range []struct { + name, query string + cols, rows int + }{ + {name: "inactive attachment"}, + {name: "invalid dimensions", query: "?cols=bad&rows=0"}, + {name: "visible attachment", query: "?cols=91&rows=27", cols: 91, rows: 27}, + {name: "partial dimensions", query: "?cols=91", cols: 91}, + } { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/"+tc.query, nil) + geometry := parseGeometry(req) + assert := assert.New(t) + assert.Equal(tc.cols, geometry.Cols) + assert.Equal(tc.rows, geometry.Rows) + }) + } } func readWebSocketUntil( From a4fde93f9cf9248efa32cc520595472f724ba671 Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:00:15 -0700 Subject: [PATCH 3/7] test(workspaces): focus split hydration coverage Keep the delayed-details case focused on saved split membership, the shared base identity, and avoiding a runtime launch. The existing navigation case covers socket retention across switching and reopening, including a runtime poll and restored Workspace selection. Co-authored-by: GPT-6 Astra --- .../terminal/WorkspaceTerminalView.test.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts b/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts index b14d677bb0..964c5d0f8b 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.test.ts @@ -977,7 +977,7 @@ describe("WorkspaceTerminalView", () => { }); localStorage.setItem("kenn-forge-workspace-active-tab:ws-1", "home"); localStorage.setItem("kenn-forge-workspace-terminal-layout:ws-1", persistedSplitWorkflowLayout(runningSession.key)); - const view = render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); + render(WorkspaceTerminalView, { props: { workspaceId: "ws-1" } }); await waitFor(() => expect(mocks.getWorkspaceRuntime).toHaveBeenCalled()); await waitFor(() => expect(localStorage.getItem("kenn-forge-workspace-terminal-layout:ws-1")).toContain("session:ws-1:helper"), @@ -995,16 +995,6 @@ describe("WorkspaceTerminalView", () => { await waitFor(() => expect(sockets).toHaveLength(2)); const base = sockets.find((socket) => new URL(socket.url).pathname === "/ws/v1/workspaces/ws-1/terminal")!; expect(base).toBeDefined(); - base.onopen(); - await fireEvent.click(screen.getByRole("tab", { name: "Helper" })); - await fireEvent.click(screen.getByRole("tab", { name: "Workspace", exact: true })); - await view.rerender({ workspaceId: "" }); - await view.rerender({ workspaceId: "ws-1" }); - await screen.findByRole("tab", { name: "Workspace", exact: true }); - expect(sockets.filter((socket) => new URL(socket.url).pathname === "/ws/v1/workspaces/ws-1/terminal")).toHaveLength( - 1, - ); - expect(base.close).not.toHaveBeenCalled(); expect(mocks.launchWorkspaceSession).not.toHaveBeenCalled(); }); From ca73762f4fb91611b97f31701df3bc384e40a57f Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:40:48 -0700 Subject: [PATCH 4/7] fix(terminal): share Rust workspace terminals across devices The opt-in Rust owner still rejected a second terminal viewer. Count live attachments so phone and desktop can share input and output without one detach ending the other attachment. Preserve the existing output drain, stop, and post-exit bounds. The socket-free lifecycle regression reproduced the premature exit and now passes. Rust and Go static checks passed. Socket-backed end-to-end validation remains unverified locally because the environment prohibits those fixtures. Co-authored-by: GPT-6 Astra --- .../workspacetest/pty_owner_e2e_test.go | 53 ++++++++++------ rust/pty-manager/src/main.rs | 62 +++++++++++-------- 2 files changed, 71 insertions(+), 44 deletions(-) diff --git a/internal/server/workspacetest/pty_owner_e2e_test.go b/internal/server/workspacetest/pty_owner_e2e_test.go index 26ebbadfa0..9493b00419 100644 --- a/internal/server/workspacetest/pty_owner_e2e_test.go +++ b/internal/server/workspacetest/pty_owner_e2e_test.go @@ -597,15 +597,14 @@ func TestWorkspaceRuntimePlainShellUsesPtyOwnerWhenTmuxUnavailableE2E(t *testing ) } -func TestRustPtyManagerRejectsConcurrentAttachmentsE2E(t *testing.T) { +func TestRustPtyManagerSharesConcurrentAttachmentsE2E(t *testing.T) { if runtime.GOOS == "windows" { - t.Skip("concurrent attach coverage is exercised by the Rust owner tests on Windows") + t.Skip("test fixture uses /bin/sh") } requirePTYAvailable(t) runParallelWorkspacePTYTest(t) require := require.New(t) - assert := assert.New(t) managerPath := buildRustPtyManagerForTest(t) ptyOwnerDir := longRustPtyOwnerDirForTest(t) @@ -644,28 +643,44 @@ func TestRustPtyManagerRejectsConcurrentAttachmentsE2E(t *testing.T) { t.Context(), session, ptysize.Geometry{Cols: 100, Rows: 20}, ) - if second != nil { - second.Close() + require.NoError(err) + defer second.Close() + require.Contains( + readPtyOwnerOutputUntil(t, second.Output, "got:before-second"), + "got:before-second", + ) + for _, input := range []*ptyowner.Attachment{first, second} { + marker := "from-first" + if input == second { + marker = "from-second" + } + require.NoError(input.Write([]byte(marker + "\r"))) + for _, output := range []*ptyowner.Attachment{first, second} { + require.Contains( + readPtyOwnerOutputUntil(t, output.Output, "got:"+marker), + "got:"+marker, + ) + } } - require.Error(err) - assert.Contains(err.Error(), "already has an active attachment") first.Close() - var third *ptyowner.Attachment - require.Eventually(func() bool { - var attachErr error - third, attachErr = client.Attach( - t.Context(), session, - ptysize.Geometry{Cols: 80, Rows: 24}, - ) - return attachErr == nil - }, 2*time.Second, 20*time.Millisecond) - defer third.Close() - require.NoError(third.Write([]byte("after-close\n"))) + require.NoError(second.Write([]byte("after-close\r"))) require.Contains( - readPtyOwnerOutputUntil(t, third.Output, "got:after-close"), + readPtyOwnerOutputUntil(t, second.Output, "got:after-close"), "got:after-close", ) + second.Close() + third, err := client.Attach( + t.Context(), session, + ptysize.Geometry{Cols: 80, Rows: 24}, + ) + require.NoError(err) + defer third.Close() + require.NoError(third.Write([]byte("after-reconnect\r"))) + require.Contains( + readPtyOwnerOutputUntil(t, third.Output, "got:after-reconnect"), + "got:after-reconnect", + ) } func TestWorkspacePtyOwnerTerminalSharesConcurrentAttachmentsE2E(t *testing.T) { diff --git a/rust/pty-manager/src/main.rs b/rust/pty-manager/src/main.rs index 4d8be6169b..b06074cd10 100644 --- a/rust/pty-manager/src/main.rs +++ b/rust/pty-manager/src/main.rs @@ -171,7 +171,7 @@ struct Shared { title_parser: TitleParserState, subscribers: Vec, next_subscriber_id: u64, - attached: bool, + active_attachments: usize, attachment_ended_after_exit: bool, child_reaped: bool, exited: bool, @@ -539,22 +539,7 @@ fn handle_attach( ) -> Result<()> { { let mut shared = runtime.shared.lock().expect("shared poisoned"); - if shared.attached { - drop(shared); - write_response( - &mut stream, - Response { - kind: "error", - ok: false, - error: Some("pty owner already has an active attachment".to_string()), - exit_code: None, - output: Vec::new(), - title: None, - }, - )?; - return Ok(()); - } - shared.attached = true; + shared.active_attachments += 1; } let mut active_attachment = ActiveAttachment { shared: Arc::clone(&runtime.shared), @@ -951,22 +936,22 @@ fn add_subscriber(shared: &mut Shared, tx: mpsc::SyncSender>) -> u64 { id } -// After the child exits, keep serving so the attached client can drain its +// After the child exits, keep serving so attached clients can drain their // output and exit frame, or a client that reconnects can still collect them. -// Leave once such an attachment ends, or after a bounded linger, matching the +// Leave once all such attachments end, or after a bounded linger, matching the // Go owner's waitAfterNaturalExit. After a stop, wait (bounded) for the killed // child's exit to close the output so the attached client gets its exit frame. fn owner_should_exit(shared: &Arc>, completed_at: &mut Option) -> bool { let shared = shared.lock().expect("shared poisoned"); if let Some(stop_requested_at) = shared.stop_requested_at { - return (shared.output_closed && !shared.attached) + return (shared.output_closed && shared.active_attachments == 0) || stop_requested_at.elapsed() >= OWNER_STOP_TIMEOUT; } if !shared.output_closed { return false; } let completed_at = *completed_at.get_or_insert_with(Instant::now); - (!shared.attached && shared.attachment_ended_after_exit) + (shared.active_attachments == 0 && shared.attachment_ended_after_exit) || completed_at.elapsed() >= OWNER_POST_EXIT_LINGER } @@ -1460,7 +1445,7 @@ impl Drop for ActiveAttachment { .subscribers .retain(|subscriber| subscriber.id != subscriber_id); } - shared.attached = false; + shared.active_attachments -= 1; if shared.output_closed { shared.attachment_ended_after_exit = true; } @@ -2240,6 +2225,33 @@ mod tests { assert!(owner_should_exit(&shared, &mut completed_at)); } + #[test] + fn owner_waits_for_every_attachment_after_output_closes() { + for stop_requested_at in [None, Some(Instant::now())] { + let shared = Arc::new(Mutex::new(Shared { + active_attachments: 2, + output_closed: true, + stop_requested_at, + ..Shared::default() + })); + let first = ActiveAttachment { + shared: Arc::clone(&shared), + subscriber_id: None, + }; + let second = ActiveAttachment { + shared: Arc::clone(&shared), + subscriber_id: None, + }; + let mut completed_at = None; + + drop(first); + assert!(!owner_should_exit(&shared, &mut completed_at)); + + drop(second); + assert!(owner_should_exit(&shared, &mut completed_at)); + } + } + #[test] fn stop_signals_group_until_child_is_reaped() { let kill_calls = Arc::new(AtomicUsize::new(0)); @@ -2421,7 +2433,7 @@ mod tests { #[test] fn owner_waits_after_stop_for_attachment_until_bounded_timeout() { let shared = Arc::new(Mutex::new(Shared { - attached: true, + active_attachments: 1, output_closed: true, stop_requested_at: Some(Instant::now()), ..Shared::default() @@ -2429,11 +2441,11 @@ mod tests { let mut completed_at = None; assert!(!owner_should_exit(&shared, &mut completed_at)); - shared.lock().expect("shared poisoned").attached = false; + shared.lock().expect("shared poisoned").active_attachments = 0; assert!(owner_should_exit(&shared, &mut completed_at)); let unfinished = Arc::new(Mutex::new(Shared { - attached: true, + active_attachments: 1, stop_requested_at: Some(Instant::now() - OWNER_STOP_TIMEOUT), ..Shared::default() })); From 97a1b620cc0ebaecabddcac2b4e980bcb79c6473 Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:53:48 -0700 Subject: [PATCH 5/7] test(terminal): wait for shared terminal input readiness Require the current base-terminal socket to claim resize before the first phone input and both desktop attachment inputs. Keep the shared process identity, output, and failed runtime discovery assertions unchanged. The mocked terminal tests and Chromium/Firefox collection passed, as did frontend core checks. Live browser validation remains unverified locally because this environment prohibits browser fixtures. Co-authored-by: GPT-6 Astra --- .../00-workspace-create-and-launch.spec.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts index 3d2467dd93..00afe12d35 100644 --- a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts @@ -1022,7 +1022,11 @@ test.describe("workspace create-and-launch full stack", () => { }); await expect(phonePage.locator(".mobile-workspace-terminal__stage")).toBeVisible(); await expect - .poll(async () => (await workspaceBaseWebSockets(phonePage, created.id)).filter((entry) => !entry.closed)) + .poll(async () => + (await workspaceBaseWebSockets(phonePage, created.id)).filter( + (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), + ), + ) .toHaveLength(1); const input = phonePage.getByRole("textbox", { name: "Terminal command" }); @@ -1039,6 +1043,13 @@ test.describe("workspace create-and-launch full stack", () => { await expect.poll(() => desktopOutput).toContain(`shared-base-process:${processId}`); const desktopInput = page.locator(".workspace-stage .xterm-helper-textarea"); await desktopInput.focus(); + await expect + .poll(async () => + (await workspaceBaseWebSockets(page, created.id)).some( + (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), + ), + ) + .toBe(true); await page.keyboard.type("desktop-joined"); await page.keyboard.press("Enter"); await expect.poll(() => desktopOutput).toContain(`shared-base-reply:${processId}:desktop-joined`); @@ -1062,8 +1073,7 @@ test.describe("workspace create-and-launch full stack", () => { await expect .poll(async () => (await workspaceBaseWebSockets(page, created.id)).some( - (entry) => - !entry.closed && entry.sent.some((frame) => /"type":"(?:claim_resize|resize|refresh)"/.test(frame)), + (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), ), ) .toBe(true); From b7a6f6de2517cf27d85df80e35fa8816538499fb Mon Sep 17 00:00:00 2001 From: salmonumbrella <182032677+salmonumbrella@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:27:43 -0700 Subject: [PATCH 6/7] fix(terminal): preserve slot identity during navigation Capture the visible slot identity when registering it instead of reading a removed parent session during cleanup. Fix the shared owner and remove the redundant workflow-only null guard. Update the existing fixtures to use complete terminal settings, retain the base Workspace pane, and observe the base connection heartbeat before input. Keep shared-process and diff-output assertions intact. The socket-free navigation regression reproduced the null-key exception and now passes. Related unit tests, frontend core checks, collection, and non-mutating lint passed. Live browser validation remains unverified locally because the environment prohibits browser fixtures. Co-authored-by: GPT-6 Astra --- .../terminal/SessionTerminalSlot.svelte | 5 ++-- .../terminal/TerminalSplitTree.test.ts | 28 ++++++++++++++++++- .../terminal/WorkspaceHost.browser.svelte.ts | 2 ++ .../terminal/WorkspaceTerminalView.svelte | 5 ++-- .../00-workspace-create-and-launch.spec.ts | 6 ++-- .../00-workspace-tab-persistence.spec.ts | 11 +++++--- 6 files changed, 44 insertions(+), 13 deletions(-) diff --git a/frontend/src/lib/components/terminal/SessionTerminalSlot.svelte b/frontend/src/lib/components/terminal/SessionTerminalSlot.svelte index 4abfc5a09a..133cc9a37a 100644 --- a/frontend/src/lib/components/terminal/SessionTerminalSlot.svelte +++ b/frontend/src/lib/components/terminal/SessionTerminalSlot.svelte @@ -30,8 +30,9 @@ $effect(() => { const el = node; if (el === null) return; - setSessionSlotVisible(hostKey, el, visible); - return () => setSessionSlotVisible(hostKey, el, false); + const key = hostKey; + setSessionSlotVisible(key, el, visible); + return () => setSessionSlotVisible(key, el, false); }); diff --git a/frontend/src/lib/components/terminal/TerminalSplitTree.test.ts b/frontend/src/lib/components/terminal/TerminalSplitTree.test.ts index fc76568fb5..da2c003a3a 100644 --- a/frontend/src/lib/components/terminal/TerminalSplitTree.test.ts +++ b/frontend/src/lib/components/terminal/TerminalSplitTree.test.ts @@ -2,7 +2,8 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/svelte"; import { clearActiveTabbedPanelDrag, readTabbedPanelTabDrag } from "../shared/tabbed-panel-drag.js"; import { sessionPaneKey } from "../../stores/session-pane-key.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import type { ComponentProps } from "svelte"; +import { tick, type ComponentProps } from "svelte"; +import { SvelteMap } from "svelte/reactivity"; import AppRuntimeHarness from "../../../test/AppRuntimeHarness.svelte"; import TerminalSplitTree from "./TerminalSplitTree.svelte"; import type { PaneNode } from "./terminal-layout"; @@ -125,6 +126,31 @@ describe("TerminalSplitTree", () => { } }); + it("releases the old slot when navigation removes its session", async () => { + const session = sessions[0]!; + const currentSessions = new SvelteMap([["current", sessions]]); + render(AppRuntimeHarness, { + props: { + component: TerminalSplitTree, + workspaceId: "ws-1", + node: split(), + get sessions() { + return currentSessions.get("current") ?? []; + }, + displayLabels: {}, + activeSessionKey: session.key, + }, + }); + const hostKey = sessionHostKey("ws-1", undefined, session.key, session.created_at); + expect(isSessionSlotVisible(hostKey)).toBe(true); + + currentSessions.set("current", []); + await tick(); + + expect(screen.getAllByText("Session unavailable")).toHaveLength(2); + expect(isSessionSlotVisible(hostKey)).toBe(false); + }); + it("uses the launch target harness icon in an agent pane header", () => { const agentSessions = [ { diff --git a/frontend/src/lib/components/terminal/WorkspaceHost.browser.svelte.ts b/frontend/src/lib/components/terminal/WorkspaceHost.browser.svelte.ts index c7398b4179..e9d4877bee 100644 --- a/frontend/src/lib/components/terminal/WorkspaceHost.browser.svelte.ts +++ b/frontend/src/lib/components/terminal/WorkspaceHost.browser.svelte.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vite-plus/test" import { DEFAULT_TERMINAL_SETTINGS } from "../../api/types.js"; import { makeAppRuntime, type OwnedAppRuntime } from "../../app/runtime.js"; import { createDiffStore } from "../../stores/diff.svelte.js"; +import { createSettingsStore } from "../../stores/settings.svelte.js"; import { STORES_KEY } from "../../context.js"; import { createMockApiFetch, jsonResponse, type MockRouteOverride } from "../../../test/mockApiFetch.js"; @@ -111,6 +112,7 @@ function waitForReparent(): Promise { } const settingsStore = { + ...createSettingsStore(), getTerminalFontSize: () => DEFAULT_TERMINAL_SETTINGS.font_size, getQuickActions: () => [], getTerminalSettings: () => DEFAULT_TERMINAL_SETTINGS, diff --git a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte index b5e5c9874b..71058f21c6 100644 --- a/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte +++ b/frontend/src/lib/components/terminal/WorkspaceTerminalView.svelte @@ -5290,10 +5290,9 @@ {@const session = runtimeSessions.find( (candidate) => candidate.key === sessionKey, )} - {@const hostKey = session ? sessionHostKeyFor(session) : null} - {#if session && hostKey !== null && isSessionTerminalMounted(session.key)} + {#if session && isSessionTerminalMounted(session.key)} {/if} diff --git a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts index 00afe12d35..b74ff7ad12 100644 --- a/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-create-and-launch.spec.ts @@ -1024,7 +1024,7 @@ test.describe("workspace create-and-launch full stack", () => { await expect .poll(async () => (await workspaceBaseWebSockets(phonePage, created.id)).filter( - (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), + (entry) => !entry.closed && entry.sent.includes('{"type":"heartbeat"}'), ), ) .toHaveLength(1); @@ -1046,7 +1046,7 @@ test.describe("workspace create-and-launch full stack", () => { await expect .poll(async () => (await workspaceBaseWebSockets(page, created.id)).some( - (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), + (entry) => !entry.closed && entry.sent.includes('{"type":"heartbeat"}'), ), ) .toBe(true); @@ -1073,7 +1073,7 @@ test.describe("workspace create-and-launch full stack", () => { await expect .poll(async () => (await workspaceBaseWebSockets(page, created.id)).some( - (entry) => !entry.closed && entry.sent.some((frame) => frame.includes('"type":"claim_resize"')), + (entry) => !entry.closed && entry.sent.includes('{"type":"heartbeat"}'), ), ) .toBe(true); diff --git a/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts b/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts index 86cd9591d4..618ce6a716 100644 --- a/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts +++ b/frontend/tests/e2e-full/00-workspace-tab-persistence.spec.ts @@ -354,7 +354,8 @@ test.describe("workspace tab persistence", () => { await expect(page.getByRole("region", { name: "Session launcher" })).toBeVisible(); await expect(workflow.getByRole("tab", { name: "Diff" })).toHaveCount(0); - await expect(panes).toHaveCount(0); + await expect(panes).toHaveCount(1); + await expect(panes).toHaveAttribute("data-pane-key", "home"); const diffResponse = page.waitForResponse( (response) => @@ -425,7 +426,8 @@ test.describe("workspace tab persistence", () => { await rightDiffHost.press("j"); await rightDiffHost.press("k"); await expect(workflow.getByRole("tab", { name: "Diff" })).toHaveCount(0); - await expect(panes).toHaveCount(0); + await expect(panes).toHaveCount(1); + await expect(panes).toHaveAttribute("data-pane-key", "home"); await expect(page.locator(".right-sidebar .workspace-diff")).toBeVisible(); const diffToolbar = page.locator(".right-sidebar .diff-toolbar"); await expect(diffToolbar.locator(".compact-more-btn")).toBeVisible(); @@ -478,13 +480,14 @@ test.describe("workspace tab persistence", () => { await expect(betaDiffFile).toHaveCount(0); await page.keyboard.press("Escape"); await expect(alphaDiffFile).toBeVisible(); - await expect(panes).toHaveCount(0); + await expect(panes).toHaveCount(1); + await expect(panes).toHaveAttribute("data-pane-key", "home"); await expect(page.getByRole("region", { name: "Session launcher" })).toBeVisible(); await openTerminalWorkflowTab(page); await expect(workflow.getByRole("tab", { name: "Terminal" })).toHaveAttribute("aria-selected", "true"); await expect(page.locator(".right-sidebar .workspace-diff")).toBeVisible(); - await expect(panes).toHaveCount(1); + await expect(panes).toHaveCount(2); await workflow.locator(".tabbed-panel-tab-panel.active .terminal-container").click(); for (const key of ["j", "k", "[", "]"]) { From 8c9af36ddd8d91a915e7d69d292d4247cc63b9b8 Mon Sep 17 00:00:00 2001 From: Marius van Niekerk Date: Wed, 18 Nov 2026 23:59:51 +0000 Subject: [PATCH 7/7] test(terminal): close the failed second dial response body The shared-terminal test now opens a second websocket on the same terminal. Main turned the bodyclose lint back on after this branch started, so that new dial failed lint once the branch was rebased. Close the handshake response on a failed dial, the same way the other dials in this file do. Generated with Claude Code (claude-opus-5-5) Co-Authored-By: Claude Opus 5.5 --- internal/terminal/handler_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/terminal/handler_test.go b/internal/terminal/handler_test.go index 5741149669..f67573afa9 100644 --- a/internal/terminal/handler_test.go +++ b/internal/terminal/handler_test.go @@ -255,7 +255,10 @@ func TestHandlerAttachesPtyOwnerTerminal(t *testing.T) { ) require.Contains(readWebSocketUntil(t, conn, "ready"), "ready") - second, _, err := websocket.Dial(t.Context(), terminalURL, nil) + second, secondResp, err := websocket.Dial(t.Context(), terminalURL, nil) + if err != nil && secondResp != nil && secondResp.Body != nil { + _ = secondResp.Body.Close() + } require.NoError(err) defer second.Close(websocket.StatusNormalClosure, "done") require.Contains(readWebSocketUntil(t, second, "ready"), "ready")