Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
fac47ff
feat(web-shell): expose assistant turn settlement
dreamWB Aug 28, 2026
e4e4880
docs(web-shell): clarify settlement message availability
dreamWB Aug 28, 2026
5bcf741
fix(web-shell): harden turn settlement delivery
dreamWB Aug 29, 2026
945c806
fix(web-shell): harden prompt settlement recovery
dreamWB Aug 29, 2026
bc1d3b6
fix(web-shell): settle assistant turns in split view
dreamWB Aug 29, 2026
bc2961b
fix(web-shell): fail closed restored prompt correlation
dreamWB Aug 29, 2026
bb0139e
fix(webui): settle production-shaped replay terminals
dreamWB Aug 29, 2026
981cc54
Merge remote-tracking branch 'origin/main' into codex/assistant-turn-…
wenshao Aug 29, 2026
b3b8ab8
fix(web-shell): follow in-package daemon relocation
dreamWB Aug 29, 2026
668fdfd
fix(web-shell): harden assistant turn settlement delivery
dreamWB Aug 30, 2026
5605d2c
fix(web-shell): scope journal incompleteness to one turn
dreamWB Aug 30, 2026
4b34ad3
Merge branch 'main' into codex/assistant-turn-settled-event
wenshao Aug 30, 2026
9ad7be2
fix(web-shell): stabilize journal marker ownership
dreamWB Aug 30, 2026
78dc634
Merge remote-tracking branch 'origin/main' into codex/assistant-turn-…
dreamWB Aug 30, 2026
201ad84
fix(web-shell): preserve live journal marker claims
dreamWB Aug 30, 2026
b106023
Merge branch 'main' into codex/assistant-turn-settled-event
dreamWB Sep 1, 2026
822e464
Merge branch 'main' into codex/assistant-turn-settled-event
dreamWB Sep 1, 2026
63678c6
Merge branch 'main' into codex/assistant-turn-settled-event
dreamWB Sep 1, 2026
4ca4e4c
Merge branch 'main' into codex/assistant-turn-settled-event
dreamWB Sep 1, 2026
97026b5
Merge remote-tracking branch 'origin/main' into codex/assistant-turn-…
dreamWB Sep 1, 2026
288118c
fix(web-shell): correct turn settlement across resyncs and replacements
dreamWB Sep 1, 2026
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
64 changes: 64 additions & 0 deletions docs/design/2026-08-28-web-shell-assistant-turn-settlement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Web Shell assistant turn settlement

## Goal

Expose a host callback for the semantic end of an assistant turn without requiring consumers to infer completion from prompt-status transitions or scan a changing transcript.

The callback is a generic Web Shell lifecycle contract. It is not tied to any embedding product, artifact projection, or workspace side effect.

## Contract

`onAssistantTurnSettled` receives:

- `sessionId` and daemon-assigned `promptId`; their tuple is the stable idempotency key;
- `outcome`: `completed`, `cancelled`, or `failed`;
- the daemon `stopReason` when a turn completed;
Comment thread
dreamWB marked this conversation as resolved.
Resolved
- `transcriptComplete`, which is false when replay integrity is degraded or bounded live-journal repair could not restore the complete turn before failing or being discarded;
- the final visible assistant message when it remains available in the committed current-session transcript; turns without assistant content and events delivered across a session switch omit it, while cancelled and failed turns may carry partial content.

The callback is optional. Existing `onSessionChange({ type: 'turn_complete' })` behavior remains unchanged.

## Lifecycle and ordering

The daemon prompt terminal (`turn_complete` or `turn_error`) is authoritative. Prompt-status `idle`, render completion, and history replay are not terminal signals.

If a process or transport fails without delivering either terminal event, no settlement is published. This fail-closed behavior avoids reporting an unproven completion; connection health remains a separate lifecycle.

The daemon session provider publishes a settlement only after it has:

1. flushed buffered transcript deltas;
2. applied `assistant.done` and the terminal event's own transcript projection;
3. completed live-journal repair when a truncated active turn can be repaired, or classified the retained transcript as incomplete before discarding an unsuccessful repair.

Ordinary session load, branch/split transcript replay, and older-history pagination never publish settlements. A terminal received while reconnecting an already active prompt may publish because it is a previously unseen live lifecycle transition, not history playback.

Duplicate terminal delivery is suppressed for the lifetime of a mounted session provider using `(sessionId, promptId)`. Hosts must use the same key for durable idempotency across remounts.

`prompt_cancelled` is a cancellation request, not a confirmed prompt terminal, and does not publish a settlement by itself. Waiting for permission or `ask_user_question` also does not publish.

Listener failures are isolated from daemon stream processing. Artifact, tool-result persistence, and workspace projection keep their independent lifecycle.

## Implementation boundary

The WebUI daemon session layer owns authoritative terminal observation, transcript ordering, replay suppression, repair, and duplicate suppression. It exposes a subscription hook with prompt-level settlement metadata.

Web Shell owns projection of the final visible assistant message and the public callback type. It does not add daemon routes or change daemon event payloads.

## Tests

- `TC-01`: normal terminal publishes once with the complete final message.
- `TC-02`: assistant/tool/assistant turn returns the final assistant message.
- `TC-03`: permission or `ask_user_question` waiting does not publish.
- `TC-04`: confirmed cancellation publishes `cancelled`; cancellation request alone does not.
- `TC-05`: `turn_error` publishes `failed` and preserves any partial assistant message.
- `TC-06`: reconnect catch-up for an active local prompt publishes once.
- `TC-07`: ordinary history replay and older-history pagination do not publish.
- `TC-08`: duplicate terminal events publish once for a mounted provider.
- `TC-09`: session switch cannot attribute an old terminal to the new session.
- `TC-10`: successful live-journal repair delays publication until the repaired transcript is committed; failed repair marks `transcriptComplete: false`.
- `TC-11`: listener exceptions do not interrupt subsequent daemon events or listeners.
- `TC-12`: clearing or replacing a repair episode releases its held settlement once with `transcriptComplete: false`.
- `TC-13`: degraded catch-up replay and unrecoverable live-journal markers publish with `transcriptComplete: false`.
- `TC-14`: a terminal after reconnect consumes the restored-active snapshot and allows live or catch-up repair to finish.

No visual UI changes are introduced, so browser screenshot validation is not applicable. Package unit tests, build, typecheck, and repository preflight are the delivery gates.
27 changes: 27 additions & 0 deletions packages/web-shell/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,33 @@ export function App() {
> **注意**:不要在已有 `DaemonSessionProvider` 下使用
> `WebShellWithProviders`,否则会创建嵌套的重复 Provider。

### Assistant Turn 终态回调

宿主需要在一轮 Assistant 回答真正结束后处理结果时,应使用
`onAssistantTurnSettled`,不要从 `onStreamingStateChange('idle')` 推断:

```tsx
<WebShellWithProviders
onAssistantTurnSettled={(event) => {
const key = `${event.sessionId}:${event.promptId}`;
persistResultOnce(key, event.message?.content, event.outcome);
}}
/>
```

该回调来自 daemon 的 prompt 终态,并在终态 transcript 已提交后触发。普通历史加载、
分支回放和向前分页不会触发;断线期间遗漏、重连后补收的活动 prompt 终态可以触发。
`(sessionId, promptId)` 是跨挂载幂等键。单个 Provider 挂载期间重复终态会被抑制,
宿主仍应使用该键做持久化幂等。

`outcome` 为 `completed`、`cancelled` 或 `failed`。取消和失败可能没有 Assistant
消息,也可能携带终止前的部分内容。`transcriptComplete: false` 表示 Web Shell 已收到
终态,但 replay 已被标记为不完整,或受限 live journal 的修复在失败、会话切换或
repair episode 被替换前未能恢复完整 transcript。等待 permission 或
`ask_user_question` 不属于终态。Artifact 和 workspace projection 有各自的生命周期,
不由该回调表示。进程硬崩溃且没有送达 prompt 终态时不会触发回调;连接失败应由连接
状态单独处理,不能被当作已完成的 turn。

### 3. 只读 ChatRecord JSONL

`WebShellTranscript` 只接收已经投影完成的 blocks,不连接 daemon,也不提供 composer、
Expand Down
218 changes: 218 additions & 0 deletions packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,17 @@ const {
| { data: string; media_type: string }[]
| undefined,
streamingState: 'idle' as StreamingState,
promptSettledListener: undefined as
| ((event: {
sessionId: string;
promptId: string;
outcome: 'completed' | 'cancelled' | 'failed';
stopReason?: string;
eventId?: number;
transcriptComplete: boolean;
error?: { message: string; code?: string };
}) => void)
| undefined,
sessionHasActivePrompt: false,
blocks: [] as unknown[],
liveBlocks: undefined as unknown[] | undefined,
Expand Down Expand Up @@ -554,6 +565,11 @@ vi.mock('@qwen-code/webui/daemon-react-sdk', () => {
useActions: () => mockSessionActions,
useConnection: () => mockConnection,
useDaemonSessionOwnerGuard: () => ownerGuard,
useDaemonPromptSettled: (
listener: typeof testState.promptSettledListener,
) => {
testState.promptSettledListener = listener;
},
useDaemonFollowupSuggestion: () => ({
followupState: null,
clear: mockFollowup.clear,
Expand Down Expand Up @@ -5211,6 +5227,7 @@ beforeEach(() => {
testState.inputAnnotations = undefined;
testState.promptImages = undefined;
testState.streamingState = 'idle';
testState.promptSettledListener = undefined;
testState.sessionHasActivePrompt = false;
testState.blocks = [];
testState.liveBlocks = undefined;
Expand Down Expand Up @@ -12786,6 +12803,207 @@ describe('App session callbacks', () => {
});
});

it('exposes the final assistant message for an authoritative settled turn', async () => {
const base = {
promptId: 'prompt-1',
clientReceivedAt: 1,
createdAt: 1,
updatedAt: 1,
};
testState.blocks = [
{ ...base, id: 'user-1', kind: 'user', text: 'question' },
{
...base,
id: 'assistant-before-tool',
kind: 'assistant',
text: 'I will check.',
streaming: false,
},
{
id: 'tool-1',
kind: 'tool',
toolCallId: 'call-1',
title: 'Lookup',
status: 'completed',
preview: { kind: 'generic' },
clientReceivedAt: 1,
createdAt: 1,
updatedAt: 1,
},
{
...base,
id: 'assistant-final',
kind: 'assistant',
text: 'The final answer.',
streaming: false,
serverTimestamp: 42,
},
{
...base,
id: 'assistant-subagent',
kind: 'assistant',
parentToolCallId: 'call-1',
text: 'Subagent internal answer',
streaming: false,
serverTimestamp: 43,
},
];
const onAssistantTurnSettled = vi.fn();
renderApp({ onAssistantTurnSettled });
await flush();

act(() => {
testState.promptSettledListener?.({
sessionId: 'session-1',
promptId: 'prompt-1',
outcome: 'completed',
stopReason: 'end_turn',
eventId: 10,
transcriptComplete: true,
});
});

expect(onAssistantTurnSettled).toHaveBeenCalledWith({
sessionId: 'session-1',
promptId: 'prompt-1',
outcome: 'completed',
stopReason: 'end_turn',
eventId: 10,
transcriptComplete: true,
message: {
id: 'assistant-final',
content: 'The final answer.',
isStreaming: false,
timestamp: 42,
},
});
});

it('does not project a previous session terminal onto the current transcript', async () => {
testState.blocks = [
{
id: 'assistant-current',
kind: 'assistant',
promptId: 'shared-prompt-id',
text: 'Current session answer',
streaming: false,
clientReceivedAt: 1,
createdAt: 1,
updatedAt: 1,
},
];
const onAssistantTurnSettled = vi.fn();
renderApp({ onAssistantTurnSettled });
await flush();

act(() => {
testState.promptSettledListener?.({
sessionId: 'previous-session',
promptId: 'shared-prompt-id',
outcome: 'completed',
stopReason: 'end_turn',
eventId: 10,
transcriptComplete: true,
});
});

expect(onAssistantTurnSettled).toHaveBeenCalledWith({
sessionId: 'previous-session',
promptId: 'shared-prompt-id',
outcome: 'completed',
stopReason: 'end_turn',
eventId: 10,
transcriptComplete: true,
});
});

it('includes available partial assistant content for a failed turn', async () => {
testState.blocks = [
{
id: 'assistant-partial',
kind: 'assistant',
promptId: 'prompt-failed',
text: 'Partial answer before failure',
streaming: false,
clientReceivedAt: 1,
createdAt: 1,
updatedAt: 1,
},
];
const onAssistantTurnSettled = vi.fn();
renderApp({ onAssistantTurnSettled });
await flush();

act(() => {
testState.promptSettledListener?.({
sessionId: 'session-1',
promptId: 'prompt-failed',
outcome: 'failed',
eventId: 11,
transcriptComplete: true,
error: { message: 'model unavailable', code: 'model_error' },
});
});

expect(onAssistantTurnSettled).toHaveBeenCalledWith(
expect.objectContaining({
outcome: 'failed',
message: expect.objectContaining({
id: 'assistant-partial',
content: 'Partial answer before failure',
isStreaming: false,
}),
}),
);
});

it('omits the message when the settled prompt has no assistant content', async () => {
testState.blocks = [
{
id: 'assistant-previous',
kind: 'assistant',
promptId: 'prompt-previous',
text: 'Previous answer',
streaming: false,
clientReceivedAt: 1,
createdAt: 1,
updatedAt: 1,
},
{
id: 'user-failed',
kind: 'user',
promptId: 'prompt-failed-before-content',
text: 'Question that failed immediately',
clientReceivedAt: 2,
createdAt: 2,
updatedAt: 2,
},
];
const onAssistantTurnSettled = vi.fn();
renderApp({ onAssistantTurnSettled });
await flush();

act(() => {
testState.promptSettledListener?.({
sessionId: 'session-1',
promptId: 'prompt-failed-before-content',
outcome: 'failed',
eventId: 12,
transcriptComplete: true,
error: { message: 'model unavailable', code: 'model_error' },
});
});

expect(onAssistantTurnSettled).toHaveBeenCalledWith({
sessionId: 'session-1',
promptId: 'prompt-failed-before-content',
outcome: 'failed',
eventId: 12,
transcriptComplete: true,
error: { message: 'model unavailable', code: 'model_error' },
});
});

it('gates direct submissions and dispatches compatible submit events', async () => {
const onSubmitBefore = vi.fn().mockResolvedValue(undefined);
const onSessionChange = vi.fn();
Expand Down
Loading
Loading