diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs index 6ce5d5c1f6..07dbd6e479 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs @@ -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}), }) } @@ -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()); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts index f1dacfa53a..a62043d0a7 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts @@ -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', () => ({ @@ -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, } })); @@ -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' }); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts index b25fe733ab..4b018bf747 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts @@ -79,6 +79,7 @@ export class RelaySessionHistory { onError: (error: unknown) => void, onResumed?: () => Promise, private readonly onFlush?: () => void, + onResync?: () => void, ) { this.fail = error => { this.rejectReady(error); this.rejectPage?.(error); onError(error); }; this.resumeInteraction = onResumed; @@ -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. diff --git a/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts b/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts index 023026f27f..d315d8f5da 100644 --- a/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts +++ b/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts @@ -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()); const historyViews = vi.hoisted(() => new Map()); @@ -19,6 +20,7 @@ vi.mock('../store/FlowChatStore', () => ({ getState: () => ({ sessions }), getSessionHistoryViewState: (sessionId: string) => historyViews.get(sessionId), loadSessionHistory, + retireRelaySessionTurns, }, })); @@ -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 () => { diff --git a/src/web-ui/src/flow_chat/services/SessionRollbackService.ts b/src/web-ui/src/flow_chat/services/SessionRollbackService.ts index 2f59c5f366..cb2b948ff3 100644 --- a/src/web-ui/src/flow_chat/services/SessionRollbackService.ts +++ b/src/web-ui/src/flow_chat/services/SessionRollbackService.ts @@ -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); 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 8bbaa6f161..85a6579ffb 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -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(), @@ -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, @@ -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'); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index e6eb7def73..4e0dcb0775 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -2058,6 +2058,8 @@ interface SurfaceStateContainer { readonly relaySessionRecords: Map; /** Turns the replica changed that the rendered session does not reflect yet. */ readonly relayPendingRecordTurns: Map>; + /** Sessions rebuilding from a restarted host stream until its replay is ready. */ + readonly relayResyncingSessions: Set; readonly relaySessionHistory: Map; } @@ -2080,6 +2082,7 @@ function createSurfaceStateContainer(surfaceId: DeviceSurfaceId): SurfaceStateCo relayMailboxReads: new Map(), relaySessionRecords: new Map(), relayPendingRecordTurns: new Map(), + relayResyncingSessions: new Set(), relaySessionHistory: new Map(), }; } @@ -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); @@ -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; @@ -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); } @@ -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 @@ -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; diff --git a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts index e5b40ac24f..0be75d4971 100644 --- a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts @@ -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); }