diff --git a/src/web-ui/AGENTS-CN.md b/src/web-ui/AGENTS-CN.md index e2960af273..aefc23aabb 100644 --- a/src/web-ui/AGENTS-CN.md +++ b/src/web-ui/AGENTS-CN.md @@ -87,3 +87,12 @@ pnpm --dir src/web-ui run test:run src/app/layout/useNavResize.test.tsx src/app/ ``` 这些本地 DOM 测试覆盖手势状态和弹簧收敛,不代表原生 WebView 渲染或真实远程场景验证。 + +编辑/回滚结果、旧版本被控端响应与延迟记录重放使用以下聚焦检查: + +```bash +pnpm --dir src/web-ui run test:run src/flow_chat/services/SessionRollbackService.test.ts src/flow_chat/services/UserMessageEditService.test.ts src/flow_chat/store/FlowChatStore.test.ts src/flow_chat/session-stream/SessionRecordReplica.test.ts src/flow_chat/services/RelaySessionHistory.test.ts +``` + +这些测试通过模拟 Peer 记录验证共享操作服务和实际展示状态,包括设备切换与 redo; +不代表真实 Desktop-to-Desktop 或 Desktop-to-CLI 连接验证。 diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index db6d0cc71b..ed98e59c5f 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -207,6 +207,16 @@ run `pnpm --dir src/web-ui run test:run src/flow_chat/services/flow-chat-manager Missing fence identities (including legacy payloads) must reload authoritative history; an explicit settled-Turn identity must preserve newer live Turns. +For edit/rollback receipts, legacy peer outcomes, and delayed record replay: + +```bash +pnpm --dir src/web-ui run test:run src/flow_chat/services/SessionRollbackService.test.ts src/flow_chat/services/UserMessageEditService.test.ts src/flow_chat/store/FlowChatStore.test.ts src/flow_chat/session-stream/SessionRecordReplica.test.ts src/flow_chat/services/RelaySessionHistory.test.ts +``` + +These tests exercise the shared mutation services and real presentation store +with simulated Peer records, including device switches and redo. They do not +establish live Desktop-to-Desktop or Desktop-to-CLI behavior. + For text-entry guards, composer sanitization, or keyboard focus routing, run `pnpm --dir src/web-ui run test:run src/shared/utils/textInputGuard.test.tsx src/flow_chat/components/RichTextInput.test.tsx src/flow_chat/hooks/useComposerDefaultFocus.test.tsx src/flow_chat/utils/chatInputKeyOwnership.test.ts`. These cover DOM event ownership, controlled fields, IME and selection preservation; 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 99f25f4cd7..bf890268f1 100644 --- a/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts +++ b/src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const hostQueueMock = vi.hoisted(() => ({ supported: vi.fn(() => false), refresh: vi.fn() })); vi.mock('./hostDialogQueue', () => ({ @@ -34,7 +34,7 @@ import { stateMachineManager, } from '../state-machine'; import { pendingQueueManager } from './flow-chat-manager/PendingQueueModule'; -import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { activateSurface, getActiveSurfaceScope, LOCAL_SURFACE_ID } from '@/infrastructure/peer-device/deviceSurface'; import { beginSubmittedMessagePreview, getSubmittedMessagePreviews, @@ -42,6 +42,7 @@ import { import { localTurnCatalogRevision } from '../utils/flowChatTurnIdentity'; describe('SessionRollbackService', () => { + afterEach(() => activateSurface(LOCAL_SURFACE_ID)); it('rejects detached history mutation before any local backend call', async () => { sessions.set('dispatch-session', { config: { dispatchJobId: 'job-remote' } }); await expect(rollbackSessionToTurn({ sessionId: 'dispatch-session', targetTurnId: 'turn-1', kind: 'rollback' })) @@ -146,6 +147,78 @@ describe('SessionRollbackService', () => { })); }); + it('includes sparse cached and catalog-only history in a legacy peer rollback', async () => { + const session = sessions.get('session-1'); + session.dialogTurns.push({ id: 'turn-9', storageTurnIndex: 9 }); + const catalog = { + sessionId: 'session-1', revision: 'catalog-history', + entries: [ + { ordinal: 0, storageTurnIndex: 1, turnId: 'turn-1' }, + { ordinal: 1, storageTurnIndex: 2, turnId: 'turn-2' }, + { ordinal: 2, storageTurnIndex: 5, turnId: 'turn-5' }, + { ordinal: 3, storageTurnIndex: 7, turnId: 'turn-7' }, + { ordinal: 4, storageTurnIndex: 9, turnId: 'turn-9' }, + ], + }; + session.turnCatalog = catalog; + historyViews.set('session-1', { + catalog, + loadedRanges: [{ startOrdinal: 0, endOrdinalExclusive: 2, turns: [ + { id: 'turn-1', storageTurnIndex: 1 }, { id: 'turn-2', storageTurnIndex: 2 }, + ] }], + }); + agentApiMock.rollbackSessionToTurn.mockResolvedValue({ + status: 'completed', retiredTurnIds: [], restoredFiles: [], + composer: { kind: 'replace', text: 'test2' }, + }); + + await rollbackSessionToTurn({ sessionId: 'session-1', targetTurnId: 'turn-2', kind: 'rollback' }); + + const retired = retireRelaySessionTurns.mock.calls[0][1] as string[]; + expect(new Set(retired)).toEqual(new Set(['turn-2', 'turn-5', 'turn-7', 'turn-9'])); + expect(isSessionTurnRetired('session-1', 'turn-1')).toBe(false); + }); + + it('captures retired identities before awaiting the host, preserving a new Turn in the same slot', async () => { + agentApiMock.rollbackSessionToTurn.mockImplementationOnce(async () => { + sessions.get('session-1').dialogTurns = [{ id: 'new-turn', storageTurnIndex: 7 }]; + return { status: 'completed', retiredTurnIds: [], restoredFiles: [], composer: { kind: 'preserve' } }; + }); + + await rollbackSessionToTurn({ sessionId: 'session-1', targetTurnId: 'turn-7', kind: 'rollback' }); + + expect(retireRelaySessionTurns).toHaveBeenCalledWith('session-1', ['turn-7']); + expect(isSessionTurnRetired('session-1', 'new-turn')).toBe(false); + }); + + it('abandons a rollback when the device changes during the host queue check', async () => { + activateSurface('peer-a'); + hostQueueMock.supported.mockReturnValue(true); + hostQueueMock.refresh.mockImplementationOnce(async () => { + activateSurface('peer-b'); + return { items: [] }; + }); + + await expect(rollbackSessionToTurn({ sessionId: 'session-1', targetTurnId: 'turn-7', kind: 'rollback' })) + .rejects.toThrow('Device surface changed'); + expect(agentApiMock.rollbackSessionToTurn).not.toHaveBeenCalled(); + expect(retireRelaySessionTurns).not.toHaveBeenCalled(); + }); + + it('does not apply a rollback receipt to another device with the same Session ID', async () => { + activateSurface('peer-a'); + agentApiMock.rollbackSessionToTurn.mockImplementationOnce(async () => { + activateSurface('peer-b'); + return { status: 'completed', retiredTurnIds: ['turn-7'], restoredFiles: [], composer: { kind: 'preserve' } }; + }); + + await expect(rollbackSessionToTurn({ sessionId: 'session-1', targetTurnId: 'turn-7', kind: 'rollback' })) + .rejects.toThrow('Device surface changed'); + expect(retireRelaySessionTurns).not.toHaveBeenCalled(); + expect(loadSessionHistory).not.toHaveBeenCalled(); + expect(eventBusMock.emit).not.toHaveBeenCalled(); + }); + it('omits a controller-minted catalog revision the host never issued', async () => { // Peer Device sessions build their catalog from replicated records; the // host computes its own revision, so a local one would always look stale. diff --git a/src/web-ui/src/flow_chat/services/SessionRollbackService.ts b/src/web-ui/src/flow_chat/services/SessionRollbackService.ts index 3d9f865e1c..1ce8939432 100644 --- a/src/web-ui/src/flow_chat/services/SessionRollbackService.ts +++ b/src/web-ui/src/flow_chat/services/SessionRollbackService.ts @@ -3,7 +3,7 @@ import { agentAPI } from '@/infrastructure/api'; import { globalEventBus } from '@/infrastructure/event-bus'; import { createLogger } from '@/shared/utils/logger'; import { flowChatStore } from '../store/FlowChatStore'; -import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { getActiveSurfaceScope, type SurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import { finishSubmittedMessagePreview } from './submittedMessagePresentation'; import { assertSessionMutationLease, @@ -20,7 +20,7 @@ import { resolveMaterializedSessionTurnIdentity, resolveStorageTurnIndex, } from '../utils/flowChatTurnIdentity'; -import type { Session } from '../types/flow-chat'; +import type { Session, SessionHistoryViewState } from '../types/flow-chat'; import type { SessionTurnCatalog } from '@/shared/types/session-history'; import { pendingQueueManager } from './flow-chat-manager/PendingQueueModule'; import { resolveSessionDriverId } from '../session-drivers/resolve'; @@ -41,10 +41,11 @@ export interface RollbackSessionToTurnResult { composerText?: string; } -async function reloadAuthoritativeSession(sessionId: string): Promise { +async function reloadAuthoritativeSession(sessionId: string, scope: SurfaceScope): Promise { await flowChatStore.loadSessionHistory(sessionId, { deferFullHistoryUntilActive: true, }); + scope.assertCurrent('finish rollback history reload'); completeSessionMutationReconciliation(sessionId); } @@ -82,14 +83,40 @@ function validProjectedCatalogRevision( return coversProjectedTurns ? catalog.revision : undefined; } +function projectedRollbackTurnIds( + session: Session, + historyView: SessionHistoryViewState | undefined, + targetTurnId: string, + boundaryStorageTurnIndex: number | undefined, +): Set { + const ids = new Set([targetTurnId]); + if (boundaryStorageTurnIndex === undefined) return ids; + for (const turn of [ + ...session.dialogTurns, + ...(historyView?.loadedRanges.flatMap(range => range.turns) ?? []), + ]) { + const index = resolveStorageTurnIndex(session, turn); + if (index !== undefined && index >= boundaryStorageTurnIndex) ids.add(turn.id); + } + for (const catalog of [session.turnCatalog, historyView?.catalog]) { + if (catalog?.sessionId !== session.sessionId) continue; + for (const entry of catalog.entries) { + if (entry.turnId && entry.storageTurnIndex >= boundaryStorageTurnIndex) ids.add(entry.turnId); + } + } + return ids; +} + export async function rollbackSessionToTurn( request: RollbackSessionToTurnRequest, ): Promise { + const scope = getActiveSurfaceScope(); if (resolveSessionDriverId(request.sessionId, flowChatStore.getState().sessions.get(request.sessionId)) === 'dispatch') { throw new Error('History rollback is unavailable for a detached remote session.'); } if (hostQueueSupported(request.sessionId)) { const queue = await hostDialogQueue(request.sessionId).refresh(); + scope.assertCurrent('check rollback queue'); if (queue.items.length) throw new Error('Clear the host message queue before changing Session history'); } const lease = request.lease @@ -115,9 +142,10 @@ export async function rollbackSessionToTurn( if (!session) { throw new Error(`Session does not exist: ${request.sessionId}`); } + const historyView = flowChatStore.getSessionHistoryViewState(request.sessionId); const target = resolveMaterializedSessionTurnIdentity( session, - flowChatStore.getSessionHistoryViewState(request.sessionId), + historyView, request.targetTurnId, ); if (!target) { @@ -127,6 +155,13 @@ export async function rollbackSessionToTurn( const expectedCatalogRevision = validProjectedCatalogRevision(session, target.catalog); const fromTurnIndex = target.ordinal ?? session.dialogTurns.findIndex(turn => turn.id === request.targetTurnId); + // Capture identities before the RPC. Older peers omit retiredTurnIds or + // report only active/queued Turns; a completed targeted rollback still + // confirms that this already-observed suffix is no longer visible. + // Do not collect by storage index after the await: an edit may reuse it. + const retiredTurnIds = projectedRollbackTurnIds( + session, historyView, request.targetTurnId, expectedStorageTurnIndex, + ); const workspaceId = session.workspaceId ?? session.config.workspaceId; if (!workspaceId) throw new Error('Session workspace ID is unavailable; reload the workspace catalog'); @@ -137,30 +172,33 @@ export async function rollbackSessionToTurn( expectedStorageTurnIndex, expectedCatalogRevision, }); + scope.assertCurrent('apply session rollback'); if (outcome.status === 'recovery_required') { refreshFiles(outcome.affectedFiles); requireSessionMutationReconciliation(lease, outcome.reason); - await reloadAuthoritativeSession(request.sessionId); + await reloadAuthoritativeSession(request.sessionId, scope); throw new Error(`Rollback requires recovery: ${outcome.reason}`); } - markSessionTurnsRetired(request.sessionId, outcome.retiredTurnIds); + outcome.retiredTurnIds.forEach(turnId => retiredTurnIds.add(turnId)); + markSessionTurnsRetired(request.sessionId, retiredTurnIds); // A device surface renders a host replica that reloading does not rewrite. - flowChatStore.retireRelaySessionTurns(request.sessionId, outcome.retiredTurnIds); + flowChatStore.retireRelaySessionTurns(request.sessionId, [...retiredTurnIds]); // A send preview renders whenever its Turn is absent; never let a retired // Turn's preview stand in for it. - const scope = getActiveSurfaceScope(); - outcome.retiredTurnIds.forEach(turnId => ( + retiredTurnIds.forEach(turnId => ( finishSubmittedMessagePreview(scope, request.sessionId, turnId) )); refreshFiles(outcome.restoredFiles); try { - await reloadAuthoritativeSession(request.sessionId); + await reloadAuthoritativeSession(request.sessionId, scope); } catch (error) { - requireSessionMutationReconciliation( - lease, - error instanceof Error ? error.message : String(error), - ); + if (scope.isCurrent()) { + requireSessionMutationReconciliation( + lease, + error instanceof Error ? error.message : String(error), + ); + } throw error; } return { diff --git a/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.test.ts b/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.test.ts index dfed487193..cb531ed271 100644 --- a/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.test.ts +++ b/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.test.ts @@ -94,4 +94,19 @@ describe('SessionRecordReplica', () => { expect(replica.apply(record(2))).toBeNull(); expect(replica.apply(record(11))?.turn?.modelRounds[0].textItems).toHaveLength(1); }); + + it.each(['before', 'after'] as const)('hands a rollback receipt fence over to a tombstone arriving %s the receipt', order => { + const replica = new SessionRecordReplica('session'); + replica.apply(record(1)); + const tombstone = { sessionId: 'session', id: 'turn/turn', revision: 10, deleted: true } as const; + if (order === 'before') replica.apply(tombstone); + replica.retireTurns(['turn']); + expect(replica.snapshot('turn').turn).toBeNull(); + expect(replica.apply(record(5))?.turn ?? null).toBeNull(); + if (order === 'after') { + expect(replica.apply(tombstone)).toEqual({ turnId: 'turn', turn: null }); + } + expect(replica.apply(record(9))?.turn).toBeNull(); + expect(replica.apply(record(11))?.turn?.modelRounds[0].textItems).toHaveLength(1); + }); }); diff --git a/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.ts b/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.ts index 08c098c436..76f5ae40a4 100644 --- a/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.ts +++ b/src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.ts @@ -10,10 +10,43 @@ export type SessionRecord = SessionRecordUpsert | {sessionId:string;id:string;re export interface SessionRecordChange {turnId:string;turn:DialogTurnData|null} /** Web UI presentation types wrap the shared lossless record reducer. */ export class SessionRecordReplica extends SharedReplica { + // A rollback ACK is authoritative even before its stream reset/tombstones + // arrive. Keep that fence with this replica, never with a global Session ID + // or an invented record revision. A new host epoch creates a fresh replica. + private readonly retiredTurns = new Set(); + private readonly tombstonedTurns = new Set(); + + retireTurns(turnIds: readonly string[]): void { + turnIds.forEach(turnId => { + // The stream's tombstone may beat the RPC receipt. + if (!this.tombstonedTurns.has(turnId)) this.retiredTurns.add(turnId); + }); + } + + override ingest(record: SessionRecord): string | null { + if ( + !record.deleted && record.sessionId === this.sessionId + && record.turn.sessionId === this.sessionId && this.retiredTurns.has(record.turn.turnId) + ) return null; + const turnId = super.ingest(record); + if (record.deleted && turnId !== null && record.id === `turn/${turnId}` + && super.snapshot(turnId).turn === null) { + // Once the host supplies a real tombstone its revision owns the fence. + // Newer authoritative upserts (redo) may then restore the same identity. + this.retiredTurns.delete(turnId); + this.tombstonedTurns.add(turnId); + } else if (turnId !== null && this.tombstonedTurns.has(turnId) + && super.snapshot(turnId).turn !== null) { + this.tombstonedTurns.delete(turnId); + } + return turnId; + } + override apply(record: SessionRecord): SessionRecordChange | null { return super.apply(record) as SessionRecordChange | null; } override snapshot(turnId: string): SessionRecordChange { + if (this.retiredTurns.has(turnId)) return { turnId, turn: null }; return super.snapshot(turnId) as SessionRecordChange; } } 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 fef2dc7941..e1fbe7166f 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -27,6 +27,9 @@ import { import { dispatchJobStore } from '@/features/dispatch/dispatchJobStore'; import { resetLiveSessionInteractionStoreForTest } from '../services/liveSessionInteractionStore'; import { resourceBudget } from '@/shared/utils/resourceBudget'; +import { rollbackSessionToTurn } from '../services/SessionRollbackService'; +import { editAndRerunUserMessage } from '../services/UserMessageEditService'; +import { useSessionMutationStore } from './sessionMutationStore'; import { HARNESS_IDS } from '@/shared/agents/identity'; import { askUserQuestionDraftKey, @@ -55,6 +58,7 @@ function fixtureWorkspaceId(rootPath: string, connectionId?: string, sshHost?: s } const apiMocks = vi.hoisted(() => ({ + rollbackSessionToTurn: vi.fn(), getSessionInteractionMailbox: vi.fn(async (sessionId: string) => ({sessionId, userQuestions:{revision:0,questions:[]}, permissions:{revision:0,requests:[]}})), subscribeRelaySession: vi.fn(), loadOlderRelaySession: vi.fn(), @@ -99,6 +103,7 @@ const configManagerMock = vi.hoisted(() => { }); const stateMachineManagerMock = vi.hoisted(() => ({ + getCurrentState: vi.fn(() => 'idle'), delete: vi.fn(), getOrCreate: vi.fn(), reset: vi.fn(), @@ -106,6 +111,7 @@ const stateMachineManagerMock = vi.hoisted(() => ({ })); vi.mock('@/infrastructure/api', () => ({ + agentAPI: { rollbackSessionToTurn: apiMocks.rollbackSessionToTurn }, sessionAPI: { listSessions: apiMocks.listSessions, loadSessionMetadata: apiMocks.loadSessionMetadata, @@ -115,6 +121,10 @@ vi.mock('@/infrastructure/api', () => ({ }, })); +vi.mock('../services/hostDialogQueue', () => ({ + hostQueueSupported: () => false, +})); + vi.mock('@/infrastructure/api/service-api/SessionAPI', () => ({ sessionAPI: { listSessions: apiMocks.listSessions, @@ -171,6 +181,7 @@ vi.mock('@/infrastructure/config/services/ConfigManager', () => ({ vi.mock('../state-machine', () => ({ stateMachineManager: stateMachineManagerMock, + SessionExecutionState: { IDLE: 'idle' }, SessionExecutionEvent: { START: 'start', }, @@ -8457,6 +8468,120 @@ describe('FlowChatStore device surfaces', () => { expect(session.totalTurnCount).toBe(1); }); + it.each([ + ['rollback', []], ['edit-rerun', []], + ['rollback', ['turn-1', 'turn-2']], ['edit-rerun', ['turn-1', 'turn-2']], + ] as const)( + 'removes the confirmed suffix for %s with peer retired IDs %j', async (kind, retiredTurnIds) => { + const sessionId = `peer-legacy-${kind}`; + await openPeerSession(sessionId, 3); + useSessionMutationStore.setState({ mutations: new Map(), retiredTurnIds: new Map() }); + apiMocks.rollbackSessionToTurn.mockResolvedValueOnce({ + status: 'completed', sessionId, changed: true, hiddenTurnCount: 2, + boundaryStorageTurnIndex: 1, targetTurnId: 'turn-1', + retiredTurnIds, restoredFiles: [], + composer: { kind: 'replace', text: 'test2' }, + }); + const rerun = vi.fn(async () => { + // The edited prompt must not be submitted over the stale suffix. + expect(turnIds(sessionId)).toEqual(['turn-0']); + }); + + if (kind === 'edit-rerun') { + await editAndRerunUserMessage({ + sessionId, turnId: 'turn-1', originalContent: 'test2', + editedContent: 'test2 edited', rerun, + }); + expect(rerun).toHaveBeenCalledOnce(); + } else { + const result = await rollbackSessionToTurn({ sessionId, targetTurnId: 'turn-1', kind }); + expect(result.composerText).toBe('test2'); + } + expect(turnIds(sessionId)).toEqual(['turn-0']); + expect(sessionToVirtualItems(flowChatStore.getState().sessions.get(sessionId)!)) + .toEqual(expect.arrayContaining([expect.objectContaining({ turnId: 'turn-0' })])); + expect(sessionToVirtualItems(flowChatStore.getState().sessions.get(sessionId)!) + .some(item => item.turnId === 'turn-1' || item.turnId === 'turn-2')).toBe(false); + expect(apiMocks.restoreSessionView).not.toHaveBeenCalled(); + }, + ); + + it('keeps the transcript and send previews when the host rejects a rollback', async () => { + const sessionId = 'peer-rejected-rollback'; + await openPeerSession(sessionId, 3); + useSessionMutationStore.setState({ mutations: new Map(), retiredTurnIds: new Map() }); + const scope = getActiveSurfaceScope(); + beginSubmittedMessagePreview(scope, sessionId, 'turn-2', { + id: 'preview-2', content: 'test3', timestamp: 2, + }); + apiMocks.rollbackSessionToTurn.mockRejectedValueOnce(new Error('Rollback target is stale')); + + await expect(rollbackSessionToTurn({ sessionId, targetTurnId: 'turn-1', kind: 'rollback' })) + .rejects.toThrow('Rollback target is stale'); + + expect(turnIds(sessionId)).toEqual(['turn-0', 'turn-1', 'turn-2']); + expect(getSubmittedMessagePreviews(scope, sessionId)).toHaveLength(1); + }); + + it('does not revive rolled-back turns from records already in flight', async () => { + await openPeerSession('peer-late-rollback', 3); + // One record is buffered before the ACK, another arrives after it. + apiMocks.relayRecord?.(itemRecord('peer-late-rollback', 1, 1, 20)); + flowChatStore.retireRelaySessionTurns('peer-late-rollback', ['turn-1', 'turn-2']); + apiMocks.relayRecord?.(itemRecord('peer-late-rollback', 2, 1, 21)); + flowChatStore.settleRelaySessionRecords('peer-late-rollback'); + + expect(turnIds('peer-late-rollback')).toEqual(['turn-0']); + }); + + it('accepts a new Turn at the retired storage index and an authoritative redo replay', async () => { + const sessionId = 'peer-rollback-new-turn'; + await openPeerSession(sessionId, 3); + flowChatStore.retireRelaySessionTurns(sessionId, ['turn-1', 'turn-2']); + const next = itemRecord(sessionId, 1, 0, 30); + next.turn.turnId = 'edited-turn'; + next.round.turnId = 'edited-turn'; + next.round.id = 'edited-round'; + next.item.data.id = 'edited-text'; + next.id = 'item/edited-text'; + apiMocks.relayRecord?.(next); + flowChatStore.settleRelaySessionRecords(sessionId); + expect(turnIds(sessionId)).toEqual(['turn-0', 'edited-turn']); + + // Redo/host restart supplies a new authoritative epoch. The ACK fence + // belongs to the old replica and must not become a permanent blacklist. + apiMocks.relayGap?.({ sessionId, reason: 'host stream restarted', resync: true }); + for (let turn = 0; turn < 3; turn += 1) apiMocks.relayRecord?.(itemRecord(sessionId, turn, 0, turn + 1)); + apiMocks.relayReady?.({ sessionId, hasMore: false, oldestSeq: 1, cursor: 3 }); + expect(turnIds(sessionId)).toEqual(['turn-0', 'turn-1', 'turn-2']); + }); + + it('fences a retired Turn even before this surface has opened its history subscription', async () => { + const sessionId = 'peer-rollback-before-open'; + activateSurface(PEER_SURFACE_ID); + seedSession(sessionId); + flowChatStore.retireRelaySessionTurns(sessionId, ['turn-1']); + apiMocks.subscribeRelaySession.mockImplementationOnce(async () => { + apiMocks.relayRecord?.(itemRecord(sessionId, 0, 0, 1)); + apiMocks.relayRecord?.(itemRecord(sessionId, 1, 0, 2)); + apiMocks.relayReady?.({ sessionId, hasMore: false, oldestSeq: 1, cursor: 2 }); + return 'subscription-after-rollback'; + }); + await flowChatStore.loadRelaySessionHistory(sessionId); + expect(turnIds(sessionId)).toEqual(['turn-0']); + + // Same local identities on a different device must remain independent. + activateSurface('another-peer'); + seedSession(sessionId); + apiMocks.subscribeRelaySession.mockImplementationOnce(async () => { + apiMocks.relayRecord?.(itemRecord(sessionId, 1, 0, 1)); + apiMocks.relayReady?.({ sessionId, hasMore: false, oldestSeq: 1, cursor: 1 }); + return 'another-peer-subscription'; + }); + await flowChatStore.loadRelaySessionHistory(sessionId); + expect(turnIds(sessionId)).toEqual(['turn-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 c970de5a7f..b3058eee3b 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -6381,6 +6381,12 @@ export class FlowChatStore { public retireRelaySessionTurns(sessionId: string, turnIds: readonly string[]): void { const surface = this.activeSurface; if (surface.surfaceId === 'local' || turnIds.length === 0) return; + let replica = surface.relaySessionRecords.get(sessionId); + if (!replica) { + replica = new SessionRecordReplica(sessionId); + surface.relaySessionRecords.set(sessionId, replica); + } + replica.retireTurns(turnIds); const retired = new Set(turnIds); const pending = surface.relayPendingRecordTurns.get(sessionId); if (pending) { diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index b0e2f10bcc..e6017af02b 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -226,6 +226,16 @@ listener alone recovers an interaction emitted before attachment. Rollback remains an explicit runtime operation; it never falls back to a controller-local mutation. Never log catalog preview text. + A successful targeted rollback confirms the pre-request suffix even when + an older host omits `retiredTurnIds` or supplies only active/queued IDs. + Capture that suffix's stable identities from materialized Turns and the + catalog before invoking; after completion remove them and their send + previews before reporting success or submitting the edited prompt. Do not + delete by storage index after the response: a new Turn may reuse that slot. + Fence delayed records in the surface's replica until the host supplies its + real tombstone revision or starts a new authoritative replay. This must not + blacklist another device's equal IDs or prevent host-authoritative redo. + 15. **Git ownership trust is read on the peer, granted at the machine.** `git_get_repository_trust` is a read-only probe and routes to the peer host. `git_trust_repository` writes the peer user's global Git