From ba326b6747e1e0a8d02dc66cc901f452a50dd5d1 Mon Sep 17 00:00:00 2001 From: "jinye.djy" Date: Mon, 10 Aug 2026 01:54:58 +0800 Subject: [PATCH] fix(webui): Preserve active sessions during restore Keep the committed WebUI session live while a replacement restore is prepared, then switch ownership atomically after replay staging succeeds. Preserve the active session across target failures, superseded requests, and controlled workspace resolution, with transition-aware WebShell gating and focused coverage. Refs #8678 Co-authored-by: Qwen-Coder --- ...9-transactional-webui-session-switching.md | 68 + ...-serve-webui-live-journal-recovery.test.ts | 242 +- packages/web-shell/client/App.test.tsx | 250 +- packages/web-shell/client/App.tsx | 415 ++- .../client/components/ChatPane.test.tsx | 30 + .../web-shell/client/components/ChatPane.tsx | 16 +- .../WorkspaceSessionProvider.test.tsx | 328 +++ .../components/WorkspaceSessionProvider.tsx | 272 +- packages/web-shell/client/i18n.tsx | 5 +- packages/web-shell/client/index.test.tsx | 13 +- .../session/DaemonSessionProvider.test.tsx | 2535 ++++++++++++++++- .../daemon/session/DaemonSessionProvider.tsx | 1683 ++++++++++- .../webui/src/daemon/session/actions.test.ts | 52 + packages/webui/src/daemon/session/actions.ts | 394 ++- packages/webui/src/daemon/session/index.ts | 4 + packages/webui/src/daemon/session/types.ts | 24 + 16 files changed, 5765 insertions(+), 566 deletions(-) create mode 100644 docs/design/2026-08-09-transactional-webui-session-switching.md create mode 100644 packages/web-shell/client/components/WorkspaceSessionProvider.test.tsx diff --git a/docs/design/2026-08-09-transactional-webui-session-switching.md b/docs/design/2026-08-09-transactional-webui-session-switching.md new file mode 100644 index 00000000000..2e88457272e --- /dev/null +++ b/docs/design/2026-08-09-transactional-webui-session-switching.md @@ -0,0 +1,68 @@ +# Transactional WebUI session switching + +## Context + +Issue #8678 showed two separate large-session problems. The restore request could exceed the former shared ten-second timeout, and the WebUI detached the visible session before the target restore had completed. The timeout and daemon-side resource-safety work is handled by #8691. This design addresses the client-side ownership gap: a failed, timed-out, or superseded restore must not erase a healthy session that the user was already viewing. + +The core invariant is that the currently committed session owns the transcript, event stream, workspace metadata, active prompt waiters, and session-scoped actions until a target restore has completed remote work, local replay staging, and a final generation/deadline check. A target failure leaves the committed session visibly unchanged. + +## Compatibility contract + +Transactional switching requires a successful daemon capability snapshot that advertises `client_identity`, plus concrete non-empty client ids for both the committed source and every restored candidate. A daemon that explicitly omits the feature uses the existing detach-first path. An unavailable capability snapshot, or a modern response that omits an advertised client identity, fails closed while preserving the source. + +`DaemonConnectionState.sessionTransition` exposes `queued`, `preparing`, and `failed` phases. Only queued and preparing block new session mutations. Failed is diagnostic and recoverable; the source remains usable and controlled WebShell hosts are asked to restore their committed target. + +## Desired and committed ownership + +The provider keeps desired props separate from committed refs. Changes to session id, workspace, restore mode, or requested client identity enter a coordinator instead of restarting the current runner. Initial mount without a committed session retains the existing bootstrap path. + +The main WebShell workspace wrapper no longer keys the provider by session or workspace. While a desired workspace is resolving or being registered, the committed App remains mounted and its mutation UI is gated. A terminal target-resolution or restore failure is latched for that desired generation, so unrelated rerenders cannot create a retry loop; the host callback receives the still-committed tuple. Split-view panes keep their existing independent providers and keys. + +## Coordinator and terminal arbitration + +Each provider runs at most one ordinary load, resume, reload, resync, or repair RPC. Identical requests coalesce. A newer request rejects the older public intent with `AbortError`, replaces the single queued target, and waits for the non-cancellable raw request to settle before starting. The queued target inherits an absolute deadline from its original invocation, so an expired request is never sent later. + +SDK settlement, watchdog, caller abort, supersede, and commit use explicit state rather than `Promise.race` ordering. A final check covers intent identity, provider generation, owner generation, target identity, abort state, and the absolute deadline after staging and immediately before commit. User and controlled requests take precedence over automatic full resync, which in turn takes precedence over memory repair. + +## Pure staging and commit + +The candidate replay is materialized in a temporary transcript store. Transcript state, pagination anchors, connection metadata, notices, workspace signals, follow-up and mid-turn side channels, pending permissions, prompt terminal events, and live-journal repair state remain local until commit. A malformed event may produce a staged warning, but neither that warning nor any other side effect is published if staging fails or the intent is superseded. + +Commit is a synchronous linearization point: + +1. claim public success and remove the watchdog and abort listener; +2. flush the source's already-valid transcript batch, increment the owner generation, and stop the source runner; +3. install the candidate transcript, history, session ref, workspace, client id, and synchronous connection ref; +4. publish staged notices and side channels; +5. settle or rebind prompt waiters; +6. resolve the public load promise; +7. start candidate metadata and SSE work; +8. issue one non-blocking best-effort detach for the source. + +The public promise therefore observes a consistent candidate owner and transcript but does not wait for React rendering, metadata, SSE connection, or source detach. Detach uses the frozen endpoint, token, session id, and client id, is attempted at most once, and never blocks a later restore. Failures are consumed and logged. + +## Events, resync, and prompts + +Ordinary target preparation leaves the source SSE and existing prompt/control work active. Every runner cleanup is scoped to the session and generation captured by that runner; it cannot read a later global session ref and accidentally clear the new owner. Session-scoped asynchronous completions likewise verify captured owner identity before modifying shared UI state. + +`state_resync_required` is the exception to continued streaming. Events before the sentinel are synchronously flushed, the stream generation advances at the sentinel, and already-yielded or buffered suffix events are discarded. The stale stream stops immediately, but the source attachment and legal transcript prefix remain frozen. A failed reload leaves that prefix visible with a recoverable warning; a successful reload atomically replaces it. + +On a cross-session commit, the candidate is installed before source prompt waiters are locally rejected, and no daemon prompt cancellation is sent. On same-session reload, a staged terminal settles a matching waiter; otherwise an active daemon prompt is rebound, while an authoritative inactive snapshot deterministically ends an already-bound waiter. + +## WebShell integration + +Sidebar, overview, open-session events, `/resume`, the resume dialog, and bound scheduled runs share the same transactional open helper and an invocation token. Completion code checks the committed owner tuple together with the invocation token, preventing an older same-session request from clearing a newer spinner or firing work against its target. + +The main composer and split-view `ChatPane` both inspect the public transition state before running slash handlers or optimistic input side effects. New prompts, shell/model/mode mutations, and conflicting session operations are gated while cancel, permission responses, existing prompt completion, and read-only controls remain available on the committed source. + +Worktree, branch, git-mode intent, and recap generation are not cleared before restore. Session-scoped metadata is keyed to its committed owner so the first candidate render cannot display source metadata. Bound scheduled runs rely on the restore promise for the restore phase; the existing 30-second timer begins only after commit and limits catch-up. + +## Deliberate limits + +This change does not optimize JSONL reading, replay size, checkpoints, or selective restore. Staging briefly holds the source transcript and candidate replay together. A CPU-heavy restore in a shared ACP child may still delay source event delivery even though ownership remains correct. + +There is no global attachment scheduler, cleanup registry, or daemon-wide A+1 live-session guarantee. Fresh create/attach, SDK self-heal, branch creation/adoption, and cross-provider resource accounting remain outside this PR. Best-effort detach failure can retain an invisible client reference until the existing server reaper runs. These resource guarantees would require a wider daemon/wire design and are intentionally not implied by the visible-state transaction implemented here. + +## Verification + +Unit tests cover capability gating, target coalescing, latest-only serialization, deadlines, late candidates, atomic transcript commit, source prompt and control continuity, stale async completions, controlled workspace resolution, metadata ownership, and post-commit scheduled-run catch-up. A focused JSDOM/real-daemon scenario delays the target response while exercising the source, then checks atomic handoff and failure preservation. An approximately 80 MiB transcript remains manual memory and tracing evidence rather than a timing assertion. diff --git a/integration-tests/cli/qwen-serve-webui-live-journal-recovery.test.ts b/integration-tests/cli/qwen-serve-webui-live-journal-recovery.test.ts index 1e59d75d855..4cfcf16faa5 100644 --- a/integration-tests/cli/qwen-serve-webui-live-journal-recovery.test.ts +++ b/integration-tests/cli/qwen-serve-webui-live-journal-recovery.test.ts @@ -30,6 +30,8 @@ let dom: JSDOM; let createRoot: typeof import('react-dom/client').createRoot; let DaemonSessionProvider: typeof import('@qwen-code/webui/daemon-react-sdk').DaemonSessionProvider; let useTranscriptBlocks: typeof import('@qwen-code/webui/daemon-react-sdk').useTranscriptBlocks; +let useActions: typeof import('@qwen-code/webui/daemon-react-sdk').useActions; +let useConnection: typeof import('@qwen-code/webui/daemon-react-sdk').useConnection; const originalGlobalDescriptors = new Map( ['window', 'document', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'].map( (key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const, @@ -57,9 +59,8 @@ beforeAll(async () => { value: true, }); ({ createRoot } = await import('react-dom/client')); - ({ DaemonSessionProvider, useTranscriptBlocks } = await import( - '@qwen-code/webui/daemon-react-sdk' - )); + ({ DaemonSessionProvider, useActions, useConnection, useTranscriptBlocks } = + await import('@qwen-code/webui/daemon-react-sdk')); }); afterAll(() => { @@ -213,4 +214,239 @@ describe('qwen serve WebUI live journal recovery', () => { fs.rmSync(workspace, { recursive: true, force: true }); } }, 30_000); + + it('keeps the source usable until a delayed target load commits', async () => { + const workspace = makeTempWorkspace('webui-transactional-switch'); + const originalFetch = globalThis.fetch; + const releaseTargetResponse = createDeferred(); + let switchPromise: Promise | undefined; + try { + activeDaemon = await spawnDaemon({ + workspaceCwd: workspace, + env: { + QWEN_CLI_ENTRY: MOCK_AGENT_PATH, + MOCK_ACP_MODE: 'echo', + }, + }); + const source = await activeDaemon.client.createOrAttachSession({ + sessionScope: 'thread', + }); + await activeDaemon.client.prompt(source.sessionId, { + prompt: [{ type: 'text', text: 'source transcript' }], + }); + const target = await activeDaemon.client.createOrAttachSession({ + sessionScope: 'thread', + }); + await activeDaemon.client.prompt(target.sessionId, { + prompt: [{ type: 'text', text: 'target transcript' }], + }); + + globalThis.fetch = async (input, init) => { + const url = + typeof input === 'string' + ? input + : input instanceof URL + ? input.href + : input.url; + const response = await originalFetch(input, init); + if ( + new URL(url, 'http://localhost').pathname === + `/session/${target.sessionId}/load` + ) { + await releaseTargetResponse.promise; + } + return response; + }; + + let blocks: readonly DaemonTranscriptBlock[] = []; + let actions: ReturnType | undefined; + let connection: ReturnType | undefined; + function Harness() { + blocks = useTranscriptBlocks(); + actions = useActions(); + connection = useConnection(); + return null; + } + const container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => { + root?.render( + // eslint-disable-next-line react/no-children-prop + createElement(DaemonSessionProvider, { + autoConnect: true, + baseUrl: activeDaemon!.base, + token: activeDaemon!.token, + sessionId: source.sessionId, + children: createElement(Harness), + }), + ); + }); + await waitFor( + () => + connection?.sessionId === source.sessionId && + JSON.stringify(blocks).includes('source transcript'), + 'source session restore', + ); + + await act(async () => { + switchPromise = actions!.loadSession(target.sessionId); + await Promise.resolve(); + }); + await waitFor( + () => connection?.sessionTransition?.phase === 'preparing', + 'target session preparation', + ); + await expect(actions!.heartbeat()).resolves.toMatchObject({ + sessionId: source.sessionId, + }); + await activeDaemon.client.prompt(source.sessionId, { + prompt: [{ type: 'text', text: 'source remains live' }], + }); + await waitFor( + () => JSON.stringify(blocks).includes('source remains live'), + 'source SSE during target preparation', + ); + expect(connection?.sessionId).toBe(source.sessionId); + expect(JSON.stringify(blocks)).toContain('source transcript'); + + releaseTargetResponse.resolve(); + await act(async () => { + await switchPromise; + }); + await waitFor( + () => + connection?.sessionId === target.sessionId && + JSON.stringify(blocks).includes('target transcript'), + 'atomic target commit', + ); + expect(JSON.stringify(blocks)).not.toContain('source transcript'); + } finally { + releaseTargetResponse.resolve(); + await switchPromise?.catch(() => undefined); + globalThis.fetch = originalFetch; + if (root) { + await act(async () => root?.unmount()); + root = undefined; + } + await activeDaemon?.dispose(); + activeDaemon = undefined; + fs.rmSync(workspace, { recursive: true, force: true }); + } + }, 30_000); + + it('preserves the source after a target load returns 504', async () => { + const workspace = makeTempWorkspace('webui-transactional-504'); + const originalFetch = globalThis.fetch; + try { + activeDaemon = await spawnDaemon({ + workspaceCwd: workspace, + env: { + QWEN_CLI_ENTRY: MOCK_AGENT_PATH, + MOCK_ACP_MODE: 'echo', + }, + }); + const source = await activeDaemon.client.createOrAttachSession({ + sessionScope: 'thread', + }); + await activeDaemon.client.prompt(source.sessionId, { + prompt: [{ type: 'text', text: 'source survives timeout' }], + }); + const target = await activeDaemon.client.createOrAttachSession({ + sessionScope: 'thread', + }); + globalThis.fetch = async (input, init) => { + const url = + typeof input === 'string' + ? input + : input instanceof URL + ? input.href + : input.url; + if ( + new URL(url, 'http://localhost').pathname === + `/session/${target.sessionId}/load` + ) { + return new Response( + JSON.stringify({ + code: 'session_restore_timeout', + errorKind: 'restore_timeout', + retryable: true, + }), + { + status: 504, + headers: { 'content-type': 'application/json' }, + }, + ); + } + return originalFetch(input, init); + }; + + let blocks: readonly DaemonTranscriptBlock[] = []; + let actions: ReturnType | undefined; + let connection: ReturnType | undefined; + function Harness() { + blocks = useTranscriptBlocks(); + actions = useActions(); + connection = useConnection(); + return null; + } + const container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => { + root?.render( + // eslint-disable-next-line react/no-children-prop + createElement(DaemonSessionProvider, { + autoConnect: true, + baseUrl: activeDaemon!.base, + token: activeDaemon!.token, + sessionId: source.sessionId, + children: createElement(Harness), + }), + ); + }); + await waitFor( + () => + connection?.sessionId === source.sessionId && + JSON.stringify(blocks).includes('source survives timeout'), + 'source session restore', + ); + + await act(async () => { + await expect( + actions!.loadSession(target.sessionId), + ).rejects.toMatchObject({ status: 504 }); + }); + await waitFor( + () => connection?.sessionTransition?.phase === 'failed', + 'failed target transition', + ); + expect(connection).toMatchObject({ + status: 'connected', + sessionId: source.sessionId, + sessionTransition: { phase: 'failed' }, + }); + expect(JSON.stringify(blocks)).toContain('source survives timeout'); + } finally { + globalThis.fetch = originalFetch; + if (root) { + await act(async () => root?.unmount()); + root = undefined; + } + await activeDaemon?.dispose(); + activeDaemon = undefined; + fs.rmSync(workspace, { recursive: true, force: true }); + } + }, 30_000); }); + +function createDeferred(): { + promise: Promise; + resolve(value?: T | PromiseLike): void; +} { + let resolve!: (value?: T | PromiseLike) => void; + const promise = new Promise((res) => { + resolve = (value) => res(value as T | PromiseLike); + }); + return { promise, resolve }; +} diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index 2ea86430f1a..75956c6ed77 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -8746,6 +8746,81 @@ describe('App session callbacks', () => { expect(arg?.['branch']).toBeUndefined(); }); + it('preserves the git mode intent when an existing-session switch fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + mockConnection.sessionId = undefined; + mockWorkspace.capabilities = { + workspaces: [ + { id: 'primary', cwd: '/workspace', primary: true, trusted: true }, + ], + }; + mockWorkspace.client.workspaceByCwd.mockImplementation(() => ({ + workspaceGit: vi.fn().mockResolvedValue({ branch: 'main' }), + workspaceSkills: mockWorkspaceActions.loadSkillsStatus, + })); + mockSessionActions.loadSession.mockRejectedValueOnce( + new Error('restore failed'), + ); + renderApp(); + await flush(); + await flush(); + act(() => { + testState.latestChatEditorProps?.onGitModeIntentChange?.({ + mode: 'branch', + name: 'feat/test', + }); + }); + + await act(async () => { + window.dispatchEvent( + new CustomEvent('qwen:open-session', { detail: 'session-2' }), + ); + await flush(); + }); + + expect(testState.latestChatEditorProps?.gitModeIntent).toEqual({ + mode: 'branch', + name: 'feat/test', + }); + }); + + it('clears the git mode intent after the committed owner changes', async () => { + mockConnection.sessionId = undefined; + mockWorkspace.capabilities = { + workspaces: [ + { id: 'primary', cwd: '/workspace', primary: true, trusted: true }, + ], + }; + mockWorkspace.client.workspaceByCwd.mockImplementation(() => ({ + workspaceGit: vi.fn().mockResolvedValue({ branch: 'main' }), + workspaceSkills: mockWorkspaceActions.loadSkillsStatus, + })); + const { rerender } = renderApp(); + await flush(); + await flush(); + act(() => { + testState.latestChatEditorProps?.onGitModeIntentChange?.({ + mode: 'branch', + name: 'feat/test', + }); + mockConnection.sessionId = 'session-2'; + mockConnection.clientId = 'client-2'; + }); + rerender(); + await flush(); + + act(() => { + mockConnection.sessionId = undefined; + mockConnection.clientId = undefined; + }); + rerender(); + await flush(); + + expect(testState.latestChatEditorProps?.gitModeIntent).toEqual({ + mode: 'current', + }); + }); + it('hides the git mode chip when the workspace is not trusted', async () => { mockConnection.sessionId = undefined; mockWorkspace.capabilities = { @@ -9226,6 +9301,20 @@ describe('App session callbacks', () => { ]); }); + it('discards an automatic recap after the transcript owner is replaced', async () => { + const { recap } = await triggerAutoRecap(); + testState.blocks = []; + + await act(async () => { + recap.resolve({ sessionId: 'session-1', recap: 'Previous owner recap' }); + await recap.promise; + }); + + expect(mockStore.dispatch).not.toHaveBeenCalledWith([ + expect.objectContaining({ source: 'recap' }), + ]); + }); + it('discards an automatic recap after starting a new session', async () => { const { recap, container } = await triggerAutoRecap(); await act(async () => { @@ -9257,7 +9346,7 @@ describe('App session callbacks', () => { ]); }); - it('discards an automatic recap after switching to an existing session', async () => { + it('keeps an automatic recap while an existing-session switch is only preparing', async () => { const { recap, container } = await triggerAutoRecap(); await act(async () => { container @@ -9273,12 +9362,12 @@ describe('App session callbacks', () => { expect(mockSessionActions.loadSession).toHaveBeenCalledWith('session-2', { workspaceCwd: undefined, }); - expect(mockStore.dispatch).not.toHaveBeenCalledWith([ + expect(mockStore.dispatch).toHaveBeenCalledWith([ expect.objectContaining({ source: 'recap' }), ]); }); - it('discards an automatic recap after resuming a session by command', async () => { + it('keeps an automatic recap while a command resume is only preparing', async () => { const { recap } = await triggerAutoRecap(); await act(async () => { testState.latestChatEditorProps?.onSubmit('/resume session-3'); @@ -9289,8 +9378,10 @@ describe('App session callbacks', () => { await recap.promise; }); - expect(mockSessionActions.loadSession).toHaveBeenCalledWith('session-3'); - expect(mockStore.dispatch).not.toHaveBeenCalledWith([ + expect(mockSessionActions.loadSession).toHaveBeenCalledWith('session-3', { + workspaceCwd: undefined, + }); + expect(mockStore.dispatch).toHaveBeenCalledWith([ expect.objectContaining({ source: 'recap' }), ]); }); @@ -9416,6 +9507,35 @@ describe('App session callbacks', () => { ); }); + it('does not finish a same-id switch before its target workspace commits', async () => { + const { rerender } = renderApp(); + await flush(); + editorFocus.mockClear(); + + await act(async () => { + window.dispatchEvent( + new CustomEvent('qwen:open-session', { + detail: { + sessionId: 'session-1', + workspaceCwd: '/target-workspace', + }, + }), + ); + await Promise.resolve(); + }); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(editorFocus).not.toHaveBeenCalled(); + + mockConnection.workspaceCwd = '/target-workspace'; + rerender(); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(editorFocus).toHaveBeenCalledOnce(); + }); + it('does not steal focus when an approval appears before deferred session focus', async () => { vi.useFakeTimers(); const { container, rerender } = renderApp(); @@ -10957,6 +11077,22 @@ describe('App session callbacks', () => { expect(onToast).not.toHaveBeenCalled(); }); + it('does not invoke host slash commands while a target is unresolved', async () => { + const onSlashCommand = vi.fn(() => true); + const { container } = renderApp({ + desiredTargetPending: true, + onSlashCommand, + }); + await flush(); + + testState.prompt = '/deploy production'; + await clickSubmit(container); + await flush(); + + expect(onSlashCommand).not.toHaveBeenCalled(); + expect(mockSessionActions.sendPrompt).not.toHaveBeenCalled(); + }); + it('reports a host slash command error and continues default handling', async () => { const error = new Error('host handler exploded'); const onSlashCommand = vi.fn(() => { @@ -13875,7 +14011,9 @@ describe('App session callbacks', () => { await flush(); expect(container.querySelector('[data-testid="inline-panel"]')).toBeNull(); - expect(mockSessionActions.loadSession).toHaveBeenCalledWith('session-2'); + expect(mockSessionActions.loadSession).toHaveBeenCalledWith('session-2', { + workspaceCwd: undefined, + }); }); it('dispatches rename only after the current session name changes', async () => { @@ -14709,6 +14847,23 @@ describe('App manual-run orchestration (scheduled tasks)', () => { }); }); + it('blocks a programmatic run while the desired target is unresolved', async () => { + const { container, rerender } = renderApp(); + await flush(); + await openRunHandler(container); + rerender({ desiredTargetPending: true }); + await flush(); + const run = testState.latestScheduledTasksProps?.onRunPrompt; + if (!run) throw new Error('onRunPrompt was not recaptured'); + + await act(async () => { + await expect(run('do the thing', null)).rejects.toMatchObject({ + name: 'InvalidStateError', + }); + }); + expect(mockSessionActions.sendPrompt).not.toHaveBeenCalled(); + }); + it('rejects an unbound run that settles without admitting (cancel path)', async () => { // Default sendPrompt resolves WITHOUT onAdmitted → onSubmitBefore cancel / // never reached the session: the caller must skip recording a run. @@ -14768,7 +14923,7 @@ describe('App manual-run orchestration (scheduled tasks)', () => { void second; }); - it('rejects a bound run when the session switch times out', async () => { + it('rejects a bound run when post-commit catch-up times out', async () => { const { container } = renderApp(); await flush(); const run = await openRunHandler(container); @@ -14783,7 +14938,86 @@ describe('App manual-run orchestration (scheduled tasks)', () => { await act(async () => { vi.advanceTimersByTime(30_000); }); - expect((err as Error | undefined)?.message).toMatch(/Timed out switching/); + expect((err as Error | undefined)?.message).toMatch( + /Timed out catching up/, + ); + }); + + it('starts the bound-run catch-up deadline only after restore commits', async () => { + admitOnSend(); + let resolveRestore: (() => void) | undefined; + mockSessionActions.loadSession.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveRestore = resolve; + }), + ); + const { container, rerender } = renderApp(); + await flush(); + const run = await openRunHandler(container); + vi.useFakeTimers(); + let err: unknown; + let runPromise: Promise | undefined; + await act(async () => { + runPromise = run('do the thing', 'slow-session'); + void runPromise.catch((error: unknown) => { + err = error; + }); + await Promise.resolve(); + vi.advanceTimersByTime(74_000); + }); + expect(err).toBeUndefined(); + + mockConnection.sessionId = 'slow-session'; + mockConnection.catchingUp = true; + await act(async () => { + resolveRestore?.(); + rerender(); + await Promise.resolve(); + }); + await act(async () => { + vi.advanceTimersByTime(29_000); + }); + expect(err).toBeUndefined(); + + await act(async () => { + mockConnection.catchingUp = false; + rerender(); + await Promise.resolve(); + }); + await expect(runPromise).resolves.toBeUndefined(); + expect(err).toBeUndefined(); + expect(mockSessionActions.sendPrompt).toHaveBeenCalledWith( + 'do the thing', + expect.objectContaining({ onAdmitted: expect.any(Function) }), + ); + }); + + it('clears a pending bound-run catch-up deadline on unmount', async () => { + const { container, unmount } = renderApp(); + await flush(); + const run = await openRunHandler(container); + vi.useFakeTimers(); + let error: unknown; + await act(async () => { + void run('do the thing', 'never-active').catch((cause: unknown) => { + error = cause; + }); + await Promise.resolve(); + }); + + await act(async () => { + unmount(); + await Promise.resolve(); + }); + expect(error).toMatchObject({ + name: 'AbortError', + message: 'Scheduled run interrupted by unmount', + }); + await act(async () => { + vi.advanceTimersByTime(30_000); + }); + expect(error).toMatchObject({ name: 'AbortError' }); }); it('"create via chat" starts a fresh session and primes the composer', async () => { diff --git a/packages/web-shell/client/App.tsx b/packages/web-shell/client/App.tsx index 70db4cf0306..c0c0c991a20 100644 --- a/packages/web-shell/client/App.tsx +++ b/packages/web-shell/client/App.tsx @@ -433,10 +433,9 @@ interface ArtifactPanelSessionState { interface PaneArtifactSnapshot { artifacts: readonly DaemonSessionArtifact[]; } -// Cap on how long a manual "run now" waits for its bound session to become -// active before giving up, so the scheduled-tasks UI can't stay stuck disabled -// if the switch never completes. -const BOUND_RUN_SWITCH_TIMEOUT_MS = 30_000; +// Cap on post-restore catch-up for a manual "run now". The restore itself uses +// the provider's session-restore deadline. +const BOUND_RUN_CATCH_UP_TIMEOUT_MS = 30_000; function availableSkillInfos(status: { skills?: Array<{ @@ -801,6 +800,7 @@ interface AppProps extends WebShellProps { initialSelectedWorkspaceCwd?: string; lockedWorkspaceCwd?: string; lockedWorkspaceCapability?: DaemonWorkspaceCapability; + desiredTargetPending?: boolean; restartSseOnPrompt?: boolean; historyPageSize?: number; } @@ -1616,6 +1616,7 @@ export function App({ initialSelectedWorkspaceCwd, lockedWorkspaceCwd, lockedWorkspaceCapability, + desiredTargetPending = false, }: AppProps = {}) { const [chatWidthMode, setChatWidthMode] = useState(readChatWidthMode); @@ -1659,9 +1660,12 @@ export function App({ const [sidebarCollapsed, setSidebarCollapsed] = useState(() => readSidebarCollapsed(sidebarOptions.defaultCollapsed), ); - const [sidebarSwitchingSessionId, setSidebarSwitchingSessionId] = useState< - string | null - >(null); + const [sidebarSwitchTarget, setSidebarSwitchTarget] = useState<{ + sessionId: string; + workspaceCwd?: string; + invocation: number; + restoreCommitted: boolean; + } | null>(null); const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false); const [forceMobileDrawer, setForceMobileDrawer] = useState(false); const closeMobileDrawer = useCallback(() => { @@ -1997,22 +2001,38 @@ export function App({ // re-runs (branch change, focus, poll) keep the live value to avoid flicker. const gitStatusWorkspaceCwdRef = useRef(undefined); /** Worktree metadata for the current session (set after creation). */ - const [sessionWorktree, setSessionWorktree] = useState< + const [storedSessionWorktree, setSessionWorktree] = useState< { slug: string; path: string; branch: string } | undefined >(undefined); /** Branch metadata for the current session (set after creation with branch mode). */ - const [sessionBranch, setSessionBranch] = useState< + const [storedSessionBranch, setSessionBranch] = useState< { name: string; baseBranch: string } | undefined >(undefined); - const [sessionStatusDisplayName, setSessionStatusDisplayName] = useState< - string | undefined - >(undefined); - // Tracks the session id from the latest effect run. In-flight fetches - // compare their captured sid against this ref on resolve: a match means + const [storedSessionStatusDisplayName, setSessionStatusDisplayName] = + useState(undefined); + // Tracks the committed owner from the latest effect run. In-flight fetches + // compare their captured key against this ref on resolve: a match means // the response is still relevant and may set OR clear the worktree state; - // a mismatch means connection.sessionId moved on (reconnect cycling or a - // user-initiated switch) and the stale response is dropped. - const worktreeSessionIdRef = useRef(undefined); + // a mismatch means the session, workspace, or client attachment moved on. + const metadataOwnerKey = connection.sessionId + ? JSON.stringify([ + connection.sessionId, + connection.workspaceCwd, + connection.clientId, + ]) + : undefined; + const worktreeOwnerKeyRef = useRef(undefined); + const metadataBelongsToCurrentSession = + worktreeOwnerKeyRef.current === metadataOwnerKey; + const sessionWorktree = metadataBelongsToCurrentSession + ? storedSessionWorktree + : undefined; + const sessionBranch = metadataBelongsToCurrentSession + ? storedSessionBranch + : undefined; + const sessionStatusDisplayName = metadataBelongsToCurrentSession + ? storedSessionStatusDisplayName + : undefined; // Restore worktree info from the server when switching to an existing // session. The effect intentionally does NOT cancel in-flight fetches on // cleanup: connection.sessionId can cycle through several sessions during @@ -2020,15 +2040,16 @@ export function App({ // discard the one response we actually need. useEffect(() => { const sid = connection.sessionId; - const previousSid = worktreeSessionIdRef.current; - worktreeSessionIdRef.current = sid; + const ownerKey = metadataOwnerKey; + const previousOwnerKey = worktreeOwnerKeyRef.current; + worktreeOwnerKeyRef.current = ownerKey; if (!sid) { setSessionWorktree(undefined); setSessionBranch(undefined); setSessionStatusDisplayName(undefined); return; } - if (previousSid !== sid) { + if (previousOwnerKey !== ownerKey) { setSessionWorktree(undefined); setSessionBranch(undefined); setSessionStatusDisplayName(undefined); @@ -2043,7 +2064,7 @@ export function App({ workspace.client .sessionStatus(sid) .then((summary) => { - if (worktreeSessionIdRef.current === sid) { + if (worktreeOwnerKeyRef.current === ownerKey) { setSessionWorktree(summary.worktree); setSessionBranch(summary.branch); setSessionStatusDisplayName(summary.displayName); @@ -2051,7 +2072,7 @@ export function App({ return workspace.client .listWorkspaceSessions(summary.workspaceCwd, { pageSize: 200 }) .then((sessions) => { - if (worktreeSessionIdRef.current !== sid) return; + if (worktreeOwnerKeyRef.current !== ownerKey) return; const listedSession = sessions.find( (session) => session.sessionId === sid, ); @@ -2062,7 +2083,7 @@ export function App({ .catch(() => undefined); }) .catch(() => { - if (worktreeSessionIdRef.current === sid) { + if (worktreeOwnerKeyRef.current === ownerKey) { setSessionWorktree(undefined); setSessionBranch(undefined); setSessionStatusDisplayName(undefined); @@ -2071,8 +2092,11 @@ export function App({ }, [ connection.catchingUp, connection.loadingTranscript, + connection.clientId, connection.sessionId, connection.status, + connection.workspaceCwd, + metadataOwnerKey, workspace.client, ]); // Active workspace: the connected session's workspace, else the workspace @@ -3315,7 +3339,7 @@ export function App({ ); const pendingApproval = useShallowMemo(rawPendingApproval); const canActOnPendingApproval = !( - connection.catchingUp && sidebarSwitchingSessionId !== null + connection.catchingUp && sidebarSwitchTarget !== null ); const pendingAskUserApproval = isAskUserPermission(pendingApproval) ? canActOnPendingApproval @@ -4447,15 +4471,32 @@ export function App({ const [selectedTheme, setSelectedTheme] = useState( providedTheme ?? WebShellThemeId.Dark, ); - const [currentModel, setCurrentModel] = useState(''); + const [storedCurrentModel, setStoredCurrentModel] = useState(''); + const currentModelOwnerKeyRef = useRef(metadataOwnerKey); + const currentModel = + currentModelOwnerKeyRef.current === metadataOwnerKey + ? storedCurrentModel + : ''; const currentModelRef = useRef(currentModel); currentModelRef.current = currentModel; - const setPendingModel = useCallback((modelId: string) => { - currentModelRef.current = modelId; - setCurrentModel(modelId); - }, []); + const setCurrentModel = useCallback( + (modelId: string) => { + currentModelOwnerKeyRef.current = metadataOwnerKey; + currentModelRef.current = modelId; + setStoredCurrentModel(modelId); + }, + [metadataOwnerKey], + ); + const setPendingModel = setCurrentModel; const connectionRef = useRef(connection); connectionRef.current = connection; + const isSessionTargetPending = useCallback( + () => + desiredTargetPending || + connectionRef.current.sessionTransition?.phase === 'queued' || + connectionRef.current.sessionTransition?.phase === 'preparing', + [desiredTargetPending], + ); const refreshActiveSessionDisplayName = useCallback(async () => { const activeConnection = connectionRef.current; if (!activeConnection.sessionId || !activeConnection.workspaceCwd) return; @@ -4466,6 +4507,8 @@ export function App({ ); if ( connectionRef.current.sessionId !== activeConnection.sessionId || + connectionRef.current.workspaceCwd !== activeConnection.workspaceCwd || + connectionRef.current.clientId !== activeConnection.clientId || connectionRef.current.displayName ) { return; @@ -4488,13 +4531,22 @@ export function App({ return false; }, [pushToast, t]); const sessionDisplayName = connection.displayName ?? sessionStatusDisplayName; - const [currentMode, setCurrentMode] = useState('default'); + const [storedCurrentMode, setStoredCurrentMode] = useState('default'); + const currentModeOwnerKeyRef = useRef(metadataOwnerKey); + const currentMode = + currentModeOwnerKeyRef.current === metadataOwnerKey + ? storedCurrentMode + : 'default'; const currentModeRef = useRef(currentMode); currentModeRef.current = currentMode; - const setPendingMode = useCallback((modeId: string) => { - currentModeRef.current = modeId; - setCurrentMode(modeId); - }, []); + const setPendingMode = useCallback( + (modeId: string) => { + currentModeOwnerKeyRef.current = metadataOwnerKey; + currentModeRef.current = modeId; + setStoredCurrentMode(modeId); + }, + [metadataOwnerKey], + ); const [isPreparingPrompt, setIsPreparingPrompt] = useState(false); const createSessionPromiseRef = useRef | null>( null, @@ -4504,10 +4556,26 @@ export function App({ const [gitModeIntent, setGitModeIntent] = useState({ mode: 'current', }); - const gitModeIntentRef = useRef(gitModeIntent); + const gitModeIntentOwnerKeyRef = useRef(metadataOwnerKey); + const visibleGitModeIntent: SessionGitIntent = + gitModeIntentOwnerKeyRef.current === metadataOwnerKey + ? gitModeIntent + : { mode: 'current' }; + const gitModeIntentRef = useRef(visibleGitModeIntent); + gitModeIntentRef.current = visibleGitModeIntent; + const updateGitModeIntent = useCallback( + (intent: SessionGitIntent) => { + gitModeIntentOwnerKeyRef.current = metadataOwnerKey; + gitModeIntentRef.current = intent; + setGitModeIntent(intent); + }, + [metadataOwnerKey], + ); useEffect(() => { - gitModeIntentRef.current = gitModeIntent; - }, [gitModeIntent]); + if (gitModeIntentOwnerKeyRef.current === metadataOwnerKey) return; + gitModeIntentOwnerKeyRef.current = metadataOwnerKey; + setGitModeIntent({ mode: 'current' }); + }, [metadataOwnerKey]); const newSessionSuggestionSubmitTokenRef = useRef(0); const pendingNewSessionSuggestionSubmitRef = useRef<{ token: number; @@ -4600,7 +4668,7 @@ export function App({ // Clear the pending intent only on success. On failure the // composer chip stays in the selected mode so the user knows // the intent was not fulfilled and can retry. - setGitModeIntent({ mode: 'current' }); + updateGitModeIntent({ mode: 'current' }); }); // One-shot: the picker targets only the *next* new session, so clear // it after creation. The next new chat defaults back to the primary @@ -4617,7 +4685,7 @@ export function App({ }; void promise.then(clearPreparation, clearPreparation); return promise; - }, [lockedWorkspaceCwd, sessionActions, workspaces]); + }, [lockedWorkspaceCwd, sessionActions, updateGitModeIntent, workspaces]); const onSubmitBeforeRef = useRef(onSubmitBefore); onSubmitBeforeRef.current = onSubmitBefore; const onSlashCommandRef = useRef(onSlashCommand); @@ -4685,6 +4753,12 @@ export function App({ onOptimisticUserMessage?: (message: OptimisticUserMessage) => void; }, ) => { + if (isSessionTargetPending()) { + throw new DOMException( + 'A session switch is still preparing', + 'InvalidStateError', + ); + } const isUserPrompt = !text.trimStart().startsWith('/'); const previousLastSubmittedPrompt = lastSubmittedPromptRef.current; const previousLastSubmittedImages = lastSubmittedImagesRef.current; @@ -4801,6 +4875,7 @@ export function App({ clearFollowup, ensureSessionForPrompt, getComposerWorkspaceCwd, + isSessionTargetPending, scheduleDelayedSessionListReload, sessionActions, store, @@ -4862,9 +4937,9 @@ export function App({ ); useEffect(() => { if (!gitModeEligible) { - setGitModeIntent({ mode: 'current' }); + updateGitModeIntent({ mode: 'current' }); } - }, [gitModeEligible]); + }, [gitModeEligible, updateGitModeIntent]); const handleOpenGitDiff = useCallback(() => { if (!gitDiffWorkspaceCwd) return; setGitDialog({ @@ -5806,6 +5881,10 @@ export function App({ const handleSetMode = useCallback( (modeId: string) => { + if (isSessionTargetPending()) { + pushToast('warning', t('editor.sessionLoading')); + return; + } if (!isDaemonApprovalMode(modeId)) { reportError( new Error(`Unsupported approval mode: ${modeId}`), @@ -5821,7 +5900,7 @@ export function App({ .setApprovalMode(modeId) .then((result) => { const effectiveMode = result.mode || modeId; - setCurrentMode(effectiveMode); + setPendingMode(effectiveMode); const approval = pendingApprovalRef.current; if (!approval) return; const shouldAutoApprove = @@ -5851,7 +5930,15 @@ export function App({ reportError(error, t('local.approvalMode')); }); }, - [sessionActions, reportError, store, t, setPendingMode], + [ + isSessionTargetPending, + pushToast, + sessionActions, + reportError, + store, + t, + setPendingMode, + ], ); useEffect(() => { @@ -6019,11 +6106,11 @@ export function App({ useEffect(() => { setCurrentModel(connection.currentModel ?? ''); - }, [connection.currentModel, connection.sessionId]); + }, [connection.currentModel, metadataOwnerKey, setCurrentModel]); useEffect(() => { - setCurrentMode(connection.currentMode ?? 'default'); - }, [connection.currentMode, connection.sessionId]); + setPendingMode(connection.currentMode ?? 'default'); + }, [connection.currentMode, metadataOwnerKey, setPendingMode]); useEffect(() => { const previousGoalSessionId = lastGoalSessionIdRef.current; @@ -6081,14 +6168,14 @@ export function App({ workspaces, ]); - const lastRenameSessionRef = useRef(undefined); + const lastRenameOwnerRef = useRef(undefined); const lastRenameNameRef = useRef(undefined); useEffect(() => { const sessionId = connection.sessionId; const displayName = connection.displayName; if (!sessionId || !displayName) return; - if (sessionId !== lastRenameSessionRef.current) { - lastRenameSessionRef.current = sessionId; + if (metadataOwnerKey !== lastRenameOwnerRef.current) { + lastRenameOwnerRef.current = metadataOwnerKey; lastRenameNameRef.current = displayName; return; } @@ -6099,7 +6186,7 @@ export function App({ sessionId, newName: displayName, }); - }, [connection.sessionId, connection.displayName]); + }, [connection.displayName, connection.sessionId, metadataOwnerKey]); useEffect(() => { const nextGoal = getLatestActiveGoalFromBlocks(blocks); @@ -6147,7 +6234,7 @@ export function App({ useEffect(() => { lastRecapBlockCountRef.current = 0; autoRecapVersionRef.current += 1; - }, [connection.sessionId]); + }, [metadataOwnerKey]); useEffect(() => { const AWAY_THRESHOLD_MS = 3 * 60 * 1000; const MIN_NEW_BLOCKS = 4; @@ -6162,7 +6249,8 @@ export function App({ if (Date.now() - hiddenAt < AWAY_THRESHOLD_MS) return; if (streamingStateRef.current !== 'idle') return; if (!connection.sessionId) return; - const currentCount = store.getSnapshot().blocks.length; + const transcriptBlocks = store.getSnapshot().blocks; + const currentCount = transcriptBlocks.length; if (currentCount - lastRecapBlockCountRef.current < MIN_NEW_BLOCKS) return; lastRecapBlockCountRef.current = currentCount; @@ -6183,6 +6271,7 @@ export function App({ autoRecapVersionRef.current !== version || connectionRef.current.sessionId !== sessionId || result.sessionId !== sessionId || + store.getSnapshot().blocks !== transcriptBlocks || currentUserBlockId !== userBlockId || streamingStateRef.current !== 'idle' ) { @@ -6264,18 +6353,15 @@ export function App({ const branchCurrentSession = useCallback( (name?: string) => { + if (isSessionTargetPending()) { + pushToast('warning', t('editor.sessionLoading')); + return; + } if (!requireActiveSessionForLocalCommand()) return; sessionActions .branchSession(name || undefined) .then((result) => { - store.dispatch([ - { - type: 'status', - text: t('branch.success', { - name: result.displayName, - }), - }, - ]); + pushToast('info', t('branch.success', { name: result.displayName })); }) .catch((error: unknown) => { reportError(error, t('branch.failed')); @@ -6283,9 +6369,10 @@ export function App({ }, [ reportError, + pushToast, + isSessionTargetPending, requireActiveSessionForLocalCommand, sessionActions, - store, t, ], ); @@ -6326,7 +6413,7 @@ export function App({ setSelectedWorkspaceCwd(targetWorkspaceCwd); // Starting a fresh chat drops any pending git mode intent so it never // leaks into the next created session. - setGitModeIntent({ mode: 'current' }); + updateGitModeIntent({ mode: 'current' }); // Close the drawer before awaiting so a failed createSession() doesn't leave // it stuck open with the page scroll still locked, matching loadSidebarSession. closeMobileDrawer(); @@ -6366,6 +6453,7 @@ export function App({ reloadLoadedSkills, scheduleComposerFocus, sessionActions, + updateGitModeIntent, ], ); /** @@ -6775,26 +6863,37 @@ export function App({ } }, [createNewSession, onSessionIdChange]); + const sessionOpenInvocationRef = useRef(0); const loadSidebarSession = useCallback( async (sessionId: string, workspaceCwd?: string) => { + const invocation = ++sessionOpenInvocationRef.current; composerFocusRequestRef.current += 1; - setSidebarSwitchingSessionId(sessionId); - setGitModeIntent({ mode: 'current' }); - setSessionWorktree(undefined); - setSessionBranch(undefined); - // Close the drawer before awaiting the load; the transcript clears - // immediately and shows its loading skeleton for the selected session. + setSidebarSwitchTarget({ + sessionId, + ...(workspaceCwd !== undefined ? { workspaceCwd } : {}), + invocation, + restoreCommitted: false, + }); + // Navigation chrome can close immediately, but session-owned metadata, + // recap generation, and transcript remain attached to the current owner + // until the provider commits the target. closeMobileDrawer(); // Loading another session should reveal its chat, not stay on the // Settings/Status panel (no-op when the panel is closed). closePanel(); try { - autoRecapVersionRef.current += 1; await sessionActions.loadSession(sessionId, { workspaceCwd }); + if (sessionOpenInvocationRef.current === invocation) { + setSidebarSwitchTarget((current) => + current?.invocation === invocation + ? { ...current, restoreCommitted: true } + : current, + ); + } } catch (error) { - setSidebarSwitchingSessionId((current) => - current === sessionId ? null : current, - ); + if (sessionOpenInvocationRef.current === invocation) { + setSidebarSwitchTarget(null); + } throw error; } }, @@ -6842,20 +6941,26 @@ export function App({ useEffect(() => { if ( - sidebarSwitchingSessionId !== null && - connection.sessionId === sidebarSwitchingSessionId && + sidebarSwitchTarget?.restoreCommitted === true && + connection.sessionId === sidebarSwitchTarget.sessionId && + (sidebarSwitchTarget.workspaceCwd === undefined || + connection.workspaceCwd === sidebarSwitchTarget.workspaceCwd) && !connection.loadingTranscript && - !connection.catchingUp + !connection.catchingUp && + connection.sessionTransition?.phase !== 'queued' && + connection.sessionTransition?.phase !== 'preparing' ) { - setSidebarSwitchingSessionId(null); - scheduleComposerFocus(sidebarSwitchingSessionId); + setSidebarSwitchTarget(null); + scheduleComposerFocus(sidebarSwitchTarget.sessionId); } }, [ connection.catchingUp, connection.loadingTranscript, connection.sessionId, + connection.sessionTransition?.phase, + connection.workspaceCwd, scheduleComposerFocus, - sidebarSwitchingSessionId, + sidebarSwitchTarget, ]); // Manual "run now" from the scheduled-tasks page. A bound task runs in its @@ -6872,15 +6977,37 @@ export function App({ prompt: string; resolve: () => void; reject: (err: unknown) => void; - timer: ReturnType; + timer?: ReturnType; } | null>(null); - const clearPendingBoundRun = useCallback((sessionId: string) => { - const cur = pendingBoundRunRef.current; - if (cur && cur.sessionId === sessionId) { - clearTimeout(cur.timer); + const clearPendingBoundRun = useCallback( + ( + sessionId: string, + expected?: NonNullable, + ) => { + const cur = pendingBoundRunRef.current; + if ( + cur && + cur.sessionId === sessionId && + (expected === undefined || cur === expected) + ) { + if (cur.timer !== undefined) clearTimeout(cur.timer); + pendingBoundRunRef.current = null; + } + }, + [], + ); + useEffect( + () => () => { + const pending = pendingBoundRunRef.current; + if (!pending) return; + if (pending.timer !== undefined) clearTimeout(pending.timer); pendingBoundRunRef.current = null; - } - }, []); + pending.reject( + new DOMException('Scheduled run interrupted by unmount', 'AbortError'), + ); + }, + [], + ); // Enqueue a manual-run prompt in the CURRENT session, resolving as soon as the // daemon ADMITS it — not when the whole turn finishes. sendPrompt resolves via // waitForAcceptedPromptCompletion (turn end), which is too late: a long or @@ -6893,11 +7020,11 @@ export function App({ // handled the rejection and skipped recording — an unrecorded run the user // could retry into a duplicate. Staying tied to admission guarantees any // accepted prompt is recorded, and the run controls stay busy (not free to - // re-fire) until the send admits or settles. The earlier "session never becomes - // active" phase is still bounded by the switch timeout in runTaskManually. If - // the send settles WITHOUT admitting (onSubmitBefore cancel) or throws before - // admission, reject so the caller skips recording a run that never reached the - // session. + // re-fire) until the send admits or settles. If the send settles WITHOUT + // admitting (onSubmitBefore cancel) or throws before admission, reject so the + // caller skips recording a run that never reached the session. Restore uses + // the provider's deadline; the 30-second timer starts only after commit and + // bounds the remaining catch-up phase. const enqueueManualRun = useCallback( (prompt: string): Promise => new Promise((resolve, reject) => { @@ -6937,7 +7064,7 @@ export function App({ ) { return; } - clearTimeout(pending.timer); + if (pending.timer !== undefined) clearTimeout(pending.timer); pendingBoundRunRef.current = null; // Resolves at prompt admission (see enqueueManualRun); the switch-timeout was // cleared above, so a long turn can't trip it. Recording happens in the @@ -6958,29 +7085,35 @@ export function App({ // reject the old promise so its caller doesn't record a dropped run. const prev = pendingBoundRunRef.current; if (prev) { - clearTimeout(prev.timer); + if (prev.timer !== undefined) clearTimeout(prev.timer); pendingBoundRunRef.current = null; prev.reject(new Error('superseded by another run')); } return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - clearPendingBoundRun(sessionId); - reject(new Error('Timed out switching to the task session')); - }, BOUND_RUN_SWITCH_TIMEOUT_MS); - pendingBoundRunRef.current = { + const pending: NonNullable = { sessionId, prompt, resolve, reject, - timer, }; + pendingBoundRunRef.current = pending; loadSidebarSession(sessionId) // Fire immediately when the session was already active (no dep change // to trigger the effect); a no-op if the load is still settling, in // which case the effect picks it up. - .then(() => tryFireBoundRun()) + .then(() => { + if (pendingBoundRunRef.current !== pending) return; + tryFireBoundRun(); + if (pendingBoundRunRef.current !== pending) return; + pending.timer = setTimeout(() => { + if (pendingBoundRunRef.current !== pending) return; + clearPendingBoundRun(sessionId, pending); + reject(new Error('Timed out catching up the task session')); + }, BOUND_RUN_CATCH_UP_TIMEOUT_MS); + }) .catch((error: unknown) => { - clearPendingBoundRun(sessionId); + if (pendingBoundRunRef.current !== pending) return; + clearPendingBoundRun(sessionId, pending); reject(error); }); }); @@ -7089,11 +7222,20 @@ export function App({ ); const rewindConversationOnly = useCallback( - (promptId: string) => - sessionActions + (promptId: string) => { + if (isSessionTargetPending()) { + return Promise.reject( + new DOMException( + 'A session switch is still preparing', + 'InvalidStateError', + ), + ); + } + return sessionActions .rewindSession(promptId, { rewindFiles: false }) - .then(() => undefined), - [sessionActions], + .then(() => undefined); + }, + [isSessionTargetPending, sessionActions], ); const handleRewindError = useCallback( @@ -7181,6 +7323,10 @@ export function App({ commitComposerAccepted?: ComposerSubmitCommit, metadata?: { inputAnnotations?: DaemonInputAnnotation[] }, ) => { + if (isSessionTargetPending()) { + pushToast('warning', t('editor.sessionLoading')); + return false; + } if ( invokeSlashCommandHandler(text, onSlashCommandRef.current, reportError) ) { @@ -7894,13 +8040,7 @@ export function App({ if (cmd === 'resume') { const sessionId = text.slice(match[0].length).trim(); if (sessionId) { - closeMobileDrawer(); - // Resuming a session means the user wants to see that chat, so - // close any open Settings/Status panel (no-op when already closed), - // consistent with createNewSession / loadSidebarSession. - closePanel(); - autoRecapVersionRef.current += 1; - sessionActions.loadSession(sessionId).catch((error: unknown) => { + loadSidebarSession(sessionId).catch((error: unknown) => { reportError(error, 'Failed to load session'); }); } else { @@ -8159,7 +8299,6 @@ export function App({ dispatchReadOnlyStatus, branchCurrentSession, closeMobileDrawer, - closePanel, openPanel, openScheduledTasks, openGoals, @@ -8178,6 +8317,7 @@ export function App({ createSideTask, sideTasksAvailable, openEnvironmentTasksPanel, + loadSidebarSession, hiddenCommands, pushToast, reportError, @@ -8196,6 +8336,7 @@ export function App({ t, workspaceActions, updateFailedPrompt, + isSessionTargetPending, ], ); @@ -8497,11 +8638,14 @@ export function App({ }; }, [resetEscapeState]); - const isDisabled = shouldDisableComposerInput({ - catchingUp: Boolean(connection.catchingUp), - pendingApproval: pendingApproval !== null, - isPreparingPrompt, - }); + const isSessionTransitionPending = isSessionTargetPending(); + const isDisabled = + isSessionTransitionPending || + shouldDisableComposerInput({ + catchingUp: Boolean(connection.catchingUp), + pendingApproval: pendingApproval !== null, + isPreparingPrompt, + }); const composerPlaceholderInputState = { catchingUp: Boolean(connection.catchingUp), isPreparingPrompt, @@ -8518,6 +8662,10 @@ export function App({ const handleModelSelect = useCallback( (modelId: string) => { + if (isSessionTargetPending()) { + pushToast('warning', t('editor.sessionLoading')); + return; + } if (!connectionRef.current.sessionId) { setPendingModel(modelId); return; @@ -8546,7 +8694,15 @@ export function App({ }) .finally(() => setModelActionBusy(false)); }, - [sessionActions, store, reportError, t, setPendingModel], + [ + isSessionTargetPending, + pushToast, + sessionActions, + store, + reportError, + t, + setPendingModel, + ], ); const handleDeleteModel = useCallback( @@ -9168,14 +9324,9 @@ export function App({ { - closeMobileDrawer(); - closePanel(); - autoRecapVersionRef.current += 1; - sessionActions - .loadSession(sessionId) - .catch((error: unknown) => { - reportError(error, 'Failed to load session'); - }); + void loadSidebarSession(sessionId).catch((error: unknown) => { + reportError(error, 'Failed to load session'); + }); }} onClose={() => setShowResumeDialog(false)} /> @@ -10574,7 +10725,9 @@ export function App({ onCancel={handleCancel} isRunning={streamingState !== 'idle'} isPreparing={ - isPreparingPrompt || isStartingNewSessionSuggestion + isPreparingPrompt || + isStartingNewSessionSuggestion || + isSessionTransitionPending } cancelArmed={cancelArmed} disabled={ @@ -10605,8 +10758,12 @@ export function App({ gitBranch={activeGitBranch} gitWorktree={Boolean(sessionWorktree)} gitCwd={sessionWorktree?.path} - gitModeIntent={gitModeEligible ? gitModeIntent : undefined} - onGitModeIntentChange={gitModeEligible ? setGitModeIntent : undefined} + gitModeIntent={ + gitModeEligible ? visibleGitModeIntent : undefined + } + onGitModeIntentChange={ + gitModeEligible ? updateGitModeIntent : undefined + } gitStatus={selectedWorkspaceGitStatus} onOpenGitDiff={ gitDiffWorkspaceCwd diff --git a/packages/web-shell/client/components/ChatPane.test.tsx b/packages/web-shell/client/components/ChatPane.test.tsx index b31e3d60e82..a8bb7a83ee7 100644 --- a/packages/web-shell/client/components/ChatPane.test.tsx +++ b/packages/web-shell/client/components/ChatPane.test.tsx @@ -787,6 +787,36 @@ describe('ChatPane', () => { expect(enqueuePrompt).not.toHaveBeenCalled(); }); + it('gates new pane writes before UI side effects during a session transition', () => { + connectionState.sessionTransition = { + phase: 'preparing', + operation: 'load', + origin: 'action', + targetSessionId: 'session-b', + }; + const onSlashCommand = vi.fn(() => true); + render({ onSlashCommand }); + let returned: boolean | undefined; + + act(() => { + returned = latestOnSubmit!('/deploy production'); + testid('pane-pick-mode')?.click(); + testid('pane-pick-model')?.click(); + testid('pane-cancel')?.click(); + }); + + expect(returned).toBe(false); + expect(onSlashCommand).not.toHaveBeenCalled(); + expect(sendPrompt).not.toHaveBeenCalled(); + expect(setApprovalMode).not.toHaveBeenCalled(); + expect(setModel).not.toHaveBeenCalled(); + expect(cancel).toHaveBeenCalledOnce(); + expect(latestChatEditorProps).toMatchObject({ + disabled: true, + isPreparing: true, + }); + }); + it('forwards a slash command the host does not handle', () => { const onSlashCommand = vi.fn(); render({ onSlashCommand }); diff --git a/packages/web-shell/client/components/ChatPane.tsx b/packages/web-shell/client/components/ChatPane.tsx index 7298810110c..51db42aaa8f 100644 --- a/packages/web-shell/client/components/ChatPane.tsx +++ b/packages/web-shell/client/components/ChatPane.tsx @@ -298,6 +298,9 @@ export function ChatPane({ }, [artifacts, connection.sessionId, onPaneArtifactsChange]); const streamingStateRef = useRef(streamingState); streamingStateRef.current = streamingState; + const sessionTransitionPending = + connection.sessionTransition?.phase === 'queued' || + connection.sessionTransition?.phase === 'preparing'; const firstPromptAdmittedRef = useRef(false); const reloadTranscript = useCallback( async (signal: AbortSignal) => { @@ -454,6 +457,7 @@ export function ChatPane({ ): boolean => { const trimmed = text.trim(); if (!trimmed) return false; + if (sessionTransitionPending) return false; if ( invokeSlashCommandHandler(text, onSlashCommandRef.current, reportError) ) { @@ -501,6 +505,7 @@ export function ChatPane({ onFirstPromptAdmitted, reportError, restartSseOnPrompt, + sessionTransitionPending, ], ); @@ -568,6 +573,7 @@ export function ChatPane({ ); const handleSelectMode = useCallback( (modeId: string) => { + if (sessionTransitionPending) return; // Modes always arrive from the toolbar's own picker, but narrow anyway so // the daemon action gets a well-typed value (mirrors App's handleSetMode). if (!isDaemonApprovalMode(modeId)) { @@ -604,17 +610,18 @@ export function ChatPane({ reportError(error, 'Failed to set approval mode'), ); }, - [actions, reportError], + [actions, reportError, sessionTransitionPending], ); const handleSelectModel = useCallback( (modelId: string) => { + if (sessionTransitionPending) return; actions .setModel(modelId) .catch((error: unknown) => reportError(error, 'Failed to switch model'), ); }, - [actions, reportError], + [actions, reportError, sessionTransitionPending], ); const headerLabel = @@ -856,6 +863,7 @@ export function ChatPane({ onSubmit={handleSubmit} onCancel={handleCancel} isRunning={isResponding} + isPreparing={sessionTransitionPending} commands={commands} queuedMessages={queuedTexts} onPopQueuedMessages={editLastQueuedPrompt} @@ -871,7 +879,7 @@ export function ChatPane({ onSelectMode={handleSelectMode} onSelectModel={handleSelectModel} dialogOpen={approvalActive} - disabled={approvalActive} + disabled={approvalActive || sessionTransitionPending} voiceTarget={hidden ? undefined : voiceTarget} voiceStatusRevision={voiceStatusRevision} followupState={followupState} @@ -884,7 +892,7 @@ export function ChatPane({ /> {CustomComposerFooter && ( ({ + connection: { + status: 'connected', + sessionId: 'session-a', + workspaceCwd: '/work/a', + } as Record, + workspace: { + status: 'connected', + capabilities: { + workspaceCwd: '/work/a', + workspaces: [ + { id: 'a', cwd: '/work/a', primary: true, trusted: true }, + { id: 'b', cwd: '/work/b', primary: false, trusted: true }, + ], + }, + refreshCapabilities: vi.fn(async () => undefined), + } as Record, + addWorkspace: vi.fn(), + providerMounts: 0, + providerUnmounts: 0, + providerProps: [] as Array>, + appProps: [] as Array>, +})); + +vi.mock('@qwen-code/webui/daemon-react-sdk', () => ({ + DaemonSessionProvider: ({ + children, + ...props + }: Record & { children: ReactNode }) => { + mocks.providerProps.push(props); + useEffect(() => { + mocks.providerMounts += 1; + return () => { + mocks.providerUnmounts += 1; + }; + }, []); + return children; + }, + useConnection: () => mocks.connection, + useWorkspace: () => mocks.workspace, + useWorkspaceActions: () => ({ addWorkspace: mocks.addWorkspace }), +})); + +vi.mock('../App', () => ({ + App: (props: Record) => { + mocks.appProps.push(props); + return ( + + {String( + props['lockedWorkspaceCwd'] ?? + props['initialSelectedWorkspaceCwd'] ?? + '', + )} + + ); + }, +})); + +import { WorkspaceSessionProvider } from './WorkspaceSessionProvider'; + +describe('WorkspaceSessionProvider transactional targets', () => { + let container: HTMLDivElement; + let root: ReturnType; + + beforeEach(() => { + mocks.connection = { + status: 'connected', + sessionId: 'session-a', + workspaceCwd: '/work/a', + }; + mocks.workspace = { + status: 'connected', + capabilities: { + workspaceCwd: '/work/a', + workspaces: [ + { id: 'a', cwd: '/work/a', primary: true, trusted: true }, + { id: 'b', cwd: '/work/b', primary: false, trusted: true }, + ], + }, + refreshCapabilities: vi.fn(async () => undefined), + }; + mocks.addWorkspace.mockReset(); + mocks.providerMounts = 0; + mocks.providerUnmounts = 0; + mocks.providerProps = []; + mocks.appProps = []; + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + }); + + const renderTarget = async ( + sessionId: string, + workspaceCwd?: string, + onSessionIdChange?: ( + sessionId: string | undefined, + workspaceId?: string, + workspaceCwd?: string, + ) => void, + clientId?: string, + ) => { + await act(async () => { + root.render( + , + ); + }); + }; + + it('keeps the committed App mounted until the desired workspace commits', async () => { + await renderTarget('session-a', '/work/a'); + expect(container.textContent).toBe('/work/a'); + expect(mocks.providerMounts).toBe(1); + + await renderTarget('session-b', '/work/b'); + + expect(mocks.providerProps.at(-1)).toMatchObject({ + sessionId: 'session-b', + workspaceCwd: '/work/b', + }); + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: true, + }); + expect(container.textContent).toBe('/work/a'); + expect(mocks.providerMounts).toBe(1); + expect(mocks.providerUnmounts).toBe(0); + + mocks.connection = { + status: 'connected', + sessionId: 'session-b', + workspaceCwd: '/work/b', + }; + const firstCommittedRender = mocks.appProps.length; + await renderTarget('session-b', '/work/b'); + + expect(container.textContent).toBe('/work/b'); + expect(mocks.appProps[firstCommittedRender]).toMatchObject({ + initialSelectedWorkspaceCwd: '/work/b', + desiredTargetPending: false, + }); + expect(mocks.providerMounts).toBe(1); + }); + + it('forwards a session with no explicit workspace before capabilities load', async () => { + mocks.workspace = { + status: 'connecting', + capabilities: undefined, + refreshCapabilities: vi.fn(async () => undefined), + }; + + await renderTarget('session-a'); + + expect(mocks.providerProps.at(-1)).toMatchObject({ + sessionId: 'session-a', + workspaceCwd: undefined, + }); + }); + + it('stabilizes the implicit primary workspace for older capabilities', async () => { + mocks.workspace = { + status: 'connected', + capabilities: { workspaceCwd: '/work/a' }, + refreshCapabilities: vi.fn(async () => undefined), + }; + + await renderTarget('session-a'); + + expect(container.textContent).toBe('/work/a'); + expect(mocks.providerMounts).toBe(1); + expect(mocks.providerUnmounts).toBe(0); + }); + + it('keeps the committed App gated while workspace resolution is pending', async () => { + await renderTarget('session-a', '/work/a', undefined, 'client-a'); + mocks.workspace = { + status: 'connected', + capabilities: undefined, + refreshCapabilities: vi.fn(async () => undefined), + }; + + await renderTarget('session-b', '/work/b', undefined, 'client-b'); + + expect(container.textContent).toBe('/work/a'); + expect(mocks.providerProps.at(-1)).toMatchObject({ + sessionId: 'session-a', + workspaceCwd: '/work/a', + clientId: 'client-a', + }); + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: true, + }); + expect(mocks.providerMounts).toBe(1); + expect(mocks.providerUnmounts).toBe(0); + }); + + it('keeps a same-session cross-workspace target gated until resolution', async () => { + await renderTarget('session-a', '/work/a', undefined, 'client-a'); + mocks.workspace = { + status: 'connected', + capabilities: undefined, + refreshCapabilities: vi.fn(async () => undefined), + }; + + await renderTarget('session-a', '/work/b', undefined, 'client-a'); + + expect(mocks.providerProps.at(-1)).toMatchObject({ + sessionId: 'session-a', + workspaceCwd: '/work/a', + clientId: 'client-a', + }); + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: true, + }); + }); + + it('keeps the committed App and rolls the host back for a missing workspace', async () => { + const onSessionIdChange = vi.fn(); + await renderTarget('session-a', '/work/a'); + mocks.workspace = { + ...mocks.workspace, + capabilities: { + workspaceCwd: '/work/a', + workspaces: [{ id: 'a', cwd: '/work/a', primary: true, trusted: true }], + }, + }; + + await renderTarget('session-b', '/work/missing', onSessionIdChange); + + expect(container.textContent).toBe('/work/a'); + expect(mocks.providerProps.at(-1)).toMatchObject({ + sessionId: 'session-a', + workspaceCwd: '/work/a', + }); + expect(mocks.providerMounts).toBe(1); + expect(mocks.providerUnmounts).toBe(0); + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: false, + }); + expect(onSessionIdChange).toHaveBeenCalledWith( + 'session-a', + undefined, + '/work/a', + ); + + await renderTarget('session-b', '/work/missing', onSessionIdChange); + await renderTarget('session-b', '/work/missing', onSessionIdChange); + expect(onSessionIdChange).toHaveBeenCalledTimes(1); + }); + + it('ignores a failed transition from an older requested client', async () => { + const onSessionIdChange = vi.fn(); + await renderTarget('session-a', '/work/a', onSessionIdChange, 'client-a'); + onSessionIdChange.mockClear(); + mocks.connection = { + status: 'connected', + sessionId: 'session-a', + workspaceCwd: '/work/a', + clientId: 'client-a', + sessionTransition: { + phase: 'failed', + operation: 'load', + origin: 'controlled', + targetSessionId: 'session-b', + targetWorkspaceCwd: '/work/b', + targetClientId: 'client-b', + }, + }; + + await renderTarget('session-b', '/work/b', onSessionIdChange, 'client-c'); + + expect(onSessionIdChange).not.toHaveBeenCalled(); + }); + + it('ungates the committed App after the desired transition fails', async () => { + const onSessionIdChange = vi.fn(); + await renderTarget('session-a', '/work/a', onSessionIdChange, 'client-a'); + onSessionIdChange.mockClear(); + + await renderTarget('session-b', '/work/b', onSessionIdChange, 'client-b'); + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: true, + }); + + mocks.connection = { + status: 'connected', + sessionId: 'session-a', + workspaceCwd: '/work/a', + clientId: 'client-a', + sessionTransition: { + phase: 'failed', + operation: 'load', + origin: 'controlled', + targetSessionId: 'session-b', + targetWorkspaceCwd: '/work/b', + targetClientId: 'client-b', + }, + }; + await renderTarget('session-b', '/work/b', onSessionIdChange, 'client-b'); + + expect(mocks.appProps.at(-1)).toMatchObject({ + desiredTargetPending: false, + }); + expect(onSessionIdChange).toHaveBeenCalledWith( + 'session-a', + undefined, + '/work/a', + ); + + await renderTarget('session-b', '/work/b', onSessionIdChange, 'client-b'); + await renderTarget('session-b', '/work/b', onSessionIdChange, 'client-b'); + expect(onSessionIdChange).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/web-shell/client/components/WorkspaceSessionProvider.tsx b/packages/web-shell/client/components/WorkspaceSessionProvider.tsx index c080852f3c1..9b518576afb 100644 --- a/packages/web-shell/client/components/WorkspaceSessionProvider.tsx +++ b/packages/web-shell/client/components/WorkspaceSessionProvider.tsx @@ -1,7 +1,15 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { + type ReactNode, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; import { WifiOffIcon } from 'lucide-react'; import { DaemonSessionProvider, + useConnection, useWorkspace, useWorkspaceActions, } from '@qwen-code/webui/daemon-react-sdk'; @@ -26,6 +34,60 @@ interface WorkspaceSessionProviderProps { webShellProps: WebShellProps; } +function SessionCommitObserver({ + desiredSessionId, + desiredWorkspace, + desiredWorkspaceRequired, + desiredClientId, + onCommit, + onFailure, + children, +}: { + desiredSessionId?: string; + desiredWorkspace?: DaemonWorkspaceCapability; + desiredWorkspaceRequired: boolean; + desiredClientId?: string; + onCommit: () => void; + onFailure: () => void; + children: (desiredCommitted: boolean) => ReactNode; +}) { + const connection = useConnection(); + const reportedFailureRef = useRef< + typeof connection.sessionTransition | undefined + >(undefined); + const desiredCommitted = + connection.sessionId === desiredSessionId && + (!desiredWorkspaceRequired || desiredWorkspace !== undefined) && + (!desiredWorkspace || connection.workspaceCwd === desiredWorkspace.cwd) && + (!desiredClientId || connection.clientId === desiredClientId) && + !connection.sessionTransition; + useEffect(() => { + if (desiredCommitted) onCommit(); + }, [desiredCommitted, onCommit]); + useEffect(() => { + const transition = connection.sessionTransition; + if ( + transition?.phase !== 'failed' || + transition === reportedFailureRef.current || + transition.targetSessionId !== desiredSessionId || + (desiredWorkspace && + transition.targetWorkspaceCwd !== desiredWorkspace.cwd) || + (desiredClientId && transition.targetClientId !== desiredClientId) + ) { + return; + } + reportedFailureRef.current = transition; + onFailure(); + }, [ + connection.sessionTransition, + desiredClientId, + desiredSessionId, + desiredWorkspace, + onFailure, + ]); + return children(desiredCommitted); +} + export function WorkspaceSessionProvider({ sessionId, workspaceId, @@ -86,15 +148,144 @@ export function WorkspaceSessionProvider({ lockWorkspaceCwd && registeredWorkspace?.requestedCwd === lockWorkspaceCwd ? registeredWorkspace.workspace : undefined; + const implicitPrimaryWorkspace = useMemo( + () => + workspace.capabilities?.workspaces?.find((entry) => entry.primary) ?? + (workspace.capabilities?.workspaceCwd + ? { + id: 'primary', + cwd: workspace.capabilities.workspaceCwd, + primary: true, + trusted: true, + } + : undefined), + [workspace.capabilities?.workspaceCwd, workspace.capabilities?.workspaces], + ); const targetWorkspace = effectiveWorkspaceCwd ? (pathWorkspace ?? registeredLockedWorkspace) - : workspace.capabilities?.workspaces?.find( - (entry) => entry.id === effectiveWorkspaceId, - ); + : effectiveWorkspaceId + ? workspace.capabilities?.workspaces?.find( + (entry) => entry.id === effectiveWorkspaceId, + ) + : implicitPrimaryWorkspace; + const [committedTarget, setCommittedTarget] = useState<{ + sessionId?: string; + workspace?: DaemonWorkspaceCapability; + clientId?: string; + }>(); + useEffect(() => { + if (!committedTarget && targetWorkspace) { + setCommittedTarget({ + sessionId: effectiveSessionId, + workspace: targetWorkspace, + ...(clientId ? { clientId } : {}), + }); + } + }, [clientId, committedTarget, effectiveSessionId, targetWorkspace]); + const hasCommittedTarget = committedTarget?.workspace !== undefined; + const hasExplicitWorkspaceTarget = Boolean( + effectiveWorkspaceCwd || effectiveWorkspaceId, + ); const t = useMemo( () => getTranslator(normalizeLanguage(webShellProps.language)), [webShellProps.language], ); + const providerWorkspace = targetWorkspace ?? committedTarget?.workspace; + const providerSessionId = targetWorkspace + ? effectiveSessionId + : hasExplicitWorkspaceTarget + ? committedTarget?.sessionId + : effectiveSessionId; + const providerClientId = targetWorkspace + ? clientId + : hasExplicitWorkspaceTarget + ? committedTarget?.clientId + : clientId; + const appWorkspace = committedTarget?.workspace ?? providerWorkspace; + const commitDesiredTarget = useCallback(() => { + if (!targetWorkspace) return; + setFailedTransitionTargetKey(undefined); + setCommittedTarget({ + sessionId: effectiveSessionId, + workspace: targetWorkspace, + ...(clientId ? { clientId } : {}), + }); + }, [clientId, effectiveSessionId, targetWorkspace]); + const notifyCommittedTarget = useCallback(() => { + const committedWorkspace = committedTarget?.workspace; + if (!committedWorkspace) return; + webShellProps.onSessionIdChange?.( + committedTarget.sessionId, + committedWorkspace.primary ? undefined : committedWorkspace.id, + committedWorkspace.cwd, + ); + }, [committedTarget, webShellProps]); + const desiredTargetKey = JSON.stringify([ + effectiveSessionId, + targetWorkspace?.cwd ?? + effectiveWorkspaceCwd ?? + (effectiveWorkspaceId ? `id:${effectiveWorkspaceId}` : undefined), + clientId, + ]); + const committedTargetKey = JSON.stringify([ + committedTarget?.sessionId, + committedTarget?.workspace?.cwd, + committedTarget?.clientId, + ]); + const [failedDesiredTargetKey, setFailedDesiredTargetKey] = + useState(); + const [failedTransitionTargetKey, setFailedTransitionTargetKey] = + useState(); + useEffect(() => { + setFailedTransitionTargetKey((failedKey) => + failedKey === undefined || failedKey === desiredTargetKey + ? failedKey + : undefined, + ); + }, [desiredTargetKey]); + const failDesiredTransition = useCallback(() => { + setFailedTransitionTargetKey(desiredTargetKey); + notifyCommittedTarget(); + }, [desiredTargetKey, notifyCommittedTarget]); + + useEffect(() => { + if (targetWorkspace) { + if (failedDesiredTargetKey === desiredTargetKey) { + setFailedDesiredTargetKey(undefined); + } + return; + } + if (!hasCommittedTarget) return; + const targetFailed = + workspace.status === 'error' || + (lockWorkspaceCwd !== undefined && + registrationErrorCwd === lockWorkspaceCwd) || + (!lockWorkspaceCwd && + workspace.capabilities !== undefined && + Boolean(effectiveWorkspaceCwd || effectiveWorkspaceId)); + if (!targetFailed || failedDesiredTargetKey === desiredTargetKey) { + return; + } + setFailedDesiredTargetKey(desiredTargetKey); + notifyCommittedTarget(); + }, [ + desiredTargetKey, + effectiveWorkspaceCwd, + effectiveWorkspaceId, + failedDesiredTargetKey, + hasCommittedTarget, + lockWorkspaceCwd, + notifyCommittedTarget, + registrationErrorCwd, + targetWorkspace, + workspace.capabilities, + workspace.status, + ]); + const desiredTargetPending = + hasCommittedTarget && + desiredTargetKey !== committedTargetKey && + failedDesiredTargetKey !== desiredTargetKey && + failedTransitionTargetKey !== desiredTargetKey; useEffect(() => { if (!lockWorkspaceCwd || !workspace.capabilities || pathWorkspace) return; @@ -151,7 +342,8 @@ export function WorkspaceSessionProvider({ if ( (effectiveWorkspaceCwd || effectiveWorkspaceId) && - workspace.status === 'error' + workspace.status === 'error' && + !hasCommittedTarget ) { return ( ); } - if (lockWorkspaceCwd && registrationErrorCwd === lockWorkspaceCwd) { + if ( + lockWorkspaceCwd && + registrationErrorCwd === lockWorkspaceCwd && + !hasCommittedTarget + ) { return ( ); } - if (lockWorkspaceCwd && !targetWorkspace) { + if (lockWorkspaceCwd && !targetWorkspace && !hasCommittedTarget) { return (
); } - if ((effectiveWorkspaceCwd || effectiveWorkspaceId) && !targetWorkspace) { + if ( + (effectiveWorkspaceCwd || effectiveWorkspaceId) && + !targetWorkspace && + !hasCommittedTarget + ) { return ( - + + {(desiredCommitted) => { + const visibleAppWorkspace = + desiredCommitted && targetWorkspace + ? targetWorkspace + : appWorkspace; + return ( + + ); + }} + ); } diff --git a/packages/web-shell/client/i18n.tsx b/packages/web-shell/client/i18n.tsx index 93991cb8869..0556bf2ef50 100644 --- a/packages/web-shell/client/i18n.tsx +++ b/packages/web-shell/client/i18n.tsx @@ -1406,7 +1406,7 @@ const EN: Messages = { 'system.taskCancelled': 'Background task cancelled', 'branch.failed': 'Failed to branch session.', 'branch.success': (v) => - `Copied session. New session name: "${v?.name ?? ''}". Switched to the new session.`, + `Copied session. New session name: "${v?.name ?? ''}".`, 'fork.empty': 'Please provide a directive. Usage: /fork ', 'fork.failed': (v) => `Failed to launch fork: ${v?.reason ?? ''}`, 'fork.notStarted': 'Background agent was not launched.', @@ -4152,8 +4152,7 @@ const ZH: Messages = { 'system.taskFailed': '后台任务执行失败', 'system.taskCancelled': '后台任务已取消', 'branch.failed': '分支会话失败。', - 'branch.success': (v) => - `已复制会话,新会话名称为: "${v?.name ?? ''}",当前已切换到新的会话。`, + 'branch.success': (v) => `已复制会话,新会话名称为: "${v?.name ?? ''}"。`, 'fork.empty': '请提供任务指令。用法:/fork <指令>', 'fork.failed': (v) => `启动后台智能体失败:${v?.reason ?? ''}`, 'fork.notStarted': '后台智能体未启动。', diff --git a/packages/web-shell/client/index.test.tsx b/packages/web-shell/client/index.test.tsx index 51678aefa40..8a64570fae1 100644 --- a/packages/web-shell/client/index.test.tsx +++ b/packages/web-shell/client/index.test.tsx @@ -23,6 +23,7 @@ let workspaceCapabilities: { }; const addWorkspace = vi.fn(); const refreshCapabilities = vi.fn(); +let sessionConnection: Record = { status: 'connected' }; vi.mock('@qwen-code/webui/daemon-react-sdk', async () => { const React = await import('react'); return { @@ -33,12 +34,17 @@ vi.mock('@qwen-code/webui/daemon-react-sdk', async () => { DaemonSessionProvider: ({ children, ...props - }: { - children: React.ReactNode; - }) => { + }: { children: React.ReactNode } & Record) => { sessionProviderProps.push(props); + sessionConnection = { + status: 'connected', + sessionId: props['sessionId'], + workspaceCwd: props['workspaceCwd'], + clientId: props['clientId'], + }; return React.createElement(React.Fragment, null, children); }, + useConnection: () => sessionConnection, useWorkspace: () => ({ capabilities: workspaceCapabilities, refreshCapabilities, @@ -97,6 +103,7 @@ afterEach(() => { }; addWorkspace.mockReset(); refreshCapabilities.mockReset(); + sessionConnection = { status: 'connected' }; vi.restoreAllMocks(); }); diff --git a/packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx b/packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx index 4448aa016f1..c987388c6e5 100644 --- a/packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx +++ b/packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx @@ -6,7 +6,7 @@ // @vitest-environment jsdom -import { act, type ReactNode } from 'react'; +import { act, StrictMode, type ReactNode } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { @@ -230,6 +230,38 @@ const sdkMocks = vi.hoisted(() => { } class MockDaemonSessionClient { + constructor(options?: { + client?: MockClient; + session?: Partial; + state?: Record; + hasActivePrompt?: boolean; + lastEventId?: number; + replaySnapshot?: MockSession['replaySnapshot']; + historyHasMore?: boolean; + historyAnchorRecordId?: string; + replayDegraded?: boolean; + }) { + if (!options?.session) return; + if ( + options.lastEventId !== undefined && + (!Number.isInteger(options.lastEventId) || options.lastEventId < 0) + ) { + throw new TypeError('invalid lastEventId'); + } + const session = createMockSession({ + ...options.session, + state: options.state, + hasActivePrompt: options.hasActivePrompt, + lastEventId: options.lastEventId, + replaySnapshot: options.replaySnapshot, + historyHasMore: options.historyHasMore, + historyAnchorRecordId: options.historyAnchorRecordId, + replayDegraded: options.replayDegraded, + }); + session.client = options.client; + Object.assign(this, session); + } + static createOrAttach = vi.fn( async (client: unknown, _req: unknown): Promise => takeSession(client), @@ -242,6 +274,14 @@ const sdkMocks = vi.hoisted(() => { _clientId?: string, ): Promise => takeSession(client), ); + static resume = vi.fn( + async ( + client: unknown, + _sessionId: string, + _opts?: unknown, + _clientId?: string, + ): Promise => takeSession(client), + ); } return { @@ -377,6 +417,11 @@ const sdkMocks = vi.hoisted(() => { async (client: unknown, _sessionId: string): Promise => takeSession(client), ); + MockDaemonSessionClient.resume.mockReset(); + MockDaemonSessionClient.resume.mockImplementation( + async (client: unknown, _sessionId: string): Promise => + takeSession(client), + ); }, }; }); @@ -398,6 +443,10 @@ describe('DaemonSessionProvider', () => { ( globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); sdkMocks.reset(); }); @@ -7789,42 +7838,33 @@ describe('DaemonSessionProvider', () => { ]); }); - it('loads controlled sessionId changes', async () => { - const nextSession = createDeferred(); + it('uses a changed controlled client id on the legacy switch path', async () => { sdkMocks.sessions.push( - createMockSession({ - sessionId: 'session-a', - replaySnapshot: createTextReplaySnapshot('old transcript'), - }), + createMockSession({ sessionId: 'session-a', clientId: 'client-old' }), ); - let blocks: readonly DaemonTranscriptBlock[] = []; - let connection: DaemonConnectionState | undefined; function Harness() { - blocks = useDaemonTranscriptBlocks(); - connection = useDaemonConnection(); + useDaemonConnection(); return null; } await renderWithProvider(, { autoConnect: true, sessionId: 'session-a', + clientId: 'client-old', }); - expect(connection).toMatchObject({ sessionId: 'session-a' }); - expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'old transcript' }, - ]); sdkMocks.MockDaemonSessionClient.load.mockClear(); - sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( - async () => nextSession.promise, + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ sessionId: 'session-a', clientId: 'client-new' }), ); act(() => { root?.render( , @@ -7834,54 +7874,24 @@ describe('DaemonSessionProvider', () => { await flushPromises(); }); - expect(connection).toMatchObject({ - sessionId: 'session-b', - loadingTranscript: true, - }); - expect(blocks).toEqual([]); - nextSession.resolve( - createMockSession({ - sessionId: 'session-b', - replaySnapshot: createTextReplaySnapshot('new transcript'), - }), - ); - await act(async () => { - await wait(5); - await flushPromises(); - }); - expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledWith( expect.anything(), - 'session-b', - { workspaceCwd: '/mock-workspace', timeoutMs: 70_000 }, - expect.any(String), + 'session-a', + expect.any(Object), + 'client-new', ); - expect(connection).toMatchObject({ sessionId: 'session-b' }); - expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'new transcript' }, - ]); }); - it('clears transcript loading after replay before metadata finishes', async () => { - const providers = createDeferred(); - const commands = - createDeferred>>(); - const context = - createDeferred>>(); - sdkMocks.workspaceProviders.mockReturnValueOnce(providers.promise); + it('transactionally commits a changed controlled client identity', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', detachFetch); sdkMocks.sessions.push( - createMockSession({ - sessionId: 'session-a', - replaySnapshot: createTextReplaySnapshot('restored transcript'), - supportedCommands: vi.fn(() => commands.promise), - context: vi.fn(() => context.promise), - }), + createMockSession({ sessionId: 'session-a', clientId: 'client-old' }), ); - let blocks: readonly DaemonTranscriptBlock[] = []; let connection: DaemonConnectionState | undefined; function Harness() { - blocks = useDaemonTranscriptBlocks(); connection = useDaemonConnection(); return null; } @@ -7889,137 +7899,2189 @@ describe('DaemonSessionProvider', () => { await renderWithProvider(, { autoConnect: true, sessionId: 'session-a', + clientId: 'client-old', + }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ sessionId: 'session-a', clientId: 'client-new' }), + ); + + act(() => { + root?.render( + + + , + ); }); await act(async () => { await flushPromises(); }); - expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'restored transcript' }, - ]); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledWith( + expect.anything(), + 'session-a', + expect.any(Object), + 'client-new', + ); expect(connection).toMatchObject({ - status: 'connected', sessionId: 'session-a', - loadingTranscript: undefined, + clientId: 'client-new', }); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-a/detach', + expect.objectContaining({ method: 'POST', keepalive: true }), + ); + }); - providers.resolve({ + it('keeps the current session visible while a modern daemon prepares the target', async () => { + sdkMocks.capabilities.mockResolvedValue({ v: 1, + mode: 'http-bridge', + features: ['client_identity'], + modelServices: [], workspaceCwd: '/mock-workspace', - initialized: true, - providers: [], - }); - commands.resolve({ - v: 1, - sessionId: 'session-a', - availableCommands: [], - availableSkills: [], }); - context.resolve({ - v: 1, + const detachFetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', detachFetch); + const target = createDeferred(); + const currentSession = createMockSession({ sessionId: 'session-a', - workspaceCwd: '/mock-workspace', - state: {}, - }); - await act(async () => { - await flushPromises(); + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('old transcript'), }); - }); - - it('ignores stale metadata after switching to another session', async () => { - const providersA = createDeferred(); - const commandsA = - createDeferred>>(); - const contextA = - createDeferred>>(); - sdkMocks.workspaceProviders.mockReturnValueOnce(providersA.promise); - sdkMocks.sessions.push( - createMockSession({ - sessionId: 'session-a', - replaySnapshot: createTextReplaySnapshot('session a transcript'), - supportedCommands: vi.fn(() => commandsA.promise), - context: vi.fn(() => contextA.promise), - }), - createMockSession({ - sessionId: 'session-b', - replaySnapshot: createTextReplaySnapshot('session b transcript'), - }), - ); + sdkMocks.sessions.push(currentSession); + let actions: DaemonSessionActions | undefined; let blocks: readonly DaemonTranscriptBlock[] = []; let connection: DaemonConnectionState | undefined; function Harness() { + actions = useDaemonActions(); blocks = useDaemonTranscriptBlocks(); connection = useDaemonConnection(); return null; } - await renderWithProvider(, { - autoConnect: true, - sessionId: 'session-a', - }); + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + const load = requireActions(actions).loadSession('session-b'); await act(async () => { await flushPromises(); }); - expect(connection).toMatchObject({ sessionId: 'session-a' }); + + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + sessionTransition: { + phase: 'preparing', + targetSessionId: 'session-b', + }, + }); expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'session a transcript' }, + { kind: 'assistant', text: 'old transcript' }, ]); + expect(currentSession.detach).not.toHaveBeenCalled(); - act(() => { - root?.render( - - - , - ); - }); + target.resolve( + createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + replaySnapshot: createTextReplaySnapshot('new transcript'), + }), + ); await act(async () => { + await load; await flushPromises(); }); + expect(connection).toMatchObject({ + status: 'connected', sessionId: 'session-b', - loadingTranscript: undefined, + clientId: 'client-b', }); + expect(connection).not.toHaveProperty('sessionTransition'); expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'session b transcript' }, + { kind: 'assistant', text: 'new transcript' }, ]); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-a/detach', + expect.objectContaining({ method: 'POST', keepalive: true }), + ); + }); - providersA.resolve({ + it('does not expose source metadata in the first target commit snapshot', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const targetProviders = createDeferred(); + const targetGit = createDeferred(); + const targetCommands = + createDeferred>>(); + const targetContext = + createDeferred>>(); + sdkMocks.workspaceProviders + .mockResolvedValueOnce({ + v: 1, + workspaceCwd: '/mock-workspace', + initialized: true, + providers: [], + }) + .mockReturnValueOnce(targetProviders.promise); + sdkMocks.workspaceGit + .mockResolvedValueOnce({ + v: 1, + workspaceCwd: '/mock-workspace', + branch: 'source-branch', + }) + .mockReturnValueOnce(targetGit.promise); + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + context: vi.fn(async () => ({ + v: 1 as const, + sessionId: 'session-a', + workspaceCwd: '/mock-workspace', + state: { + models: { currentModelId: 'source-model' }, + modes: { currentModeId: 'source-mode' }, + }, + })), + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + const snapshots: DaemonConnectionState[] = []; + + function Harness() { + actions = useDaemonActions(); + snapshots.push(useDaemonConnection()); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + expect(snapshots.at(-1)).toMatchObject({ + sessionId: 'session-a', + currentModel: 'source-model', + currentMode: 'source-mode', + gitBranch: 'source-branch', + }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + workspaceCwd: '/target-workspace', + supportedCommands: vi.fn(() => targetCommands.promise), + context: vi.fn(() => targetContext.promise), + }), + ); + + await act(async () => { + await requireActions(actions).loadSession('session-b', { + workspaceCwd: '/target-workspace', + }); + }); + + const firstTargetSnapshot = snapshots.find( + (snapshot) => snapshot.sessionId === 'session-b', + ); + expect(firstTargetSnapshot).toMatchObject({ + status: 'connected', + sessionId: 'session-b', + clientId: 'client-b', + workspaceCwd: '/target-workspace', + }); + for (const field of [ + 'gitBranch', + 'gitStatus', + 'commands', + 'skills', + 'models', + 'currentModel', + 'currentMode', + 'contextWindow', + 'providers', + 'supportedCommands', + 'context', + ] as const) { + expect(firstTargetSnapshot?.[field]).toBeUndefined(); + } + + targetProviders.resolve({ v: 1, - workspaceCwd: '/mock-workspace', + workspaceCwd: '/target-workspace', initialized: true, providers: [], }); - commandsA.resolve({ + targetGit.resolve({ v: 1, - sessionId: 'session-a', + workspaceCwd: '/target-workspace', + branch: 'target-branch', + }); + targetCommands.resolve({ + v: 1, + sessionId: 'session-b', availableCommands: [], availableSkills: [], }); - contextA.resolve({ + targetContext.resolve({ v: 1, - sessionId: 'session-a', - workspaceCwd: '/mock-workspace', - state: { models: { currentModel: 'stale-model' } }, + sessionId: 'session-b', + workspaceCwd: '/target-workspace', + state: {}, }); await act(async () => { await flushPromises(); }); - - expect(connection).toMatchObject({ sessionId: 'session-b' }); - expect(connection?.currentModel).not.toBe('stale-model'); - expect(blocks).toMatchObject([ - { kind: 'assistant', text: 'session b transcript' }, - ]); }); - it('loads controlled sessionId on mount without creating a session', async () => { - sdkMocks.sessions.push(createMockSession({ sessionId: 'session-a' })); - let connection: DaemonConnectionState | undefined; + it('does not detach the initial owner during StrictMode effect replay', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let connection: DaemonConnectionState | undefined; + + function Harness() { + connection = useDaemonConnection(); + return null; + } + + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render( + + + + + , + ); + }); + await act(async () => { + await flushPromises(); + }); + + expect(connection).toMatchObject({ sessionId: 'session-a' }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + expect(detachFetch).not.toHaveBeenCalled(); + + await act(async () => { + root?.unmount(); + root = null; + await flushPromises(); + }); + expect(detachFetch).toHaveBeenCalledOnce(); + }); + + it('keeps admitted source work and controls active while blocking new writes', async () => { + enableTransactionalSessionSwitches(); + const target = createDeferred(); + const terminal = createDeferred(); + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + submitPrompt: vi.fn(async () => ({ + promptId: 'prompt-a', + lastEventId: 1, + })), + events: createTurnCompleteEvents(terminal, 'prompt-a'), + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + const prompt = requireActions(actions).sendPrompt('finish on source'); + await act(async () => { + await flushPromises(); + }); + const load = requireActions(actions).loadSession('session-b'); + await act(async () => { + await flushPromises(); + }); + + await expect( + requireActions(actions).sendPrompt('new write'), + ).rejects.toThrow('A session switch is still preparing'); + await expect( + requireActions(actions).renameSession('wrong owner'), + ).rejects.toThrow('A session transition is already in progress'); + await expect( + requireActions(actions).respondToPermission('permission-a', { + outcome: { outcome: 'selected', optionId: 'allow' }, + }), + ).resolves.toBe(true); + expect(source.respondToSessionPermission).toHaveBeenCalled(); + + await act(async () => { + terminal.resolve(); + await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' }); + await flushPromises(); + }); + expect(source.detach).not.toHaveBeenCalled(); + + target.reject(new Error('target unavailable')); + await act(async () => { + await expect(load).rejects.toThrow('target unavailable'); + await flushPromises(); + }); + }); + + it.each([ + ['401', new DaemonHttpError(401, undefined, 'unauthorized')], + ['403', new DaemonHttpError(403, undefined, 'forbidden')], + ['404', new DaemonHttpError(404, undefined, 'missing')], + ['409', new DaemonHttpError(409, undefined, 'already restoring')], + ['429', new DaemonHttpError(429, undefined, 'capacity')], + ['503', new DaemonHttpError(503, undefined, 'unavailable')], + [ + '504', + new DaemonHttpError(504, { code: 'session_restore_timeout' }, 'timeout'), + ], + ['network error', new Error('network unavailable')], + ])( + 'preserves the current owner and transcript when transactional restore fails with %s', + async (_case, restoreError) => { + sdkMocks.capabilities.mockResolvedValue({ + v: 1, + mode: 'http-bridge', + features: ['client_identity'], + modelServices: [], + workspaceCwd: '/mock-workspace', + }); + const currentSession = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('still here'), + }); + sdkMocks.sessions.push(currentSession); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockRejectedValueOnce(restoreError); + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b'), + ).rejects.toBe(restoreError); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + sessionTransition: { phase: 'failed', targetSessionId: 'session-b' }, + }); + expect(blocks).toMatchObject([{ kind: 'assistant', text: 'still here' }]); + expect(currentSession.detach).not.toHaveBeenCalled(); + }, + ); + + it('does not publish staged replay side effects when the deadline wins before commit', async () => { + enableTransactionalSessionSwitches(); + clearSidechannelMidTurnInjected(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('source transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let notices: readonly DaemonSessionNotice[] = []; + let signals: DaemonWorkspaceEventSignals | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + notices = useDaemonSessionNotices().notices; + signals = useDaemonWorkspaceEventSignals(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + vi.useFakeTimers(); + vi.setSystemTime(0); + try { + const deadlineEvent = { + id: 3, + v: 1 as const, + type: 'session_died' as const, + get data() { + vi.setSystemTime(75_001); + return { message: 'target died' }; + }, + } satisfies DaemonEvent; + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + replaySnapshot: { + compactedReplay: [ + { + id: 1, + v: 1, + type: 'settings_changed', + data: { + key: 'ui.theme', + scope: 'workspace', + value: 'Qwen Dark', + }, + }, + { + id: 2, + v: 1, + type: 'mid_turn_message_injected', + originatorClientId: 'client-b', + data: { + sessionId: 'session-b', + messages: ['target-only message'], + }, + }, + deadlineEvent, + ], + liveJournal: [], + }, + }), + ); + + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b'), + ).rejects.toThrow('Session transition timed out'); + await flushPromises(); + }); + + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'source transcript' }, + ]); + expect(signals?.settingsVersion).toBe(0); + expect(getSidechannelMidTurnInjected()).toEqual([]); + expect(notices).not.toContainEqual( + expect.objectContaining({ code: 'daemon.session_died' }), + ); + expect(warn).not.toHaveBeenCalledWith( + '[DaemonSessionProvider] daemon notice:', + expect.anything(), + ); + } finally { + warn.mockRestore(); + clearSidechannelMidTurnInjected(); + vi.useRealTimers(); + } + }); + + it('drops source SSE events that arrive after a same-session commit', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const releaseLateEvent = createDeferred(); + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('source transcript'), + events: async function* lateSourceEvents() { + await releaseLateEvent.promise; + yield { + id: 30, + v: 1, + type: 'session_update', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'stale source event' }, + }, + }, + }; + }, + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-b', + replaySnapshot: createTextReplaySnapshot('committed transcript'), + }), + ); + + await act(async () => { + await requireActions(actions).reloadSession(new AbortController().signal); + releaseLateEvent.resolve(); + await flushPromises(); + await flushTranscriptDispatch(); + }); + + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'committed transcript' }, + ]); + expect(blocks).not.toContainEqual( + expect.objectContaining({ text: 'stale source event' }), + ); + }); + + it('keeps the buffered source prefix when a same-session resume commits', async () => { + vi.useFakeTimers(); + const emitBufferedEvent = createDeferred(); + const keepSourceOpen = createDeferred(); + try { + enableTransactionalSessionSwitches(); + sdkMocks.capabilities.mockResolvedValue({ + v: 1, + mode: 'http-bridge', + features: ['client_identity', 'session_transcript_pagination'], + modelServices: [], + workspaceCwd: '/mock-workspace', + }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const target = createDeferred(); + const targetContext = + createDeferred>>(); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + historyHasMore: true, + historyAnchorRecordId: 'record-1', + context: vi.fn(async () => ({ + v: 1 as const, + sessionId: 'session-a', + workspaceCwd: '/mock-workspace', + state: { models: { currentModelId: 'source-model' } }, + })), + replaySnapshot: { + compactedReplay: [ + { + id: 1, + v: 1, + type: 'session_update', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'source transcript' }, + _meta: { + usage: { inputTokens: 7_000, totalTokens: 7_500 }, + }, + }, + }, + }, + { + id: 2, + v: 1, + type: 'turn_complete', + data: { stopReason: 'end_turn' }, + }, + ], + liveJournal: [], + }, + events: async function* sourceEvents() { + await emitBufferedEvent.promise; + yield { + id: 30, + v: 1, + type: 'session_update', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: ' buffered prefix' }, + }, + }, + }; + await keepSourceOpen.promise; + }, + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let history: ReturnType | undefined; + const connections: DaemonConnectionState[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + history = useDaemonTranscriptHistory(); + connections.push(useDaemonConnection()); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + expect(history?.hasMore).toBe(true); + sdkMocks.MockDaemonSessionClient.resume.mockImplementationOnce( + async () => target.promise, + ); + let resume: Promise | undefined; + await act(async () => { + resume = requireActions(actions).resumeSession('session-a'); + emitBufferedEvent.resolve(); + await flushPromises(); + }); + + await act(async () => { + target.resolve( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-b', + replaySnapshot: { compactedReplay: [], liveJournal: [] }, + context: vi.fn(() => targetContext.promise), + }), + ); + await resume; + await flushPromises(); + }); + + expect(JSON.stringify(blocks)).toContain('buffered prefix'); + expect(history?.hasMore).toBe(true); + const committed = connections.find( + (connection) => connection.clientId === 'client-b', + ); + expect(committed).toMatchObject({ + currentModel: 'source-model', + tokenCount: 7_000, + tokenUsage: { inputTokens: 7_000, totalTokens: 7_500 }, + }); + } finally { + await act(async () => { + keepSourceOpen.resolve(); + await flushPromises(); + }); + vi.useRealTimers(); + } + }); + + it('applies an authoritative empty same-session load snapshot', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('stale transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-b', + replaySnapshot: { compactedReplay: [], liveJournal: [] }, + }), + ); + + await act(async () => { + await requireActions(actions).reloadSession(new AbortController().signal); + await flushPromises(); + }); + + expect(blocks).toEqual([]); + }); + + it('does not reuse a same-id transcript from another workspace', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'shared-session-id', + clientId: 'client-a', + workspaceCwd: '/workspace-a', + replaySnapshot: createTextReplaySnapshot('workspace A transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.resume.mockResolvedValueOnce( + createMockSession({ + sessionId: 'shared-session-id', + clientId: 'client-b', + workspaceCwd: '/workspace-b', + replaySnapshot: { compactedReplay: [], liveJournal: [] }, + }), + ); + + await act(async () => { + await requireActions(actions).resumeSession('shared-session-id', { + workspaceCwd: '/workspace-b', + }); + await flushPromises(); + }); + + expect(blocks).toEqual([]); + }); + + it('does not rebind a prompt waiter to a same-id session in another workspace', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'shared-session-id', + clientId: 'client-a', + workspaceCwd: '/workspace-a', + submitPrompt: vi.fn(async () => ({ + promptId: 'source-prompt', + lastEventId: 1, + })), + events: createIdleEvents(), + }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + workspaceCwd: '/workspace-a', + }); + const prompt = requireActions(actions).sendPrompt('source work'); + await act(async () => { + await flushPromises(); + }); + sdkMocks.MockDaemonSessionClient.resume.mockResolvedValueOnce( + createMockSession({ + sessionId: 'shared-session-id', + clientId: 'client-b', + workspaceCwd: '/workspace-b', + hasActivePrompt: false, + }), + ); + + await act(async () => { + await requireActions(actions).resumeSession('shared-session-id', { + workspaceCwd: '/workspace-b', + }); + await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' }); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + sessionId: 'shared-session-id', + workspaceCwd: '/workspace-b', + clientId: 'client-b', + }); + }); + + it('reports target failure after the source closes remotely', async () => { + enableTransactionalSessionSwitches(); + const closeSource = createDeferred(); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + events: async function* sourceEvents() { + await closeSource.promise; + yield { + id: 1, + v: 1, + type: 'session_closed', + data: { reason: 'client_close' }, + }; + }, + }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + const load = requireActions(actions).loadSession('session-b'); + closeSource.resolve(); + await act(async () => { + await flushPromises(); + }); + expect(connection).toMatchObject({ + status: 'disconnected', + sessionId: undefined, + }); + + target.reject(new Error('target failed')); + await act(async () => { + await expect(load).rejects.toThrow('target failed'); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + status: 'disconnected', + sessionId: undefined, + sessionTransition: { + phase: 'failed', + targetSessionId: 'session-b', + }, + }); + }); + + it('runs a deferred source resync after a target restore fails', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const releaseResync = createDeferred(); + const target = createDeferred(); + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('stale transcript'), + events: async function* sourceResyncEvents() { + await releaseResync.promise; + yield { + v: 1, + type: 'state_resync_required', + data: { reason: 'ring_evicted' }, + }; + }, + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load + .mockImplementationOnce(async () => target.promise) + .mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-resynced', + replaySnapshot: createTextReplaySnapshot('resynced transcript'), + }), + ); + + const load = requireActions(actions).loadSession('session-b'); + await act(async () => { + await flushPromises(); + releaseResync.resolve(); + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + + target.reject(new Error('target failed')); + await act(async () => { + await expect(load).rejects.toThrow('target failed'); + await flushPromises(); + }); + + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(2); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'resynced transcript' }, + ]); + }); + + it('retries a deferred live journal repair after a target restore fails', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const terminalGate = createDeferred(); + const target = createDeferred(); + const terminalEvent: DaemonEvent = { + id: 6, + v: 1, + type: 'turn_complete', + promptId: 'prompt-live', + data: { promptId: 'prompt-live', stopReason: 'end_turn' }, + }; + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + hasActivePrompt: true, + lastEventId: 5, + replaySnapshot: { + compactedReplay: [], + liveJournal: [ + { + v: 1, + type: 'history_truncated', + promptId: 'prompt-live', + data: { + reason: 'replay_window_exceeded', + scope: 'live_journal', + truncatedEvents: 2, + retainedEvents: 1, + maxBytes: 512, + maxEvents: 1, + fullTranscriptAvailable: true, + }, + }, + { + id: 5, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'retained tail' }, + }, + }, + }, + ], + }, + events: async function* sourceTerminal( + options: { signal?: AbortSignal } = {}, + ) { + await terminalGate.promise; + if (options.signal?.aborted) return; + yield terminalEvent; + await new Promise((resolve) => + options.signal?.addEventListener('abort', () => resolve(), { + once: true, + }), + ); + }, + }); + const repaired = createMockSession({ + sessionId: 'session-a', + clientId: 'client-repaired', + lastEventId: 6, + replaySnapshot: { + compactedReplay: [ + { + id: 4, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'user_message_chunk', + content: { type: 'text', text: 'complete prompt' }, + }, + }, + }, + { + id: 5, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'complete repaired answer' }, + }, + }, + }, + terminalEvent, + ], + liveJournal: [], + }, + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load + .mockImplementationOnce(async () => target.promise) + .mockResolvedValueOnce(repaired); + + const load = requireActions(actions).loadSession('session-b'); + await act(async () => { + terminalGate.resolve(); + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + + target.reject(new Error('target failed')); + await act(async () => { + await expect(load).rejects.toThrow('target failed'); + await vi.waitFor(() => + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(2), + ); + await vi.waitFor(() => + expect(JSON.stringify(blocks)).toContain('complete repaired answer'), + ); + }); + }); + + it('retries a live journal repair after its raw restore is superseded', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const terminalGate = createDeferred(); + const firstRepair = createDeferred(); + const terminalEvent: DaemonEvent = { + id: 6, + v: 1, + type: 'turn_complete', + promptId: 'prompt-live', + data: { promptId: 'prompt-live', stopReason: 'end_turn' }, + }; + const source = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + hasActivePrompt: true, + lastEventId: 5, + replaySnapshot: { + compactedReplay: [], + liveJournal: [ + { + v: 1, + type: 'history_truncated', + promptId: 'prompt-live', + data: { + reason: 'replay_window_exceeded', + scope: 'live_journal', + truncatedEvents: 2, + retainedEvents: 1, + maxBytes: 512, + maxEvents: 1, + fullTranscriptAvailable: true, + }, + }, + { + id: 5, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'retained tail' }, + }, + }, + }, + ], + }, + events: async function* sourceTerminal( + options: { signal?: AbortSignal } = {}, + ) { + await terminalGate.promise; + if (options.signal?.aborted) return; + yield terminalEvent; + await new Promise((resolve) => + options.signal?.addEventListener('abort', () => resolve(), { + once: true, + }), + ); + }, + }); + const completeRepair = createMockSession({ + sessionId: 'session-a', + clientId: 'client-repaired', + replaySnapshot: { + compactedReplay: [ + { + id: 4, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'user_message_chunk', + content: { type: 'text', text: 'complete prompt' }, + }, + }, + }, + { + id: 5, + v: 1, + type: 'session_update', + promptId: 'prompt-live', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'repaired after supersede' }, + }, + }, + }, + terminalEvent, + ], + liveJournal: [], + }, + }); + sdkMocks.sessions.push(source); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load + .mockImplementationOnce(async () => firstRepair.promise) + .mockRejectedValueOnce(new Error('target failed')) + .mockResolvedValueOnce(completeRepair); + + await act(async () => { + terminalGate.resolve(); + await vi.waitFor(() => + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(), + ); + }); + const targetLoad = requireActions(actions).loadSession('session-b'); + firstRepair.resolve( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-stale-repair', + }), + ); + await act(async () => { + await expect(targetLoad).rejects.toThrow('target failed'); + await vi.waitFor(() => + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(3), + ); + await vi.waitFor(() => + expect(JSON.stringify(blocks)).toContain('repaired after supersede'), + ); + }); + }); + + it('serializes raw restores and keeps only the latest queued target', async () => { + sdkMocks.capabilities.mockResolvedValue({ + v: 1, + mode: 'http-bridge', + features: ['client_identity'], + modelServices: [], + workspaceCwd: '/mock-workspace', + }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const targetB = createDeferred(); + const targetC = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load + .mockImplementationOnce(async () => targetB.promise) + .mockImplementationOnce(async () => targetC.promise); + const loadB = requireActions(actions).loadSession('session-b'); + await act(async () => { + await flushPromises(); + }); + const loadC = requireActions(actions).loadSession('session-c'); + await expect(loadB).rejects.toMatchObject({ name: 'AbortError' }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(1); + + targetB.resolve( + createMockSession({ sessionId: 'session-b', clientId: 'client-b' }), + ); + await act(async () => { + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(2); + expect(connection?.sessionId).toBe('session-a'); + + targetC.resolve( + createMockSession({ + sessionId: 'session-c', + clientId: 'client-c', + replaySnapshot: createTextReplaySnapshot('latest'), + }), + ); + await act(async () => { + await loadC; + await flushPromises(); + }); + expect(connection?.sessionId).toBe('session-c'); + }); + + it('does not retire the original runner twice during immediate sequential commits', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load + .mockResolvedValueOnce( + createMockSession({ sessionId: 'session-b', clientId: 'client-b' }), + ) + .mockResolvedValueOnce( + createMockSession({ sessionId: 'session-c', clientId: 'client-c' }), + ); + + await act(async () => { + await requireActions(actions) + .loadSession('session-b') + .then(() => requireActions(actions).loadSession('session-c')); + await flushPromises(); + }); + + expect(connection?.sessionId).toBe('session-c'); + const detachedSessionIds = detachFetch.mock.calls.map( + ([input]) => new URL(String(input)).pathname.split('/')[2], + ); + expect(detachedSessionIds.filter((id) => id === 'session-a')).toHaveLength( + 1, + ); + expect(detachedSessionIds.filter((id) => id === 'session-b')).toHaveLength( + 1, + ); + }); + + it('coalesces identical transactional restores', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + + const first = requireActions(actions).reloadSession( + new AbortController().signal, + ); + const coalescedController = new AbortController(); + const second = requireActions(actions).reloadSession( + coalescedController.signal, + ); + await act(async () => { + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + coalescedController.abort(); + await expect(second).rejects.toMatchObject({ name: 'AbortError' }); + + target.resolve( + createMockSession({ sessionId: 'session-a', clientId: 'client-b' }), + ); + await act(async () => { + await expect(first).resolves.toBeUndefined(); + await flushPromises(); + }); + }); + + it('keeps a coalesced restore alive when its first caller aborts', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + + const firstController = new AbortController(); + const secondController = new AbortController(); + const first = requireActions(actions).reloadSession(firstController.signal); + const second = requireActions(actions).reloadSession( + secondController.signal, + ); + await act(async () => { + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + + firstController.abort(); + await expect(first).rejects.toMatchObject({ name: 'AbortError' }); + + target.resolve( + createMockSession({ sessionId: 'session-a', clientId: 'client-b' }), + ); + await act(async () => { + await expect(second).resolves.toBeUndefined(); + await flushPromises(); + }); + }); + + it('fails closed when a modern restore omits its client identity', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('source transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + const malformedCandidate = createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + replaySnapshot: createTextReplaySnapshot('must not commit'), + }); + Object.assign(malformedCandidate, { clientId: undefined }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + malformedCandidate, + ); + + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b'), + ).rejects.toThrow('restore returned no clientId'); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + sessionTransition: { phase: 'failed' }, + }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'source transcript' }, + ]); + const requestedClientId = + sdkMocks.MockDaemonSessionClient.load.mock.calls.find( + (call) => call[1] === 'session-b', + )?.[3]; + expect(requestedClientId).toEqual(expect.any(String)); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-b/detach', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ + 'X-Qwen-Client-Id': requestedClientId, + }), + }), + ); + }); + + it.each([ + [ + 'session identity', + createMockSession({ + sessionId: 'session-c', + clientId: 'client-b', + workspaceCwd: '/workspace-b', + }), + 'unexpected sessionId session-c', + ], + [ + 'workspace identity', + createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + workspaceCwd: '/workspace-c', + }), + 'unexpected workspaceCwd /workspace-c', + ], + ])( + 'fails closed when a modern restore returns the wrong %s', + async (_case, candidate, expectedError) => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + workspaceCwd: '/workspace-a', + replaySnapshot: createTextReplaySnapshot('source transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + workspaceCwd: '/workspace-a', + }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce(candidate); + + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b', { + workspaceCwd: '/workspace-b', + }), + ).rejects.toThrow(expectedError); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + workspaceCwd: '/workspace-a', + sessionTransition: { phase: 'failed' }, + }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'source transcript' }, + ]); + expect(detachFetch).toHaveBeenCalledWith( + `http://127.0.0.1:4170/session/${candidate.sessionId}/detach`, + expect.objectContaining({ + headers: expect.objectContaining({ + 'X-Qwen-Client-Id': candidate.clientId, + }), + }), + ); + }, + ); + + it('fails closed when a modern restore returns the wrong requested client identity', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'requested-client', + replaySnapshot: createTextReplaySnapshot('source transcript'), + }), + ); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + clientId: 'requested-client', + }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-b', + clientId: 'unexpected-client', + }), + ); + + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b'), + ).rejects.toThrow('unexpected clientId unexpected-client'); + await flushPromises(); + }); + + expect(connection).toMatchObject({ + sessionId: 'session-a', + clientId: 'requested-client', + sessionTransition: { phase: 'failed' }, + }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'source transcript' }, + ]); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-b/detach', + expect.objectContaining({ + headers: expect.objectContaining({ + 'X-Qwen-Client-Id': 'unexpected-client', + }), + }), + ); + }); + + it('fails closed when the current modern session has no client identity', async () => { + enableTransactionalSessionSwitches(); + const malformedSource = createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + replaySnapshot: createTextReplaySnapshot('source transcript'), + }); + Object.assign(malformedSource, { clientId: undefined }); + sdkMocks.sessions.push(malformedSource); + let actions: DaemonSessionActions | undefined; + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + + await act(async () => { + await expect( + requireActions(actions).loadSession('session-b'), + ).rejects.toThrow('current session has no clientId'); + await flushPromises(); + }); + + expect(sdkMocks.MockDaemonSessionClient.load).not.toHaveBeenCalled(); + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + sessionTransition: { phase: 'failed' }, + }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'source transcript' }, + ]); + }); + + it('times out publicly without committing a late restore result', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', detachFetch); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + vi.useFakeTimers(); + try { + let outcome: Promise | undefined; + await act(async () => { + outcome = requireActions(actions) + .loadSession('session-b') + .catch((error: unknown) => error); + await flushPromises(); + await vi.advanceTimersByTimeAsync(75_000); + }); + + await expect(outcome).resolves.toMatchObject({ + message: 'Session transition timed out', + }); + expect(connection).toMatchObject({ + sessionId: 'session-a', + sessionTransition: { phase: 'failed' }, + }); + + await act(async () => { + target.resolve( + createMockSession({ sessionId: 'session-b', clientId: 'client-b' }), + ); + await flushPromises(); + }); + + expect(connection?.sessionId).toBe('session-a'); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-b/detach', + expect.objectContaining({ method: 'POST', keepalive: true }), + ); + } finally { + vi.useRealTimers(); + } + }); + + it('clears the transition gate after an aborted restore settles', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + let connection: DaemonConnectionState | undefined; + + function Harness() { + actions = useDaemonActions(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + const controller = new AbortController(); + const load = requireActions(actions).reloadSession(controller.signal); + await act(async () => { + await vi.waitFor(() => + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(2), + ); + }); + controller.abort(); + await expect(load).rejects.toMatchObject({ name: 'AbortError' }); + + target.resolve( + createMockSession({ sessionId: 'session-a', clientId: 'client-stale' }), + ); + await act(async () => { + await flushPromises(); + }); + + expect(connection?.sessionId).toBe('session-a'); + expect(connection?.sessionTransition).toBeUndefined(); + }); + + it('retires a restore that settles after the provider unmounts', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', detachFetch); + const target = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => target.promise, + ); + const outcome = requireActions(actions) + .loadSession('session-b') + .catch((error: unknown) => error); + await act(async () => { + await flushPromises(); + root?.unmount(); + root = null; + await flushPromises(); + }); + await expect(outcome).resolves.toMatchObject({ name: 'AbortError' }); + + target.resolve( + createMockSession({ sessionId: 'session-b', clientId: 'client-b' }), + ); + await act(async () => { + await flushPromises(); + }); + expect(detachFetch).toHaveBeenCalledWith( + 'http://127.0.0.1:4170/session/session-b/detach', + expect.objectContaining({ method: 'POST', keepalive: true }), + ); + }); + + it('retires each owner once when unmounted immediately after commit', async () => { + enableTransactionalSessionSwitches(); + const detachFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal('fetch', detachFetch); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ sessionId: 'session-b', clientId: 'client-b' }), + ); + + await act(async () => { + await requireActions(actions).loadSession('session-b'); + root?.unmount(); + root = null; + await flushPromises(); + }); + + const detachedSessionIds = detachFetch.mock.calls.map( + ([input]) => new URL(String(input)).pathname.split('/')[2], + ); + expect(detachedSessionIds.filter((id) => id === 'session-a')).toHaveLength( + 1, + ); + expect(detachedSessionIds.filter((id) => id === 'session-b')).toHaveLength( + 1, + ); + }); + + it('loads controlled sessionId changes', async () => { + const nextSession = createDeferred(); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + replaySnapshot: createTextReplaySnapshot('old transcript'), + }), + ); + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + sessionId: 'session-a', + }); + expect(connection).toMatchObject({ sessionId: 'session-a' }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'old transcript' }, + ]); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load.mockImplementationOnce( + async () => nextSession.promise, + ); + + act(() => { + root?.render( + + + , + ); + }); + await act(async () => { + await flushPromises(); + }); + + expect(connection).toMatchObject({ + sessionId: 'session-b', + loadingTranscript: true, + }); + expect(blocks).toEqual([]); + nextSession.resolve( + createMockSession({ + sessionId: 'session-b', + replaySnapshot: createTextReplaySnapshot('new transcript'), + }), + ); + await act(async () => { + await wait(5); + await flushPromises(); + }); + + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledWith( + expect.anything(), + 'session-b', + { workspaceCwd: '/mock-workspace', timeoutMs: 70_000 }, + expect.any(String), + ); + expect(connection).toMatchObject({ sessionId: 'session-b' }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'new transcript' }, + ]); + }); + + it('retries a controlled target after its provider generation changes', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ sessionId: 'session-a', clientId: 'client-a' }), + ); + const firstTarget = createDeferred(); + const replacementTarget = createMockSession({ + sessionId: 'session-b', + clientId: 'client-b', + replaySnapshot: createTextReplaySnapshot('replacement transcript'), + }); + let connection: DaemonConnectionState | undefined; + let refreshCapabilities: (() => Promise) | undefined; + + function Harness() { + connection = useDaemonConnection(); + refreshCapabilities = useOptionalDaemonWorkspace()?.refreshCapabilities; + return null; + } + const renderTarget = (targetSessionId: string) => { + root?.render( + + + + + , + ); + }; + + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => renderTarget('session-a')); + await act(async () => { + await flushPromises(); + }); + sdkMocks.MockDaemonSessionClient.load.mockClear(); + sdkMocks.MockDaemonSessionClient.load + .mockImplementationOnce(async (client: unknown) => { + const session = await firstTarget.promise; + session.client = client as MockClient; + return session; + }) + .mockImplementationOnce(async (client: unknown) => { + replacementTarget.client = client as MockClient; + return replacementTarget; + }); + + act(() => renderTarget('session-b')); + await act(async () => { + await flushPromises(); + }); + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledOnce(); + + sdkMocks.capabilities.mockResolvedValueOnce({ + v: 1, + mode: 'http-bridge', + features: ['client_identity', 'workspace_runtime_removal'], + modelServices: [], + workspaceCwd: '/mock-workspace', + }); + await act(async () => { + await refreshCapabilities?.(); + await flushPromises(); + }); + firstTarget.resolve( + createMockSession({ sessionId: 'session-b', clientId: 'client-stale' }), + ); + await act(async () => { + await flushPromises(); + }); + + expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(2); + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-b', + clientId: 'client-b', + }); + }); + + it('clears transcript loading after replay before metadata finishes', async () => { + const providers = createDeferred(); + const commands = + createDeferred>>(); + const context = + createDeferred>>(); + sdkMocks.workspaceProviders.mockReturnValueOnce(providers.promise); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + replaySnapshot: createTextReplaySnapshot('restored transcript'), + supportedCommands: vi.fn(() => commands.promise), + context: vi.fn(() => context.promise), + }), + ); + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + sessionId: 'session-a', + }); + await act(async () => { + await flushPromises(); + }); + + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'restored transcript' }, + ]); + expect(connection).toMatchObject({ + status: 'connected', + sessionId: 'session-a', + loadingTranscript: undefined, + }); + + providers.resolve({ + v: 1, + workspaceCwd: '/mock-workspace', + initialized: true, + providers: [], + }); + commands.resolve({ + v: 1, + sessionId: 'session-a', + availableCommands: [], + availableSkills: [], + }); + context.resolve({ + v: 1, + sessionId: 'session-a', + workspaceCwd: '/mock-workspace', + state: {}, + }); + await act(async () => { + await flushPromises(); + }); + }); + + it('ignores stale metadata after switching to another session', async () => { + const providersA = createDeferred(); + const commandsA = + createDeferred>>(); + const contextA = + createDeferred>>(); + sdkMocks.workspaceProviders.mockReturnValueOnce(providersA.promise); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + replaySnapshot: createTextReplaySnapshot('session a transcript'), + supportedCommands: vi.fn(() => commandsA.promise), + context: vi.fn(() => contextA.promise), + }), + createMockSession({ + sessionId: 'session-b', + replaySnapshot: createTextReplaySnapshot('session b transcript'), + }), + ); + let blocks: readonly DaemonTranscriptBlock[] = []; + let connection: DaemonConnectionState | undefined; + + function Harness() { + blocks = useDaemonTranscriptBlocks(); + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + sessionId: 'session-a', + }); + await act(async () => { + await flushPromises(); + }); + expect(connection).toMatchObject({ sessionId: 'session-a' }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'session a transcript' }, + ]); + + act(() => { + root?.render( + + + , + ); + }); + await act(async () => { + await flushPromises(); + }); + expect(connection).toMatchObject({ + sessionId: 'session-b', + loadingTranscript: undefined, + }); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'session b transcript' }, + ]); + + providersA.resolve({ + v: 1, + workspaceCwd: '/mock-workspace', + initialized: true, + providers: [], + }); + commandsA.resolve({ + v: 1, + sessionId: 'session-a', + availableCommands: [], + availableSkills: [], + }); + contextA.resolve({ + v: 1, + sessionId: 'session-a', + workspaceCwd: '/mock-workspace', + state: { models: { currentModel: 'stale-model' } }, + }); + await act(async () => { + await flushPromises(); + }); + + expect(connection).toMatchObject({ sessionId: 'session-b' }); + expect(connection?.currentModel).not.toBe('stale-model'); + expect(blocks).toMatchObject([ + { kind: 'assistant', text: 'session b transcript' }, + ]); + }); + + it('loads controlled sessionId on mount without creating a session', async () => { + sdkMocks.sessions.push(createMockSession({ sessionId: 'session-a' })); + let connection: DaemonConnectionState | undefined; function Harness() { connection = useDaemonConnection(); @@ -8130,6 +10192,112 @@ describe('DaemonSessionProvider', () => { expect(connection).not.toHaveProperty('sessionId'); }); + it('commits a controlled workspace after clearing the current session', async () => { + const session = createMockSession({ + sessionId: 'session-a', + workspaceCwd: '/workspace-a', + }); + sdkMocks.sessions.push(session); + let connection: DaemonConnectionState | undefined; + + function Harness() { + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + sessionId: 'session-a', + workspaceCwd: '/workspace-a', + }); + expect(connection).toMatchObject({ + sessionId: 'session-a', + workspaceCwd: '/workspace-a', + }); + + act(() => { + root?.render( + + + , + ); + }); + await act(async () => { + await flushPromises(); + }); + + expect(session.detach).toHaveBeenCalledOnce(); + expect(connection).toMatchObject({ workspaceCwd: '/workspace-b' }); + expect(connection).not.toHaveProperty('sessionId'); + }); + + it('routes actions through the committed workspace after a controlled target fails', async () => { + enableTransactionalSessionSwitches(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })), + ); + sdkMocks.sessions.push( + createMockSession({ + sessionId: 'session-a', + clientId: 'client-a', + workspaceCwd: '/workspace-a', + }), + ); + let actions: DaemonSessionActions | undefined; + + function Harness() { + actions = useDaemonActions(); + return null; + } + + await renderWithProvider(, { + autoConnect: true, + sessionId: 'session-a', + workspaceCwd: '/workspace-a', + }); + sdkMocks.MockDaemonSessionClient.load.mockRejectedValueOnce( + new Error('target unavailable'), + ); + act(() => { + root?.render( + + + , + ); + }); + await act(async () => { + await flushPromises(); + }); + + sdkMocks.MockDaemonSessionClient.load.mockResolvedValueOnce( + createMockSession({ + sessionId: 'session-c', + clientId: 'client-c', + workspaceCwd: '/workspace-a', + }), + ); + await act(async () => { + await requireActions(actions).loadSession('session-c'); + await flushPromises(); + }); + + const loadC = sdkMocks.MockDaemonSessionClient.load.mock.calls.find( + (call) => call[1] === 'session-c', + ); + expect(loadC?.[2]).toMatchObject({ workspaceCwd: '/workspace-a' }); + }); + it('does not clear a deferred session created after an empty controlled render', async () => { sdkMocks.sessions.push( createMockSession({ sessionId: 'created-session' }), @@ -8632,6 +10800,7 @@ describe('DaemonSessionProvider', () => { }); it('reloads stale transcript after epoch-reset resync', async () => { + enableTransactionalSessionSwitches(); const startEpochReset = createDeferred(); const epochResetDelivered = createDeferred(); const reloaded = createDeferred(); @@ -8730,10 +10899,80 @@ describe('DaemonSessionProvider', () => { const pendingPrompt = promptResult; if (!pendingPrompt) throw new Error('prompt was not started'); await expect(pendingPrompt).resolves.toEqual({ - stopReason: 'cancelled', + stopReason: 'end_turn', }); }); + it('freezes the valid resync prefix and drops the stale suffix on reload failure', async () => { + enableTransactionalSessionSwitches(); + const startResync = createDeferred(); + const session = createMockSession({ + sessionId: 'session-resync-prefix', + clientId: 'client-a', + events: async function* resyncBurst() { + await startResync.promise; + yield { + id: 1, + v: 1, + type: 'session_update', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'valid prefix' }, + }, + }, + }; + yield { + id: 2, + v: 1, + type: 'state_resync_required', + data: { + reason: 'ring_evicted', + lastDeliveredId: 2, + earliestAvailableId: 4, + }, + }; + yield { + id: 3, + v: 1, + type: 'session_update', + data: { + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'stale suffix' }, + }, + }, + }; + }, + }); + sdkMocks.sessions.push(session); + let blocks: readonly DaemonTranscriptBlock[] = []; + let awaitingResync = false; + let connection: DaemonConnectionState | undefined; + + function Harness() { + blocks = useDaemonTranscriptBlocks(); + awaitingResync = useDaemonTranscriptState().awaitingResync; + connection = useDaemonConnection(); + return null; + } + + await renderWithProvider(, { autoConnect: true }); + sdkMocks.MockDaemonSessionClient.load.mockRejectedValueOnce( + new Error('snapshot unavailable'), + ); + await act(async () => { + startResync.resolve(); + await flushPromises(); + await flushPromises(); + }); + expect(connection?.sessionTransition?.phase).toBe('failed'); + + expect(JSON.stringify(blocks)).toContain('valid prefix'); + expect(JSON.stringify(blocks)).not.toContain('stale suffix'); + expect(awaitingResync).toBe(true); + }); + it('reloads the session snapshot after ring-evicted resync', async () => { const reloaded = createDeferred(); const firstSession = createMockSession({ @@ -8831,6 +11070,7 @@ describe('DaemonSessionProvider', () => { }); it('settles active prompts from replay snapshot after ring eviction', async () => { + enableTransactionalSessionSwitches(); const ringEvicted = createDeferred(); const reloaded = createDeferred(); const firstSession = createMockSession({ @@ -8921,6 +11161,9 @@ describe('DaemonSessionProvider', () => { await act(async () => { ringEvicted.resolve(); + await flushPromises(); + }); + await act(async () => { await reloaded.promise; await flushPromises(); }); @@ -8945,6 +11188,7 @@ describe('DaemonSessionProvider', () => { }); it('rejects active prompts from replay turn_error after ring eviction', async () => { + enableTransactionalSessionSwitches(); const ringEvicted = createDeferred(); const reloaded = createDeferred(); const firstSession = createMockSession({ @@ -9074,6 +11318,7 @@ describe('DaemonSessionProvider', () => { }); it('does not settle unaccepted prompts from historical replay turns', async () => { + enableTransactionalSessionSwitches(); const accepted = createDeferred(); const ringEvicted = createDeferred(); const reloaded = createDeferred(); @@ -9097,6 +11342,7 @@ describe('DaemonSessionProvider', () => { }); const reloadedSession = createMockSession({ sessionId: 'session-ring-unaccepted-prompt', + hasActivePrompt: true, replaySnapshot: { compactedReplay: [ { @@ -9166,6 +11412,9 @@ describe('DaemonSessionProvider', () => { await act(async () => { ringEvicted.resolve(); + await flushPromises(); + }); + await act(async () => { await reloaded.promise; await flushPromises(); }); @@ -9185,6 +11434,7 @@ describe('DaemonSessionProvider', () => { }); it('keeps own user messages when replay rebuilds after ring eviction', async () => { + enableTransactionalSessionSwitches(); const reloaded = createDeferred(); const firstSession = createMockSession({ sessionId: 'session-own-user-replay', @@ -9267,6 +11517,7 @@ describe('DaemonSessionProvider', () => { }); it('skips malformed replay events without dropping later replay history', async () => { + enableTransactionalSessionSwitches(); const reloaded = createDeferred(); const malformedReplayEvent = { id: 12, @@ -9371,6 +11622,7 @@ describe('DaemonSessionProvider', () => { }); it('retries when ring-evicted reload fails once', async () => { + enableTransactionalSessionSwitches(); const reloaded = createDeferred(); const firstSession = createMockSession({ sessionId: 'session-ring-retry', @@ -9464,6 +11716,7 @@ describe('DaemonSessionProvider', () => { }); it('accepts live events after ring-evicted reload reconnects', async () => { + enableTransactionalSessionSwitches(); const reattachDelivered = createDeferred(); const firstSession = createMockSession({ sessionId: 'session-reattach', @@ -11110,6 +13363,16 @@ function createTextReplaySnapshot(text: string): MockSession['replaySnapshot'] { }; } +function enableTransactionalSessionSwitches(): void { + sdkMocks.capabilities.mockResolvedValue({ + v: 1, + mode: 'http-bridge', + features: ['client_identity'], + modelServices: [], + workspaceCwd: '/mock-workspace', + }); +} + function createMockSession(opts: Partial = {}): MockSession { const session = { sessionId: opts.sessionId ?? 'session-1', diff --git a/packages/webui/src/daemon/session/DaemonSessionProvider.tsx b/packages/webui/src/daemon/session/DaemonSessionProvider.tsx index 1cb47e3297e..4aa514094cd 100644 --- a/packages/webui/src/daemon/session/DaemonSessionProvider.tsx +++ b/packages/webui/src/daemon/session/DaemonSessionProvider.tsx @@ -25,6 +25,7 @@ import { matchTurnEvent, normalizeDaemonEvent, type CreateSessionRequest, + type DaemonCapabilities, type DaemonEvent, type DaemonSseConnectReason, type DaemonTranscriptBlock, @@ -37,6 +38,7 @@ import { createDaemonSessionActions, getPromptSettledKey, resolveSessionRestoreTimeouts, + type SessionTransitionRequest, } from './actions.js'; import { eventPromptId, @@ -101,6 +103,8 @@ import type { DaemonSessionContextValue, DaemonSessionNotice, DaemonSessionProviderProps, + DaemonSessionTransitionOperation, + DaemonSessionTransitionOrigin, DaemonWorkspaceEventSignals, PendingSessionLoad, SettledPrompt, @@ -120,6 +124,10 @@ export type { DaemonSessionContextValue, DaemonSessionNotice, DaemonSessionProviderProps, + DaemonSessionTransitionOperation, + DaemonSessionTransitionOrigin, + DaemonSessionTransitionPhase, + DaemonSessionTransitionState, DaemonTodoItem, DaemonTodoList, DaemonTodoPriority, @@ -156,9 +164,342 @@ interface TranscriptHistoryMaterialization { permissionBlockByRequestId: Record; } +interface SessionRunnerControl { + session?: DaemonSessionClient; + flush(): void; + stop(): void; +} + +interface StagedSessionCandidate { + session: DaemonSessionClient; + connection: DaemonConnectionState; + transcript?: DaemonTranscriptState; + transcriptHistory: { + sessionId: string; + beforeRecordId?: string; + cursor?: string; + hasMore: boolean; + loading: false; + capacityReached: boolean; + paginationError: boolean; + }; + transcriptHistoryState: { + hasMore: boolean; + loading: false; + capacityReached: boolean; + paginationError: boolean; + }; + replayEvents: readonly DaemonEvent[]; + sideEffectEvents: readonly DaemonUiEvent[]; + sidechannelEvents: readonly DaemonEvent[]; + notices: readonly SessionNoticeInput[]; + dismissNoticeIds: readonly string[]; +} + +interface SessionTransitionIntent { + key: string; + request: SessionTransitionRequest; + operation: DaemonSessionTransitionOperation; + origin: DaemonSessionTransitionOrigin; + deadlineAt?: number; + timer?: ReturnType; + source?: DaemonSessionClient; + sourceGeneration: number; + providerGeneration: number; + commitClaimed: boolean; + publicSettled: boolean; + primarySettled: boolean; + superseded: boolean; + rawStarted: boolean; + candidate?: DaemonSessionClient; + candidateCleanup?: { sessionId: string; clientId: string }; + candidateRetired: boolean; + baseUrl: string; + token?: string; + startLegacy(): Promise; + removeAbortListener?: () => void; + resolve(): void; + reject(error: unknown): void; + coalesced: Array<{ + settled: boolean; + removeAbortListener?: () => void; + resolve(): void; + reject(error: unknown): void; + }>; +} + const SESSION_TRANSCRIPT_PAGINATION_FEATURE = 'session_transcript_pagination'; const WORKSPACE_ACP_PREHEAT_FEATURE = 'workspace_acp_preheat'; const WORKSPACE_ACP_STATUS_FEATURE = 'workspace_acp_status'; +const CLIENT_IDENTITY_FEATURE = 'client_identity'; + +function stageSessionCandidate(input: { + session: DaemonSessionClient; + capabilities: DaemonCapabilities; + currentConnection: DaemonConnectionState; + currentTranscriptHistory: { + sessionId?: string; + beforeRecordId?: string; + cursor?: string; + hasMore: boolean; + loading: boolean; + capacityReached: boolean; + paginationError: boolean; + }; + maxBlocks: number; + subagentTranscriptMode: 'full' | 'summary'; + eventOptions: { suppressOwnUserEcho: boolean; includeRawEvent: boolean }; + mode: SessionTransitionRequest['mode']; + replaySource?: PendingSessionLoad['replaySource']; + repairEpisode?: LiveJournalRepairEpisode; +}): StagedSessionCandidate { + const { + session, + capabilities, + currentConnection, + currentTranscriptHistory, + maxBlocks, + subagentTranscriptMode, + eventOptions, + mode, + replaySource, + repairEpisode, + } = input; + const replayEvents = [ + ...session.replaySnapshot.compactedReplay, + ...session.replaySnapshot.liveJournal, + ]; + let repairedEpisode: LiveJournalRepairEpisode | undefined; + let repairSuffix: LiveJournalRepairSuffix | undefined; + if (replaySource === 'memory') { + repairSuffix = repairEpisode + ? findLiveJournalRepairSuffix(replayEvents, repairEpisode.target.promptId) + : undefined; + if ( + !repairEpisode || + repairEpisode.sessionId !== session.sessionId || + session.replayDegraded || + !repairSuffix + ) { + throw new Error( + session.replayDegraded + ? 'Fresh replay is degraded' + : 'Fresh replay does not contain the complete target turn', + ); + } + repairedEpisode = repairEpisode; + } + + const sourceEvents = repairSuffix?.events ?? replayEvents; + const firstPersistedRecordId = + replayEvents + .filter((event) => event.type === 'session_update') + .map(getPersistedReplayRecordId) + .find((recordId): recordId is string => recordId !== undefined) ?? + replayEvents + .filter((event) => event.type === 'history_truncated') + .map(getPersistedReplayRecordId) + .find((recordId): recordId is string => recordId !== undefined) ?? + session.historyAnchorRecordId; + const historyHasMore = + capabilities.features.includes(SESSION_TRANSCRIPT_PAGINATION_FEATURE) && + (session.historyHasMore || + replayEvents.some(hasFullTranscriptBeforeReplay)) && + firstPersistedRecordId !== undefined; + const sameLogicalSession = + session.sessionId === currentConnection.sessionId && + session.workspaceCwd === currentConnection.workspaceCwd; + + const noticeInputs: SessionNoticeInput[] = []; + const dismissedNoticeIds: string[] = []; + const stagedAddNotice: AddDaemonSessionNotice = (noticeInput) => { + noticeInputs.push(noticeInput); + return { + ...noticeInput, + id: noticeInput.id ?? `staged-daemon-notice-${noticeInputs.length}`, + createdAt: noticeInput.createdAt ?? Date.now(), + }; + }; + let stagedConnection: DaemonConnectionState = sameLogicalSession + ? { ...currentConnection } + : { + ...currentConnection, + gitBranch: undefined, + gitStatus: undefined, + commands: undefined, + skills: undefined, + models: undefined, + currentModel: undefined, + currentMode: undefined, + contextWindow: undefined, + providers: undefined, + supportedCommands: undefined, + context: undefined, + }; + const stageConnection: Dispatch> = ( + update, + ) => { + stagedConnection = + typeof update === 'function' ? update(stagedConnection) : update; + }; + const replayOpts = { + ...eventOptions, + suppressOwnUserEcho: false, + }; + const eventGroups: Array<{ + transcript: DaemonUiEvent[]; + sideEffects: DaemonUiEvent[]; + }> = []; + const sidechannelEvents: DaemonEvent[] = []; + for (const replayEvent of sourceEvents) { + try { + const normalized = normalizeAndFilterEvent( + replayEvent, + session.clientId, + replayOpts, + stageConnection, + { suppressLog: true }, + ); + const transcriptEvents = filterDaemonUiEventsForTranscript( + replayEvent, + normalized, + stagedAddNotice, + (id) => dismissedNoticeIds.push(id), + { hideHistoryTruncation: historyHasMore, suppressLogs: true }, + ); + const projected = + subagentTranscriptMode === 'summary' + ? projectMainTranscriptEvents(transcriptEvents) + : transcriptEvents; + const transcript = [...projected]; + if (replayEvent.type === 'turn_complete') { + transcript.push( + assistantDoneFromTurnEvent( + replayEvent, + (replayEvent.data as DaemonTurnCompleteData | undefined) + ?.stopReason ?? 'end_turn', + ), + ); + } else if (replayEvent.type === 'turn_error') { + transcript.push(assistantDoneFromTurnEvent(replayEvent, 'error')); + } + eventGroups.push({ transcript, sideEffects: normalized }); + if ( + parseSidechannelFollowupSuggestion(replayEvent) || + parseSidechannelMidTurnInjected(replayEvent) || + isPendingPromptEvent(replayEvent) + ) { + sidechannelEvents.push(replayEvent); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + noticeInputs.push({ + severity: 'warning', + category: 'protocol', + operation: 'normalize_event', + code: 'daemon.replay_event_malformed', + message: 'Skipped malformed replay event', + debugMessage: message, + recoverable: true, + }); + eventGroups.push({ transcript: [], sideEffects: [] }); + } + } + + const stageStore = createDaemonTranscriptStore( + repairedEpisode + ? { + ...repairedEpisode.checkpoint, + maxBlocks: repairedEpisode.checkpoint.maxBlocks, + } + : { + maxBlocks: Number.MAX_SAFE_INTEGER, + retainSubagentBlocks: subagentTranscriptMode === 'full', + }, + ); + for (const group of eventGroups) stageStore.dispatch(group.transcript); + const stagedTranscript = stageStore.getSnapshot(); + const exceededCapacity = + !repairedEpisode && stagedTranscript.blocks.length > maxBlocks; + const committedTranscript = { + ...stagedTranscript, + maxBlocks: repairedEpisode + ? stagedTranscript.maxBlocks + : Math.max(maxBlocks, stagedTranscript.blocks.length), + }; + + const replayTokenUsage = getReplayTokenUsage(replayEvents); + const replayTokenCount = getTokenCountFromUsage(replayTokenUsage); + const preserveExistingTranscript = + replayEvents.length === 0 && mode === 'resume' && sameLogicalSession; + const transcriptHistory = repairedEpisode + ? { + ...currentTranscriptHistory, + sessionId: session.sessionId, + ...(firstPersistedRecordId !== undefined + ? { beforeRecordId: firstPersistedRecordId, cursor: undefined } + : {}), + loading: false as const, + } + : preserveExistingTranscript + ? { + ...currentTranscriptHistory, + sessionId: session.sessionId, + loading: false as const, + } + : { + sessionId: session.sessionId, + ...(firstPersistedRecordId !== undefined + ? { beforeRecordId: firstPersistedRecordId } + : {}), + hasMore: exceededCapacity ? false : historyHasMore, + loading: false as const, + capacityReached: exceededCapacity, + paginationError: false as const, + }; + stagedConnection = { + ...stagedConnection, + status: 'connected', + sessionId: session.sessionId, + clientId: session.clientId, + workspaceCwd: session.workspaceCwd, + displayName: + getSessionDisplayName(session.state) ?? + (sameLogicalSession ? currentConnection.displayName : undefined), + tokenUsage: + replayTokenUsage ?? + (preserveExistingTranscript ? currentConnection.tokenUsage : undefined), + tokenCount: + replayTokenCount ?? + (preserveExistingTranscript ? (currentConnection.tokenCount ?? 0) : 0), + capabilities, + error: undefined, + errorStatus: undefined, + missingSession: false, + loadingTranscript: undefined, + catchingUp: session.lastEventId !== undefined ? true : undefined, + sessionTransition: undefined, + }; + delete stagedConnection.sessionTransition; + + return { + session, + connection: stagedConnection, + transcript: preserveExistingTranscript ? undefined : committedTranscript, + transcriptHistory, + transcriptHistoryState: { + hasMore: transcriptHistory.hasMore, + loading: false, + capacityReached: transcriptHistory.capacityReached, + paginationError: transcriptHistory.paginationError, + }, + replayEvents, + sideEffectEvents: eventGroups.flatMap((group) => group.sideEffects), + sidechannelEvents, + notices: noticeInputs, + dismissNoticeIds: dismissedNoticeIds, + }; +} function assistantDoneFromTurnEvent( event: DaemonEvent, @@ -515,9 +856,6 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const resolvedWorkspaceCwdRef = useRef(resolvedWorkspaceCwd); resolvedWorkspaceCwdRef.current = resolvedWorkspaceCwd; const activeWorkspaceCwdRef = useRef(resolvedWorkspaceCwd); - if (resolvedWorkspaceCwd) { - activeWorkspaceCwdRef.current = resolvedWorkspaceCwd; - } const store = useMemo( () => @@ -569,6 +907,9 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const repairReloadRef = useRef< DaemonSessionActions['reloadSession'] | undefined >(undefined); + const requestSessionResyncRef = useRef< + ((reason: string) => void) | undefined + >(undefined); const tryLiveJournalRepairRef = useRef<(() => void) | undefined>(undefined); const passiveAssistantDoneTimerRef = useRef< ReturnType | undefined @@ -581,6 +922,84 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const skipNextCleanupDetachSessionIdRef = useRef( undefined, ); + const runnerControlRef = useRef(undefined); + const nextRunnerSseReasonRef = useRef( + undefined, + ); + const preserveRunnerSessionRef = useRef( + undefined, + ); + const ownerGenerationRef = useRef(0); + const providerGenerationRef = useRef(0); + const providerIdentityRef = useRef({ + baseUrl: resolvedBaseUrl, + token: resolvedToken, + store, + client: workspace?.client, + capabilities: workspace?.capabilities, + getCapabilities: workspace?.getCapabilities, + autoConnect, + autoReconnect, + modelServiceId: createSessionRequest?.modelServiceId, + sessionScope: createSessionRequest?.sessionScope, + maxQueued, + maxBlocks, + shouldDeferInitialSessionCreation, + }); + const providerIdentityChangedRef = useRef(false); + if ( + providerIdentityRef.current.baseUrl !== resolvedBaseUrl || + providerIdentityRef.current.token !== resolvedToken || + providerIdentityRef.current.store !== store || + providerIdentityRef.current.client !== workspace?.client || + providerIdentityRef.current.capabilities !== workspace?.capabilities || + providerIdentityRef.current.getCapabilities !== + workspace?.getCapabilities || + providerIdentityRef.current.autoConnect !== autoConnect || + providerIdentityRef.current.autoReconnect !== autoReconnect || + providerIdentityRef.current.modelServiceId !== + createSessionRequest?.modelServiceId || + providerIdentityRef.current.sessionScope !== + createSessionRequest?.sessionScope || + providerIdentityRef.current.maxQueued !== maxQueued || + providerIdentityRef.current.maxBlocks !== maxBlocks || + providerIdentityRef.current.shouldDeferInitialSessionCreation !== + shouldDeferInitialSessionCreation + ) { + providerIdentityRef.current = { + baseUrl: resolvedBaseUrl, + token: resolvedToken, + store, + client: workspace?.client, + capabilities: workspace?.capabilities, + getCapabilities: workspace?.getCapabilities, + autoConnect, + autoReconnect, + modelServiceId: createSessionRequest?.modelServiceId, + sessionScope: createSessionRequest?.sessionScope, + maxQueued, + maxBlocks, + shouldDeferInitialSessionCreation, + }; + providerGenerationRef.current += 1; + providerIdentityChangedRef.current = true; + } + const activeTransitionRef = useRef( + undefined, + ); + const queuedTransitionRef = useRef( + undefined, + ); + const deferredResyncRef = useRef< + { source: DaemonSessionClient; reason: string } | undefined + >(undefined); + const cancelSessionTransitionRef = useRef< + ((reason: string) => void) | undefined + >(undefined); + const pumpSessionTransitionRef = useRef<() => void>(() => undefined); + const controlledTransitionOriginRef = useRef< + DaemonSessionTransitionOrigin | undefined + >(undefined); const settledRestoredActivePromptSessionsRef = useRef< WeakSet >(new WeakSet()); @@ -589,10 +1008,12 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const loadWarningsRef = useRef(loadWarnings); const historyPageSizeRef = useRef(historyPageSize); const subagentTranscriptModeRef = useRef(subagentTranscriptMode); - const clientIdRef = useRef(undefined); - if (!clientIdRef.current || clientId) { - clientIdRef.current = getStableClientId(clientId); - } + const initialClientIdRef = useRef(clientId); + const requestedClientIdRef = useRef(clientId); + requestedClientIdRef.current = clientId; + const clientIdRef = useRef( + getStableClientId(initialClientIdRef.current), + ); eventOptionsRef.current = { suppressOwnUserEcho, includeRawEvent }; reconnectConfigRef.current = { reconnectDelayMs, maxReconnectDelayMs }; loadWarningsRef.current = loadWarnings; @@ -613,20 +1034,31 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const [restoreSessionNonce, setRestoreSessionNonce] = useState(0); const [attachSessionNonce, setAttachSessionNonce] = useState(0); const [newSessionNonce, setNewSessionNonce] = useState(0); + const [controlledTargetRetryNonce, setControlledTargetRetryNonce] = + useState(0); const [connection, setConnection] = useState({ status: autoConnect ? 'connecting' : 'idle', ...(initialRestoreSessionId ? { sessionId: initialRestoreSessionId } : {}), }); const connectionRef = useRef(connection); connectionRef.current = connection; + const setConnectionSynchronous = useCallback( + (update: SetStateAction) => { + const next = + typeof update === 'function' ? update(connectionRef.current) : update; + connectionRef.current = next; + setConnection(next); + }, + [], + ); useEffect(() => { if (!workspace?.capabilities) return; - setConnection((current) => + setConnectionSynchronous((current) => current.capabilities === workspace.capabilities ? current : { ...current, capabilities: workspace.capabilities }, ); - }, [workspace?.capabilities]); + }, [setConnectionSynchronous, workspace?.capabilities]); const noticeIdRef = useRef(0); const [notices, setNotices] = useState([]); const addNotice = useCallback((input) => { @@ -660,16 +1092,58 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { useState(INITIAL_WORKSPACE_EVENT_SIGNALS); const hasCurrentSessionActivePromptRef = useRef<() => boolean>(() => false); const mountedRef = useRef(false); + const detachedSessionClientsRef = useRef(new WeakSet()); + const bestEffortDetach = useCallback( + ( + target: DaemonSessionClient, + endpoint: { baseUrl?: string; token?: string } = { + baseUrl: resolvedBaseUrl, + token: resolvedToken, + }, + identity: { sessionId?: string; clientId?: string } = {}, + ) => { + if (detachedSessionClientsRef.current.has(target)) return; + detachedSessionClientsRef.current.add(target); + const sessionId = identity.sessionId ?? target.sessionId; + const clientId = identity.clientId ?? target.clientId; + if (!endpoint.baseUrl || !clientId) { + console.warn( + '[DaemonSessionProvider] cannot retire session attachment without endpoint and client identity', + { sessionId }, + ); + return; + } + void detachDaemonClient({ + baseUrl: endpoint.baseUrl, + token: endpoint.token, + sessionId, + clientId, + }).catch((error: unknown) => { + console.warn( + '[DaemonSessionProvider] best-effort session detach failed:', + error, + ); + }); + }, + [resolvedBaseUrl, resolvedToken], + ); useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; - liveJournalRepairRef.current?.controller?.abort(); - liveJournalRepairRef.current = undefined; - tryLiveJournalRepairRef.current = undefined; + queueMicrotask(() => { + if (!mountedRef.current) { + liveJournalRepairRef.current?.controller?.abort(); + liveJournalRepairRef.current = undefined; + tryLiveJournalRepairRef.current = undefined; + cancelSessionTransitionRef.current?.('Session provider unmounted'); + const current = sessionRef.current; + if (current) bestEffortDetach(current); + } + }); }; - }, []); + }, [bestEffortDetach]); useEffect(() => { if (!autoConnect) return undefined; @@ -748,10 +1222,14 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { }; // Drop buffered events. Used before `store.reset()`: pending events belong // to the epoch the reset is discarding, so flushing them would be wrong. - const clearPendingTranscriptEvents = () => { - cancelTranscriptFlush(); - pendingTranscriptEvents = []; + const runnerControl: SessionRunnerControl = { + flush: flushTranscriptSync, + stop: () => { + disposed = true; + abort.abort(); + }, }; + runnerControlRef.current = runnerControl; const tryLiveJournalRepair = () => { if (disposed || abort.signal.aborted) return; const repair = liveJournalRepairRef.current; @@ -760,6 +1238,8 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { repair.attempted || !repair.terminalSeen || pendingSessionLoadRef.current || + activeTransitionRef.current || + queuedTransitionRef.current || transcriptHistoryRef.current.loading || sessionRef.current?.sessionId !== repair.sessionId || hasCurrentSessionActivePromptRef.current() @@ -774,6 +1254,15 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { void reload(controller.signal, { replaySource: 'memory' }).catch( (error: unknown) => { if (liveJournalRepairRef.current !== repair) return; + if ( + controller.signal.aborted || + (error instanceof DOMException && error.name === 'AbortError') + ) { + repair.controller = undefined; + repair.attempted = false; + queueMicrotask(() => tryLiveJournalRepairRef.current?.()); + return; + } addNotice({ id: `daemon.live_journal_repair.failed:${repair.target.signature}`, severity: 'warning', @@ -803,7 +1292,8 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { let reconnectSessionId = restoreSessionId; let shouldCreateFreshSession = !restoreSessionId && newSessionNonce > 0; let reconnectAttempt = 0; - let nextSseConnectReason: DaemonSseConnectReason | undefined; + let nextSseConnectReason = nextRunnerSseReasonRef.current; + nextRunnerSseReasonRef.current = undefined; let skipMetadataRefresh = false; let hasCurrentSessionActivePrompt = () => false; // Set when the user explicitly deletes the session (server @@ -879,6 +1369,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { reconnectSessionId = existingSession.sessionId; lastSessionIdRef.current = existingSession.sessionId; attachedExistingSession = true; + capabilities = connectionRef.current.capabilities; } } if (!session) { @@ -910,6 +1401,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { caps.features.includes('client_heartbeat'); const effectWorkspaceCwd = restoreWorkspaceCwd ?? + activeWorkspaceCwdRef.current ?? resolvedWorkspaceCwdRef.current ?? caps.workspaceCwd; activeWorkspaceCwdRef.current = effectWorkspaceCwd; @@ -1056,9 +1548,11 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { ? DaemonSessionClient.resume : DaemonSessionClient.load; const targetSessionId = restoreSessionId ?? reconnectSessionId; - const requestClientId = clientId - ? clientIdRef.current - : getStableClientId(undefined, targetSessionId); + const requestedClientId = requestedClientIdRef.current; + const requestClientId = getStableClientId( + requestedClientId, + targetSessionId, + ); loadingRequestedSession = Boolean(restoreSessionId); if (targetSessionId && !preservingTranscriptDuringLoad) { setConnection((current) => ({ @@ -1123,12 +1617,14 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { requestClientId, ); loadingRequestedSession = false; - if (!clientId && nextSession.clientId) { + if (nextSession.clientId) { clientIdRef.current = nextSession.clientId; - persistStableClientId( - nextSession.clientId, - nextSession.sessionId, - ); + if (!requestedClientId) { + persistStableClientId( + nextSession.clientId, + nextSession.sessionId, + ); + } } if (disposed || abort.signal.aborted) { void detachDaemonClient({ @@ -1263,7 +1759,10 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { const replaySnapshotEventCount = nextSession.replaySnapshot.compactedReplay.length + nextSession.replaySnapshot.liveJournal.length; - if (replaySnapshotEventCount > 0) { + if ( + replaySnapshotEventCount > 0 || + attemptedLoad?.replaySource === 'configured' + ) { setPromptStatus('idle'); clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); needsStoreReset = true; @@ -1297,6 +1796,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { } const activeSession = session; + runnerControl.session = activeSession; // Prompt activity is session state returned by /load. Surface it // immediately so a refreshed page shows the running state without // waiting for auxiliary data such as providers, commands, or context. @@ -1385,7 +1885,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { ) && (activeSession.historyHasMore || replayHistoryWasTruncated) && firstPersistedRecordId !== undefined; - if (!repairingEpisode) { + if (!repairingEpisode && !attachedExistingSession) { transcriptHistoryRef.current = { sessionId: activeSession.sessionId, ...(firstPersistedRecordId !== undefined @@ -1726,6 +2226,13 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { : activeSession.context(), gitPromise, ]); + if ( + disposed || + abort.signal.aborted || + sessionRef.current !== activeSession + ) { + return; + } const providers = providerResult?.status === 'fulfilled' ? providerResult.value @@ -1859,39 +2366,18 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { } let sawEvent = false; let resyncRequested = false; - const requestEpochResetReload = () => { - // An epoch reset means the daemon/EventBus timeline was rebuilt. - // The current SSE cursor and any restored/local prompt activity may - // describe the old epoch, so do a full /load and let - // hasActivePrompt from that fresh snapshot become authoritative. - const active = activePromptsRef.current.get( - activeSession.sessionId, - ); - active?.controller.abort(); - activePromptsRef.current.delete(activeSession.sessionId); - if (restoredActivePrompt) { - settleRestoredActivePrompt(); - } - clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); - setPromptStatus('idle'); - clearPendingTranscriptEvents(); - store.reset(); - activeSession.setLastEventId(0); - reconnectSessionId = activeSession.sessionId; + const requestSnapshotResync = (reason: string) => { + // The stream declared its cursor/base invalid. Preserve the last + // valid transcript prefix and attachment, but stop consuming this + // epoch immediately. The coordinator replaces it only after a pure + // snapshot stage succeeds. + flushTranscriptSync(); + if (reason === 'epoch_reset') activeSession.setLastEventId(0); resyncRequested = true; nextSseConnectReason = 'state_resync'; - session = undefined; - sessionRef.current = undefined; - hasCurrentSessionActivePromptRef.current = () => false; - setConnection((current) => ({ - ...current, - status: 'connecting', - error: undefined, - errorStatus: resolveConnectionErrorStatus( - undefined, - current.errorStatus, - ), - })); + nextRunnerSseReasonRef.current = 'state_resync'; + requestSessionResyncRef.current?.(reason); + runnerControl.stop(); }; const eventStreamController = new AbortController(); eventStream = { @@ -1914,7 +2400,11 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { maxQueued, ...(sseConnectReason ? { sseConnectReason } : {}), })) { - if (sessionRef.current?.sessionId !== activeSession.sessionId) { + if ( + disposed || + abort.signal.aborted || + sessionRef.current !== activeSession + ) { break; } if (!sawEvent) { @@ -1972,10 +2462,17 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { typeof event.data === 'object' && event.data !== null ? (event.data as Record).reason : undefined; - if (reason === 'epoch_reset') { - requestEpochResetReload(); - break; - } + // Everything yielded before the sentinel is valid. Commit that + // prefix now, publish the sentinel's local stale marker, and + // stop this stream generation before the iterator can yield a + // suffix against the stale base. + flushTranscriptSync(); + dispatchTranscriptNow(transcriptUiEvents); + bumpWorkspaceEventSignals(uiEvents, setWorkspaceEventSignals); + requestSnapshotResync( + typeof reason === 'string' ? reason : 'ring_evicted', + ); + break; } bumpWorkspaceEventSignals(uiEvents, setWorkspaceEventSignals); if (uiEvents.length > 0) { @@ -2149,54 +2646,6 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { } else if (pendingRepair?.terminalSeen) { queueMicrotask(tryLiveJournalRepair); } - // ── state_resync_required handling ────────────────────── - // Resyncs are transcript recovery signals, not prompt terminal - // signals. For epoch_reset and ring_evicted we reload the session - // snapshot; the fresh /load response is the source of truth for - // hasActivePrompt and transcript replay. - if (event.type === 'state_resync_required') { - const reason = - typeof event.data === 'object' && event.data !== null - ? (event.data as Record).reason - : undefined; - if (reason !== 'epoch_reset') { - // Resync asks us to rebuild transcript state, but it is not a - // prompt terminal signal. Keep loading alive for local/restored - // prompts until turn_complete, turn_error, or prompt_cancelled. - if (!hasSessionActivePrompt()) { - setPromptStatus('idle'); - clearPassiveAssistantDoneTimer( - passiveAssistantDoneTimerRef, - ); - } - clearPendingTranscriptEvents(); - store.reset(); - // Ring eviction means the SSE replay window has a real gap. - // Resetting and continuing on the same stream can only replay - // the surviving tail; reload the session snapshot instead so - // compactedReplay/liveJournal rebuild the bounded replay - // window. - console.warn( - '[DaemonSessionProvider] ring eviction detected, reloading session (sessionId=%s)', - activeSession.sessionId, - ); - resyncRequested = true; - nextSseConnectReason = 'state_resync'; - session = undefined; - sessionRef.current = undefined; - hasCurrentSessionActivePromptRef.current = () => false; - setConnection((current) => ({ - ...current, - status: 'connecting', - error: undefined, - errorStatus: resolveConnectionErrorStatus( - undefined, - current.errorStatus, - ), - })); - break; - } - } // session_closed with reason 'client_close' means the // user explicitly deleted the session. Stop the // reconnect loop — without this, the next iteration @@ -2281,7 +2730,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { nextSseConnectReason = 'stream_end'; // Keep the session handle after a normal SSE close so the next // subscription can resume from DaemonSessionClient.lastEventId. - if (sessionRef.current?.sessionId === activeSession.sessionId) { + if (sessionRef.current === activeSession) { console.debug('[DaemonSessionProvider] SSE stream ended'); if (!hasSessionActivePrompt()) { // A transport close is only a safe "done" signal for passive @@ -2470,6 +2919,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { })); } + if (disposed || abort.signal.aborted) return; if (!autoReconnect) { sessionRef.current = undefined; setConnection((current) => ({ @@ -2499,7 +2949,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { void run(); return () => { - const session = sessionRef.current; + const session = runnerControl.session; disposed = true; abort.abort(); // Apply buffered transcript events before tearing down (do NOT drop them). @@ -2511,36 +2961,50 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { // is an orphaned dispatch and on a session switch the next run resets the // store anyway. flushTranscriptSync(); - hasCurrentSessionActivePromptRef.current = () => false; - setPromptStatus('idle'); - clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); + if (runnerControlRef.current === runnerControl) { + runnerControlRef.current = undefined; + } const keepSessionForNextEffect = + session === preserveRunnerSessionRef.current || session?.sessionId === skipNextCleanupDetachSessionIdRef.current; - const isUnmounting = !mountedRef.current; - if ( - pendingSessionLoadRef.current && - (!keepSessionForNextEffect || isUnmounting) - ) { - if (pendingSessionLoadRef.current.timeout !== undefined) { - clearTimeout(pendingSessionLoadRef.current.timeout); - } - pendingSessionLoadRef.current.reject( - new DOMException('Session load interrupted by cleanup', 'AbortError'), - ); - pendingSessionLoadRef.current = undefined; - } - if ((!keepSessionForNextEffect || isUnmounting) && session?.clientId) { - void detachDaemonClient({ - baseUrl: resolvedBaseUrl!, - token: resolvedToken, - sessionId: session.sessionId, - clientId: session.clientId, - }).catch((err) => - console.warn('[DaemonSessionProvider] detach failed:', err), - ); + if (session === preserveRunnerSessionRef.current) { + preserveRunnerSessionRef.current = undefined; } - if (!keepSessionForNextEffect || isUnmounting) { - sessionRef.current = undefined; + const releaseCapturedSession = (unmounted: boolean) => { + if (keepSessionForNextEffect && !unmounted) return; + if (!unmounted) { + hasCurrentSessionActivePromptRef.current = () => false; + setPromptStatus('idle'); + clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); + } + if (pendingSessionLoadRef.current) { + if (pendingSessionLoadRef.current.timeout !== undefined) { + clearTimeout(pendingSessionLoadRef.current.timeout); + } + pendingSessionLoadRef.current.reject( + new DOMException( + 'Session load interrupted by cleanup', + 'AbortError', + ), + ); + pendingSessionLoadRef.current = undefined; + } + if (session) { + bestEffortDetach(session, { + baseUrl: resolvedBaseUrl, + token: resolvedToken, + }); + } + if (sessionRef.current === session) { + sessionRef.current = undefined; + } + }; + if (!mountedRef.current) { + queueMicrotask(() => { + if (!mountedRef.current) releaseCapturedSession(true); + }); + } else { + releaseCapturedSession(false); } }; }, [ @@ -2548,7 +3012,6 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { autoReconnect, resolvedBaseUrl, resolvedToken, - workspaceCwd, modelServiceId, sessionScope, maxQueued, @@ -2560,8 +3023,8 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { restoreSessionNonce, attachSessionNonce, newSessionNonce, - clientId, shouldDeferInitialSessionCreation, + bestEffortDetach, clearNotices, addNotice, dismissNotice, @@ -2591,7 +3054,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { session .heartbeat() .then(() => { - if (disposed) return; + if (disposed || sessionRef.current !== session) return; if ( heartbeatFailureState.consecutiveFailures >= heartbeatFailureThreshold @@ -2611,7 +3074,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { heartbeatFailureState.lastHttpError = undefined; }) .catch((error: unknown) => { - if (disposed) return; + if (disposed || sessionRef.current !== session) return; heartbeatFailureState.consecutiveFailures += 1; const message = error instanceof Error ? error.message : 'Session heartbeat failed'; @@ -2701,6 +3164,835 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { heartbeatIntervalMs, ]); + const clearTransitionTimer = useCallback( + (intent: SessionTransitionIntent) => { + if (intent.timer !== undefined) clearTimeout(intent.timer); + intent.timer = undefined; + intent.removeAbortListener?.(); + intent.removeAbortListener = undefined; + }, + [], + ); + + const settleTransition = useCallback( + ( + intent: SessionTransitionIntent, + outcome: { ok: true } | { ok: false; error: unknown }, + ) => { + if (intent.publicSettled) return; + intent.publicSettled = true; + clearTransitionTimer(intent); + if (outcome.ok) { + if (!intent.primarySettled) { + intent.primarySettled = true; + intent.resolve(); + } + for (const waiter of intent.coalesced) { + if (waiter.settled) continue; + waiter.settled = true; + waiter.removeAbortListener?.(); + waiter.resolve(); + } + } else { + if (!intent.primarySettled) { + intent.primarySettled = true; + intent.reject(outcome.error); + } + for (const waiter of intent.coalesced) { + if (waiter.settled) continue; + waiter.settled = true; + waiter.removeAbortListener?.(); + waiter.reject(outcome.error); + } + } + intent.coalesced.length = 0; + }, + [clearTransitionTimer], + ); + + const retireTransitionCandidate = useCallback( + (intent: SessionTransitionIntent) => { + if (!intent.candidate || intent.candidateRetired) return; + intent.candidateRetired = true; + bestEffortDetach( + intent.candidate, + { + baseUrl: intent.baseUrl, + token: intent.token, + }, + intent.candidateCleanup, + ); + }, + [bestEffortDetach], + ); + + const markTransitionTimedOut = useCallback( + (intent: SessionTransitionIntent) => { + if (intent.publicSettled || intent.commitClaimed) return; + intent.superseded = true; + const error = Object.assign(new Error('Session transition timed out'), { + _alreadyDispatched: true as const, + }); + settleTransition(intent, { + ok: false, + error, + }); + const ownsVisibleTransition = + queuedTransitionRef.current === intent || + activeTransitionRef.current === intent; + if (queuedTransitionRef.current === intent) { + queuedTransitionRef.current = undefined; + } + retireTransitionCandidate(intent); + if (!ownsVisibleTransition) return; + if (intent.origin === 'repair') return; + const sourceStillCurrent = sessionRef.current === intent.source; + setConnectionSynchronous((current) => ({ + ...current, + sessionTransition: { + phase: 'failed', + operation: intent.operation, + origin: intent.origin, + targetSessionId: intent.request.sessionId, + ...(intent.request.workspaceCwd !== undefined + ? { targetWorkspaceCwd: intent.request.workspaceCwd } + : {}), + ...(intent.request.clientId !== undefined + ? { targetClientId: intent.request.clientId } + : {}), + error: { + message: 'Session transition timed out', + }, + }, + })); + addNotice({ + severity: 'warning', + category: 'connection', + operation: + intent.request.mode === 'resume' ? 'resume_session' : 'load_session', + code: 'daemon.session_transition.failed', + message: sourceStillCurrent + ? `Could not open session ${intent.request.sessionId}. The current session is still active.` + : `Could not open session ${intent.request.sessionId} after the current session disconnected.`, + debugMessage: error.message, + recoverable: true, + }); + }, + [ + addNotice, + retireTransitionCandidate, + setConnectionSynchronous, + settleTransition, + ], + ); + + const publishStagedCandidate = useCallback( + (staged: StagedSessionCandidate, intent: SessionTransitionIntent) => { + const source = intent.source; + const sourceRunner = + runnerControlRef.current?.session === source + ? runnerControlRef.current + : undefined; + sourceRunner?.flush(); + ownerGenerationRef.current += 1; + if (sourceRunner && source) preserveRunnerSessionRef.current = source; + sourceRunner?.stop(); + + if (staged.transcript) store.reset(staged.transcript); + transcriptHistoryRef.current = staged.transcriptHistory; + setTranscriptHistoryState(staged.transcriptHistoryState); + sessionRef.current = staged.session; + lastSessionIdRef.current = staged.session.sessionId; + activeWorkspaceCwdRef.current = staged.session.workspaceCwd; + clientIdRef.current = staged.session.clientId; + persistStableClientId(staged.session.clientId, staged.session.sessionId); + setConnectionSynchronous(staged.connection); + + if ( + !source || + source.sessionId !== staged.session.sessionId || + source.workspaceCwd !== staged.session.workspaceCwd + ) { + clearNotices(); + } + for (const id of staged.dismissNoticeIds) dismissNotice(id); + for (const notice of staged.notices) addNotice(notice); + if (staged.sideEffectEvents.length > 0) { + bumpWorkspaceEventSignals( + staged.sideEffectEvents, + setWorkspaceEventSignals, + ); + } + for (const event of staged.sidechannelEvents) { + try { + const followup = parseSidechannelFollowupSuggestion(event); + if (followup) publishSidechannelFollowupSuggestion(followup); + const midTurn = parseSidechannelMidTurnInjected(event); + if (midTurn) publishSidechannelMidTurnInjected(midTurn); + if (isPendingPromptEvent(event)) publishPendingPromptEvent(event); + } catch (error) { + console.warn( + '[DaemonSessionProvider] staged sidechannel publication failed:', + error, + ); + } + } + + const sameSession = + source?.sessionId === staged.session.sessionId && + source.workspaceCwd === staged.session.workspaceCwd; + if (!sameSession && source) { + const active = activePromptsRef.current.get(source.sessionId); + active?.controller.abort( + new DOMException( + 'Session switch interrupted prompt wait', + 'AbortError', + ), + ); + activePromptsRef.current.delete(source.sessionId); + settledPromptsRef.current.clear(); + } + for (const event of staged.replayEvents) { + settleActivePromptFromTurnEvent( + activePromptsRef.current, + settledPromptsRef.current, + staged.session.sessionId, + event, + store, + setPromptStatus, + passiveAssistantDoneTimerRef, + { requireBoundPromptId: true }, + ); + } + const stagedActive = activePromptsRef.current.get( + staged.session.sessionId, + ); + if ( + sameSession && + !staged.session.hasActivePrompt && + stagedActive !== undefined + ) { + stagedActive.controller.abort( + new DOMException( + 'Prompt was no longer active after session reload', + 'AbortError', + ), + ); + activePromptsRef.current.delete(staged.session.sessionId); + } + const hasActivePrompt = + staged.session.hasActivePrompt || + activePromptsRef.current.has(staged.session.sessionId); + hasCurrentSessionActivePromptRef.current = () => hasActivePrompt; + setPromptStatus(hasActivePrompt ? 'streaming' : 'idle'); + liveJournalRepairRef.current?.controller?.abort(); + liveJournalRepairRef.current = undefined; + + manualSessionClearRef.current = false; + setRestoreSessionId(undefined); + setRestoreWorkspaceCwd(undefined); + setRestoreSessionNonce((nonce) => nonce + 1); + if (source) { + bestEffortDetach(source, { + baseUrl: intent.baseUrl, + token: intent.token, + }); + } + }, + [ + addNotice, + bestEffortDetach, + clearNotices, + dismissNotice, + setConnectionSynchronous, + store, + ], + ); + + const scheduleDeferredResync = useCallback(() => { + queueMicrotask(() => { + if (activeTransitionRef.current || queuedTransitionRef.current) { + return; + } + const deferred = deferredResyncRef.current; + if (!deferred) return; + if (sessionRef.current !== deferred.source) { + deferredResyncRef.current = undefined; + return; + } + deferredResyncRef.current = undefined; + requestSessionResyncRef.current?.(deferred.reason); + }); + }, []); + + const pumpSessionTransition = useCallback(() => { + if (activeTransitionRef.current) return; + const intent = queuedTransitionRef.current; + if (!intent) return; + queuedTransitionRef.current = undefined; + activeTransitionRef.current = intent; + intent.rawStarted = true; + setConnectionSynchronous((current) => ({ + ...current, + sessionTransition: { + phase: 'preparing', + operation: intent.operation, + origin: intent.origin, + targetSessionId: intent.request.sessionId, + ...(intent.request.workspaceCwd !== undefined + ? { targetWorkspaceCwd: intent.request.workspaceCwd } + : {}), + ...(intent.request.clientId !== undefined + ? { targetClientId: intent.request.clientId } + : {}), + }, + })); + + const finishRaw = () => { + if (activeTransitionRef.current === intent) { + activeTransitionRef.current = undefined; + } + pumpSessionTransitionRef.current(); + if ( + mountedRef.current && + !activeTransitionRef.current && + !queuedTransitionRef.current && + connectionRef.current.sessionTransition?.phase !== 'failed' + ) { + setConnectionSynchronous((current) => { + if (!current.sessionTransition) return current; + const next = { ...current }; + delete next.sessionTransition; + return next; + }); + } + if (mountedRef.current) { + scheduleDeferredResync(); + queueMicrotask(() => tryLiveJournalRepairRef.current?.()); + } + }; + + void (async () => { + const abandon = (message: string) => { + retireTransitionCandidate(intent); + if (!intent.publicSettled) { + settleTransition(intent, { + ok: false, + error: new DOMException(message, 'AbortError'), + }); + } + }; + const client = + workspaceClientRef.current ?? + new DaemonClient({ baseUrl: resolvedBaseUrl!, token: resolvedToken }); + let capabilities: DaemonCapabilities; + try { + const getWorkspaceCapabilities = workspaceGetCapabilitiesRef.current; + capabilities = + workspaceCapabilitiesRef.current ?? + (getWorkspaceCapabilities + ? await getWorkspaceCapabilities() + : await client.capabilities()); + } catch (error) { + const message = error instanceof Error ? `: ${error.message}` : ''; + throw new Error( + `Could not verify daemon session ownership support${message}`, + ); + } + if ( + intent.superseded || + !mountedRef.current || + intent.sourceGeneration !== ownerGenerationRef.current || + intent.providerGeneration !== providerGenerationRef.current || + (sessionRef.current !== undefined && + sessionRef.current !== intent.source) + ) { + abandon('Session transition is no longer active'); + return; + } + if (!capabilities.features.includes(CLIENT_IDENTITY_FEATURE)) { + await intent.startLegacy(); + settleTransition(intent, { ok: true }); + return; + } + if (!intent.source?.clientId) { + throw new Error( + 'The daemon advertises client identity but the current session has no clientId', + ); + } + const workspaceCwd = + intent.request.workspaceCwd ?? + activeWorkspaceCwdRef.current ?? + intent.source.workspaceCwd ?? + capabilities.workspaceCwd; + const candidateRequestClientId = getStableClientId( + intent.request.clientId ?? clientId, + intent.request.sessionId, + ); + intent.candidateCleanup = { + sessionId: intent.request.sessionId, + clientId: candidateRequestClientId, + }; + const candidate = await ( + intent.request.mode === 'resume' + ? DaemonSessionClient.resume + : DaemonSessionClient.load + )( + client, + intent.request.sessionId, + { + workspaceCwd, + timeoutMs: + resolveSessionRestoreTimeouts(capabilities).requestTimeoutMs, + ...(intent.request.mode === 'load' && + intent.request.replaySource !== 'memory' && + historyPageSizeRef.current !== undefined && + capabilities.features.includes(SESSION_TRANSCRIPT_PAGINATION_FEATURE) + ? { historyPageSize: historyPageSizeRef.current } + : {}), + }, + candidateRequestClientId, + ); + intent.candidate = candidate; + if (candidate.clientId) { + intent.candidateCleanup = { + sessionId: candidate.sessionId, + clientId: candidate.clientId, + }; + } + if (!candidate.clientId) { + throw new Error( + 'The daemon advertises client identity but restore returned no clientId', + ); + } + if ( + intent.request.clientId !== undefined && + candidate.clientId !== intent.request.clientId + ) { + throw new Error( + `Session restore returned unexpected clientId ${candidate.clientId}`, + ); + } + if (candidate.sessionId !== intent.request.sessionId) { + throw new Error( + `Session restore returned unexpected sessionId ${candidate.sessionId}`, + ); + } + if ( + intent.request.workspaceCwd !== undefined && + candidate.workspaceCwd !== intent.request.workspaceCwd + ) { + throw new Error( + `Session restore returned unexpected workspaceCwd ${candidate.workspaceCwd}`, + ); + } + if ( + intent.superseded || + !mountedRef.current || + activeTransitionRef.current !== intent || + intent.sourceGeneration !== ownerGenerationRef.current || + intent.providerGeneration !== providerGenerationRef.current || + (sessionRef.current !== undefined && + sessionRef.current !== intent.source) + ) { + abandon('Session owner changed before transition commit'); + return; + } + const staged = stageSessionCandidate({ + session: candidate, + capabilities, + currentConnection: connectionRef.current, + currentTranscriptHistory: { ...transcriptHistoryRef.current }, + maxBlocks, + subagentTranscriptMode: subagentTranscriptModeRef.current, + eventOptions: eventOptionsRef.current, + mode: intent.request.mode, + replaySource: intent.request.replaySource, + repairEpisode: liveJournalRepairRef.current, + }); + if ( + intent.superseded || + !mountedRef.current || + activeTransitionRef.current !== intent || + intent.sourceGeneration !== ownerGenerationRef.current || + intent.providerGeneration !== providerGenerationRef.current || + (sessionRef.current !== undefined && + sessionRef.current !== intent.source) + ) { + abandon('Session transition became stale before commit'); + return; + } + if (intent.deadlineAt !== undefined && Date.now() >= intent.deadlineAt) { + markTransitionTimedOut(intent); + return; + } + // The public success is claimed at the same linearization point as the + // synchronous store/ref handoff. A later React cleanup cannot turn it + // back into a timeout or abort. + intent.commitClaimed = true; + clearTransitionTimer(intent); + publishStagedCandidate(staged, intent); + settleTransition(intent, { ok: true }); + })() + .catch((error: unknown) => { + if (intent.commitClaimed) { + console.error( + '[DaemonSessionProvider] session transition commit failed after the ownership claim:', + error, + ); + settleTransition(intent, { ok: true }); + return; + } + retireTransitionCandidate(intent); + const sourceStillCurrent = sessionRef.current === intent.source; + const sourceWasLost = sessionRef.current === undefined; + const shouldExposeFailure = + !intent.superseded && (sourceStillCurrent || sourceWasLost); + const shouldExposeGenericFailure = + shouldExposeFailure && intent.origin !== 'repair'; + const publicError = shouldExposeGenericFailure + ? Object.assign( + error instanceof Error ? error : new Error(String(error)), + { _alreadyDispatched: true as const }, + ) + : error; + if (!intent.publicSettled) + settleTransition(intent, { ok: false, error: publicError }); + if (shouldExposeGenericFailure) { + const message = + error instanceof Error ? error.message : String(error); + setConnectionSynchronous((current) => ({ + ...current, + sessionTransition: { + phase: 'failed', + operation: intent.operation, + origin: intent.origin, + targetSessionId: intent.request.sessionId, + ...(intent.request.workspaceCwd !== undefined + ? { targetWorkspaceCwd: intent.request.workspaceCwd } + : {}), + ...(intent.request.clientId !== undefined + ? { targetClientId: intent.request.clientId } + : {}), + error: { message }, + }, + })); + addNotice({ + severity: 'warning', + category: 'connection', + operation: + intent.request.mode === 'resume' + ? 'resume_session' + : 'load_session', + code: 'daemon.session_transition.failed', + message: sourceStillCurrent + ? `Could not open session ${intent.request.sessionId}. The current session is still active.` + : `Could not open session ${intent.request.sessionId} after the current session disconnected.`, + debugMessage: message, + recoverable: true, + }); + } + }) + .finally(finishRaw); + }, [ + addNotice, + clearTransitionTimer, + clientId, + maxBlocks, + markTransitionTimedOut, + publishStagedCandidate, + retireTransitionCandidate, + resolvedBaseUrl, + resolvedToken, + scheduleDeferredResync, + setConnectionSynchronous, + settleTransition, + ]); + pumpSessionTransitionRef.current = pumpSessionTransition; + + const enqueueSessionTransition = useCallback( + ( + request: SessionTransitionRequest, + startLegacy: () => Promise, + ): Promise => { + if (request.signal?.aborted) { + return Promise.reject( + new DOMException('Session load cancelled', 'AbortError'), + ); + } + const origin = controlledTransitionOriginRef.current ?? request.origin; + controlledTransitionOriginRef.current = undefined; + const source = sessionRef.current; + if (!source) return startLegacy(); + const knownCapabilities = + workspaceCapabilitiesRef.current ?? connectionRef.current.capabilities; + if ( + knownCapabilities && + !knownCapabilities.features.includes(CLIENT_IDENTITY_FEATURE) + ) { + return startLegacy(); + } + const operation: DaemonSessionTransitionOperation = + request.replaySource === 'memory' || + source.sessionId === request.sessionId + ? 'reload' + : request.mode; + const targetWorkspace = + request.workspaceCwd ?? + activeWorkspaceCwdRef.current ?? + resolvedWorkspaceCwdRef.current; + const targetClientId = request.clientId ?? clientId; + const key = JSON.stringify([ + request.sessionId, + targetWorkspace, + request.mode, + request.replaySource, + targetClientId, + providerGenerationRef.current, + ]); + const exact = + activeTransitionRef.current?.key === key + ? activeTransitionRef.current + : queuedTransitionRef.current?.key === key + ? queuedTransitionRef.current + : undefined; + if (exact && !exact.superseded && !exact.publicSettled) { + return new Promise((resolve, reject) => { + const waiter: SessionTransitionIntent['coalesced'][number] = { + settled: false, + resolve, + reject, + }; + exact.coalesced.push(waiter); + if (request.signal) { + const onAbort = () => { + if (waiter.settled) return; + waiter.settled = true; + waiter.removeAbortListener?.(); + const error = + request.signal?.reason ?? + new DOMException('Session load cancelled', 'AbortError'); + reject(error); + if ( + !exact.commitClaimed && + exact.primarySettled && + exact.coalesced.every((entry) => entry.settled) + ) { + exact.superseded = true; + settleTransition(exact, { ok: false, error }); + if (queuedTransitionRef.current === exact) { + queuedTransitionRef.current = undefined; + } + if (!exact.rawStarted) retireTransitionCandidate(exact); + } + }; + request.signal.addEventListener('abort', onAbort, { once: true }); + waiter.removeAbortListener = () => + request.signal?.removeEventListener('abort', onAbort); + if (request.signal.aborted) onAbort(); + } + }); + } + + const supersede = (intent: SessionTransitionIntent | undefined) => { + if (!intent || intent.superseded || intent.commitClaimed) return; + if (intent.origin === 'resync' && origin !== 'resync') { + deferredResyncRef.current = { + source: intent.source!, + reason: 'superseded_resync', + }; + } + intent.superseded = true; + if (intent.origin === 'repair' && origin !== 'repair') { + const repair = liveJournalRepairRef.current; + if (repair && repair.sessionId === intent.source?.sessionId) { + repair.controller?.abort(); + repair.controller = undefined; + repair.attempted = false; + } + } + settleTransition(intent, { + ok: false, + error: new DOMException( + 'Session transition superseded by a newer request', + 'AbortError', + ), + }); + if (!intent.rawStarted) retireTransitionCandidate(intent); + }; + supersede(activeTransitionRef.current); + supersede(queuedTransitionRef.current); + queuedTransitionRef.current = undefined; + + return new Promise((resolve, reject) => { + const timeouts = resolveSessionRestoreTimeouts( + workspaceCapabilitiesRef.current ?? + connectionRef.current.capabilities, + ); + const deadlineAt = + timeouts.watchdogTimeoutMs === undefined + ? undefined + : Date.now() + timeouts.watchdogTimeoutMs; + const intent: SessionTransitionIntent = { + key, + request: { + ...request, + ...(targetWorkspace !== undefined + ? { workspaceCwd: targetWorkspace } + : {}), + ...(targetClientId !== undefined + ? { clientId: targetClientId } + : {}), + }, + operation, + origin, + ...(deadlineAt !== undefined ? { deadlineAt } : {}), + source, + sourceGeneration: ownerGenerationRef.current, + providerGeneration: providerGenerationRef.current, + commitClaimed: false, + publicSettled: false, + primarySettled: false, + superseded: false, + rawStarted: false, + candidateRetired: false, + baseUrl: resolvedBaseUrl!, + token: resolvedToken, + startLegacy, + resolve, + reject, + coalesced: [], + }; + if (timeouts.watchdogTimeoutMs !== undefined) { + intent.timer = setTimeout( + () => markTransitionTimedOut(intent), + timeouts.watchdogTimeoutMs, + ); + } + if (request.signal) { + const onAbort = () => { + if ( + intent.commitClaimed || + intent.publicSettled || + intent.primarySettled + ) { + return; + } + intent.primarySettled = true; + intent.removeAbortListener?.(); + intent.removeAbortListener = undefined; + intent.reject( + request.signal?.reason ?? + new DOMException('Session load cancelled', 'AbortError'), + ); + if (intent.coalesced.some((waiter) => !waiter.settled)) return; + intent.superseded = true; + settleTransition(intent, { + ok: false, + error: new DOMException('Session load cancelled', 'AbortError'), + }); + if (queuedTransitionRef.current === intent) { + queuedTransitionRef.current = undefined; + } + if (!intent.rawStarted) retireTransitionCandidate(intent); + }; + request.signal.addEventListener('abort', onAbort, { once: true }); + intent.removeAbortListener = () => + request.signal?.removeEventListener('abort', onAbort); + if (request.signal.aborted) onAbort(); + } + queuedTransitionRef.current = intent; + setConnectionSynchronous((current) => ({ + ...current, + sessionTransition: { + phase: activeTransitionRef.current ? 'queued' : 'preparing', + operation, + origin, + targetSessionId: request.sessionId, + ...(targetWorkspace !== undefined + ? { targetWorkspaceCwd: targetWorkspace } + : {}), + ...(targetClientId !== undefined ? { targetClientId } : {}), + }, + })); + pumpSessionTransitionRef.current(); + }); + }, + [ + clientId, + markTransitionTimedOut, + resolvedBaseUrl, + resolvedToken, + retireTransitionCandidate, + setConnectionSynchronous, + settleTransition, + ], + ); + + const beginSessionTransition = useCallback( + (request: SessionTransitionRequest, startLegacy: () => Promise) => + enqueueSessionTransition(request, startLegacy), + [enqueueSessionTransition], + ); + + const cancelSessionTransition = useCallback( + (reason: string) => { + deferredResyncRef.current = undefined; + const error = new DOMException(reason, 'AbortError'); + const queued = queuedTransitionRef.current; + if (queued) { + queued.superseded = true; + settleTransition(queued, { ok: false, error }); + retireTransitionCandidate(queued); + queuedTransitionRef.current = undefined; + } + const active = activeTransitionRef.current; + if (active && !active.commitClaimed) { + active.superseded = true; + settleTransition(active, { ok: false, error }); + } + if (mountedRef.current) { + setConnectionSynchronous((current) => { + if (!current.sessionTransition) return current; + const next = { ...current }; + delete next.sessionTransition; + return next; + }); + } + }, + [retireTransitionCandidate, setConnectionSynchronous, settleTransition], + ); + cancelSessionTransitionRef.current = cancelSessionTransition; + + const isSessionTransitionPending = useCallback( + () => + activeTransitionRef.current !== undefined || + queuedTransitionRef.current !== undefined, + [], + ); + + useEffect(() => { + if (!providerIdentityChangedRef.current) return; + providerIdentityChangedRef.current = false; + cancelSessionTransition('Session provider configuration changed'); + setControlledTargetRetryNonce((nonce) => nonce + 1); + }, [ + cancelSessionTransition, + resolvedBaseUrl, + resolvedToken, + store, + workspace?.capabilities, + workspace?.client, + workspace?.getCapabilities, + autoConnect, + autoReconnect, + modelServiceId, + sessionScope, + maxQueued, + maxBlocks, + shouldDeferInitialSessionCreation, + ]); + const actions = useMemo( () => createDaemonSessionActions({ @@ -2784,6 +4076,9 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { setRestoreSessionNonce, setAttachSessionNonce, setNewSessionNonce, + beginSessionTransition, + cancelSessionTransition, + isSessionTransitionPending, clearLiveJournalRepair: () => { liveJournalRepairRef.current?.controller?.abort(); liveJournalRepairRef.current = undefined; @@ -2791,7 +4086,10 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { }), [ addNotice, + beginSessionTransition, + cancelSessionTransition, clientId, + isSessionTransitionPending, resolvedBaseUrl, resolvedToken, restartEventStreamOnPrompt, @@ -2799,6 +4097,32 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { ], ); repairReloadRef.current = actions.reloadSession; + requestSessionResyncRef.current = (reason: string) => { + const source = sessionRef.current; + if (!source) return; + const pendingHigherPriorityTransition = [ + activeTransitionRef.current, + queuedTransitionRef.current, + ].some((intent) => intent && intent.origin !== 'repair'); + if (pendingHigherPriorityTransition) { + deferredResyncRef.current = { source, reason }; + return; + } + controlledTransitionOriginRef.current = 'resync'; + void actions + .reloadSession(new AbortController().signal, { + replaySource: 'configured', + }) + .catch((error: unknown) => { + const aborted = + error instanceof DOMException && error.name === 'AbortError'; + if (aborted) return; + console.warn( + '[DaemonSessionProvider] transactional session resync failed:', + { reason, error }, + ); + }); + }; useEffect(() => { if (promptStatus !== 'idle') return; queueMicrotask(() => tryLiveJournalRepairRef.current?.()); @@ -3005,21 +4329,60 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { loadMore: loadMoreTranscript, }; }, [connection.sessionId, loadMoreTranscript, transcriptHistoryState]); - const lastHandledSessionIdRef = useRef< - string | undefined | typeof UNHANDLED_SESSION - >(UNHANDLED_SESSION); + const lastHandledSessionIdRef = useRef( + UNHANDLED_SESSION, + ); useEffect(() => { - if (lastHandledSessionIdRef.current === sessionId) return; - lastHandledSessionIdRef.current = sessionId; + const desiredKey = JSON.stringify([ + sessionId, + resolvedWorkspaceCwd, + clientId, + controlledTargetRetryNonce, + ]); + if (lastHandledSessionIdRef.current === desiredKey) return; + lastHandledSessionIdRef.current = desiredKey; const currentSessionId = connectionRef.current.sessionId; - if (sessionId === currentSessionId) return; + const currentWorkspaceCwd = activeWorkspaceCwdRef.current; + const currentClientId = sessionRef.current?.clientId; + if (!sessionId && !currentSessionId) { + activeWorkspaceCwdRef.current = resolvedWorkspaceCwd; + setConnectionSynchronous((current) => ({ + ...current, + workspaceCwd: resolvedWorkspaceCwd, + })); + cancelSessionTransition('Controlled empty workspace target changed'); + return; + } + if ( + sessionId === currentSessionId && + (resolvedWorkspaceCwd === undefined || + resolvedWorkspaceCwd === currentWorkspaceCwd) && + (clientId === undefined || clientId === currentClientId) + ) { + cancelSessionTransition('Controlled session target returned to current'); + return; + } const request = sessionId - ? actions.loadSession(sessionId) + ? (() => { + controlledTransitionOriginRef.current = 'controlled'; + return actions.loadSession(sessionId, { + ...(resolvedWorkspaceCwd !== undefined + ? { workspaceCwd: resolvedWorkspaceCwd } + : {}), + }); + })() : currentSessionId - ? actions.clearSession() + ? actions.clearSession().then(() => { + if (lastHandledSessionIdRef.current !== desiredKey) return; + activeWorkspaceCwdRef.current = resolvedWorkspaceCwd; + setConnectionSynchronous((current) => ({ + ...current, + workspaceCwd: resolvedWorkspaceCwd, + })); + }) : undefined; if (!request) return; @@ -3030,7 +4393,15 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) { error, ); }); - }, [actions, sessionId]); + }, [ + actions, + cancelSessionTransition, + clientId, + controlledTargetRetryNonce, + resolvedWorkspaceCwd, + sessionId, + setConnectionSynchronous, + ]); return ( @@ -3204,6 +4575,7 @@ function filterDaemonUiEventsForTranscript( behavior: { hideHistoryTruncation?: boolean; suppressSideEffects?: boolean; + suppressLogs?: boolean; } = {}, ): DaemonUiEvent[] { if (behavior.hideHistoryTruncation && isHistoricalReplayMarker(sourceEvent)) { @@ -3234,7 +4606,10 @@ function filterDaemonUiEventsForTranscript( const notice = addNotice( daemonErrorEventToNotice(sourceEvent, event as DaemonUiErrorEvent), ); - if (notice.category === 'protocol' || notice.category === 'connection') { + if ( + !behavior.suppressLogs && + (notice.category === 'protocol' || notice.category === 'connection') + ) { console.warn('[DaemonSessionProvider] daemon notice:', notice); } } diff --git a/packages/webui/src/daemon/session/actions.test.ts b/packages/webui/src/daemon/session/actions.test.ts index 6f4e7f59e2a..cccf4105e21 100644 --- a/packages/webui/src/daemon/session/actions.test.ts +++ b/packages/webui/src/daemon/session/actions.test.ts @@ -35,6 +35,12 @@ describe('getConnectionAfterSessionClear', () => { error: 'old error', errorStatus: 404, missingSession: true, + sessionTransition: { + phase: 'preparing', + operation: 'load', + origin: 'action', + targetSessionId: 'session-b', + }, } as DaemonConnectionState, 'session-a', ); @@ -54,6 +60,7 @@ describe('getConnectionAfterSessionClear', () => { expect(next).not.toHaveProperty('tokenCount'); expect(next).not.toHaveProperty('supportedCommands'); expect(next).not.toHaveProperty('context'); + expect(next).not.toHaveProperty('sessionTransition'); // Workspace-scoped slash commands and skills survive a clear so skill-backed // commands (e.g. /review) keep autocompleting in the fresh deferred session // before its first prompt creates a session (mirrors #6153 / #6066). @@ -852,6 +859,51 @@ describe('createDaemonSessionActions', () => { await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' }); expect(restartEventStream).not.toHaveBeenCalled(); }); + + it('drops a session-scoped action result after the owner changes', async () => { + const source = createMockSession('session-a'); + const tasks = createDeferred<{ + v: 1; + sessionId: string; + tasks: never[]; + }>(); + source.tasks.mockReturnValueOnce(tasks.promise); + const addNotice = vi.fn(); + const { actions, sessionRef } = createActionsHarness({ + addNotice, + session: source, + }); + + const pending = actions.getTasks(); + sessionRef.current = createMockSession( + 'session-b', + ) as unknown as DaemonSessionClient; + tasks.resolve({ v: 1, sessionId: 'session-a', tasks: [] }); + + await expect(pending).rejects.toMatchObject({ name: 'AbortError' }); + expect(addNotice).not.toHaveBeenCalled(); + }); + + it('finishes source cancellation remotely without updating a newer owner', async () => { + const source = createMockSession('session-a'); + const cancelled = createDeferred(); + source.cancel.mockReturnValueOnce(cancelled.promise); + const addNotice = vi.fn(); + const { actions, sessionRef } = createActionsHarness({ + addNotice, + session: source, + }); + + const pending = actions.cancel(); + sessionRef.current = createMockSession( + 'session-b', + ) as unknown as DaemonSessionClient; + cancelled.resolve(undefined); + + await expect(pending).rejects.toMatchObject({ name: 'AbortError' }); + expect(source.cancel).toHaveBeenCalledOnce(); + expect(addNotice).not.toHaveBeenCalled(); + }); }); function createActionsHarness( diff --git a/packages/webui/src/daemon/session/actions.ts b/packages/webui/src/daemon/session/actions.ts index 1ded9b4bfc2..7e7cae30fd4 100644 --- a/packages/webui/src/daemon/session/actions.ts +++ b/packages/webui/src/daemon/session/actions.ts @@ -116,6 +116,22 @@ export interface CreateDaemonSessionActionsArgs { setAttachSessionNonce: Dispatch>; setNewSessionNonce: Dispatch>; clearLiveJournalRepair?: () => void; + beginSessionTransition?: ( + request: SessionTransitionRequest, + startLegacy: () => Promise, + ) => Promise; + cancelSessionTransition?: (reason: string) => void; + isSessionTransitionPending?: () => boolean; +} + +export interface SessionTransitionRequest { + sessionId: string; + clientId?: string; + mode: 'load' | 'resume'; + workspaceCwd?: string; + signal?: AbortSignal; + replaySource?: PendingSessionLoad['replaySource']; + origin: 'action' | 'repair'; } export function getConnectionAfterSessionClear( @@ -123,6 +139,7 @@ export function getConnectionAfterSessionClear( clearedSessionId: string | undefined, ): DaemonConnectionState { const next = { ...current }; + delete next.sessionTransition; if (!clearedSessionId || current.sessionId === clearedSessionId) { delete next.sessionId; delete next.clientId; @@ -181,9 +198,36 @@ export function createDaemonSessionActions({ setAttachSessionNonce, setNewSessionNonce, clearLiveJournalRepair = () => undefined, + beginSessionTransition, + cancelSessionTransition = () => undefined, + isSessionTransitionPending = () => false, }: CreateDaemonSessionActionsArgs): DaemonSessionActions { const silentHardFailureNoticeKeys = new Set(); + function requireStableSessionForMutation( + title: string, + operation: DaemonNoticeOperation, + ): void { + if (!isSessionTransitionPending()) return; + throw dispatchActionError( + addNotice, + title, + new DOMException( + 'A session transition is already in progress', + 'InvalidStateError', + ), + operation, + ); + } + + function throwIfSessionOwnerChanged(session: DaemonSessionClient): void { + if (sessionRef.current === session) return; + throw new DOMException( + 'Session action completed after the active session changed', + 'AbortError', + ); + } + function clearActiveSessionState() { clearLiveJournalRepair(); silentHardFailureNoticeKeys.clear(); @@ -277,87 +321,117 @@ export function createDaemonSessionActions({ signal?: AbortSignal, replaySource?: PendingSessionLoad['replaySource'], ): Promise { - if (replaySource !== 'memory') { - clearLiveJournalRepair(); - } if (signal?.aborted) { return Promise.reject( new DOMException('Session load cancelled', 'AbortError'), ); } - manualSessionClearRef.current = false; - const loadPromise = startPendingSessionLoad( - sessionId, - mode, - signal, - replaySource, - ); - const currentSession = sessionRef.current; - const currentSessionId = currentSession?.sessionId; - const activePrompt = currentSessionId - ? activePromptsRef.current.get(currentSessionId) - : undefined; - activePrompt?.reject?.( - new DOMException('Session switch interrupted prompt wait', 'AbortError'), - ); - if (currentSessionId) { - activePromptsRef.current.delete(currentSessionId); - } - resetCurrentSessionActivePrompt(); - const reloadingCurrentSession = - mode === 'load' && currentSessionId === sessionId; - if (currentSession) { - const detachCurrentSession = () => - currentSession.detach().catch((error: unknown) => { - console.warn( - '[DaemonSessionActions] detach before session switch failed:', - error, - ); - }); - if (reloadingCurrentSession) { - skipNextCleanupDetachSessionIdRef.current = sessionId; - void loadPromise.then(detachCurrentSession, () => undefined); - } else { - void detachCurrentSession(); + const startLegacy = () => { + if (replaySource !== 'memory') { + clearLiveJournalRepair(); } - } - if (!reloadingCurrentSession) sessionRef.current = undefined; - if (!reloadingCurrentSession) { - setConnection((current) => ({ - ...current, - status: 'connecting', + manualSessionClearRef.current = false; + const loadPromise = startPendingSessionLoad( sessionId, - clientId: undefined, - displayName: undefined, - error: undefined, - errorStatus: undefined, - missingSession: false, - loadingTranscript: true, - catchingUp: undefined, - })); - } - setPromptStatus('idle'); - settledPromptsRef.current.clear(); - clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); - if (!reloadingCurrentSession) store.reset(); - setRestoreMode(mode); - setRestoreSessionId(sessionId); - setRestoreWorkspaceCwd(workspaceCwd ?? getConnection().workspaceCwd); - setRestoreSessionNonce((nonce) => nonce + 1); - return loadPromise.catch((error: unknown) => { - if (!isAbortError(error)) { + mode, + signal, + replaySource, + ); + const currentSession = sessionRef.current; + const currentSessionId = currentSession?.sessionId; + const activePrompt = currentSessionId + ? activePromptsRef.current.get(currentSessionId) + : undefined; + activePrompt?.reject?.( + new DOMException( + 'Session switch interrupted prompt wait', + 'AbortError', + ), + ); + if (currentSessionId) { + activePromptsRef.current.delete(currentSessionId); + } + resetCurrentSessionActivePrompt(); + const reloadingCurrentSession = + mode === 'load' && currentSessionId === sessionId; + if (currentSession) { + const detachCurrentSession = () => + currentSession.detach().catch((error: unknown) => { + console.warn( + '[DaemonSessionActions] detach before session switch failed:', + error, + ); + }); + if (reloadingCurrentSession) { + skipNextCleanupDetachSessionIdRef.current = sessionId; + void loadPromise.then(detachCurrentSession, () => undefined); + } else { + void detachCurrentSession(); + } + } + if (!reloadingCurrentSession) sessionRef.current = undefined; + if (!reloadingCurrentSession) { setConnection((current) => ({ ...current, - loadingTranscript: undefined, + status: 'connecting', + sessionId, + clientId: undefined, + displayName: undefined, + error: undefined, + errorStatus: undefined, + missingSession: false, + loadingTranscript: true, catchingUp: undefined, })); } - throw error; - }); + setPromptStatus('idle'); + settledPromptsRef.current.clear(); + clearPassiveAssistantDoneTimer(passiveAssistantDoneTimerRef); + if (!reloadingCurrentSession) store.reset(); + setRestoreMode(mode); + setRestoreSessionId(sessionId); + setRestoreWorkspaceCwd(workspaceCwd ?? getConnection().workspaceCwd); + setRestoreSessionNonce((nonce) => nonce + 1); + return loadPromise.catch((error: unknown) => { + if (!isAbortError(error)) { + setConnection((current) => ({ + ...current, + loadingTranscript: undefined, + catchingUp: undefined, + })); + } + throw error; + }); + }; + if (beginSessionTransition) { + return beginSessionTransition( + { + sessionId, + mode, + ...(workspaceCwd !== undefined ? { workspaceCwd } : {}), + ...(signal ? { signal } : {}), + ...(replaySource ? { replaySource } : {}), + origin: replaySource === 'memory' ? 'repair' : 'action', + }, + startLegacy, + ); + } + return startLegacy(); } return { async sendPrompt(text, options) { + if (isSessionTransitionPending()) { + throw dispatchActionError( + addNotice, + 'Prompt failed', + new DOMException( + 'A session switch is still preparing', + 'InvalidStateError', + ), + 'send_prompt', + ); + } const session = requireSessionForAction( addNotice, sessionRef.current, @@ -425,7 +499,7 @@ export function createDaemonSessionActions({ ); } catch (error) { if (isAbortError(error)) { - if (sessionRef.current?.sessionId === sessionId) { + if (sessionRef.current === session) { store.dispatch({ type: 'assistant.done', reason: 'cancelled' }); } return { stopReason: 'cancelled' }; @@ -433,7 +507,7 @@ export function createDaemonSessionActions({ if (isDaemonTurnError(error)) { throw error; } - if (sessionRef.current?.sessionId === sessionId) { + if (sessionRef.current === session) { store.dispatch({ type: 'assistant.done', reason: 'error' }); } throw dispatchActionError( @@ -447,16 +521,14 @@ export function createDaemonSessionActions({ if (active?.controller === ctrl) { activePromptsRef.current.delete(sessionId); } - if ( - sessionRef.current?.sessionId === sessionId && - !hasSessionActivePrompt() - ) { + if (sessionRef.current === session && !hasSessionActivePrompt()) { setPromptStatus('idle'); } } }, async submitPrompt(text, options) { + requireStableSessionForMutation('Prompt failed', 'send_prompt'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -518,6 +590,7 @@ export function createDaemonSessionActions({ options.signal.reason ?? new DOMException('Aborted', 'AbortError') ); } + throwIfSessionOwnerChanged(session); return { promptId: accepted.promptId }; }, @@ -539,6 +612,7 @@ export function createDaemonSessionActions({ } try { await withActionTimeout(session.cancel(), 'Cancel timed out'); + throwIfSessionOwnerChanged(session); } catch (error) { throw dispatchActionError( addNotice, @@ -554,16 +628,14 @@ export function createDaemonSessionActions({ ) { activePromptsRef.current.delete(session.sessionId); } - if ( - sessionRef.current?.sessionId === session.sessionId && - !hasSessionActivePrompt() - ) { + if (sessionRef.current === session && !hasSessionActivePrompt()) { setPromptStatus('idle'); } } }, async setModel(modelId) { + requireStableSessionForMutation('Set model failed', 'switch_model'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -575,6 +647,7 @@ export function createDaemonSessionActions({ session.setModel(modelId), 'Set model timed out', ); + throwIfSessionOwnerChanged(session); setConnection((current) => ({ ...current, currentModel: modelId })); return result; } catch (error) { @@ -588,6 +661,10 @@ export function createDaemonSessionActions({ }, async setApprovalMode(mode, opts) { + requireStableSessionForMutation( + 'Set approval mode failed', + 'set_approval_mode', + ); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -602,6 +679,7 @@ export function createDaemonSessionActions({ }), 'Set approval mode timed out', ); + throwIfSessionOwnerChanged(session); setConnection((current) => ({ ...current, currentMode: result.mode || mode, @@ -625,10 +703,12 @@ export function createDaemonSessionActions({ 'submit_permission', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.respondToSessionPermission(requestId, response), 'Permission response timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -657,10 +737,12 @@ export function createDaemonSessionActions({ ...(answers ? { answers } : {}), }; try { - return await withActionTimeout( + const result = await withActionTimeout( session.respondToSessionPermission(requestId, response), 'Permission response timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -674,17 +756,24 @@ export function createDaemonSessionActions({ async heartbeat() { const session = sessionRef.current; if (!session || !heartbeatSupportedRef.current) return undefined; - return withActionTimeout(session.heartbeat(), 'Heartbeat timed out'); + const result = await withActionTimeout( + session.heartbeat(), + 'Heartbeat timed out', + ); + throwIfSessionOwnerChanged(session); + return result; }, async listSessions(options) { const session = sessionRef.current; if (!session) return []; try { - return await withActionTimeout( + const result = await withActionTimeout( session.client.listWorkspaceSessions(session.workspaceCwd, options), 'List sessions timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -726,6 +815,17 @@ export function createDaemonSessionActions({ worktree?: { slug?: string }; branch?: { name: string }; }) { + if (isSessionTransitionPending()) { + throw dispatchActionError( + addNotice, + 'Create session failed', + new DOMException( + 'A session switch is still preparing', + 'InvalidStateError', + ), + 'create_session', + ); + } try { manualSessionClearRef.current = false; // Fold the initial approval mode into the create request so the daemon @@ -811,6 +911,17 @@ export function createDaemonSessionActions({ }, async attachSession() { + if (isSessionTransitionPending()) { + throw dispatchActionError( + addNotice, + 'Attach session failed', + new DOMException( + 'A session switch is still preparing', + 'InvalidStateError', + ), + 'attach_session', + ); + } const session = requireSessionForAction( addNotice, sessionRef.current, @@ -823,7 +934,11 @@ export function createDaemonSessionActions({ }, async clearSession() { + cancelSessionTransition('Session cleared'); const session = sessionRef.current; + if (session) { + skipNextCleanupDetachSessionIdRef.current = session.sessionId; + } manualSessionClearRef.current = true; clearActiveSessionState(); sessionRef.current = undefined; @@ -835,11 +950,16 @@ export function createDaemonSessionActions({ await withActionTimeout(session.detach(), 'Clear session timed out'); } catch (error) { console.warn('[DaemonSessionActions] detach on clear failed:', error); + } finally { + if (skipNextCleanupDetachSessionIdRef.current === session.sessionId) { + skipNextCleanupDetachSessionIdRef.current = undefined; + } } } }, async newSession() { + cancelSessionTransition('New session requested'); manualSessionClearRef.current = false; clearActiveSessionState(); setConnection((current) => ({ @@ -852,6 +972,9 @@ export function createDaemonSessionActions({ }, async releaseSession(sessionId) { + if (sessionRef.current?.sessionId === sessionId) { + cancelSessionTransition('Current session released'); + } try { const session = requireSessionForAction( addNotice, @@ -874,6 +997,7 @@ export function createDaemonSessionActions({ }, async closeSession() { + cancelSessionTransition('Session closed'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -904,6 +1028,7 @@ export function createDaemonSessionActions({ session.supportedCommands(), 'Refresh commands timed out', ); + throwIfSessionOwnerChanged(session); const { commands, skills } = mapSupportedCommands(status); setConnection((current) => ({ ...current, @@ -933,6 +1058,7 @@ export function createDaemonSessionActions({ session.context(), 'Load context timed out', ); + throwIfSessionOwnerChanged(session); setConnection((current) => ({ ...current, context, @@ -960,10 +1086,12 @@ export function createDaemonSessionActions({ 'load_context_usage', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.contextUsage(opts), 'Load context usage timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -975,6 +1103,10 @@ export function createDaemonSessionActions({ }, async renameSession(displayName) { + requireStableSessionForMutation( + 'Rename session failed', + 'rename_session', + ); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -982,10 +1114,12 @@ export function createDaemonSessionActions({ 'rename_session', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.updateMetadata({ displayName }), 'Rename session timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1004,10 +1138,12 @@ export function createDaemonSessionActions({ 'recap_session', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.recap(), 'Recap session timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1022,13 +1158,20 @@ export function createDaemonSessionActions({ prompt: string, opts?: { signal?: AbortSignal }, ): AsyncGenerator { + requireStableSessionForMutation( + 'Generate content failed', + 'generate_session_content', + ); const session = requireSessionForAction( addNotice, sessionRef.current, 'Generate content failed', 'generate_session_content', ); - yield* session.generateContent(prompt, opts); + for await (const event of session.generateContent(prompt, opts)) { + throwIfSessionOwnerChanged(session); + yield event; + } }, async getRewindSnapshots(): Promise<{ @@ -1041,10 +1184,12 @@ export function createDaemonSessionActions({ 'rewind_snapshots', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.getRewindSnapshots(), 'Load rewind snapshots timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1059,6 +1204,10 @@ export function createDaemonSessionActions({ promptId: string, opts?: { rewindFiles?: boolean }, ): Promise { + requireStableSessionForMutation( + 'Rewind session failed', + 'rewind_session', + ); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1066,10 +1215,12 @@ export function createDaemonSessionActions({ 'rewind_session', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.rewind(promptId, opts), 'Rewind session timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1084,6 +1235,7 @@ export function createDaemonSessionActions({ question: string, opts?: { signal?: AbortSignal }, ): Promise { + requireStableSessionForMutation('Side question failed', 'btw_session'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1091,10 +1243,12 @@ export function createDaemonSessionActions({ 'btw_session', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.btw(question, opts), 'Side question timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { if (opts?.signal?.aborted || isAbortError(error)) { throw error; @@ -1112,6 +1266,7 @@ export function createDaemonSessionActions({ message: string, opts?: { signal?: AbortSignal }, ): Promise { + if (isSessionTransitionPending()) return { accepted: false }; // Best-effort and silent: no session / idle session / transport failure / // abort all resolve `{ accepted: false }` so the caller falls back to its // own next-turn queue. Never raises a user-facing notice — a queued @@ -1121,7 +1276,8 @@ export function createDaemonSessionActions({ const session = sessionRef.current; if (!session) return { accepted: false }; try { - return await session.enqueueMidTurnMessage(message, opts); + const result = await session.enqueueMidTurnMessage(message, opts); + return sessionRef.current === session ? result : { accepted: false }; } catch (err) { // An abort is the designed settle-time cancel (the message stays in the // browser queue for the next turn), not a failure — stay silent. Any @@ -1164,7 +1320,9 @@ export function createDaemonSessionActions({ }, ); } - return await session.removeMidTurnMessage(messageId); + const result = await session.removeMidTurnMessage(messageId); + throwIfSessionOwnerChanged(session); + return result; }, async getPendingPrompts(opts) { @@ -1174,7 +1332,9 @@ export function createDaemonSessionActions({ if (opts?.sessionId && session.sessionId !== opts.sessionId) { throw new Error('Session changed before pending prompts refresh'); } - return await session.getPendingPrompts(); + const result = await session.getPendingPrompts(); + throwIfSessionOwnerChanged(session); + return result; }, async removePendingPrompt(promptId: string, opts) { @@ -1186,10 +1346,16 @@ export function createDaemonSessionActions({ promptId, ); } - return await session.removePendingPrompt(promptId); + const result = await session.removePendingPrompt(promptId); + throwIfSessionOwnerChanged(session); + return result; }, async sendShellCommand(command: string) { + requireStableSessionForMutation( + 'Shell command failed', + 'send_shell_command', + ); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1201,7 +1367,9 @@ export function createDaemonSessionActions({ const ctrl = new AbortController(); activePromptsRef.current.set(shellKey, { controller: ctrl }); try { - return await session.shellCommand(command, ctrl.signal); + const result = await session.shellCommand(command, ctrl.signal); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1213,10 +1381,7 @@ export function createDaemonSessionActions({ if (activePromptsRef.current.get(shellKey)?.controller === ctrl) { activePromptsRef.current.delete(shellKey); } - if ( - sessionRef.current?.sessionId === session.sessionId && - !hasSessionActivePrompt() - ) { + if (sessionRef.current === session && !hasSessionActivePrompt()) { setPromptStatus('idle'); } } @@ -1226,7 +1391,12 @@ export function createDaemonSessionActions({ const session = sessionRef.current; if (!session) throw new Error('Daemon session is not connected'); try { - return await withActionTimeout(session.tasks(), 'Get tasks timed out'); + const result = await withActionTimeout( + session.tasks(), + 'Get tasks timed out', + ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { if ( error instanceof Error && @@ -1260,10 +1430,12 @@ export function createDaemonSessionActions({ 'cancel_task', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.cancelTask(taskId, kind), 'Cancel task timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1275,6 +1447,7 @@ export function createDaemonSessionActions({ }, async clearGoal() { + requireStableSessionForMutation('Clear goal failed', 'clear_goal'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1282,10 +1455,12 @@ export function createDaemonSessionActions({ 'clear_goal', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.clearGoal(), 'Clear goal timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1304,7 +1479,12 @@ export function createDaemonSessionActions({ 'load_stats', ); try { - return await withActionTimeout(session.stats(), 'Load stats timed out'); + const result = await withActionTimeout( + session.stats(), + 'Load stats timed out', + ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, @@ -1318,7 +1498,12 @@ export function createDaemonSessionActions({ async loadArtifacts(): Promise { const session = sessionRef.current; if (!session) throw new Error('Daemon session is not connected'); - return withActionTimeout(session.artifacts(), 'Load artifacts timed out'); + const result = await withActionTimeout( + session.artifacts(), + 'Load artifacts timed out', + ); + throwIfSessionOwnerChanged(session); + return result; }, async respondToGlobalPermission( @@ -1347,6 +1532,10 @@ export function createDaemonSessionActions({ }, async branchSession(name?: string) { + requireStableSessionForMutation( + 'Branch session failed', + 'branch_session', + ); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1389,6 +1578,7 @@ export function createDaemonSessionActions({ }, async forkSession(directive: string): Promise { + requireStableSessionForMutation('Fork session failed', 'fork_session'); const session = requireSessionForAction( addNotice, sessionRef.current, @@ -1396,10 +1586,12 @@ export function createDaemonSessionActions({ 'fork_session', ); try { - return await withActionTimeout( + const result = await withActionTimeout( session.fork(directive), 'Fork session timed out', ); + throwIfSessionOwnerChanged(session); + return result; } catch (error) { throw dispatchActionError( addNotice, diff --git a/packages/webui/src/daemon/session/index.ts b/packages/webui/src/daemon/session/index.ts index 44f4675e8cd..921a5464389 100644 --- a/packages/webui/src/daemon/session/index.ts +++ b/packages/webui/src/daemon/session/index.ts @@ -36,6 +36,10 @@ export type { DaemonSessionContextValue, DaemonSessionNotice, DaemonSessionProviderProps, + DaemonSessionTransitionOperation, + DaemonSessionTransitionOrigin, + DaemonSessionTransitionPhase, + DaemonSessionTransitionState, DaemonTokenUsage, DaemonTodoItem, DaemonTodoList, diff --git a/packages/webui/src/daemon/session/types.ts b/packages/webui/src/daemon/session/types.ts index 062198178ea..7d509f12bf6 100644 --- a/packages/webui/src/daemon/session/types.ts +++ b/packages/webui/src/daemon/session/types.ts @@ -50,6 +50,28 @@ export type DaemonConnectionStatus = | 'disconnected' | 'error'; +export type DaemonSessionTransitionPhase = 'queued' | 'preparing' | 'failed'; + +export type DaemonSessionTransitionOperation = 'load' | 'resume' | 'reload'; + +export type DaemonSessionTransitionOrigin = + | 'action' + | 'controlled' + | 'resync' + | 'repair'; + +export interface DaemonSessionTransitionState { + phase: DaemonSessionTransitionPhase; + operation: DaemonSessionTransitionOperation; + origin: DaemonSessionTransitionOrigin; + targetSessionId?: string; + targetWorkspaceCwd?: string; + targetClientId?: string; + error?: { + message: string; + }; +} + export interface DaemonConnectionState { status: DaemonConnectionStatus; sessionId?: string; @@ -94,6 +116,8 @@ export interface DaemonConnectionState { errorStatus?: number; /** True only when the server confirmed the current session is missing. */ missingSession?: boolean; + /** A target session being prepared while the committed session stays live. */ + sessionTransition?: DaemonSessionTransitionState; } export interface DaemonTokenUsage {