Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,25 @@ no pending ticket; errors/cancellation require a new reader action rather than
a render-driven retry loop. Exhaustion is forgotten when its window/boundary
changes. Session instances isolate the controller across session switches.

Explicit source synchronization reserves the pager's presentation commit before
reading the host: publishing the snapshot can move the rendered boundary, and
must not cancel its own retry ticket. A cancelled request clears only its own
loading state, fenced by the request slot, surface, Session and presentation
owner. Errors remain retryable. Recovery accepts a changed host catalog revision
even when its previews are incomplete; a cached complete catalog from an older
revision cannot override that response. Same-revision complete previews and the
ordinary Peer snapshot merge policy remain intact.

An adjacent read can adopt a newer catalog and retire the store's active range
even when its stale-response retry returns ready. The container reacquires the
displayed reader range and confirms the adjacent page again before preparing
the viewport. This uses the existing window reader and cache, not a full-history
reload. Catalog, navigation-generation or range changes during preparation
cancel the old commit and leave the boundary available for fresh reader demand.
Repeated invalidation does not start a recursive retry. Actual read failures
retain the displayed content and expose explicit synchronization; the error
sentinel restores pointer interaction so its recovery button can be clicked.

Opening and follow-output guards remain synchronous (`isFollowingOutputNow`),
so the gesture that releases follow is evaluated against the new owner. Geometry
with no visible range remains a diagnostic refusal. Request/refusal diagnostics
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ each missing what the other had.
| `flowChatViewportGeometry.test.ts` | actual gutter centring, symmetric/omitted leading gutter and origin handoff without accumulated horizontal offset |
| `../../services/RelaySessionHistory.test.ts`, `../../store/FlowChatStore.test.ts`, `../../services/flow-chat-manager/SessionModule.test.ts` | local/SSH one-Turn restore, paint-gated adjacent prefetch without tail replacement, partial reopen without full-history drain, replay staging, live updates during older reads, failed-read retention and retry; transport fixtures, not live remote evidence |
| `flowChatHistoryPager.test.ts` | request/layout ordering, coalesced demand, prefetch without physical arrival, stale tickets, exhaustion and retry eligibility |
| `../../store/FlowChatStore.test.ts`, `ModernFlowChatContainer.history-restore.test.tsx` | explicit retry reserves the commit before a host snapshot moves the boundary; cancelled synchronization success/failure releases its loading state; changed host revisions replace stale complete catalogs while same-revision complete previews survive; controlled IO/pager fixtures, not live remote evidence |
| `useFlowChatViewportOwner.test.tsx` | top/native coordinate conversion, older-range growth creates no reader demand, synchronous write/shift accounting preserves reader travel and actual clamping |
| `flowChatLiveTailWindow.test.ts` | "does the transcript still reach the newest Turn" |
| `flowChatViewportAnchor.test.ts` | anchor geometry and the DOM contract |
Expand All @@ -72,7 +73,8 @@ each missing what the other had.
| `FlowChatOpeningBoundary.test.tsx` | opening-only activation/scroll isolation, bidirectional focus skipping, programmatic focus return, and reveal cleanup; DOM contracts only |
| `HistorySessionLoadingBoundary.test.tsx` | shared 200 ms indicator delay, immediate settled cold/warm opens, off-screen user-message independence, settled-viewport gating, atomic text/tools/code presentation, interaction blocking, session/device cancellation, failure/inactive/resume/reduced-motion handling and no streaming/remount replay; DOM/animation fixtures, not native paint or live remote evidence |
| `ModernFlowChatContainer.history-state.test.tsx` | history presentation and the submission event |
| `ModernFlowChatContainer.history-restore.test.tsx` | production container/loading boundary with controlled history IO: rollback with/without an intermediate hydration commit, empty history, retired legacy snapshots/bookmarks, cold host transfer, pending-read cancellation, navigation takeover, late success/failure, retry, deliberately empty internal projections with accessible earlier history, and Session switching on local/simulated Peer surfaces; no native layout or live transport claim |
| `ModernFlowChatContainer.history-restore.test.tsx` | production container/loading boundary with controlled history IO: rollback with/without an intermediate hydration commit, empty history, retired legacy snapshots/bookmarks, cold host transfer, pending-read cancellation, navigation takeover, late success/failure, retry, deliberately empty internal projections with accessible earlier history, and Session switching; catalog retirement during before/after paging and explicit synchronization on local/simulated SSH/Peer surfaces, preparation invalidation and late/repeated recovery cancellation; no native layout or live transport claim |
| `VirtualMessageList.history-paging.test.ts` | compiled status CSS keeps idle/loading sentinels passive and exposes pointer interaction for visible error recovery; DOM/CSS fixture, not native hit testing |
| `flowChatViewportOwnership.test.ts` | the priority order, preemption, expiry |
| `useFlowChatVirtualizer.test.ts` | the offsets-and-positions boundary |
| `useFlowChatVirtualizer.measurement.test.tsx` | `measureRenderedItems` against a real virtualizer, fractional normal-flow sizes and offscreen size reservations across reflow |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ const fixture = vi.hoisted(() => ({
extend: vi.fn(),
present: null as ((sessionId: string, presentation: SessionHistoryPresentation) => void) | null,
loadedRanges: [] as SessionHistoryViewState['loadedRanges'],
navigationGeneration: 1,
}));
vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: {
getState: () => ({ activeSessionId: fixture.session?.sessionId, sessions: new Map(fixture.session ? [[fixture.session.sessionId, fixture.session]] : []) }),
retainSessionHistory: () => () => {},
subscribeSelector: () => () => {},
getSessionHistoryViewState: () => ({
catalog: fixture.session?.turnCatalog ?? null, loadedRanges: fixture.loadedRanges, activeRange: fixture.cached?.range ?? null,
navigationGeneration: fixture.navigationGeneration,
}),
synchronizeSessionHistory: (...args: unknown[]) => fixture.synchronize(...args),
reactivateSessionHistoryWindow: () => fixture.cached,
Expand Down Expand Up @@ -95,6 +97,7 @@ vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: {
} }));

import { ModernFlowChatContainer } from './ModernFlowChatContainer';
import { FlowChatHistoryPager } from './flowChatHistoryPager';
import { registerConversationReader, stageConversationViewTransfer } from './flowChatViewHandoff';
import { activateSurface, getActiveSurfaceScope, LOCAL_SURFACE_ID } from '@/infrastructure/peer-device/deviceSurface';

Expand Down Expand Up @@ -165,13 +168,15 @@ describe('FlowChat reader restoration across history rewrites', () => {
activateSurface(LOCAL_SURFACE_ID);
fixture.session = session();
fixture.cached = presentation();
fixture.restore.mockResolvedValue(null);
fixture.extend.mockReturnValue(null);
fixture.restore.mockReset().mockResolvedValue(null);
fixture.extend.mockReset().mockReturnValue(null);
fixture.loadTurnWindow.mockReset();
fixture.synchronize.mockResolvedValue(undefined);
fixture.listProps = null;
fixture.viewportSettled = true;
fixture.present = null;
fixture.loadedRanges = [];
fixture.navigationGeneration = 1;
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener() {}, removeEventListener() {} }));
host = document.createElement('div');
document.body.append(host);
Expand Down Expand Up @@ -293,6 +298,87 @@ describe('FlowChat reader restoration across history rewrites', () => {
expect(fixture.restore).not.toHaveBeenCalled();
});

it('keeps the retry ticket when the host snapshot moves the rendered boundary', async () => {
stageBookmark();
await render();
const pager = new FlowChatHistoryPager();
pager.commitLayout('4:8', { before: 'turn-4', after: 'turn-7' });
const ticket = pager.begin('before')!;
const read = deferred<void>();
fixture.synchronize.mockReturnValueOnce(read.promise);
fixture.loadTurnWindow.mockResolvedValue({ status: 'ready', isCurrent: true });
fixture.extend.mockReturnValue(presentation(0, 8));
let request!: Promise<unknown>;
await act(async () => {
request = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
synchronizeHistory: true, isCurrent: () => pager.isCurrent(ticket),
prepareViewportForPresentationCommit: () => pager.prepareCommit(ticket),
});
});
pager.commitLayout('3:8', { before: 'turn-3', after: 'turn-7' });
await act(async () => {
read.resolve();
expect(await request).toBe('applied');
});
expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle');
expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull();
});

it.each(['resolve', 'reject'] as const)('settles loading when a synchronization ticket is cancelled before %s', async settlement => {
stageBookmark();
await render();
const read = deferred<void>();
fixture.synchronize.mockReturnValueOnce(read.promise);
let current = true;
let request!: Promise<unknown>;
await act(async () => {
request = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
synchronizeHistory: true, isCurrent: () => current,
});
});
expect(fixture.listProps!.historyBoundaryState?.before).toBe('loading');
current = false;
await act(async () => {
if (settlement === 'reject') read.reject(new Error('Read failed after cancellation'));
else read.resolve();
expect(await request).toBe('cancelled');
});
expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle');
});

it('does not clear a newer retry when a cancelled synchronization fails late', async () => {
stageBookmark();
await render();
const first = deferred<void>();
const second = deferred<void>();
fixture.synchronize.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
let firstCurrent = true;
let older!: Promise<unknown>;
let newer!: Promise<unknown>;
await act(async () => {
older = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
synchronizeHistory: true, isCurrent: () => firstCurrent,
});
});
firstCurrent = false;
await act(async () => {
newer = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
synchronizeHistory: true, isCurrent: () => true,
});
});
await act(async () => {
first.reject(new Error('Superseded source read failed'));
expect(await older).toBe('cancelled');
});
expect(fixture.listProps!.historyBoundaryState?.before).toBe('loading');
await act(async () => {
second.reject(new Error('Owning host unavailable'));
expect(await newer).toBe('not-ready');
});
expect(fixture.listProps!.historyBoundaryState?.before).toBe('error');
expect(host.querySelector('[data-turn-id="turn-4"]')).not.toBeNull();
});

it.each([false, true])('retries an orphaned reader after a failed read (explicit sync: %s)', async synchronizeHistory => {
const window = presentation(3, 7);
fixture.cached = window;
Expand Down Expand Up @@ -324,6 +410,165 @@ describe('FlowChat reader restoration across history rewrites', () => {
expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull();
});

it.each((['local', 'ssh', 'peer-device'] as const).flatMap(location =>
(['before', 'after'] as const).flatMap(direction =>
[false, true].map(synchronizeHistory => ({ location, direction, synchronizeHistory })),
),
))(
'recovers a catalog retired during $direction paging on $location (explicit sync: $synchronizeHistory)', async ({ location, direction, synchronizeHistory }) => {
if (location === 'peer-device') activateSurface('peer-device');
const withCatalog = (revision: string): Session => ({
...sessionWithCatalog(42, revision),
...(location === 'ssh' ? { remoteConnectionId: 'ssh-target', remoteSshHost: 'build-host' } : {}),
});
fixture.session = withCatalog('before-live-turn');
const window = presentation(38, 40);
fixture.cached = window;
stageBookmark(window);
await render();
fixture.restore.mockImplementation(async () => {
fixture.cached = window;
fixture.navigationGeneration += 1;
return window;
});
fixture.loadTurnWindow.mockImplementationOnce(async () => {
// Stale-response retry succeeds under a new catalog, but the old
// reader window was retired while this request was in flight.
fixture.cached = null;
fixture.navigationGeneration += 1;
fixture.session = withCatalog('after-live-turn');
return { status: 'ready', isCurrent: true };
}).mockResolvedValueOnce({ status: 'ready', isCurrent: true });
const extended = direction === 'before' ? presentation(34, 40) : presentation(38, 42);
fixture.extend.mockImplementation(() => {
if (!fixture.cached) return null;
fixture.cached = extended;
return extended;
});
const prepare = vi.fn(() => true);
let outcome: unknown;
await act(async () => {
outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!(direction, {
synchronizeHistory, prepareViewportForPresentationCommit: prepare,
});
});
expect(outcome).toBe('applied');
expect(prepare).toHaveBeenCalledTimes(1);
expect(host.querySelector(`[data-turn-id="turn-${extended.range.startOrdinal}"]`)).not.toBeNull();
expect(fixture.restore).toHaveBeenCalledTimes(1);
expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(2);
expect(fixture.synchronize).toHaveBeenCalledTimes(synchronizeHistory ? 1 : 0);
},
);

it.each(['catalog', 'navigation', 'range'] as const)(
'cancels a page superseded by a %s change during viewport preparation', async change => {
fixture.session = sessionWithCatalog(42, 'before-preparation');
const window = presentation(38, 40);
fixture.cached = window;
stageBookmark(window);
await render();
fixture.loadTurnWindow.mockResolvedValue({ status: 'ready', isCurrent: true });
const cancel = vi.fn();
let outcome: unknown;
await act(async () => {
outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
prepareViewportForPresentationCommit: async () => {
if (change === 'catalog') fixture.session = sessionWithCatalog(42, 'after-preparation');
if (change === 'navigation') fixture.navigationGeneration += 1;
if (change === 'range') fixture.cached = null;
return true;
},
cancelViewportPresentationCommit: cancel,
});
});
expect(outcome).toBe('cancelled');
expect(cancel).toHaveBeenCalledTimes(1);
expect(fixture.extend).not.toHaveBeenCalled();
expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle');
expect(host.querySelector('[data-turn-id="turn-38"]')).not.toBeNull();
},
);

it('leaves a failed post-read recovery retryable without replacing the reader', async () => {
fixture.session = sessionWithCatalog(42, 'before-live-turn');
const window = presentation(38, 40);
fixture.cached = window;
stageBookmark(window);
await render();
fixture.loadTurnWindow.mockImplementationOnce(async () => {
fixture.cached = null;
return { status: 'ready', isCurrent: true };
}).mockResolvedValue({ status: 'ready', isCurrent: true });
fixture.restore.mockRejectedValueOnce(new Error('History read timed out'));
let outcome: unknown;
await act(async () => { outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before'); });
expect(outcome).toBe('not-ready');
expect(fixture.listProps!.historyBoundaryState?.before).toBe('error');
expect(host.querySelector('[data-turn-id="turn-38"]')).not.toBeNull();
fixture.restore.mockImplementation(async () => { fixture.cached = window; return window; });
fixture.extend.mockReturnValue(presentation(34, 40));
await act(async () => {
outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { synchronizeHistory: true });
});
expect(outcome).toBe('applied');
expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle');
expect(host.querySelector('[data-turn-id="turn-34"]')).not.toBeNull();
});

it.each(['resolve', 'reject'] as const)('ignores a late post-read recovery %s after changing devices', async settlement => {
const window = presentation(38, 40);
fixture.session = sessionWithCatalog(42, 'before-live-turn');
fixture.cached = window;
stageBookmark(window);
await render();
fixture.loadTurnWindow.mockImplementationOnce(async () => {
fixture.cached = null;
return { status: 'ready', isCurrent: true };
});
const read = deferred<SessionHistoryPresentation | null>();
fixture.restore.mockReturnValueOnce(read.promise);
const prepare = vi.fn(() => true);
let outcome!: Promise<unknown>;
await act(async () => {
outcome = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', {
prepareViewportForPresentationCommit: prepare,
});
});
expect(fixture.restore).toHaveBeenCalledTimes(1);
activateSurface('peer-device');
await act(async () => {
if (settlement === 'resolve') read.resolve(window);
else read.reject(new Error('Retired recovery failed'));
await outcome;
});
expect(await outcome).toBe('cancelled');
expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(1);
expect(fixture.extend).not.toHaveBeenCalled();
expect(prepare).not.toHaveBeenCalled();
});

it('cancels repeated catalog retirement instead of recursively retrying the page', async () => {
const window = presentation(38, 40);
fixture.session = sessionWithCatalog(42, 'before-live-turn');
fixture.cached = window;
stageBookmark(window);
await render();
fixture.loadTurnWindow.mockImplementation(async () => {
fixture.cached = null;
fixture.navigationGeneration += 1;
return { status: 'ready', isCurrent: true };
});
fixture.restore.mockImplementation(async () => { fixture.cached = window; return window; });
let outcome: unknown;
await act(async () => { outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before'); });
expect(outcome).toBe('cancelled');
expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(2);
expect(fixture.restore).toHaveBeenCalledTimes(1);
expect(fixture.extend).not.toHaveBeenCalled();
expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle');
});

it('rejects a late orphan recovery after changing devices', async () => {
const window = presentation(3, 7);
fixture.cached = window;
Expand Down
Loading
Loading