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
9 changes: 9 additions & 0 deletions src/web-ui/AGENTS-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 连接验证。
10 changes: 10 additions & 0 deletions src/web-ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
77 changes: 75 additions & 2 deletions src/web-ui/src/flow_chat/services/SessionRollbackService.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => ({
Expand Down Expand Up @@ -34,14 +34,15 @@ 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,
} from './submittedMessagePresentation';
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' }))
Expand Down Expand Up @@ -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.
Expand Down
66 changes: 52 additions & 14 deletions src/web-ui/src/flow_chat/services/SessionRollbackService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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';
Expand All @@ -41,10 +41,11 @@ export interface RollbackSessionToTurnResult {
composerText?: string;
}

async function reloadAuthoritativeSession(sessionId: string): Promise<void> {
async function reloadAuthoritativeSession(sessionId: string, scope: SurfaceScope): Promise<void> {
await flowChatStore.loadSessionHistory(sessionId, {
deferFullHistoryUntilActive: true,
});
scope.assertCurrent('finish rollback history reload');
completeSessionMutationReconciliation(sessionId);
}

Expand Down Expand Up @@ -82,14 +83,40 @@ function validProjectedCatalogRevision(
return coversProjectedTurns ? catalog.revision : undefined;
}

function projectedRollbackTurnIds(
session: Session,
historyView: SessionHistoryViewState | undefined,
targetTurnId: string,
boundaryStorageTurnIndex: number | undefined,
): Set<string> {
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<RollbackSessionToTurnResult> {
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
Expand All @@ -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) {
Expand All @@ -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');
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
33 changes: 33 additions & 0 deletions src/web-ui/src/flow_chat/session-stream/SessionRecordReplica.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
private readonly tombstonedTurns = new Set<string>();

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;
}
}
Loading
Loading