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
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,15 @@ impl Reader {
Ok(true)
}

/// Announce a restarted stream. A full replay from the latest page always
/// follows, so `resync` tells the controller to rebuild its records from
/// that replay: the new epoch carries no tombstones for what it dropped.
/// Gaps appended by the host itself stay inside one epoch and omit it.
fn gap(&self, reason: &str) -> Result<()> {
(self.emit)(SessionEvent {
session_id: self.session_id.clone(),
event: "relay://session-gap".into(),
payload: serde_json::json!({"sessionId":self.session_id,"reason":reason}),
payload: serde_json::json!({"sessionId":self.session_id,"reason":reason,"resync":true}),
})
}

Expand Down Expand Up @@ -638,6 +642,8 @@ mod tests {
"relay://session-ready",
]
);
let gap = lab.events.lock().unwrap()[2].1.clone();
assert_eq!(gap["resync"], true);
let ready = lab.events.lock().unwrap().last().unwrap().1.clone();
assert_eq!(ready["cursor"], page.cursor);
assert!(lab.errors.lock().unwrap().is_empty());
Expand Down
25 changes: 25 additions & 0 deletions src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const fixture = vi.hoisted(() => ({
record: null as ((event: unknown) => void) | null,
ready: null as ((event: any) => void) | null,
error: null as ((event: any) => void) | null,
gap: null as ((event: any) => void) | null,
subscribe: vi.fn(), unsubscribe: vi.fn(async () => {}), older: vi.fn(async () => {}),
}));
vi.mock('@/infrastructure/peer-device/deviceSurface', () => ({
Expand All @@ -17,6 +18,7 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({ remoteConn
onSessionRecord: (listener: (event: unknown) => void) => { fixture.record = listener; return () => { fixture.record = null; }; },
onSessionReady: (listener: (event: any) => void) => { fixture.ready = listener; return () => { fixture.ready = null; }; },
onSessionSyncError: (listener: (event: any) => void) => { fixture.error = listener; return () => { fixture.error = null; }; },
onSessionGap: (listener: (event: any) => void) => { fixture.gap = listener; return () => { fixture.gap = null; }; },
subscribeSession: fixture.subscribe, unsubscribeSession: fixture.unsubscribe, loadOlderSession: fixture.older,
} }));

Expand Down Expand Up @@ -52,6 +54,29 @@ describe('RelaySessionHistory', () => {
expect(fixture.record).toBeNull();
});

it('renders pending records, then resyncs only for a gap the controller replays', async () => {
vi.useFakeTimers();
fixture.subscribe.mockImplementation(async () => {
fixture.ready?.({ sessionId: 'session', hasMore: false, oldestSeq: 1, cursor: 1 });
return 'subscription';
});
const order: string[] = [];
const history = new RelaySessionHistory('session', () => { order.push('record'); }, vi.fn(), vi.fn(),
undefined, () => order.push('flush'), () => order.push('resync'));
await history.open();
order.length = 0;

fixture.gap?.({ sessionId: 'session', reason: 'source lagged' });
fixture.gap?.({ sessionId: 'other', reason: 'host stream restarted', resync: true });
expect(order).toEqual([]);

fixture.record?.({ sessionId: 'session', id: 'turn/turn' });
fixture.gap?.({ sessionId: 'session', reason: 'host stream restarted', resync: true });
expect(order).toEqual(['record', 'flush', 'resync']);
history.close();
expect(fixture.gap).toBeNull();
});

it('surfaces replay failures instead of leaving the first page loading forever', async () => {
fixture.subscribe.mockImplementation(async () => {
fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', message: 'Unreadable session' });
Expand Down
10 changes: 10 additions & 0 deletions src/web-ui/src/flow_chat/services/RelaySessionHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export class RelaySessionHistory {
onError: (error: unknown) => void,
onResumed?: () => Promise<void>,
private readonly onFlush?: () => void,
onResync?: () => void,
) {
this.fail = error => { this.rejectReady(error); this.rejectPage?.(error); onError(error); };
this.resumeInteraction = onResumed;
Expand All @@ -92,6 +93,15 @@ export class RelaySessionHistory {
else this.scheduleFlush();
} catch (error) { this.fail(error); }
}));
// A restarted host stream replays its latest page under fresh revisions and
// sends no tombstones for what it dropped (a rollback, undo, or history
// rewrite). Records already received are rendered first; the replay that
// follows, up to its ready event, is then the whole truth.
this.listeners.push(remoteConnectAPI.onSessionGap(gap => {
if (!this.isCurrent() || gap.sessionId !== this.sessionId || gap.resync !== true) return;
this.flush();
try { onResync?.(); } catch (error) { this.fail(error); }
}));
this.listeners.push(remoteConnectAPI.onSessionSyncError(error => {
if (!this.isCurrent() || error.sessionId !== this.sessionId || error.targetDeviceId !== this.scope.surfaceId) return;
// Records received before the failure stay rendered.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ vi.mock('./hostDialogQueue', () => ({
const agentApiMock = vi.hoisted(() => ({ rollbackSessionToTurn: vi.fn() }));
const eventBusMock = vi.hoisted(() => ({ emit: vi.fn() }));
const loadSessionHistory = vi.hoisted(() => vi.fn(async () => undefined));
const retireRelaySessionTurns = vi.hoisted(() => vi.fn());
const sessions = vi.hoisted(() => new Map<string, any>());
const historyViews = vi.hoisted(() => new Map<string, any>());

Expand All @@ -19,6 +20,7 @@ vi.mock('../store/FlowChatStore', () => ({
getState: () => ({ sessions }),
getSessionHistoryViewState: (sessionId: string) => historyViews.get(sessionId),
loadSessionHistory,
retireRelaySessionTurns,
},
}));

Expand Down Expand Up @@ -109,6 +111,7 @@ describe('SessionRollbackService', () => {
expect(result).toMatchObject({ fromTurnIndex: 2, composerText: 'prompt' });
expect(isSessionTurnRetired('session-1', 'turn-7')).toBe(true);
expect(isSessionTurnRetired('session-1', 'turn-8')).toBe(true);
expect(retireRelaySessionTurns).toHaveBeenCalledWith('session-1', ['turn-7', 'turn-8']);
});

it('omits a stale catalog revision when the current Turn is not represented', async () => {
Expand Down
2 changes: 2 additions & 0 deletions src/web-ui/src/flow_chat/services/SessionRollbackService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ export async function rollbackSessionToTurn(
}

markSessionTurnsRetired(request.sessionId, outcome.retiredTurnIds);
// A device surface renders a host replica that reloading does not rewrite.
flowChatStore.retireRelaySessionTurns(request.sessionId, outcome.retiredTurnIds);
refreshFiles(outcome.restoredFiles);
try {
await reloadAuthoritativeSession(request.sessionId);
Expand Down
68 changes: 68 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 @@ -55,6 +55,7 @@ const apiMocks = vi.hoisted(() => ({
loadOlderRelaySession: vi.fn(),
relayRecord: null as ((value: any) => void) | null,
relayReady: null as ((value: any) => void) | null,
relayGap: null as ((value: any) => void) | null,
listSessions: vi.fn(),
loadSessionMetadata: vi.fn(),
listSessionsPage: vi.fn(),
Expand Down Expand Up @@ -147,6 +148,7 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({
onSessionInteractionChanged: () => () => {},
onSessionRecord: (listener: (value: any) => void) => { apiMocks.relayRecord = listener; return () => { apiMocks.relayRecord = null; }; },
onSessionReady: (listener: (value: any) => void) => { apiMocks.relayReady = listener; return () => { apiMocks.relayReady = null; }; },
onSessionGap: (listener: (value: any) => void) => { apiMocks.relayGap = listener; return () => { apiMocks.relayGap = null; }; },
onSessionSyncError: vi.fn(() => () => {}),
subscribeSession: apiMocks.subscribeRelaySession,
loadOlderSession: apiMocks.loadOlderRelaySession,
Expand Down Expand Up @@ -8301,6 +8303,72 @@ describe('FlowChatStore device surfaces', () => {
expect(isHostIssuedTurnCatalogRevision(catalog.revision)).toBe(false);
});

const openPeerSession = async (sessionId: string, turnCount: number) => {
activateSurface(PEER_SURFACE_ID);
seedSession(sessionId);
apiMocks.subscribeRelaySession.mockImplementationOnce(async () => {
for (let turn = 0; turn < turnCount; turn += 1) {
apiMocks.relayRecord?.(itemRecord(sessionId, turn, 0, turn + 10));
}
apiMocks.relayReady?.({ sessionId, hasMore: false, oldestSeq: 1, cursor: turnCount });
return `${sessionId}-subscription`;
});
await flowChatStore.loadRelaySessionHistory(sessionId);
};
const turnIds = (sessionId: string) => flowChatStore.getState().sessions.get(sessionId)!
.dialogTurns.map(turn => turn.id);

it('rebuilds from the replay of a restarted host stream', async () => {
await openPeerSession('peer-rewrite', 3);
expect(turnIds('peer-rewrite')).toEqual(['turn-0', 'turn-1', 'turn-2']);

// A rollback on the host restarts the stream: no tombstones, and the
// replay reuses revisions lower than the ones already reduced.
apiMocks.relayGap?.({ sessionId: 'peer-rewrite', reason: 'host stream restarted', resync: true });
apiMocks.relayRecord?.(itemRecord('peer-rewrite', 0, 1, 1));
expect(turnIds('peer-rewrite')).toEqual(['turn-0', 'turn-1', 'turn-2']);
apiMocks.relayReady?.({ sessionId: 'peer-rewrite', hasMore: false, oldestSeq: 1, cursor: 1 });

expect(turnIds('peer-rewrite')).toEqual(['turn-0']);
expect(texts('peer-rewrite')).toHaveLength(1);
expect(texts('peer-rewrite')[0]).toMatchObject({ content: 'item 1' });
const session = flowChatStore.getState().sessions.get('peer-rewrite')!;
expect(session.turnCatalog?.entries.map(entry => entry.turnId)).toEqual(['turn-0']);
expect(session).toMatchObject({ totalTurnCount: 1, loadedTurnCount: 1 });
});

it('keeps an open relay session ready when it is reloaded after a mutation', async () => {
await openPeerSession('peer-reload', 2);
const subscriptions = apiMocks.subscribeRelaySession.mock.calls.length;

await flowChatStore.loadSessionHistory('peer-reload', { deferFullHistoryUntilActive: true });

// A non-paged host stream answers a rollback with tombstones and no
// second ready, so hydrating here would block the next submission.
expect(flowChatStore.getState().sessions.get('peer-reload')!.historyState).toBe('ready');
expect(apiMocks.subscribeRelaySession).toHaveBeenCalledTimes(subscriptions);
});

it('keeps rendered turns for a host-appended gap without a replay', async () => {
await openPeerSession('peer-source-gap', 2);

apiMocks.relayGap?.({ sessionId: 'peer-source-gap', reason: 'source lagged' });
apiMocks.relayReady?.({ sessionId: 'peer-source-gap', hasMore: false, oldestSeq: 1, cursor: 2 });

expect(turnIds('peer-source-gap')).toEqual(['turn-0', 'turn-1']);
});

it('drops turns a device-surface rollback retired before the host restarts', async () => {
await openPeerSession('peer-retire', 3);

flowChatStore.retireRelaySessionTurns('peer-retire', ['turn-1', 'turn-2']);

expect(turnIds('peer-retire')).toEqual(['turn-0']);
const session = flowChatStore.getState().sessions.get('peer-retire')!;
expect(session.turnCatalog?.entries.map(entry => entry.turnId)).toEqual(['turn-0']);
expect(session.totalTurnCount).toBe(1);
});

it('applies a tombstone that lands in the same batch as the turn', async () => {
activateSurface(PEER_SURFACE_ID);
seedSession('peer-tombstone');
Expand Down
92 changes: 90 additions & 2 deletions src/web-ui/src/flow_chat/store/FlowChatStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2058,6 +2058,8 @@ interface SurfaceStateContainer {
readonly relaySessionRecords: Map<string, SessionRecordReplica>;
/** Turns the replica changed that the rendered session does not reflect yet. */
readonly relayPendingRecordTurns: Map<string, Set<string>>;
/** Sessions rebuilding from a restarted host stream until its replay is ready. */
readonly relayResyncingSessions: Set<string>;
readonly relaySessionHistory: Map<string, RelaySessionHistory>;
}

Expand All @@ -2080,6 +2082,7 @@ function createSurfaceStateContainer(surfaceId: DeviceSurfaceId): SurfaceStateCo
relayMailboxReads: new Map(),
relaySessionRecords: new Map(),
relayPendingRecordTurns: new Map(),
relayResyncingSessions: new Set(),
relaySessionHistory: new Map(),
};
}
Expand Down Expand Up @@ -3255,6 +3258,7 @@ export class FlowChatStore {
this.activeSurface.relaySessionHistory.delete(id);
this.activeSurface.relaySessionRecords.delete(id);
this.activeSurface.relayPendingRecordTurns.delete(id);
this.activeSurface.relayResyncingSessions.delete(id);
this.activeSurface.relayQuestionMailboxes.delete(id);
this.activeSurface.relayRecordVersions.delete(id);
this.activeSurface.relayMailboxVersions.delete(id);
Expand Down Expand Up @@ -6197,6 +6201,7 @@ export class FlowChatStore {
history = new RelaySessionHistory(sessionId,
record => this.applyRelaySessionRecord(record),
ready => {
this.finishRelaySessionResync(sessionId);
this.setState(previous => {
const session = previous.sessions.get(sessionId);
if (!session) return previous;
Expand All @@ -6219,7 +6224,8 @@ export class FlowChatStore {
history?.close();
}
}, () => this.refreshRelayInteractionMailbox(sessionId),
() => this.flushRelaySessionRecords(sessionId));
() => this.flushRelaySessionRecords(sessionId),
() => this.beginRelaySessionResync(sessionId));
history.setVisible(this.historyLeases.has(this.surfaceKey(sessionId)));
surface.relaySessionHistory.set(sessionId, history);
}
Expand Down Expand Up @@ -6297,6 +6303,83 @@ export class FlowChatStore {
this.seedSessionHistoryLoadedRanges(sessionId);
}

/**
* The host restarted this session's stream. Its replay carries fresh
* revisions that an existing replica could reject as older, and no
* tombstones for what the host dropped, so it is reduced into a new replica.
* Rendered turns stay until the replay is ready, then only its turns remain.
*/
private beginRelaySessionResync(sessionId: string): void {
const surface = this.activeSurface;
if (surface.surfaceId === 'local' || !surface.state.sessions.has(sessionId)) return;
surface.relaySessionRecords.set(sessionId, new SessionRecordReplica(sessionId));
surface.relayPendingRecordTurns.delete(sessionId);
surface.relayResyncingSessions.add(sessionId);
}

private finishRelaySessionResync(sessionId: string): void {
const surface = this.activeSurface;
if (!surface.relayResyncingSessions.delete(sessionId)) return;
const replica = surface.relaySessionRecords.get(sessionId);
// Optimistic submissions have no storage index and are joined by their echo.
// The ready handler then records whether older pages remain and rebuilds
// the catalog only for a complete history.
this.removeRelaySessionTurns(sessionId, turn => (
turn.storageTurnIndex !== undefined && !replica?.snapshot(turn.id).turn
), false);
}

/**
* A completed rollback on a device surface hides these turns on the host.
* The host stream only reports that after it restarts, so the rendered copy
* drops them now instead of offering a target the host no longer has.
*/
public retireRelaySessionTurns(sessionId: string, turnIds: readonly string[]): void {
const surface = this.activeSurface;
if (surface.surfaceId === 'local' || turnIds.length === 0) return;
const retired = new Set(turnIds);
const pending = surface.relayPendingRecordTurns.get(sessionId);
if (pending) {
retired.forEach(turnId => pending.delete(turnId));
if (pending.size === 0) surface.relayPendingRecordTurns.delete(sessionId);
}
this.removeRelaySessionTurns(sessionId, turn => retired.has(turn.id), true);
}

private removeRelaySessionTurns(
sessionId: string,
remove: (turn: DialogTurn) => boolean,
refreshCatalog: boolean,
): void {
const surface = this.activeSurface;
const session = surface.state.sessions.get(sessionId);
if (!session || !session.dialogTurns.some(remove)) return;
this.setState(previous => {
const current = previous.sessions.get(sessionId);
if (!current) return previous;
const dialogTurns = current.dialogTurns.filter(turn => !remove(turn));
const sourceRemoved = Boolean(current.currentTokenUsage?.turnId)
&& !dialogTurns.some(turn => turn.id === current.currentTokenUsage?.turnId);
const sessions = new Map(previous.sessions);
sessions.set(sessionId, {
...current,
dialogTurns,
currentTokenUsage: currentTokenUsageAfterSourceRemoval(current, dialogTurns, sourceRemoved),
loadedTurnCount: dialogTurns.length,
totalTurnCount: current.isPartial === false ? dialogTurns.length : undefined,
turnCatalog: undefined,
lastUserDialogMode: this.deriveLastUserDialogMode(dialogTurns),
});
return { ...previous, sessions };
});
// Loaded ranges and the catalog index ordinals that no longer exist.
surface.sessionHistoryViews.delete(sessionId);
surface.sessionHistoryTurnAccessTimes.delete(sessionId);
surface.deferredFullHistoryProjections.delete(sessionId);
surface.fullHistoryProjectionApplyRequests.delete(sessionId);
if (refreshCatalog) this.refreshRelayTurnCatalog(sessionId);
}

/**
* Both realtime delivery and historical pages use the same record owner. This
* reduces only; `RelaySessionHistory` owns when the result is rendered, and
Expand Down Expand Up @@ -8836,7 +8919,12 @@ export class FlowChatStore {
this.setSessionHistoryState(sessionId, 'failed');
throw new Error(i18nService.t('flow-chat:externalHistory.unsupportedSurface'));
}
this.setSessionHistoryState(sessionId, 'hydrating');
// An open subscription is already the live owner and announces no second
// first page; marking it hydrating again would block submission until
// an unrelated stream restart happened to report ready.
const open = this.activeSurface.relaySessionHistory.has(sessionId)
&& initialSession?.historyState === 'ready';
if (!open) this.setSessionHistoryState(sessionId, 'hydrating');
await this.loadRelaySessionHistory(sessionId);
scope.assertCurrent('load relay session history');
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,11 @@ class RemoteConnectAPIService {
}
}

onSessionGap(callback: (event: { sessionId: string; reason: string }) => void): () => void {
/**
* `resync` marks a restarted host stream: a full replay from its latest page
* follows and replaces the controller's records. Host-appended gaps omit it.
*/
onSessionGap(callback: (event: { sessionId: string; reason: string; resync?: boolean }) => void): () => void {
return api.listen('relay://session-gap', callback);
}

Expand Down
Loading