eigent/test/unit/lib/projector.test.ts

2107 lines
61 KiB
TypeScript

// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import {
completeProjectViewResync,
createProjectViewState,
deriveLiveEffects,
importIndexedDbV1,
importLegacyChatSteps,
importLocalMemoryV1,
normalizeEvent,
projectRawEvents,
projectSnapshot,
reduceProjectView,
selectPendingLegacyAsk,
selectRunArtifacts,
} from '@/lib/projector';
import { mergeRunSummary } from '@/lib/projector/runSummary';
import { describe, expect, it } from 'vitest';
function event(overrides: Record<string, unknown> = {}) {
return {
event_id: 'event-1',
project_id: 'project-1',
run_id: 'run-1',
run_sequence: 1,
run_version: 1,
cloud_cursor: 1,
event_type: 'step.created',
payload: { content: 'hello' },
legacy_step: 'activate_agent',
created_at: '2026-08-05T10:00:00Z',
...overrides,
};
}
function semanticReplayPair(step: 'decompose_text' | 'write_file') {
const narration = step === 'decompose_text';
const data = narration
? { content: 'Building the cathedral.\n' }
: { relative_path: 'cathedral.html', process_task_id: 'task-1' };
const canonical = normalizeEvent(
event({
event_type: narration ? 'activity.progress' : 'file.written',
legacy_step: step,
payload: {
semantic_schema_version: 1,
display_schema_version: 1,
semantic: {
kind: narration ? 'narration' : 'file_change',
provenance: { source: `legacy.${step}` },
},
...(narration
? {
display_title: data.content,
display_fragment_exact: true,
status: 'running',
}
: {
...data,
name: 'cathedral.html',
operation: 'written',
display_title: 'Wrote cathedral.html',
}),
},
})
);
const legacy = normalizeEvent(
{
project_id: canonical.projectId,
task_id: canonical.runId,
id: 10_000,
step,
data,
timestamp: canonical.createdAt,
},
'chat_step_v1'
);
return { canonical, legacy };
}
describe('projector pipeline', () => {
it.each([
[false, 'failed'],
[true, 'interrupted'],
] as const)(
'settles a legacy error without END as %s / %s and ignores cleanup time',
(retryable, status) => {
const steps = [
{ step: 'confirmed', timestamp: '2026-08-18T00:00:00Z', data: {} },
{
step: 'error',
timestamp: '2026-08-18T00:10:00Z',
data: { message: 'Turn failed', retryable },
},
{
step: 'deactivate_agent',
timestamp: '2026-08-18T00:11:00Z',
data: { agent_id: 'agent-1' },
},
].map((step, index) =>
normalizeEvent(
{ ...step, id: index + 1, project_id: 'project-1', task_id: 'run-1' },
'chat_step_v1'
)
);
const state = steps.reduce(
reduceProjectView,
createProjectViewState('project-1', 'replay')
);
expect(state.runs['run-1']).toMatchObject({
status,
runVersion: 0,
lastSequence: 0,
updatedAt: '2026-08-18T00:10:00.000Z',
});
expect(state.legacySteps).toHaveLength(3);
if (retryable) {
const resumed = reduceProjectView(
state,
normalizeEvent(
event({
event_type: 'run.attempt_started',
created_at: '2026-08-18T00:12:00Z',
})
)
);
expect(resumed.runs['run-1']).toMatchObject({
status: 'running',
runVersion: 1,
lastSequence: 1,
updatedAt: '2026-08-18T00:12:00.000Z',
});
}
}
);
it('keeps canonical lifecycle authority over a legacy error and subtask failure', () => {
const running = reduceProjectView(
createProjectViewState('project-1', 'replay'),
normalizeEvent(event({ event_type: 'run.attempt_started' }))
);
const legacyError = normalizeEvent(
{
project_id: 'project-1',
task_id: 'run-1',
id: 10_000,
step: 'error',
timestamp: '2026-08-18T00:10:00Z',
data: { message: 'Old failure', retryable: false },
},
'chat_step_v1'
);
const state = reduceProjectView(running, legacyError);
expect(state.runs['run-1']).toEqual(running.runs['run-1']);
const subtaskFailure = reduceProjectView(
createProjectViewState('project-1', 'replay'),
{ ...legacyError, legacyStep: 'failed' }
);
expect(subtaskFailure.runs['run-1'].status).toBe('running');
});
it.each(['decompose_text', 'write_file'] as const)(
'pairs semantic %s mirrors in either arrival order without dropping repeated steps',
(step) => {
const { canonical, legacy } = semanticReplayPair(step);
const secondCanonical = {
...canonical,
eventId: 'event-2',
runSequence: 2,
runVersion: 2,
cloudCursor: 2,
};
const secondLegacy = {
...legacy,
eventId: 'legacy-2',
payload: { ...legacy.payload, __legacy_step_id: 10_001 },
};
for (const inputs of [
[canonical, secondCanonical, legacy, secondLegacy],
[legacy, secondLegacy, canonical, secondCanonical],
[legacy, canonical, secondLegacy, secondCanonical],
]) {
const state = inputs.reduce(
reduceProjectView,
createProjectViewState('project-1', 'live')
);
expect(state.legacySteps).toHaveLength(2);
expect(
state.legacySteps.map((item) => item.crossLaneEventIds?.length)
).toEqual([1, 1]);
expect(
state.legacySteps.every((item) => item.source === 'canonical')
).toBe(true);
expect(
state.legacySteps.map((item) => item.runSequence).sort()
).toEqual([1, 2]);
expect(Object.keys(state.seenEventIds)).toHaveLength(4);
expect(state.runs['run-1'].lastSequence).toBe(2);
}
}
);
it.each([
'different content',
'different run',
'outside time window',
'different provenance',
'different path',
'missing path',
'different subtask',
])('keeps unmatched semantic replay events: %s', (difference) => {
const { canonical, legacy } = semanticReplayPair(
['different path', 'missing path', 'different subtask'].includes(
difference
)
? 'write_file'
: 'decompose_text'
);
if (difference === 'different content')
canonical.payload.display_title = 'Finished.';
if (difference === 'different run') canonical.runId = 'other-run';
if (difference === 'outside time window')
canonical.createdAt = '2026-08-05T10:03:00Z';
if (difference === 'different provenance')
canonical.payload.semantic = { kind: 'narration' };
if (difference === 'different path')
canonical.payload.relative_path = 'other/cathedral.html';
if (difference === 'missing path') delete canonical.payload.relative_path;
if (difference === 'different subtask')
canonical.payload.process_task_id = 'task-2';
const state = [canonical, legacy].reduce(
reduceProjectView,
createProjectViewState('project-1', 'rehydrate')
);
expect(state.legacySteps).toHaveLength(2);
});
it.each(['canonical-first', 'legacy-first'] as const)(
'preserves the canonical completion timestamp with a large legacy step id (%s)',
(order) => {
const canonical = normalizeEvent(
event({
event_type: 'run.completed',
legacy_step: null,
created_at: '2026-08-05T11:00:00Z',
})
);
const legacy = normalizeEvent(
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 10_000,
step: 'end',
data: { content: 'Saved historical result' },
timestamp: '2026-08-05T10:30:00Z',
},
'chat_step_v1'
);
const inputs =
order === 'canonical-first' ? [canonical, legacy] : [legacy, canonical];
const state = inputs.reduce(
reduceProjectView,
createProjectViewState('project-1', 'rehydrate')
);
expect(state.runs['run-1']).toMatchObject({
status: 'completed',
runVersion: 1,
lastSequence: 1,
updatedAt: '2026-08-05T11:00:00.000Z',
});
}
);
it('tracks why a Run waits for its Space writer until it gets it', () => {
const writer = (
sequence: number,
eventType: string,
payload: Record<string, unknown>
) =>
normalizeEvent(
event({
event_id: `writer-${sequence}`,
event_type: eventType,
legacy_step: null,
run_sequence: sequence,
run_version: sequence,
cloud_cursor: sequence,
payload,
})
);
const queued = reduceProjectView(
createProjectViewState('project-1', 'live'),
writer(1, 'workspace.writer.queued', { reason: 'task.mutating_default' })
);
expect(queued.runs['run-1'].writerWait).toEqual({
holderNeedsAttention: false,
});
const blocked = reduceProjectView(
queued,
writer(2, 'workspace.writer.queued', {
reason: 'holder_requires_attention',
semantic: {
correlation: {
blocker_run_id: 'run-0',
blocker_project_id: 'project-0',
blocker_reason: 'unknown_tool_outcome',
},
},
})
);
expect(blocked.runs['run-1'].writerWait).toEqual({
holderNeedsAttention: true,
blockerProjectId: 'project-0',
});
const attempt = reduceProjectView(
blocked,
writer(3, 'run.attempt_created', {})
);
expect(attempt.runs['run-1'].writerWait).toBe(
blocked.runs['run-1'].writerWait
);
const acquired = reduceProjectView(
attempt,
writer(4, 'workspace.writer.acquired', { waited: true })
);
expect(acquired.runs['run-1'].writerWait).toBeNull();
});
it('continues updating canonical lifecycle timestamps after legacy replay', () => {
const running = normalizeEvent(
event({ event_type: 'run.running', legacy_step: null })
);
const legacy = normalizeEvent(
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 10_000,
step: 'end',
data: { content: 'Saved historical result' },
timestamp: '2026-08-05T10:30:00Z',
},
'chat_step_v1'
);
const replayed = [running, legacy].reduce(
reduceProjectView,
createProjectViewState('project-1', 'rehydrate')
);
expect(replayed.runs['run-1']).toMatchObject({
status: 'running',
updatedAt: '2026-08-05T10:00:00.000Z',
});
const completed = reduceProjectView(
replayed,
normalizeEvent(
event({
event_id: 'event-2',
event_type: 'run.completed',
legacy_step: null,
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
created_at: '2026-08-05T11:00:00Z',
})
)
);
expect(completed.runs['run-1']).toMatchObject({
status: 'completed',
runVersion: 2,
lastSequence: 2,
updatedAt: '2026-08-05T11:00:00.000Z',
});
});
it('keeps established Run origin immutable and fails closed on conflicts', () => {
const cloud = reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event({ origin: 'cloud_restore' }))
);
const conflicted = reduceProjectView(
cloud,
normalizeEvent(
event({
event_id: 'event-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
origin: 'local',
})
)
);
expect(conflicted.runs['run-1']?.origin).toBe('cloud_restore');
expect(conflicted.needsResync).toBe(true);
expect(conflicted.resyncReason).toBe(
'run_origin_conflict:run-1:cloud_restore:local'
);
});
it('allows one authoritative origin to fill an initially unknown Run', () => {
const unknown = reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event())
);
const local = reduceProjectView(
unknown,
normalizeEvent(
event({
event_id: 'event-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
origin: 'local',
})
)
);
expect(unknown.runs['run-1']?.origin).toBeNull();
expect(local.runs['run-1']?.origin).toBe('local');
expect(local.needsResync).toBe(false);
});
it('lets a snapshot aggregate correct newer buffered provenance', () => {
const previous = projectRawEvents(
'project-1',
[
event({
event_id: 'local-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
origin: 'local',
}),
],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
runs: [
{
run_id: 'run-1',
status: 'running',
expected_next_run_sequence: 2,
run_version: 1,
updated_at: '2026-08-05T10:00:00Z',
origin: 'cloud_restore',
},
],
recent_events: [],
},
previous
);
expect(snapshot.runs['run-1']).toMatchObject({
lastSequence: 2,
origin: 'cloud_restore',
});
});
it('treats an explicit unknown snapshot origin as fail-closed authority', () => {
const previous = projectRawEvents(
'project-1',
[
event({
event_id: 'local-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
origin: 'local',
}),
],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
runs: [
{
run_id: 'run-1',
status: 'running',
expected_next_run_sequence: 2,
run_version: 1,
updated_at: '2026-08-05T10:00:00Z',
origin: null,
},
],
recent_events: [],
},
previous
);
expect(snapshot.runs['run-1']?.origin).toBeNull();
});
it('preserves established provenance when an older snapshot omits origin', () => {
const previous = projectRawEvents(
'project-1',
[
event({
event_id: 'local-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
origin: 'local',
}),
],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
runs: [
{
run_id: 'run-1',
status: 'running',
expected_next_run_sequence: 2,
run_version: 1,
updated_at: '2026-08-05T10:00:00Z',
},
],
recent_events: [],
},
previous
);
expect(snapshot.runs['run-1']?.origin).toBe('local');
});
it('deduplicates by event ID without changing object identity', () => {
const normalized = normalizeEvent(event());
const initial = createProjectViewState('project-1', 'live');
const first = reduceProjectView(initial, normalized);
const duplicate = reduceProjectView(first, normalized);
expect(duplicate).toBe(first);
expect(first.legacySteps).toHaveLength(1);
expect(first.currentCursor).toBe(1);
});
it('restores durable Artifacts outside the bounded snapshot event tail', () => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 100,
recent_events: [
event({
event_id: 'recent-100',
cloud_cursor: 100,
run_sequence: 100,
}),
],
artifact_events: [
event({
event_id: 'manifest-1',
cloud_cursor: 1,
event_type: 'artifact.manifest.finalized',
legacy_step: null,
payload: {
artifacts: [
{
artifact_id: 'artifact-1',
filename: 'report.csv',
relativePath: 'reports/report.csv',
changeType: 'generated',
uploadPolicy: 'agent_generated',
localPathAvailable: false,
},
],
},
}),
event({
event_id: 'upload-1',
cloud_cursor: 2,
run_sequence: 2,
event_type: 'artifact.uploaded',
legacy_step: null,
payload: {
artifact_id: 'artifact-1',
asset_ref: {
chat_file_id: 7,
bucket: 'assets',
key: 'reports/report.csv',
},
},
}),
],
events_truncated: true,
});
expect(snapshot.needsResync).toBe(false);
expect(selectRunArtifacts(snapshot, 'run-1')).toEqual([
expect.objectContaining({
artifactId: 'artifact-1',
assetRef: expect.objectContaining({
chatFileId: 7,
key: 'reports/report.csv',
}),
}),
]);
});
it('preserves recovery output through legacy cancellation rescans and unfreezes on a new Attempt', () => {
const make = (seq: number, type: string, payload = {}) =>
event({
event_id: `recovery-${seq}`,
run_sequence: seq,
run_version: seq,
cloud_cursor: seq,
event_type: type,
legacy_step: null,
payload,
});
const original = make(1, 'artifact.manifest.finalized', {
artifacts: [
{ artifact_id: 'note', relativePath: 'note.md', filename: 'note.md' },
],
scan_status: 'complete',
truncated: false,
});
const empty = make(4, 'artifact.manifest.finalized', {
artifacts: [],
scan_status: 'complete',
truncated: false,
});
const history = [
original,
make(2, 'runtime.interrupted'),
make(3, 'run.cancel_requested'),
empty,
make(5, 'run.cancelled'),
];
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 5,
recent_events: history,
artifact_events: [empty],
});
expect(
selectRunArtifacts(snapshot, 'run-1').map((item) => item.name)
).toEqual(['note.md']);
expect(snapshot.artifactManifestsByRun?.['run-1'].runSequence).toBe(4);
const resumed = projectRawEvents(
'project-1',
[
original,
make(2, 'runtime.interrupted'),
make(3, 'run.attempt_created'),
make(4, 'run.attempt_started'),
make(5, 'artifact.manifest.finalized', {
artifacts: [],
scan_status: 'complete',
}),
],
'rehydrate'
).state;
expect(selectRunArtifacts(resumed, 'run-1')).toEqual([]);
});
it.each(['complete', 'partial', 'unavailable'] as const)(
'retains a frozen %s manifest and interruption clock across legacy replay and hydration',
(scanStatus) => {
const { canonical, legacy } = semanticReplayPair('write_file');
const manifest = event({
event_id: 'manifest-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
event_type: 'artifact.manifest.finalized',
legacy_step: null,
created_at: '2026-08-05T10:00:01Z',
payload:
scanStatus === 'unavailable'
? {}
: {
artifacts:
scanStatus === 'partial'
? [
{
artifact_id: 'file-1',
relativePath: 'cathedral.html',
},
]
: [],
scan_status: scanStatus,
truncated: scanStatus === 'partial',
},
});
const interrupted = event({
event_id: 'interrupted-3',
run_sequence: 3,
run_version: 3,
cloud_cursor: 3,
event_type: 'runtime.interrupted',
legacy_step: null,
created_at: '2026-08-05T10:00:02Z',
payload: {},
});
const history = [canonical, manifest, interrupted];
const previous = projectRawEvents(
'project-1',
history,
'rehydrate'
).state;
const replayed = projectRawEvents(
'project-1',
[
{ ...legacy, createdAt: '2026-08-05T10:00:03Z' },
normalizeEvent(
{
project_id: 'project-1',
task_id: 'run-1',
id: 20_000,
step: 'error',
data: { message: 'Late legacy failure' },
timestamp: '2026-08-05T10:00:04Z',
},
'chat_step_v1'
),
],
'rehydrate',
previous
).state;
const hydrated = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 3,
recent_events: history,
artifact_events: [manifest],
},
replayed
);
for (const state of [replayed, hydrated]) {
expect(state.runs['run-1']).toMatchObject({
status: 'interrupted',
runVersion: 3,
lastSequence: 3,
updatedAt: '2026-08-05T10:00:02.000Z',
});
expect(state.artifactManifestsByRun?.['run-1']).toMatchObject({
scanStatus,
truncated: scanStatus === 'partial',
frozenAfterInterruption: true,
});
expect(selectRunArtifacts(state, 'run-1')).toHaveLength(
scanStatus === 'partial' ? 1 : 0
);
const fileSteps = state.legacySteps.filter(
(step) => step.step === 'write_file'
);
expect(fileSteps).toHaveLength(1);
expect(fileSteps[0]).toMatchObject({
source: 'canonical',
crossLaneEventIds: [legacy.eventId],
});
}
}
);
it('clears a frozen recovery manifest when a newer snapshot includes Resume', () => {
const make = (seq: number, type: string, payload = {}) =>
event({
event_id: `resume-${seq}`,
run_sequence: seq,
run_version: seq,
cloud_cursor: seq,
event_type: type,
legacy_step: null,
payload,
});
const original = make(1, 'artifact.manifest.finalized', {
artifacts: [
{ artifact_id: 'old', relativePath: 'old.md', filename: 'old.md' },
],
scan_status: 'complete',
truncated: false,
});
const interrupted = make(2, 'runtime.interrupted');
const previous = projectRawEvents(
'project-1',
[original, interrupted],
'rehydrate'
).state;
const resumed = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 3,
recent_events: [original, interrupted, make(3, 'run.attempt_started')],
artifact_events: [original],
},
previous
);
expect(
resumed.artifactManifestsByRun?.['run-1'].frozenAfterInterruption
).toBe(false);
const cancelled = projectRawEvents(
'project-1',
[
make(4, 'run.cancel_requested'),
make(5, 'artifact.manifest.finalized', {
artifacts: [
{ artifact_id: 'old', relativePath: 'old.md', filename: 'old.md' },
{ artifact_id: 'new', relativePath: 'new.md', filename: 'new.md' },
],
scan_status: 'complete',
truncated: false,
}),
make(6, 'run.cancelled'),
],
'live',
resumed
).state;
expect(
selectRunArtifacts(cancelled, 'run-1').map((item) => item.name)
).toEqual(['old.md', 'new.md']);
});
it('keeps a newer empty manifest when an older snapshot is replayed', () => {
const finalized = (
seq: number,
artifacts: unknown[],
status = 'complete'
) =>
event({
event_id: `manifest-${seq}`,
run_sequence: seq,
run_version: seq,
cloud_cursor: seq,
event_type: 'artifact.manifest.finalized',
legacy_step: null,
payload: { artifacts, scan_status: status, truncated: false },
});
const previous = projectRawEvents(
'project-1',
[finalized(20, [])],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 10,
recent_events: [],
artifact_events: [
finalized(10, [
{ artifact_id: 'old', relativePath: 'old.md', filename: 'old.md' },
]),
],
},
previous
);
expect(snapshot.artifactsByRun['run-1']).toEqual([]);
expect(snapshot.artifactManifestsByRun?.['run-1']).toMatchObject({
runSequence: 20,
scanStatus: 'complete',
truncated: false,
});
});
it('retains scan completeness separately from an empty artifact list', () => {
const state = projectRawEvents(
'project-1',
[
event({
event_type: 'artifact.manifest.finalized',
legacy_step: null,
payload: {
artifacts: [],
scan_status: 'unavailable',
truncated: true,
},
}),
],
'rehydrate'
).state;
expect(state.artifactsByRun['run-1']).toEqual([]);
expect(state.artifactManifestsByRun?.['run-1']).toMatchObject({
scanStatus: 'unavailable',
truncated: true,
});
});
it('does not treat a malformed missing artifact list as authoritative empty', () => {
const state = projectRawEvents(
'project-1',
[event({ event_type: 'artifact.manifest.finalized', payload: {} })],
'rehydrate'
).state;
expect(state.artifactManifestsByRun?.['run-1'].scanStatus).toBe(
'unavailable'
);
});
it('retains uploaded asset metadata when the same manifest is restored again', () => {
const finalized = event({
event_type: 'artifact.manifest.finalized',
legacy_step: null,
payload: {
artifacts: [
{
artifact_id: 'file-1',
relativePath: 'report.md',
filename: 'report.md',
},
],
},
});
const previous = projectRawEvents(
'project-1',
[
finalized,
event({
event_id: 'upload',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
event_type: 'artifact.uploaded',
payload: {
artifact_id: 'file-1',
asset_ref: { chat_file_id: 7, bucket: 'assets', key: 'report.md' },
},
}),
],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
recent_events: [],
artifact_events: [finalized],
},
previous
);
expect(snapshot.artifactsByRun['run-1'][0].assetRef?.chatFileId).toBe(7);
});
it('detects both Project cursor and Run sequence gaps', () => {
const first = reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event())
);
const next = reduceProjectView(
first,
normalizeEvent(
event({
event_id: 'event-3',
cloud_cursor: 3,
run_sequence: 3,
run_version: 3,
})
)
);
expect(next.needsResync).toBe(true);
expect(next.resyncReason).toContain('run_sequence_gap');
expect(next.currentCursor).toBe(1);
expect(next.resyncTargetCursor).toBe(3);
expect(next.seenEventIds['event-3']).toBeUndefined();
expect(next.legacySteps).toHaveLength(1);
});
it('replays a cursor gap from the last contiguous cursor', () => {
const initial = reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event())
);
const gap = reduceProjectView(
initial,
normalizeEvent(
event({ event_id: 'event-3', cloud_cursor: 3, run_sequence: 3 })
)
);
const filled = reduceProjectView(
gap,
normalizeEvent(
event({ event_id: 'event-2', cloud_cursor: 2, run_sequence: 2 })
)
);
const replayed = reduceProjectView(
filled,
normalizeEvent(
event({ event_id: 'event-3', cloud_cursor: 3, run_sequence: 3 })
)
);
expect(filled.currentCursor).toBe(2);
expect(replayed.currentCursor).toBe(3);
expect(replayed.seenEventIds['event-3']).toBe(true);
const recovered = completeProjectViewResync(replayed, 3);
expect(recovered.needsResync).toBe(false);
expect(recovered.resyncReason).toBeNull();
expect(recovered.resyncTargetCursor).toBeNull();
});
it('keeps resync active until the authoritative cursor is contiguous', () => {
const state = {
...createProjectViewState('project-1', 'live'),
currentCursor: 3,
needsResync: true,
resyncReason: 'cloud_cursor_gap:4:5',
resyncTargetCursor: 5,
};
expect(completeProjectViewResync(state, 5)).toBe(state);
});
it('does not clear a concurrently observed live gap after an older delta page', () => {
const state = {
...createProjectViewState('project-1', 'live'),
currentCursor: 10,
needsResync: true,
resyncReason: 'cloud_cursor_gap:11:12',
resyncTargetCursor: 12,
};
expect(completeProjectViewResync(state, 10)).toBe(state);
});
it('does not clear a non-gap resync at a matching cursor', () => {
const state = {
...createProjectViewState('project-1', 'live'),
currentCursor: 3,
needsResync: true,
resyncReason: 'project_scope_mismatch:project-2',
resyncTargetCursor: null,
};
expect(completeProjectViewResync(state, 3)).toBe(state);
});
it('detects a missing prefix when the first live event does not start at one', () => {
const result = projectRawEvents(
'project-1',
[event({ cloud_cursor: 4, run_sequence: 3 })],
'live'
);
expect(result.state.needsResync).toBe(true);
expect(result.effects).toContainEqual({
type: 'request_resync',
reason: 'run_sequence_gap:run-1:1:3',
});
});
it('requests another resync when a later gap extends the missing range', () => {
const initial = reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event())
);
const firstGapEvent = normalizeEvent(
event({ event_id: 'event-3', cloud_cursor: 3, run_sequence: 3 })
);
const firstGap = reduceProjectView(initial, firstGapEvent);
const laterGapEvent = normalizeEvent(
event({ event_id: 'event-4', cloud_cursor: 4, run_sequence: 4 })
);
const laterGap = reduceProjectView(firstGap, laterGapEvent);
expect(
deriveLiveEffects(firstGap, laterGap, laterGapEvent, 'live')
).toEqual([
{
type: 'request_resync',
reason: 'run_sequence_gap:run-1:2:4',
},
]);
});
it('derives effects only in live mode', () => {
const normalized = normalizeEvent(
event({ event_type: 'run.completed', legacy_step: 'end' })
);
const initial = createProjectViewState('project-1', 'live');
const next = reduceProjectView(initial, normalized);
expect(deriveLiveEffects(initial, next, normalized, 'live')).toEqual([
{ type: 'scroll_to_latest', eventId: 'event-1' },
]);
expect(deriveLiveEffects(initial, next, normalized, 'rehydrate')).toEqual(
[]
);
expect(deriveLiveEffects(initial, next, normalized, 'playback')).toEqual(
[]
);
});
it('rehydrates a semantic snapshot atomically at its watermark', () => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 12,
recent_events: [event()],
events_truncated: true,
});
expect(snapshot.currentCursor).toBe(12);
expect(snapshot.eventsTruncated).toBe(true);
expect(snapshot.mode).toBe('rehydrate');
expect(snapshot.needsResync).toBe(false);
expect(snapshot.runs['run-1'].lastSequence).toBe(1);
});
it('preserves known local history when a replacement snapshot is truncated', () => {
const previous = projectRawEvents(
'project-1',
[
event(),
event({
event_id: 'event-2',
cloud_cursor: 2,
run_sequence: 2,
payload: { content: 'older local history', __legacy_step_id: 2 },
}),
],
'rehydrate'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 12,
recent_events: [
event({
event_id: 'event-12',
cloud_cursor: 12,
run_sequence: 12,
payload: { content: 'recent', __legacy_step_id: 12 },
}),
],
events_truncated: true,
},
previous
);
expect(snapshot.eventsTruncated).toBe(true);
expect(snapshot.legacySteps.map((step) => step.stepId)).toEqual([
'event-1',
2,
12,
]);
});
it('does not regress live history or cursor when a snapshot response is stale', () => {
const previous = projectRawEvents(
'project-1',
[
event(),
event({
event_id: 'event-2',
cloud_cursor: 2,
run_sequence: 2,
created_at: '2026-08-05T10:00:02Z',
payload: { __legacy_step_id: 2 },
}),
],
'live'
).state;
const staleSnapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
recent_events: [event()],
events_truncated: false,
},
previous
);
expect(staleSnapshot.currentCursor).toBe(2);
expect(staleSnapshot.legacySteps.map((step) => step.stepId)).toEqual([
'event-1',
2,
]);
expect(staleSnapshot.runs['run-1'].lastSequence).toBe(2);
});
it('does not let a stale snapshot clear a newer live gap', () => {
const gap = reduceProjectView(
reduceProjectView(
createProjectViewState('project-1', 'live'),
normalizeEvent(event({ cloud_cursor: 10, run_sequence: 1 }))
),
normalizeEvent(
event({ event_id: 'event-12', cloud_cursor: 12, run_sequence: 2 })
)
);
const staleSnapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 10,
recent_events: [],
events_truncated: true,
},
gap
);
expect(staleSnapshot.needsResync).toBe(true);
expect(staleSnapshot.resyncTargetCursor).toBe(12);
});
it('orders cross-lane steps by time instead of comparing incompatible sequences', () => {
const previous = projectRawEvents(
'project-1',
importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 100,
step: 'ask',
data: { content: 'Continue?' },
timestamp: 200,
},
]),
'live'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 2,
recent_events: [
event({
event_id: 'reply-2',
cloud_cursor: 2,
run_sequence: 2,
legacy_step: 'human_reply',
payload: { content: 'Yes' },
created_at: '2026-08-05T10:00:01Z',
}),
],
events_truncated: true,
},
previous
);
expect(snapshot.legacySteps.map((step) => step.step)).toEqual([
'ask',
'human_reply',
]);
expect(selectPendingLegacyAsk(snapshot, new Set())).toBeNull();
});
it('preserves legacy-only live history across a complete canonical snapshot', () => {
const previous = projectRawEvents(
'project-1',
[
importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 7,
step: 'ask',
data: { content: 'Continue?' },
},
])[0],
],
'live'
).state;
const snapshot = projectSnapshot(
{
project_id: 'project-1',
current_cursor: 1,
recent_events: [event()],
events_truncated: false,
},
previous
);
expect(snapshot.eventsTruncated).toBe(false);
expect(snapshot.legacySteps.map((step) => step.step)).toEqual([
'activate_agent',
'ask',
]);
expect(snapshot.legacySteps.at(-1)?.step).toBe('ask');
});
it('deduplicates canonical and legacy frames by stable step identity', () => {
const canonical = normalizeEvent(
event({ payload: { __legacy_step_id: 9, __legacy_data: { value: 1 } } })
);
const legacy = importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'activate_agent',
data: { value: 1 },
},
])[0];
const initial = createProjectViewState('project-1', 'live');
const first = reduceProjectView(initial, legacy);
const second = reduceProjectView(first, canonical);
expect(second.legacySteps).toHaveLength(1);
expect(second.seenEventIds[legacy.eventId]).toBe(true);
expect(second.seenEventIds[canonical.eventId]).toBe(true);
});
it('deduplicates the production canonical shape without a legacy step id', () => {
const createdAt = '2026-08-05T10:00:00Z';
const legacy = importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'activate_agent',
data: { value: 1 },
timestamp: Date.parse(createdAt) / 1000 + 0.01,
},
])[0];
const canonical = normalizeEvent(
event({
event_id: 'canonical-production-event',
payload: { value: 1 },
created_at: createdAt,
})
);
const initial = createProjectViewState('project-1', 'live');
const projected = reduceProjectView(
reduceProjectView(initial, legacy),
canonical
);
expect(projected.legacySteps).toHaveLength(1);
expect(projected.legacySteps[0].stepId).toBe(9);
expect(projected.legacySteps[0].crossLaneEventIds).toEqual([
'canonical-production-event',
]);
});
it('pairs repeated identical steps one-for-one across the two lanes', () => {
const createdAt = Date.parse('2026-08-05T10:00:00Z') / 1000;
const legacy = importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'activate_agent',
data: { value: 1 },
timestamp: createdAt,
},
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 10,
step: 'activate_agent',
data: { value: 1 },
timestamp: createdAt + 1,
},
]);
const canonical = [
normalizeEvent(
event({
event_id: 'canonical-1',
payload: { value: 1 },
created_at: new Date(createdAt * 1000).toISOString(),
})
),
normalizeEvent(
event({
event_id: 'canonical-2',
cloud_cursor: 2,
run_sequence: 2,
run_version: 2,
payload: { value: 1 },
created_at: new Date((createdAt + 1) * 1000).toISOString(),
})
),
];
const projected = [...legacy, ...canonical].reduce(
reduceProjectView,
createProjectViewState('project-1', 'live')
);
expect(projected.legacySteps).toHaveLength(2);
expect(
projected.legacySteps.map((step) => step.crossLaneEventIds?.length)
).toEqual([1, 1]);
});
it('deduplicates an ask across legacy and canonical lanes by content', () => {
const legacyAsk = importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'ask',
data: { content: 'Continue?', agent: 'browser' },
},
])[0];
const canonicalAsk = normalizeEvent(
event({
event_id: 'canonical-ask',
legacy_step: 'ask',
payload: { agent: 'browser', content: 'Continue?' },
})
);
const first = reduceProjectView(
createProjectViewState('project-1', 'live'),
legacyAsk
);
const second = reduceProjectView(first, canonicalAsk);
expect(second.legacySteps).toHaveLength(1);
expect(second.legacySteps[0].stepId).toBe(9);
expect(second.seenEventIds[canonicalAsk.eventId]).toBe(true);
});
it('keeps a legacy pending ask when a canonical frame arrives later', () => {
const legacyAsk = importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'ask',
data: { agent: 'browser', content: 'Continue?' },
},
])[0];
const withAsk = reduceProjectView(
createProjectViewState('project-1', 'live'),
legacyAsk
);
const afterCanonical = reduceProjectView(
withAsk,
normalizeEvent(
event({
event_id: 'canonical-2',
cloud_cursor: 1,
run_sequence: 1,
legacy_step: 'notice',
})
)
);
expect(afterCanonical.legacySteps.map((step) => step.step)).toEqual([
'ask',
'notice',
]);
expect(afterCanonical.runs['run-1'].lastSequence).toBe(1);
expect(selectPendingLegacyAsk(afterCanonical, new Set())?.stepId).toBe(9);
});
it('closes a pending ask after a durable human reply', () => {
const state = projectRawEvents(
'project-1',
importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'ask',
data: { content: 'Continue?' },
},
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 10,
step: 'human_reply',
data: { content: 'Yes' },
},
]),
'live'
).state;
expect(selectPendingLegacyAsk(state, new Set())).toBeNull();
});
it('allows the same question to be asked again after a human reply', () => {
const state = projectRawEvents(
'project-1',
importLegacyChatSteps([
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 9,
step: 'ask',
data: { content: 'Continue?' },
},
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 10,
step: 'human_reply',
data: { content: 'Yes' },
},
{
project_id: 'project-1',
task_id: 'run-1',
step_id: 11,
step: 'ask',
data: { content: 'Continue?' },
},
]),
'live'
).state;
expect(
state.legacySteps.filter((step) => step.step === 'ask')
).toHaveLength(2);
expect(selectPendingLegacyAsk(state, new Set())?.stepId).toBe(11);
});
it('uses snapshot run aggregates even when recent events are truncated', () => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 42,
runs: [
{
run_id: 'run-older',
status: 'completed',
expected_next_run_sequence: 17,
updated_at: '2026-08-05T09:00:00Z',
},
],
recent_events: [],
events_truncated: true,
});
expect(snapshot.runs['run-older']).toEqual({
runId: 'run-older',
status: 'completed',
lastSequence: 16,
runVersion: 0,
updatedAt: '2026-08-05T09:00:00Z',
origin: null,
resumeBlockedReason: null,
totalAttemptElapsedMs: null,
});
expect(snapshot.lastSyncedAt).toBeNull();
});
it.each([108_200, 0, null, -1, Number.NaN])(
'validates canonical execution time %s',
(elapsed) => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 0,
runs: [
{
run_id: 'run-1',
status: 'completed',
run_version: 1,
expected_next_run_sequence: 2,
updated_at: '2026-08-05T10:00:00Z',
total_attempt_elapsed_ms: elapsed,
},
],
recent_events: [],
});
expect(snapshot.runs['run-1'].totalAttemptElapsedMs).toBe(
typeof elapsed === 'number' && Number.isFinite(elapsed) && elapsed >= 0
? elapsed
: null
);
}
);
it('does not use a stale elapsed total when replay advanced past the Run aggregate', () => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 2,
runs: [
{
run_id: 'run-1',
status: 'running',
run_version: 1,
expected_next_run_sequence: 3,
updated_at: '2026-08-05T10:00:00Z',
total_attempt_elapsed_ms: 5_000,
},
],
recent_events: [
event(),
event({
event_id: 'event-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
event_type: 'run.completed',
created_at: '2026-08-05T10:01:00Z',
}),
],
});
expect(snapshot.runs['run-1'].status).toBe('completed');
expect(snapshot.runs['run-1'].totalAttemptElapsedMs).toBeNull();
});
it('invalidates an active elapsed checkpoint when live execution advances', () => {
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 1,
runs: [
{
run_id: 'run-1',
status: 'running',
run_version: 1,
expected_next_run_sequence: 2,
updated_at: '2026-08-05T10:00:00Z',
total_attempt_elapsed_ms: 5_000,
},
],
recent_events: [event()],
});
expect(snapshot.runs['run-1'].totalAttemptElapsedMs).toBe(5_000);
const live = reduceProjectView(
snapshot,
normalizeEvent(
event({
event_id: 'event-2',
run_sequence: 2,
run_version: 2,
cloud_cursor: 2,
event_type: 'run.completed',
created_at: '2026-08-05T10:01:00Z',
})
)
);
expect(live.runs['run-1'].totalAttemptElapsedMs).toBeNull();
});
it('keeps a live elapsed checkpoint while the same execution continues', () => {
const waiting = {
run_id: 'run-1',
status: 'waiting_for_user',
run_version: 1,
expected_next_run_sequence: 2,
updated_at: '2026-08-05T10:00:00Z',
total_attempt_elapsed_ms: 62_000,
totalAttemptElapsedAt: '2026-08-05T10:01:00.000Z',
};
const approved = (sequence: number) =>
normalizeEvent(
event({
event_id: `approved-${sequence}`,
run_sequence: sequence,
run_version: sequence,
cloud_cursor: sequence,
event_type: 'approval.decided',
legacy_step: null,
payload: { continued_attempt: true },
created_at: '2026-08-05T10:01:00Z',
})
);
const snapshot = projectSnapshot({
project_id: 'project-1',
current_cursor: 1,
runs: [waiting],
recent_events: [event({ legacy_step: null })],
});
const continued = reduceProjectView(snapshot, approved(2));
expect(continued.runs['run-1']).toMatchObject({
status: 'running',
totalAttemptElapsedMs: 62_000,
totalAttemptElapsedAt: '2026-08-05T10:01:00.000Z',
});
// Skipped events can hide an interruption and Resume; settle on a later
// read instead of counting through them.
const afterGap = projectSnapshot({
project_id: 'project-1',
current_cursor: 0,
runs: [waiting],
recent_events: [approved(5)],
events_truncated: true,
});
expect(afterGap.runs['run-1'].totalAttemptElapsedMs).toBeNull();
});
it('keeps a live elapsed checkpoint across events appended after the Run listing', () => {
// Reopening a Session lists Runs before it reads their events, so the
// event tail can extend past the listed version while the Run continues.
const appended = (sequence: number, eventType: string) =>
event({
event_id: `event-${sequence}`,
run_sequence: sequence,
run_version: sequence,
cloud_cursor: null,
event_type: eventType,
legacy_step: null,
payload: {},
created_at: '2026-08-05T10:01:00Z',
});
const reopened = (eventTypes: string[]) =>
projectSnapshot({
project_id: 'project-1',
current_cursor: 0,
runs: [
{
run_id: 'run-1',
status: 'running',
run_version: 3,
expected_next_run_sequence: 3 + eventTypes.length,
updated_at: '2026-08-05T10:00:00Z',
total_attempt_elapsed_ms: 62_000,
totalAttemptElapsedAt: '2026-08-05T10:01:00.000Z',
},
],
recent_events: eventTypes.map((eventType, index) =>
appended(3 + index, eventType)
),
events_truncated: true,
}).runs['run-1'];
expect(
reopened(['step.created', 'tool.completed', 'approval.requested'])
).toMatchObject({
status: 'waiting_for_user',
lastSequence: 5,
totalAttemptElapsedMs: 62_000,
totalAttemptElapsedAt: '2026-08-05T10:01:00.000Z',
});
// An interruption among the appends ends that measurement.
expect(
reopened([
'step.created',
'runtime.interrupted',
'run.attempt_created',
'run.attempt_started',
])
).toMatchObject({
status: 'running',
lastSequence: 6,
totalAttemptElapsedMs: null,
});
});
describe('waiting for the user', () => {
const at = (time: string) => `2026-08-05T${time}.000Z`;
const runEvent = (
sequence: number,
eventType: string,
time: string,
payload: Record<string, unknown> = {}
) =>
normalizeEvent(
event({
event_id: `event-${sequence}`,
run_sequence: sequence,
run_version: sequence,
cloud_cursor: null,
event_type: eventType,
legacy_step: null,
payload,
created_at: at(time),
})
);
const decided = (
sequence: number,
time: string,
payload: Record<string, unknown> = {}
) =>
runEvent(sequence, 'approval.decided', time, {
continued_attempt: true,
remaining_interaction_count: 0,
...payload,
});
const listed = (
status: string,
elapsedMs: number,
measuredAt: string,
recentEvents: ReturnType<typeof runEvent>[]
) =>
projectSnapshot({
project_id: 'project-1',
current_cursor: 0,
runs: [
{
run_id: 'run-1',
status,
run_version: 3,
expected_next_run_sequence: 4,
updated_at: at('10:00:02'),
total_attempt_elapsed_ms: elapsedMs,
totalAttemptElapsedAt: at(measuredAt),
},
],
recent_events: recentEvents,
events_truncated: true,
});
it('records each wait from its request to its answer', () => {
const requested = projectRawEvents(
'project-1',
[
runEvent(1, 'run.attempt_started', '10:00:00'),
runEvent(2, 'approval.requested', '10:00:02'),
],
'live'
).state;
expect(requested.runs['run-1']).toMatchObject({
status: 'waiting_for_user',
userWaitStartedAt: at('10:00:02'),
});
expect(requested.runs['run-1'].userWaitMs).toBeUndefined();
const approved = reduceProjectView(requested, decided(3, '10:01:02'));
expect(approved.runs['run-1']).toMatchObject({
status: 'running',
userWaitMs: 60_000,
});
expect(approved.runs['run-1'].userWaitStartedAt).toBeUndefined();
});
it('starts an open wait at a listing read during that wait', () => {
// The listed total already leaves out the wait up to its read.
const reopened = listed('waiting_for_user', 2_000, '10:01:02', [
runEvent(3, 'approval.requested', '10:00:02'),
]);
expect(reopened.runs['run-1']).toMatchObject({
status: 'waiting_for_user',
totalAttemptElapsedMs: 2_000,
userWaitStartedAt: at('10:01:02'),
});
const approved = reduceProjectView(reopened, decided(4, '10:01:32'));
expect(approved.runs['run-1']).toMatchObject({
status: 'running',
totalAttemptElapsedMs: 2_000,
totalAttemptElapsedAt: at('10:01:02'),
userWaitMs: 30_000,
});
});
it('never starts a wait before a listing read while running', () => {
const reopened = listed('running', 5_000, '10:01:00', [
runEvent(3, 'step.created', '10:00:02'),
]);
expect(
reduceProjectView(
reopened,
runEvent(4, 'approval.requested', '10:01:10')
).runs['run-1'].userWaitStartedAt
).toBe(at('10:01:10'));
// A request written just before the read is already counted by it.
expect(
reduceProjectView(
reopened,
runEvent(4, 'approval.requested', '10:00:59')
).runs['run-1'].userWaitStartedAt
).toBe(at('10:01:00'));
});
it('settles a listing read on the active time when the Run stops', () => {
let state = listed('running', 5_000, '10:01:00', [
runEvent(3, 'step.created', '10:00:02'),
]);
for (const next of [
runEvent(4, 'approval.requested', '10:01:10'),
decided(5, '10:02:10'),
runEvent(6, 'run.completed', '10:02:13'),
]) {
state = reduceProjectView(state, next);
}
// 5s at the read, 10s before the request and 3s after the answer.
expect(state.runs['run-1']).toMatchObject({
status: 'completed',
totalAttemptElapsedMs: 18_000,
totalAttemptElapsedAt: at('10:02:13'),
});
expect(state.runs['run-1'].userWaitMs).toBeUndefined();
});
it('keeps waiting while another request is still open', () => {
const requested = projectRawEvents(
'project-1',
[
runEvent(1, 'run.attempt_started', '10:00:00'),
runEvent(2, 'approval.requested', '10:00:02'),
runEvent(3, 'approval.requested', '10:00:10'),
],
'live'
).state;
const firstAnswered = reduceProjectView(
requested,
decided(4, '10:00:30', {
continued_attempt: false,
remaining_interaction_count: 1,
})
);
expect(firstAnswered.runs['run-1']).toMatchObject({
status: 'waiting_for_user',
userWaitStartedAt: at('10:00:02'),
});
const bothAnswered = reduceProjectView(
firstAnswered,
decided(5, '10:00:50')
);
expect(bothAnswered.runs['run-1']).toMatchObject({
status: 'running',
userWaitMs: 48_000,
});
// A rejection that leaves nothing open still interrupts the Attempt.
expect(
reduceProjectView(
requested,
decided(4, '10:00:30', { continued_attempt: false })
).runs['run-1'].status
).toBe('interrupted');
});
it('keeps waiting when one of two open requests is cancelled', () => {
const requested = projectRawEvents(
'project-1',
[
runEvent(1, 'run.attempt_started', '10:00:00'),
runEvent(2, 'approval.requested', '10:00:02'),
runEvent(3, 'approval.requested', '10:00:10'),
],
'live'
).state;
const cancelled = (payload: Record<string, unknown> = {}) =>
runEvent(4, 'approval.cancelled', '10:00:30', {
decision: 'rejected',
continued_attempt: false,
...payload,
});
const firstCancelled = reduceProjectView(
requested,
cancelled({ remaining_interaction_count: 1 })
);
expect(firstCancelled.runs['run-1']).toMatchObject({
status: 'waiting_for_user',
userWaitStartedAt: at('10:00:02'),
});
expect(
reduceProjectView(firstCancelled, decided(5, '10:00:50')).runs['run-1']
).toMatchObject({ status: 'running', userWaitMs: 48_000 });
// A cancellation that leaves nothing open, or one recorded before the
// count was reported, still interrupts the Attempt.
for (const payload of [{ remaining_interaction_count: 0 }, {}])
expect(
reduceProjectView(requested, cancelled(payload)).runs['run-1'].status
).toBe('interrupted');
});
it('leaves the status to the Run when a request closes because the Run ended', () => {
const requested = projectRawEvents(
'project-1',
[
runEvent(1, 'run.attempt_started', '10:00:00'),
runEvent(2, 'approval.requested', '10:00:02'),
runEvent(3, 'run.cancel_requested', '10:00:10'),
],
'live'
).state;
const closed = reduceProjectView(
requested,
runEvent(4, 'approval.cancelled', '10:00:11', {
decision: 'rejected',
continued_attempt: false,
reason: 'run_terminal:cancelled',
source: 'system',
})
);
expect(closed.runs['run-1'].status).toBe('cancelling');
expect(
reduceProjectView(closed, runEvent(5, 'run.cancelled', '10:00:11'))
.runs['run-1'].status
).toBe('cancelled');
});
it('restarts the wait record at a measured Run read', () => {
const approved = reduceProjectView(
projectRawEvents(
'project-1',
[
runEvent(1, 'run.attempt_started', '10:00:00'),
runEvent(2, 'approval.requested', '10:00:02'),
],
'live'
).state,
decided(3, '10:01:02')
).runs['run-1'];
const summary = {
run_id: 'run-1',
project_id: 'project-1',
version: 4,
updated_at: at('10:01:02'),
};
const running = mergeRunSummary(
approved,
{ ...summary, status: 'running', total_attempt_elapsed_ms: 2_000 },
at('10:01:05')
);
expect(running).toMatchObject({
totalAttemptElapsedMs: 2_000,
totalAttemptElapsedAt: at('10:01:05'),
});
expect(running?.userWaitMs).toBeUndefined();
const waiting = mergeRunSummary(
approved,
{
...summary,
status: 'waiting_for_user',
total_attempt_elapsed_ms: 2_000,
},
at('10:01:05')
);
expect(waiting).toMatchObject({ userWaitStartedAt: at('10:01:05') });
expect(waiting?.userWaitMs).toBeUndefined();
});
});
it('preserves legacy raw payload across all V1 importers', () => {
const legacy = {
step_id: 9,
task_id: 'task-1',
project_id: 'project-1',
step: 'notice',
data: { content: 'legacy' },
timestamp: 123,
vendor_extension: { keep: true },
};
const imported = [
importLegacyChatSteps([legacy]),
importIndexedDbV1({ messages: [legacy] }),
importLocalMemoryV1({ steps: [legacy] }),
];
for (const events of imported) {
expect(events).toHaveLength(1);
expect(events[0].raw).toEqual(legacy);
expect(events[0].legacyStep).toBe('notice');
expect(events[0].payload.__legacy_data).toEqual({ content: 'legacy' });
}
});
it('projects playback without producing real effects', () => {
const result = projectRawEvents(
'project-1',
[event({ event_type: 'run.completed', legacy_step: 'end' })],
'playback'
);
expect(result.state.runs['run-1'].status).toBe('completed');
expect(result.effects).toEqual([]);
});
it.each([
['run.deadline_reached', 'timed_out'],
['runtime.interrupted', 'interrupted'],
['approval.cancelled', 'interrupted'],
] as const)('projects %s as the terminal status %s', (eventType, status) => {
const result = projectRawEvents(
'project-1',
[event({ event_type: eventType, legacy_step: null })],
'rehydrate'
);
expect(result.state.runs['run-1'].status).toBe(status);
});
it('projects a new attempt as running after an interruption', () => {
const result = projectRawEvents(
'project-1',
[
event({
event_id: 'interrupted-1',
event_type: 'runtime.interrupted',
legacy_step: null,
}),
event({
event_id: 'attempt-2',
event_type: 'run.attempt_started',
legacy_step: null,
cloud_cursor: 2,
run_sequence: 2,
run_version: 2,
}),
],
'rehydrate'
);
expect(result.state.runs['run-1'].status).toBe('running');
});
it('accepts already-normalized importer output without decoding it twice', () => {
const imported = importLegacyChatSteps([
{
step_id: 1,
task_id: 'run-1',
project_id: 'project-1',
step: 'notice',
data: { content: 'hello' },
},
]);
const result = projectRawEvents(
'project-1',
imported,
'rehydrate',
createProjectViewState('project-1', 'rehydrate')
);
expect(result.state.legacySteps[0].data).toEqual({ content: 'hello' });
});
});