diff --git a/packages/harness/web/e2e/assistant-end.spec.ts b/packages/harness/web/e2e/assistant-end.spec.ts new file mode 100644 index 000000000..ba05edc8c --- /dev/null +++ b/packages/harness/web/e2e/assistant-end.spec.ts @@ -0,0 +1,279 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import type { AssistantLifecycle } from "../../src/shared/assistant-session"; +import type { HarnessSession } from "../../src/shared/types"; +import { selectMockSessionFromPalette } from "./mock-navigation"; + +const lifecycle = ( + id: string, + state: AssistantLifecycle["lifecycle"] = "open", + revision = 1, +): AssistantLifecycle => ({ + version: 1, + harnessSessionId: id, + revision, + lifecycle: state, + execution: "paused", + updatedAt: Date.now(), +}); +const session = ( + id: string, + changes: Partial = {}, +): HarnessSession => ({ + id, + agentSessionId: null, + boundWorkflowPath: "/Users/demo/acme-app/leasing", + harness: "claude-code", + cwd: "/Users/demo/acme-app", + title: id, + status: "running", + ready: true, + exitCode: null, + createdAt: "2026-01-01T00:00:00.000Z", + lastActiveAt: "2026-01-01T00:00:01.000Z", + ...changes, +}); +const publish = (page: Page, message: unknown) => + page.evaluate((message) => { + (window as any).__HARNESS_TEST__.publish(message); + }, message); +const project = ( + page: Page, + revision: number, + lifecycles: AssistantLifecycle[], +) => + publish(page, { + type: "assistant.state", + snapshot: { + hostInstanceId: "host-end", + authorityRevision: "authority-end", + revision, + enabled: true, + sessions: [], + lifecycles, + }, + }); +const selected = (page: Page) => page.getByTestId("session-context"); +const openEnd = async (page: Page) => { + await page.getByTestId("session-menu").click(); + await page.getByTestId("session-end-btn").click(); +}; + +/** Keep the real hook/dialog while controlling the DELETE boundary. */ +async function openStudio(page: Page) { + const requests: Route[] = []; + const unexpected: string[] = []; + page.on("pageerror", (error) => unexpected.push(error.message)); + await page.route("**/api/sessions/*", async (route) => { + if (route.request().method() !== "DELETE") return route.continue(); + requests.push(route); + }); + await page.goto("/?seed=0"); + await expect(page.locator(".harness-terminal")).toBeVisible(); + await page.evaluate(async () => { + const url = performance + .getEntriesByType("resource") + .find( + (entry) => new URL(entry.name).pathname === "/src/lib/api.ts", + )!.name; + const { MockApi, ApiError } = await import(url); + const kill = MockApi.prototype.killSession; + MockApi.prototype.killSession = async function (id: string) { + const response = await fetch(`/api/sessions/${encodeURIComponent(id)}`, { + method: "DELETE", + }); + if (!response.ok) + throw new ApiError(response.status, "controlled cleanup response"); + return kill.call(this, id); + }; + }); + return { + requests, + unexpected, + settle: async (status: number) => { + await expect.poll(() => requests.length).toBe(1); + await requests[0]!.fulfill({ + status, + json: + status === 200 + ? { ok: true } + : { failure: { code: "cleanup_unconfirmed" } }, + }); + }, + }; +} + +test("End stays available after Terminal exit and incomplete cleanup retains A and B", async ({ + page, +}, testInfo) => { + const fixture = await openStudio(page); + await project(page, 1, [lifecycle("sess-boot"), lifecycle("sess-leasing-2")]); + await publish(page, { + type: "session.status", + session: session("sess-leasing-2", { + title: "Unaffected B", + harness: "codex", + }), + }); + await publish(page, { + type: "session.status", + session: session("sess-boot", { status: "exited", ready: false }), + }); + await expect(page.getByTestId("dead-session-pane")).toBeVisible(); + await openEnd(page); + const dialog = page.getByRole("alertdialog"); + await expect(dialog).toContainText("Terminal and Assistant work"); + await expect(dialog).toContainText("saved history remains available"); + await page.screenshot({ + path: testInfo.outputPath("managed-end-confirmation.png"), + }); + await expect( + page.getByRole("button", { name: "Keep session", exact: true }), + ).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(dialog).toHaveCount(0); + expect(fixture.requests).toHaveLength(0); + await openEnd(page); + await page.getByTestId("end-session-confirm-btn").click(); + await project(page, 2, [ + lifecycle("sess-boot", "ending", 2), + lifecycle("sess-leasing-2"), + ]); + await page.getByTestId("session-menu").click(); + await expect(page.getByTestId("session-end-btn")).toBeDisabled(); + await expect(page.getByTestId("session-end-btn")).toHaveText( + "Ending session…", + ); + await fixture.settle(409); + await expect(page.getByText(/Session cleanup is incomplete/)).toBeVisible(); + await expect(selected(page)).toHaveAttribute("data-session-id", "sess-boot"); + await expect(page.getByTestId("session-end-btn")).toBeEnabled(); + await project(page, 1, [lifecycle("sess-boot", "ended", 3)]); + await expect(page.getByTestId("session-end-btn")).toHaveText( + "Retry End session…", + ); + expect(new URL(fixture.requests[0]!.request().url()).pathname).toBe( + "/api/sessions/sess-boot", + ); + await page.keyboard.press("Escape"); + await page.screenshot({ + path: testInfo.outputPath("cleanup-incomplete.png"), + }); + await selectMockSessionFromPalette(page, "Unaffected B"); + await expect(selected(page)).toHaveAttribute( + "data-session-id", + "sess-leasing-2", + ); + await expect(page.locator(".harness-terminal")).toBeVisible(); + expect(fixture.unexpected).toEqual([]); +}); + +test("confirmed End retains Assistant history and preserves newer rows and navigation", async ({ + page, +}, testInfo) => { + const fixture = await openStudio(page); + await project(page, 1, [lifecycle("sess-boot")]); + await openEnd(page); + await page.getByTestId("end-session-confirm-btn").click(); + await expect.poll(() => fixture.requests.length).toBe(1); + await publish(page, { + type: "session.status", + session: session("sess-leasing-2", { title: "B changed during End" }), + }); + await publish(page, { + type: "session.status", + session: session("sess-new", { title: "New session during End" }), + }); + await page.getByTestId("session-tab-sess-new").click(); + await project(page, 2, [lifecycle("sess-boot", "ended", 2)]); + await fixture.settle(200); + await expect(page.getByTestId("session-tab-sess-boot")).toHaveCount(0); + await expect(selected(page)).toHaveAttribute("data-session-id", "sess-new"); + await expect(page.getByTestId("session-tab-sess-leasing-2")).toContainText( + "B changed during End", + ); + await page.getByTestId("history-trigger").click(); + await page.getByTestId("past-sessions-trigger").hover(); + await expect(page.getByTestId("exited-session-sess-boot")).toBeVisible(); + await page.screenshot({ + path: testInfo.outputPath("ended-history-retained.png"), + }); + expect(fixture.unexpected).toEqual([]); +}); + +test("an older successful End response cannot dismiss a newer Assistant Resume", async ({ + page, +}) => { + const fixture = await openStudio(page); + await project(page, 1, [lifecycle("sess-boot")]); + await openEnd(page); + await page.getByTestId("end-session-confirm-btn").click(); + await expect.poll(() => fixture.requests.length).toBe(1); + await project(page, 3, [lifecycle("sess-boot", "open", 3)]); + await publish(page, { + type: "session.status", + session: session("sess-boot", { title: "Resumed Assistant" }), + }); + await fixture.settle(200); + await openEnd(page); + await expect(page.getByRole("alertdialog")).toBeVisible(); + await expect(selected(page)).toHaveAttribute("data-session-id", "sess-boot"); + await expect(page.getByTestId("session-tab-sess-boot")).toContainText( + "Resumed Assistant", + ); + await expect(page.locator(".harness-terminal")).toBeVisible(); + expect(fixture.unexpected).toEqual([]); +}); + +test("Close on an exited Terminal requires confirmation when its Assistant is open", async ({ + page, +}) => { + const fixture = await openStudio(page); + await project(page, 1, [lifecycle("sess-boot")]); + await publish(page, { + type: "session.status", + session: session("sess-boot", { status: "exited", ready: false }), + }); + await page.getByTestId("dead-session-close").click(); + await expect(page.getByRole("alertdialog")).toContainText( + "Terminal and Assistant work", + ); + await expect( + page.getByRole("button", { name: "Keep session", exact: true }), + ).toBeFocused(); + await page.keyboard.press("Escape"); + await expect(selected(page)).toHaveAttribute("data-session-id", "sess-boot"); + expect(fixture.requests).toHaveLength(0); +}); + +test("Terminal-only End keeps its existing confirmation and sibling selection", async ({ + page, +}) => { + const fixture = await openStudio(page); + await publish(page, { + type: "assistant.state", + snapshot: { + hostInstanceId: "host-end", + authorityRevision: "authority-end", + revision: 1, + enabled: false, + sessions: [], + lifecycles: [], + }, + }); + await openEnd(page); + await expect(page.getByRole("alertdialog")).toContainText( + "kills the live terminal", + ); + await expect(page.getByRole("alertdialog")).not.toContainText( + "Assistant work", + ); + await page.getByTestId("end-session-confirm-btn").click(); + await fixture.settle(200); + await expect(selected(page)).toHaveAttribute( + "data-session-id", + "sess-leasing-2", + ); + await expect(page.getByTestId("session-tab-sess-boot")).toHaveCount(0); + await expect(page.locator(".harness-terminal")).toBeVisible(); + expect(fixture.unexpected).toEqual([]); +}); diff --git a/packages/harness/web/src/App.tsx b/packages/harness/web/src/App.tsx index 7a53d7b55..a9ab3ba43 100644 --- a/packages/harness/web/src/App.tsx +++ b/packages/harness/web/src/App.tsx @@ -78,7 +78,8 @@ import { McpAuthRestartNotice } from "./components/McpAuthRestartNotice"; import { DeadSessionPane, PastSessionPane } from "./components/DeadSessionPane"; import { EmptyState } from "./components/EmptyState"; import { Icon } from "./components/Icon"; -import { SessionBar } from "./components/SessionBar"; +import { MANAGED_END_DESCRIPTION, SessionBar } from "./components/SessionBar"; +import { EndSessionConfirm } from "./components/EndSessionConfirm"; import { SessionStepsBar } from "./components/SessionStepsBar"; import { RunSheet } from "./components/RunSheet"; import { TelemetryNotice } from "./components/TelemetryNotice"; @@ -291,6 +292,13 @@ const shellApi = createApi(); export const App = (): JSX.Element => { const harness = useHarnessState(); + const [confirmEndSessionId, setConfirmEndSessionId] = useState( + null, + ); + useEffect(() => setConfirmEndSessionId(null), [ + harness.activeSessionId, + harness.authRevision, + ]); // A project map remounts when browsing another project or agent. Keep its // viewport for this signed-in UI lifetime, without persisting map data. const agentMapViewportStore = useMemo( @@ -1446,6 +1454,13 @@ export const App = (): JSX.Element => { const activeSession = state.sessions.find((session) => session.id === harness.activeSessionId) ?? null; + const assistantLifecycles = harness.assistant.snapshot?.enabled + ? (harness.assistant.snapshot.lifecycles ?? []) + : []; + const assistantNeedsEnd = (id: string) => + assistantLifecycles.some( + (row) => row.harnessSessionId === id && row.lifecycle !== "ended", + ); const boundWorkflowPath = boundWorkflowPathOf(activeSession); const boundWorkflow = state.workflows.find((w) => w.path === boundWorkflowPath) ?? null; @@ -1566,7 +1581,12 @@ export const App = (): JSX.Element => { // hidden until the user explicitly selects one of this project's tabs. const activeProjectTab = projectMapSelected ? (focusTabs.find((session) => session.id === harness.activeSessionId) ?? - null) + (activeSession && + studioConversationProjectId && + activeSession.agentMapIdentity?.projectId === studioConversationProjectId && + assistantNeedsEnd(activeSession.id) + ? activeSession + : null)) : activeSession; const conversationSession = projectMapSelected ? activeProjectTab @@ -3201,7 +3221,9 @@ export const App = (): JSX.Element => { } onRenameSession={renameSession} boundWorkflowName={boundWorkflow?.name ?? null} - sessions={showWorkbench || projectMapSelected ? focusTabs : []} + sessions={ + !showDead && (showWorkbench || projectMapSelected) ? focusTabs : [] + } busySessionIds={harness.busySessionIds} onSelectSession={selectTab} labelOf={(session) => @@ -3211,7 +3233,13 @@ export const App = (): JSX.Element => { sessionBarSession != null && harness.busySessionIds.has(sessionBarSession.id) } - onCloseSession={(id) => void harness.closeSession(id)} + ending={ + sessionBarSession != null && + harness.endingSessionIds.has(sessionBarSession.id) + } + onCloseSession={(id) => + void harness.closeSession(id).catch(() => undefined) + } onOpenInEditor={openInEditor} editorLabel={editorLabel(harness.settings?.editor)} onToast={harness.showToast} @@ -3363,9 +3391,14 @@ export const App = (): JSX.Element => { from: conversationSession.id, }) } - onClose={() => - void harness.closeSession(conversationSession.id) - } + onClose={() => { + if (assistantNeedsEnd(conversationSession.id)) + setConfirmEndSessionId(conversationSession.id); + else + void harness + .closeSession(conversationSession.id) + .catch(() => undefined); + }} /> ) : showAgentEmpty && focusedWorkflow ? ( @@ -3906,6 +3939,18 @@ export const App = (): JSX.Element => { + {confirmEndSessionId && ( + setConfirmEndSessionId(null)} + onConfirm={() => { + const id = confirmEndSessionId; + setConfirmEndSessionId(null); + void harness.closeSession(id).catch(() => undefined); + }} + /> + )} + {/* The Overview is a card ON TOP of the shell, so it mounts beside the palette rather than standing in for the workbench. */} {overviewOpen && ( diff --git a/packages/harness/web/src/components/SessionBar.tsx b/packages/harness/web/src/components/SessionBar.tsx index bd7904738..607afa962 100644 --- a/packages/harness/web/src/components/SessionBar.tsx +++ b/packages/harness/web/src/components/SessionBar.tsx @@ -21,6 +21,9 @@ function workspaceLabelOf(path: string): string { const EMPTY_BUSY_SESSION_IDS: ReadonlySet = new Set(); +export const MANAGED_END_DESCRIPTION = + "This stops Terminal and Assistant work for this session. Its saved history remains available. Other sessions keep running."; + interface SessionBarProps { assistant?: AssistantProjection; /** The main panel is showing the Overview/intro, not a session. */ @@ -52,8 +55,9 @@ interface SessionBarProps { expandRightLabel?: string; showExpandRightLabel?: boolean; expandRightRef?: RefObject; - /** Ends a live session — kills its PTY; it stays resumable from history. */ + /** Stops the selected session's managed work and retains its saved history. */ onCloseSession: (id: string) => void; + ending?: boolean; /** Opens the session's directory in the user's editor. */ onOpenInEditor: (path: string) => void; /** The chosen editor's display name, so the item names where it lands. */ @@ -103,6 +107,7 @@ export function SessionBar({ showExpandRightLabel = false, expandRightRef, onCloseSession, + ending = false, onOpenInEditor, editorLabel, onToast, @@ -115,6 +120,13 @@ export function SessionBar({ onSelectSession = null, labelOf, }: SessionBarProps): JSX.Element { + const assistantLifecycle = assistant?.snapshot?.enabled + ? assistant.snapshot.lifecycles?.find( + (row) => row.harnessSessionId === activeSession?.id, + ) + : undefined; + const assistantNeedsEnd = + assistantLifecycle != null && assistantLifecycle.lifecycle !== "ended"; const [confirmingClose, setConfirmingClose] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const [renaming, setRenaming] = useState(false); @@ -370,18 +382,24 @@ export function SessionBar({ Open in {editorLabel} - {activeSession.status !== "exited" && ( + {(activeSession.status !== "exited" || assistantNeedsEnd) && ( )} @@ -433,6 +451,7 @@ export function SessionBar({ {confirmingClose && activeSession && ( setConfirmingClose(false)} onConfirm={() => { diff --git a/packages/harness/web/src/lib/use-harness-state.ts b/packages/harness/web/src/lib/use-harness-state.ts index 714820dbc..ce36258d0 100644 --- a/packages/harness/web/src/lib/use-harness-state.ts +++ b/packages/harness/web/src/lib/use-harness-state.ts @@ -137,6 +137,7 @@ export interface PendingWorkspace { export interface HarnessStateHook { assistant: AssistantProjection; + endingSessionIds: ReadonlySet; authRevision: number; state: AppState | null; loading: boolean; @@ -421,6 +422,10 @@ export function useHarnessState(): HarnessStateHook { const [state, setState] = useState(null); const assistantOrder = useRef(new AssistantStateOrder()).current; const [assistant, setAssistant] = useState(() => assistantOrder.current()); + const endingSessions = useRef(new Set()); + const [endingSessionIds, setEndingSessionIds] = useState>( + new Set(), + ); useEffect(() => { if (!state) return; const projectIds = new Set( @@ -1756,39 +1761,74 @@ export function useHarnessState(): HarnessStateHook { const closeSession = useCallback( async (id: string): Promise => { + if (endingSessions.current.has(id)) return; + endingSessions.current.add(id); + setEndingSessionIds(new Set(endingSessions.current)); + const selectionAtStart = switchSeqRef.current; + const lifecycleAtStart = assistantOrder + .current() + .snapshot?.lifecycles?.find((row) => row.harnessSessionId === id); try { await api.killSession(id); } catch (err) { - // Surface the failure as a toast and keep the user on the dead-session - // overlay: the re-throw below skips the local removal, so a failed kill - // never makes the session vanish from the UI as if it had succeeded. + // Neither a rejected End nor unconfirmed cleanup dismisses the row. setToast( createToastMessage( - err instanceof ApiError && err.reason - ? err.reason - : (err as Error).message, + "Session cleanup is incomplete. The session is still available; retry End session to finish stopping it.", ), ); throw err; + } finally { + endingSessions.current.delete(id); + setEndingSessionIds(new Set(endingSessions.current)); } - const remaining = (state?.sessions ?? []).filter( + const lifecycles = assistantOrder.current().snapshot?.lifecycles ?? []; + const lifecycle = lifecycles.find((row) => row.harnessSessionId === id); + // A newer Resume can finish before this older End response arrives. + if ( + lifecycle?.lifecycle === "open" && + lifecycle.revision > (lifecycleAtStart?.revision ?? -1) + ) + return; + const remaining = sessionsRef.current.filter( (session) => session.id !== id, ); - setState((prev) => (prev ? { ...prev, sessions: remaining } : prev)); - if (activeSessionId === id) { - const closed = state?.sessions.find((session) => session.id === id); + const retained = lifecycleAtStart != null || lifecycle != null; + // Apply to the latest rows: another session may have started or changed + // while End was waiting for cleanup. Assistant history stays reachable. + setState((prev) => + prev + ? { + ...prev, + sessions: retained + ? prev.sessions.map((session) => + session.id === id + ? { ...session, status: "exited", ready: false } + : session, + ) + : prev.sessions.filter((session) => session.id !== id), + } + : prev, + ); + if (activeSessionId === id && switchSeqRef.current === selectionAtStart) { + const closed = sessionsRef.current.find((session) => session.id === id); const projectId = closed?.agentMapIdentity?.projectId; + const active = (session: HarnessSession) => + session.status !== "exited" || + lifecycles.some( + (row) => row.harnessSessionId === session.id && row.lifecycle !== "ended", + ); const nextRunning = remaining.find( (session) => - session.status !== "exited" && + active(session) && projectId != null && session.agentMapIdentity?.projectId === projectId, - ) ?? remaining.find((session) => session.status !== "exited"); + ) ?? remaining.find(active); selectSession(nextRunning ? nextRunning.id : null); } }, - [state, activeSessionId, selectSession], + [assistantOrder, activeSessionId, selectSession], ); const connectWorkflow = useCallback( @@ -2413,6 +2453,7 @@ export function useHarnessState(): HarnessStateHook { return { assistant, + endingSessionIds, state, authRevision, loading,