From b71255a2e545f9f5fd77bdd66fbf6f10802bfcd4 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 20:34:27 +0800 Subject: [PATCH 1/3] fix(flow-chat): adopt host-settled turns missed during a device surface switch A turn kept running locally while the window rendered a peer device. Surface routing dropped its later chunks and terminal event, and the journal tail could not serve the gap, so the return path fell back to the persisted record. The stream still believed the turn was executing, and the shape-sensitive progress comparison then refused the complete record because live items carry attempt metadata and coalesced newlines that the persisted record does not. The turn stayed truncated for good. A host read that reports a terminal record for a turn the host is not executing now hands that turn to the persisted record, and its content guard compares painted rounds, tools and text without depending on attempt keys, newline coalescing or segment boundaries. --- .../flow_chat/session-stream/SessionStream.ts | 17 ++ .../flow_chat/session-stream/turnOwnership.ts | 9 ++ .../src/flow_chat/store/FlowChatStore.test.ts | 146 ++++++++++++++++++ .../src/flow_chat/store/FlowChatStore.ts | 125 ++++++++++++++- 4 files changed, 296 insertions(+), 1 deletion(-) diff --git a/src/web-ui/src/flow_chat/session-stream/SessionStream.ts b/src/web-ui/src/flow_chat/session-stream/SessionStream.ts index 56b8c7cc2c..f3decaceed 100644 --- a/src/web-ui/src/flow_chat/session-stream/SessionStream.ts +++ b/src/web-ui/src/flow_chat/session-stream/SessionStream.ts @@ -79,6 +79,11 @@ export class SessionStream { return this.ownership.executingTurnIds(); } + /** Hand a Turn the Host reports settled to the persisted record. */ + adoptSettledTurn(turnId: string): void { + this.ownership.settle(turnId); + } + /** Whether the persisted record may write this Turn (contract 2). */ persistedMayWrite(turnId: string): boolean { return this.ownership.persistedMayWrite(turnId); @@ -332,3 +337,15 @@ export function persistedMayWriteTurn( const stream = peekSessionStream(getActiveSurfaceScope().surfaceId, sessionId); return stream ? stream.persistedMayWrite(turnId) : true; } + +/** + * Record that the Host settled a Turn this stream still believes is executing. + * + * Its terminal event was dropped while another device surface was rendered, + * so ownership never transferred through the order. Without this the stream + * keeps vetoing the persisted record and admitting stragglers for a Turn the + * Host already finished. + */ +export function adoptHostSettledTurn(sessionId: string, turnId: string): void { + peekSessionStream(getActiveSurfaceScope().surfaceId, sessionId)?.adoptSettledTurn(turnId); +} diff --git a/src/web-ui/src/flow_chat/session-stream/turnOwnership.ts b/src/web-ui/src/flow_chat/session-stream/turnOwnership.ts index efce53a723..0e7a9e9c25 100644 --- a/src/web-ui/src/flow_chat/session-stream/turnOwnership.ts +++ b/src/web-ui/src/flow_chat/session-stream/turnOwnership.ts @@ -95,6 +95,15 @@ export class TurnOwnership { return !this.executing.has(turnId); } + /** + * The Host reported this Turn settled by other means than an event this + * stream applied — its terminal event was never delivered here. + */ + settle(turnId: string): void { + this.executing.delete(turnId); + this.settled.add(turnId); + } + /** Whether a live event may still write this Turn. */ runtimeMayWrite(turnId: string): boolean { return !this.settled.has(turnId); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 46a3ed1d11..ffced6fd83 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -16,6 +16,7 @@ import type { FlowChatState, ModelRound, Session } from '../types/flow-chat'; import { startupTrace } from '@/shared/utils/startupTrace'; import { projectEffectiveToolItem } from '../utils/toolInvocationIdentity'; import { SessionRecordReplica } from '../session-stream/SessionRecordReplica'; +import { resetSessionStreamsForTest, sessionStream } from '../session-stream/SessionStream'; import { isSessionBindingLocked } from '../utils/sessionLifecycle'; import { isHostIssuedTurnCatalogRevision } from '../utils/flowChatTurnIdentity'; import { dispatchJobStore } from '@/features/dispatch/dispatchJobStore'; @@ -7969,6 +7970,151 @@ describe('FlowChatStore reconcile snapshot content safety', () => { flowChatStore.getState().sessions.get('history-1')?.dialogTurns[0].modelRounds[0].items, ).toHaveLength(2); }); + + describe('a Turn whose terminal event this window missed', () => { + // Regression 2026-11-02: a Turn kept running locally while the window + // rendered a Peer device. Its later chunks and terminal event were dropped + // by surface routing, so on return the stream still owned the Turn and the + // complete persisted record was refused for differing only in shape. + const LIVE_ROUND_ID = 'round-0'; + + function paintInterruptedLiveTurn(): void { + flowChatStore.setState(previous => { + const session = previous.sessions.get('history-1')!; + const turn = session.dialogTurns[0]; + const liveRound = { + ...turn.modelRounds[0], + isStreaming: true, + isComplete: false, + status: 'streaming', + items: [ + { + id: 'live-thinking', + type: 'thinking', + content: 'Check the relay.\n\nThen mobile-web', + isStreaming: true, + timestamp: 2, + status: 'streaming', + attemptId: `${LIVE_ROUND_ID}:attempt:1`, + attemptIndex: 1, + }, + { + id: 'live-text', + type: 'text', + content: 'mobile-web: changed by #3544 → those are shipped as', + isStreaming: true, + timestamp: 3, + status: 'streaming', + attemptId: `${LIVE_ROUND_ID}:attempt:1`, + attemptIndex: 1, + }, + ], + } as unknown as ModelRound; + const liveTurn = { ...turn, status: 'inprogress', modelRounds: [liveRound] } as typeof turn; + return { + sessions: new Map(previous.sessions).set('history-1', { + ...session, + dialogTurns: [liveTurn], + }), + }; + }); + sessionStream('local', 'history-1').offer( + 'agentic://dialog-turn-started', + { sessionId: 'history-1', turnId: 'turn-0' }, + null, + () => {}, + ); + } + + const settledRecord = () => ({ + ...createPersistedTurn(0), + modelRounds: [ + { + ...HYDRATED_ROUND, + id: LIVE_ROUND_ID, + thinkingItems: [{ + id: 'persisted-thinking', + content: 'Check the relay.\n\n\n\nThen mobile-web, then the deploy script.', + timestamp: 2, + status: 'completed', + }], + textItems: [{ + id: 'persisted-text', + content: 'mobile-web: changed by #3544 → those are shipped as static assets.', + timestamp: 3, + status: 'completed', + }], + }, + { ...HYDRATED_ROUND, id: 'round-1', roundIndex: 1, textItems: [{ id: 'final', content: 'Done.', timestamp: 4 }] }, + ], + endTime: 5, + }); + + beforeEach(() => { + resetSessionStreamsForTest(); + }); + + it('adopts the settled host record and hands the Turn to it', async () => { + await hydrateSessionWithContent(); + paintInterruptedLiveTurn(); + expect(sessionStream('local', 'history-1').persistedMayWrite('turn-0')).toBe(false); + + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession('Idle'), + turns: [settledRecord()], + contextRestoreState: 'ready', + }); + const result = await flowChatStore.refreshPeerSessionSnapshot('history-1', { + requireActiveSession: false, + }); + + expect(result.applied).toBe(true); + const turn = flowChatStore.getState().sessions.get('history-1')!.dialogTurns[0]; + expect(turn.status).toBe('completed'); + expect(turn.modelRounds).toHaveLength(2); + expect(turn.modelRounds[0].items).toContainEqual(expect.objectContaining({ + type: 'text', + content: 'mobile-web: changed by #3544 → those are shipped as static assets.', + })); + expect(sessionStream('local', 'history-1').persistedMayWrite('turn-0')).toBe(true); + }); + + it('keeps the live projection while the host is still executing that Turn', async () => { + await hydrateSessionWithContent(); + paintInterruptedLiveTurn(); + + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession('Processing'), + turns: [settledRecord()], + contextRestoreState: 'ready', + }); + await flowChatStore.refreshPeerSessionSnapshot('history-1', { requireActiveSession: false }); + + const turn = flowChatStore.getState().sessions.get('history-1')!.dialogTurns[0]; + expect(turn.modelRounds).toHaveLength(1); + expect(sessionStream('local', 'history-1').persistedMayWrite('turn-0')).toBe(false); + }); + + it('refuses a settled record that lacks text the projection painted', async () => { + await hydrateSessionWithContent(); + paintInterruptedLiveTurn(); + + const truncated = settledRecord(); + truncated.modelRounds[0] = { + ...truncated.modelRounds[0], + textItems: [{ id: 'persisted-text', content: 'mobile-web: changed', timestamp: 3, status: 'completed' }], + }; + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession('Idle'), + turns: [truncated], + contextRestoreState: 'ready', + }); + await flowChatStore.refreshPeerSessionSnapshot('history-1', { requireActiveSession: false }); + + const turn = flowChatStore.getState().sessions.get('history-1')!.dialogTurns[0]; + expect(turn.modelRounds[0].items).toContainEqual(expect.objectContaining({ id: 'live-text' })); + }); + }); }); describe('FlowChatStore device surfaces', () => { diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 72dbddd664..d1679486dd 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -43,7 +43,7 @@ import { import { elapsedMs, nowMs } from '@/shared/utils/timing'; import { normalizeRemoteSessionScope } from '@/shared/utils/remoteSessionScope'; import { isSurfaceReconcileEnabled } from '@/infrastructure/peer-device/deviceSurfaceReconcile'; -import { persistedMayWriteTurn } from '@/flow_chat/session-stream/SessionStream'; +import { adoptHostSettledTurn, persistedMayWriteTurn } from '@/flow_chat/session-stream/SessionStream'; import { SessionRecordReplica, type SessionRecord } from '@/flow_chat/session-stream/SessionRecordReplica'; import { RelaySessionHistory } from '../services/RelaySessionHistory'; import { stateMachineManager } from '../state-machine'; @@ -729,6 +729,106 @@ function snapshotDropsProjectedTurnContent( return false; } +const SETTLED_TURN_STATUSES: ReadonlySet = new Set(['completed', 'cancelled', 'error']); + +function isSettledTurnStatus(status: string | undefined): boolean { + return status !== undefined && SETTLED_TURN_STATUSES.has(status); +} + +/** Representation-neutral text: live chunks coalesce newlines, the record does not. */ +function comparableStreamText(content: string | undefined): string { + return (content ?? '').replace(/\s+/g, ' ').trim(); +} + +function supersededAttemptKeys(round: ModelRound): Set { + const keys = new Set(); + for (const attempt of round.attempts ?? []) { + if (attempt.status === 'superseded') { + keys.add(`id:${attempt.id}`); + keys.add(`index:${attempt.index}`); + } + } + return keys; +} + +function belongsToSupersededAttempt(item: AnyFlowItem, superseded: Set): boolean { + if (superseded.size === 0) { + return false; + } + return (item.attemptId !== undefined && superseded.has(`id:${item.attemptId}`)) + || (typeof item.attemptIndex === 'number' && superseded.has(`index:${item.attemptIndex}`)); +} + +/** + * Whether a settled persisted Turn carries everything the projection painted. + * + * The persisted record of a settled Turn is built by the Runtime, while the + * projection was built by this client from live chunks. The two describe the + * same content in different shapes: attempt metadata is only partially + * persisted, live text coalesces newlines, and segment boundaries can differ. + * Comparing by `(type, attempt, ordinal)` keys therefore rejected complete + * records, which left a Turn truncated forever once its live tail was missed + * (regression: 2026-11-02, surface switch during a running Turn). + * + * This check is deliberately shape-neutral. It still refuses a read that names + * the Turn without its work: a missing round, a missing tool or tool result, or + * painted text the record does not contain. + */ +function settledReadCoversProjectedTurn( + current: DialogTurn, + settled: DialogTurn, +): boolean { + if (settled.modelRounds.length < current.modelRounds.length) { + return false; + } + + for (const currentRound of current.modelRounds) { + const settledRound = settled.modelRounds.find(round => round.id === currentRound.id); + if (!settledRound) { + return false; + } + + const superseded = supersededAttemptKeys(currentRound); + const settledItems = settledRound.items; + const settledText: Record<'text' | 'thinking', string> = { + text: comparableStreamText( + settledItems.filter(item => item.type === 'text') + .map(item => (item as RunningStreamItem).content).join(' '), + ), + thinking: comparableStreamText( + settledItems.filter(item => item.type === 'thinking') + .map(item => (item as RunningStreamItem).content).join(' '), + ), + }; + const settledTools = toolProgressEntries(settledRound); + + for (const item of currentRound.items) { + if (belongsToSupersededAttempt(item, superseded)) { + continue; + } + if (item.type === 'text' || item.type === 'thinking') { + const painted = comparableStreamText((item as RunningStreamItem).content); + if (painted && !settledText[item.type].includes(painted)) { + return false; + } + continue; + } + if (item.type === 'tool') { + const tool = item as FlowToolItem; + if (tool.id.startsWith('plan-display-')) { + continue; + } + const settledTool = settledTools.get(tool.toolCall?.id || tool.id); + if (!settledTool || (tool.toolResult && !settledTool.toolResult)) { + return false; + } + } + } + } + + return true; +} + function preserveClientDerivedDisplayItems( current: DialogTurn, persisted: DialogTurn, @@ -783,6 +883,14 @@ function preserveClientDerivedDisplayItems( * A history read carries no position for content it omitted, so "does this * write lose content" is still the only question available. This guard is * deletable once a read reports its own completeness. + * + * A Host that reports its own state settles the ownership question for a Turn + * it is not executing: the Runtime commits the terminal record before it leaves + * the processing state, so a terminal record read alongside that state is the + * settled Turn. Local stream ownership cannot veto it — a stream that missed the + * terminal event (the window was rendering another device) still believes the + * Turn is executing, and deferring to that belief froze the Turn at whatever + * the last delivered chunk painted. */ function persistedReadMayReplaceTurn( sessionId: string, @@ -790,7 +898,19 @@ function persistedReadMayReplaceTurn( incoming: DialogTurn, hostExecutingTurnId: string | undefined, hostServesRuntimeProjection: boolean, + hostStateKnown = false, ): boolean { + if ( + hostStateKnown && + incoming.id !== hostExecutingTurnId && + isSettledTurnStatus(incoming.status) + ) { + if (!settledReadCoversProjectedTurn(projected, incoming)) { + return false; + } + adoptHostSettledTurn(sessionId, incoming.id); + return true; + } if (!persistedMayWriteTurn(sessionId, incoming.id, hostExecutingTurnId)) { return ( !hostServesRuntimeProjection && @@ -8294,6 +8414,7 @@ export class FlowChatStore { snapshotTurn, activeTurnId, Boolean(runtimeEventSnapshot), + true, ) ) { mergedTurns[existingIndex] = snapshotTurn; @@ -8491,6 +8612,7 @@ export class FlowChatStore { reconciled, hostExecutingTurnId, Boolean(runtimeSnapshot), + true, ) ) { return prev; @@ -8985,6 +9107,7 @@ export class FlowChatStore { loaded, activeTurnId, Boolean(restoredRuntimeEventSnapshot), + Boolean(restoredSessionInfo?.state), ) ) { return existing; From 2e2404a6b4dca9e1beb2b093c551dc26c732169e Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 20:34:27 +0800 Subject: [PATCH 2/3] docs(session-projection): describe adoption of host-settled turns --- docs/architecture/session-projection.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/architecture/session-projection.md b/docs/architecture/session-projection.md index ad507d8506..203252a26c 100644 --- a/docs/architecture/session-projection.md +++ b/docs/architecture/session-projection.md @@ -113,6 +113,17 @@ canonical text or thinking, remove a round or tool result, or turn a settled record back into an executing one. Externally projected sessions such as ACP remain owned by their external projection. +A client can miss the terminal event entirely, for example while the window +renders another device surface. Its stream then still believes the Turn is +executing. A host read that reports the Host's own state resolves this: the +Runtime commits the terminal record before leaving the processing state, so a +terminal record for a Turn the Host is not executing is the settled Turn. The +client hands that Turn to the persisted record (`adoptHostSettledTurn`) instead +of letting its stale ownership veto the read. The remaining content guard is +shape-neutral: it refuses a read that misses a painted round, tool, tool result +or text, but not one that differs only in attempt metadata, newline coalescing +or segment boundaries. + After the terminal record is committed, `SessionHistoryChanged` is the durable fence. Local and Peer Device surfaces re-read the affected tail Turn. Remote Connect polling sends an optional authoritative `message_snapshot`, because an From be4229736f4f607a514904c500ba54360d10aac3 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 20:37:28 +0800 Subject: [PATCH 3/3] fix(flow-chat): adopt settled turns when a live event races the host read A remote controller can start the next turn while the window renders another device. Its live events then change the session during the restore read, and the store skipped the whole persisted merge, so the missed tail of the previous, already settled turn was never repaired. That race only concerns the turn the host is executing; settled turns are still adopted. --- .../src/flow_chat/store/FlowChatStore.test.ts | 27 ++++++++++ .../src/flow_chat/store/FlowChatStore.ts | 53 +++++++++++++++++-- 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index ffced6fd83..8bbaa6f161 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -8095,6 +8095,33 @@ describe('FlowChatStore reconcile snapshot content safety', () => { expect(sessionStream('local', 'history-1').persistedMayWrite('turn-0')).toBe(false); }); + it('adopts the settled Turn even when a live event for the next Turn races the read', async () => { + await hydrateSessionWithContent(); + paintInterruptedLiveTurn(); + + const nextTurn = { ...createPersistedTurn(1), status: 'inprogress', modelRounds: [] }; + apiMocks.restoreSessionView.mockImplementationOnce(async () => { + // A remote controller started the next Turn; its live start lands + // while this read is in flight. + flowChatStore.setState(previous => { + const session = previous.sessions.get('history-1')!; + return { + sessions: new Map(previous.sessions).set('history-1', { ...session }), + }; + }); + return { + session: hostSession('Processing'), + turns: [settledRecord(), nextTurn], + contextRestoreState: 'ready', + }; + }); + await flowChatStore.refreshPeerSessionSnapshot('history-1', { requireActiveSession: false }); + + const turn = flowChatStore.getState().sessions.get('history-1')!.dialogTurns[0]; + expect(turn.status).toBe('completed'); + expect(turn.modelRounds).toHaveLength(2); + }); + it('refuses a settled record that lacks text the projection painted', async () => { await hydrateSessionWithContent(); paintInterruptedLiveTurn(); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index d1679486dd..e6eb7def73 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -8358,12 +8358,55 @@ export class FlowChatStore { return prev; } const persistMergeSafe = session === initialSession; + // A live event racing this read can only have written the Turn the Host + // is executing. Turns the Host reports settled are unaffected by that + // race, and skipping them left a Turn truncated when a remote controller + // started the next Turn while this window rendered another device. + const adoptSettledTurns = (turns: DialogTurn[]): DialogTurn[] => { + let adopted = turns; + for (const snapshotTurn of snapshotTurns) { + if (snapshotTurn.id === activeTurnId || !isSettledTurnStatus(snapshotTurn.status)) { + continue; + } + const index = adopted.findIndex(turn => turn.id === snapshotTurn.id); + if ( + index === -1 || + adopted[index] === snapshotTurn || + !persistedReadMayReplaceTurn( + sessionId, + adopted[index], + snapshotTurn, + activeTurnId, + Boolean(runtimeEventSnapshot), + true, + ) + ) { + continue; + } + if (adopted === turns) { + adopted = [...turns]; + } + adopted[index] = snapshotTurn; + } + return adopted; + }; + // A live event or hydrate won the race while HostInvoke was in flight. - // Persisted-turn merge is then unsafe, but a required Runtime replay - // still needs an empty current-Turn shell — hiding the journal used to - // leave in-progress tool cards frozen. + // Persisted-turn merge is then unsafe for the executing Turn, but a + // required Runtime replay still needs an empty current-Turn shell — + // hiding the journal used to leave in-progress tool cards frozen. if (!persistMergeSafe && !runtimeReplaySnapshot) { - return prev; + const adoptedTurns = adoptSettledTurns(session.dialogTurns); + if (adoptedTurns === session.dialogTurns) { + return prev; + } + return { + ...prev, + sessions: new Map(prev.sessions).set(sessionId, { + ...session, + dialogTurns: adoptedTurns, + }), + }; } if (!persistMergeSafe && runtimeReplaySnapshot) { @@ -8371,7 +8414,7 @@ export class FlowChatStore { if (!replayTurnId) { return prev; } - const mergedTurns = [...session.dialogTurns]; + const mergedTurns = adoptSettledTurns(session.dialogTurns).slice(); const existingIndex = mergedTurns.findIndex(turn => turn.id === replayTurnId); if (existingIndex === -1) { const shell = snapshotTurns.find(turn => turn.id === replayTurnId);