Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions docs/design/2026-08-09-transactional-webui-session-switching.md
Original file line number Diff line number Diff line change
@@ -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.
242 changes: 239 additions & 3 deletions integration-tests/cli/qwen-serve-webui-live-journal-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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<void>();
let switchPromise: Promise<void> | 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<typeof useActions> | undefined;
let connection: ReturnType<typeof useConnection> | 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');
Comment on lines +317 to +323

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The success-path test never asserts the committed target is live: no post-commit prompt/heartbeat against the target, no sessionTransition-clear assertion — the final conditions are satisfied by the staged transcript install and ref swap alone.

Failure scenario: publishStagedCandidate installs store.reset(staged.transcript) and the target sessionId synchronously (the transcript content arrives from the staged replay, not the live stream), so the test's waitFor + not.toContain('source transcript') pass without a single target SSE event. A regression in the post-commit subscribe (wrong client id, missed attach, events endpoint failure) or a stuck transition latch passes both new tests while the user lands on the target with a frozen stream and a permanently gated composer.

中文说明 成功路径测试从未验证提交后目标会话的实时性:最终断言由 staged transcript 安装与 ref 交换即可满足(transcript 来自 staged replay 而非实时流)。post-commit 订阅环节的回归(client id 错误、attach 遗漏、latch 未清除)会让用户落地后得到冻结流与永久门禁的 composer,而测试全绿。建议 commit 后向目标发 prompt 并等待回显。

— DeepSeek/deepseek-v4-flash via Qwen Code /review (v0.21.8)

} 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<typeof useActions> | undefined;
let connection: ReturnType<typeof useConnection> | 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<T>(): {
promise: Promise<T>;
resolve(value?: T | PromiseLike<T>): void;
} {
let resolve!: (value?: T | PromiseLike<T>) => void;
const promise = new Promise<T>((res) => {
resolve = (value) => res(value as T | PromiseLike<T>);
});
return { promise, resolve };
}
Loading
Loading