Skip to content
Merged
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
11 changes: 11 additions & 0 deletions docs/architecture/session-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions src/web-ui/src/flow_chat/session-stream/SessionStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
9 changes: 9 additions & 0 deletions src/web-ui/src/flow_chat/session-stream/turnOwnership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
173 changes: 173 additions & 0 deletions src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -7969,6 +7970,178 @@ 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('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();

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', () => {
Expand Down
Loading
Loading