From 60f92537e7bd480ebbd966af9762a82b97100fe8 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 3 Nov 2026 13:09:59 +0800 Subject: [PATCH 1/3] fix(remote-connect): flag controller gaps that a full replay follows When the host restarts a session stream (for example after a rollback rewrites a paged history), the new epoch replays its latest page under fresh revisions and sends no tombstones for dropped turns. Mark the controller-side `relay://session-gap` with `resync: true` so the Web UI can rebuild its records from that replay. Host-appended gaps stay inside one epoch and omit the flag. Co-Authored-By: Claude --- .../remote_connect/host_stream_subscriber.rs | 8 ++++- .../src/flow_chat/store/FlowChatStore.test.ts | 35 +++++++++++++++++++ .../src/flow_chat/store/FlowChatStore.ts | 31 ++++++++-------- 3 files changed, 59 insertions(+), 15 deletions(-) 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/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 8bbaa6f161..65cf71d0db 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -7971,6 +7971,41 @@ describe('FlowChatStore reconcile snapshot content safety', () => { ).toHaveLength(2); }); + it('keeps live round timing when a Peer snapshot adopts a settled Turn', async () => { + await hydrateSessionWithContent(); + flowChatStore.updateModelRound('history-1', 'turn-0', 'round-0', round => ({ + ...round, + durationMs: 2172, + ttftMs: 690, + })); + + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession(), + turns: [{ + ...createPersistedTurn(0), + modelRounds: [{ + ...HYDRATED_ROUND, + durationMs: 0, + textItems: [ + { id: 'text-0', content: 'OpenBitFun is an agentic IDE…', timestamp: 2 }, + { id: 'text-1', content: '…with multi-device control.', timestamp: 3 }, + ], + }], + }], + contextRestoreState: 'ready', + }); + + const result = await flowChatStore.refreshPeerSessionSnapshot( + 'history-1', + { requireActiveSession: true }, + ); + + expect(result.applied).toBe(true); + const round = flowChatStore.getState().sessions.get('history-1')?.dialogTurns[0].modelRounds[0]; + expect(round?.items).toHaveLength(2); + expect(round).toMatchObject({ durationMs: 2172, ttftMs: 690 }); + }); + 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 diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index e6eb7def73..a65ad449a7 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -8386,7 +8386,7 @@ export class FlowChatStore { if (adopted === turns) { adopted = [...turns]; } - adopted[index] = snapshotTurn; + adopted[index] = preserveLiveRoundTiming(adopted[index], snapshotTurn); } return adopted; }; @@ -8443,24 +8443,27 @@ export class FlowChatStore { let turnsChanged = false; for (const snapshotTurn of snapshotTurns) { const existingIndex = mergedTurns.findIndex(turn => turn.id === snapshotTurn.id); + // The Runtime journal replay *is* the runtime writer, so it always + // establishes its own active Turn. + const isRuntimeReplayTurn = Boolean(runtimeReplaySnapshot) + && snapshotTurn.id === runtimeReplaySnapshot?.activeTurnId; if (existingIndex === -1) { mergedTurns.push(snapshotTurn); turnsChanged = true; } else if ( - // The Runtime journal replay *is* the runtime writer, so it always - // establishes its own active Turn. - runtimeReplaySnapshot && snapshotTurn.id === runtimeReplaySnapshot.activeTurnId - ? true - : persistedReadMayReplaceTurn( - sessionId, - mergedTurns[existingIndex], - snapshotTurn, - activeTurnId, - Boolean(runtimeEventSnapshot), - true, - ) + isRuntimeReplayTurn + || persistedReadMayReplaceTurn( + sessionId, + mergedTurns[existingIndex], + snapshotTurn, + activeTurnId, + Boolean(runtimeEventSnapshot), + true, + ) ) { - mergedTurns[existingIndex] = snapshotTurn; + mergedTurns[existingIndex] = isRuntimeReplayTurn + ? snapshotTurn + : preserveLiveRoundTiming(mergedTurns[existingIndex], snapshotTurn); turnsChanged = true; } } From a6b238b3b8bf9c365ed0c34005cf605671385306 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 3 Nov 2026 13:09:59 +0800 Subject: [PATCH 2/3] fix(web-ui): keep remote Session history in step with host rewrites In Peer Device Mode the controller renders a record replica that only grew. After a rollback on the CLI host, the rolled-back turns stayed on screen, and rolling back one of them again failed with "Session rollback target was not found". - Rebuild the replica from the replay after a restarted host stream and drop rendered turns the replay no longer carries once it is ready. - Drop the turns a completed rollback retired right away, so the view matches the host before its stream restarts. Co-Authored-By: Claude --- .../services/RelaySessionHistory.test.ts | 25 ++++ .../flow_chat/services/RelaySessionHistory.ts | 10 ++ .../services/SessionRollbackService.test.ts | 3 + .../services/SessionRollbackService.ts | 2 + .../src/flow_chat/store/FlowChatStore.test.ts | 91 ++++++++------ .../src/flow_chat/store/FlowChatStore.ts | 116 +++++++++++++++--- .../api/service-api/RemoteConnectAPI.ts | 6 +- 7 files changed, 199 insertions(+), 54 deletions(-) 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 65cf71d0db..0a22d486c9 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, @@ -7971,41 +7973,6 @@ describe('FlowChatStore reconcile snapshot content safety', () => { ).toHaveLength(2); }); - it('keeps live round timing when a Peer snapshot adopts a settled Turn', async () => { - await hydrateSessionWithContent(); - flowChatStore.updateModelRound('history-1', 'turn-0', 'round-0', round => ({ - ...round, - durationMs: 2172, - ttftMs: 690, - })); - - apiMocks.restoreSessionView.mockResolvedValueOnce({ - session: hostSession(), - turns: [{ - ...createPersistedTurn(0), - modelRounds: [{ - ...HYDRATED_ROUND, - durationMs: 0, - textItems: [ - { id: 'text-0', content: 'OpenBitFun is an agentic IDE…', timestamp: 2 }, - { id: 'text-1', content: '…with multi-device control.', timestamp: 3 }, - ], - }], - }], - contextRestoreState: 'ready', - }); - - const result = await flowChatStore.refreshPeerSessionSnapshot( - 'history-1', - { requireActiveSession: true }, - ); - - expect(result.applied).toBe(true); - const round = flowChatStore.getState().sessions.get('history-1')?.dialogTurns[0].modelRounds[0]; - expect(round?.items).toHaveLength(2); - expect(round).toMatchObject({ durationMs: 2172, ttftMs: 690 }); - }); - 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 @@ -8336,6 +8303,60 @@ 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 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 a65ad449a7..57259e80c8 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 @@ -8386,7 +8469,7 @@ export class FlowChatStore { if (adopted === turns) { adopted = [...turns]; } - adopted[index] = preserveLiveRoundTiming(adopted[index], snapshotTurn); + adopted[index] = snapshotTurn; } return adopted; }; @@ -8443,27 +8526,24 @@ export class FlowChatStore { let turnsChanged = false; for (const snapshotTurn of snapshotTurns) { const existingIndex = mergedTurns.findIndex(turn => turn.id === snapshotTurn.id); - // The Runtime journal replay *is* the runtime writer, so it always - // establishes its own active Turn. - const isRuntimeReplayTurn = Boolean(runtimeReplaySnapshot) - && snapshotTurn.id === runtimeReplaySnapshot?.activeTurnId; if (existingIndex === -1) { mergedTurns.push(snapshotTurn); turnsChanged = true; } else if ( - isRuntimeReplayTurn - || persistedReadMayReplaceTurn( - sessionId, - mergedTurns[existingIndex], - snapshotTurn, - activeTurnId, - Boolean(runtimeEventSnapshot), - true, - ) + // The Runtime journal replay *is* the runtime writer, so it always + // establishes its own active Turn. + runtimeReplaySnapshot && snapshotTurn.id === runtimeReplaySnapshot.activeTurnId + ? true + : persistedReadMayReplaceTurn( + sessionId, + mergedTurns[existingIndex], + snapshotTurn, + activeTurnId, + Boolean(runtimeEventSnapshot), + true, + ) ) { - mergedTurns[existingIndex] = isRuntimeReplayTurn - ? snapshotTurn - : preserveLiveRoundTiming(mergedTurns[existingIndex], snapshotTurn); + mergedTurns[existingIndex] = snapshotTurn; turnsChanged = true; } } 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); } From a98aa3ae63c9795b851438f0ac94a1d84b8af1cc Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 3 Nov 2026 13:18:12 +0800 Subject: [PATCH 3/3] fix(web-ui): keep an open remote Session submittable after a reload Reloading a device-surface Session whose relay subscription is already open marked it hydrating, but the open subscription announces no second first page. After a rollback on a host whose stream answers with tombstones instead of restarting, the Session stayed hydrating and its composer refused the next message. Keep an open, ready subscription ready. Co-Authored-By: Claude --- src/web-ui/src/flow_chat/store/FlowChatStore.test.ts | 12 ++++++++++++ src/web-ui/src/flow_chat/store/FlowChatStore.ts | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) 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 0a22d486c9..85a6579ffb 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -8337,6 +8337,18 @@ describe('FlowChatStore device surfaces', () => { 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); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 57259e80c8..4e0dcb0775 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -8919,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;