diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 76a5c0a5ef86..012787c28de7 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -369,7 +369,6 @@ 2 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-claude-subagent-row.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-owed-work-release.test.ts 3 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-command.test.ts -1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-quit.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-restart-cap.test.ts @@ -419,7 +418,6 @@ 1 test-no-real-time-wait:src/main/runtime/restored-pane-start-cli-handles.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-instant-tab.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-restart-replay.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-source-range-request.test.ts @@ -1303,7 +1301,7 @@ 4 test-timeout-needs-reason:src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts 3 test-timeout-needs-reason:src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts 5 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-queued-stop.test.ts -3 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +2 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-turn-end.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-status-feed-children.test.ts diff --git a/src/main/acp/acp-structured-host-restore-failed.test.ts b/src/main/acp/acp-structured-host-restore-failed.test.ts index 77a60307d114..008747fbb9fb 100644 --- a/src/main/acp/acp-structured-host-restore-failed.test.ts +++ b/src/main/acp/acp-structured-host-restore-failed.test.ts @@ -11,7 +11,7 @@ import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/ import type { AcpScriptedAgent } from './acp-scripted-agent.test-support' import { GROK, GROK_CONFIG_OPTIONS, PROVIDER_SESSION } from './acp-structured-adapter.test-support' import { ACP_HANDLE_TRANSPORT } from './acp-structured-agent-definitions' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import { createAcpStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' import { @@ -83,7 +83,7 @@ async function openRestoreRig(code: number, message: string) { const { rig, host, store, journalDatabase } = opened resolver.resolve = createAcpStructuredLaunchResolver(GROK, { store, - readJournal: (sessionId) => replayJournal(journalDatabase.db, sessionId), + readJournal: (sessionId) => restoreJournal(journalDatabase.db, sessionId), resolveWorkspacePath: async () => '/workspace', resolveEnvironment: async () => ({ PATH: '/usr/bin' }), resolveCommand: () => '/fake/grok' diff --git a/src/main/acp/acp-structured-launch-resolution.test.ts b/src/main/acp/acp-structured-launch-resolution.test.ts index 79baa2313bba..913f5ea6cd23 100644 --- a/src/main/acp/acp-structured-launch-resolution.test.ts +++ b/src/main/acp/acp-structured-launch-resolution.test.ts @@ -10,7 +10,17 @@ import { } from '../../shared/agent-session-provider-handle' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import { replayJournal, restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { + openTestJournalHostDatabase, + closeTestJournalHostDatabase, + publishTestJournalEpoch, + insertTestJournalRow, + insertTestJournalRowJson +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalLoad } from '../native-chat/agent-session-journal/journal-open' +import { publishJournalOutcomeEpoch } from '../native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../native-chat/agent-session-journal/journal-row-schema' import { createJournalReducerState } from '../native-chat/agent-session-journal/journal-reducer' import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import { @@ -78,6 +88,153 @@ function resolver(record: AgentSessionRecord, readJournal: () => JournalLoad | n } describe('ACP launch resolution', () => { + it('preserves resume and loss-warning decisions through a restore and an unreadable tail', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-saved-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + publishTestJournalEpoch(database.db, identity.sessionId, 'epoch-1') + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const turnIdentity = createLegacyProviderTimelineIdentityScheme({ + agent: 'grok', + sessionId: identity.sessionId + }).item({ + namespace: 'acp-1', + family: 'item', + key: { source: 'provider', value: 'turn' }, + thread: 'acp-1' + }) + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: agentJournalItemKey(turnIdentity), + revision: 1, + body: turn.body + }) + const readDecisions = async (readJournal: () => JournalLoad | null) => { + const launch = await resolver(record, readJournal).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + const full = () => replayJournal(database.db, identity.sessionId) + const restored = () => restoreJournal(database.db, identity.sessionId) + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [lostKey] }) + insertTestJournalRowJson(database.db, identity.sessionId, 3, '{damaged') + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + + it('reads an outcome chat from its records, and a newer one as unreadable', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-outcome-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const rows: JournalRow[] = [ + { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }, + { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: 'turn', + revision: 1, + body: turn.body + } + ] + // A chat this build created holds only records. + database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, 'epoch-1') + publishJournalOutcomeEpoch(db, identity.sessionId, 'epoch-1', rows) + }) + const readDecisions = async () => { + const launch = await resolver(record, () => + restoreJournal(database.db, identity.sessionId) + ).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + expect(restoreJournal(database.db, identity.sessionId)?.state.items.has('turn')).toBe(true) + // The turn on acp-1 is found, so the exchange is saved; the loss has no warning yet. + expect(await readDecisions()).toEqual({ unsaved: false, losses: [lostKey] }) + // A newer build's records are unreadable here, never a missing chat. + database.db.prepare('UPDATE journal_outcome_epochs SET format = 2').run() + expect(restoreJournal(database.db, identity.sessionId)?.newer).toBeTruthy() + expect(await readDecisions()).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + it('pins the record account home and searches the agent install dir', async () => { const { resolve, searched } = resolver(grokRecord()) const launch = await resolve({ identity }) diff --git a/src/main/acp/acp-structured-unknown-window-usage.test.ts b/src/main/acp/acp-structured-unknown-window-usage.test.ts new file mode 100644 index 000000000000..d466995345e5 --- /dev/null +++ b/src/main/acp/acp-structured-unknown-window-usage.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { readAgentJournalTurn } from '../../shared/agent-session-turn-record' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { JournalWriteProjection } from '../native-chat/agent-session-journal/journal-write-projection' +import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { PROVIDER_SESSION, replyChunk, waitFor } from './acp-structured-adapter.test-support' +import { openAttachedHostRig, promptIdOf, send } from './acp-structured-host.test-support' + +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await closeProviderTimelineRigs() +}) + +describe('an ACP usage report with an unknown window', () => { + // The protocol allows `size: 0`; the saved reader drops that window as unusable. + it('keeps the turn running, and the live chat equals what a reload reads', async () => { + // Each commit then restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true + const rig = await openAttachedHostRig() + const { host } = rig + await send(host, 'hello') + const prompt = await rig.rig.frame('session/prompt') + const { agent } = rig.rig.child() + agent.notify('session/update', replyChunk(promptIdOf(prompt), 'Oak')) + agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { sessionUpdate: 'usage_update', used: 1_200, size: 0 } + }) + agent.notify('session/update', replyChunk(promptIdOf(prompt), ' tree')) + agent.reply(prompt, { stopReason: 'end_turn' }) + await rig.rig.settle() + await waitFor(async () => + expect((await rig.turns()).map((turn) => turn.state)).toEqual(['completed']) + ) + expect(rig.rig.child().exited).toBe(false) + expect((await rig.rows()).filter((row) => row.body.kind === 'status')).toEqual([]) + expect((await rig.turns()).at(-1)?.contextUsage).toBeUndefined() + + const loaded = restoreJournal(rig.journalDatabase.db, SESSION) + expect(loaded?.damage).toBeFalsy() + expect(loaded?.newer).toBeFalsy() + const saved = [...(loaded?.state.items.values() ?? [])].flatMap( + (item) => readAgentJournalTurn(item.body) ?? [] + ) + expect(saved).toEqual(await rig.turns()) + await host.close(SESSION, 'user-close') + }) +}) diff --git a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts index 35a98d4eb00f..21e4cbd97724 100644 --- a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts +++ b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts @@ -14,7 +14,7 @@ import { createCodexJournalTranslator } from './codex-structured-journal-transla import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' const SESSION = 'codex-atomic' -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string | undefined afterEach(async () => { @@ -83,20 +83,24 @@ it('rolls back the entire Codex exit settlement when a later row fails', async ( const diskBefore = liveTestJournalRows(database.db, SESSION) const sawEarlierInserts: number[] = [] const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - return run(db) - } catch (error) { - sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(commits).not.toHaveBeenCalled() - expect( - published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) - ).toBe(true) - throw error - } - }) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + return run(db) + } catch (error) { + sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) + expect(journal.snapshot()).toEqual(before) + expect(commits).not.toHaveBeenCalled() + expect( + published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) + ).toBe(true) + throw error + } + }, + streamed, + committed + ) ) database.db.exec(`CREATE TEMP TRIGGER reject_codex_later BEFORE INSERT ON journal_rows WHEN NEW.session_id = '${SESSION}' AND NEW.seq > ${before.cursor.sequence + 1} diff --git a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts index c87728533c9f..1537abedcdf0 100644 --- a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts +++ b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts @@ -1,98 +1,25 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity -} from '../../shared/agent-session-journal-types' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import { - readAgentJournalTurn, - readAgentJournalTurnOutcome -} from '../../shared/agent-session-turn-record' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionEventSink -} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { describe, expect, it, vi } from 'vitest' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { createCodexJournalTranslator } from './codex-structured-journal-translation' import { CODEX_COMMAND_APPROVAL_METHOD, CODEX_USER_INPUT_METHOD, CodexPromptRegistry } from './codex-structured-prompt-replies' -import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' -import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' -import type { CodexSession } from './codex-structured-session-state' import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -const SESSION_ID = 'session-1' -const THREAD_ID = 'thread-abc' -const TURN_ID = 'turn-1' -const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' -const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' - -type Row = { key: string; body: AgentJournalItemBody } - -function recorder() { - const rows: Row[] = [] - const tombstones: string[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity: AgentJournalItemIdentity, body) => - rows.push({ key: agentJournalItemKey(identity), body }), - appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), - publish: () => {} - } - return { sink, rows, tombstones } -} - -function reduced(rows: readonly Row[]): Row[] { - const latest = new Map() - for (const row of rows) { - latest.set(row.key, row) - } - return [...latest.values()] -} - -function notification( - method: string, - params: unknown, - observedAt?: number -): CodexStructuredSessionEvent { - return { - type: 'notification', - sessionId: SESSION_ID, - threadId: THREAD_ID, - method, - params, - ...(observedAt !== undefined ? { observedAt } : {}) - } -} - -function translatorFor(tap: ReturnType, now?: () => number) { - return createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - ...(now ? { now } : {}) - }) -} - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - vi.useRealTimers() -}) +import { + fixture, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + journals, + notification, + recorder +} from './codex-turn-lifecycle-contract-test-fixture' describe('codex turn lifecycle rows', () => { it('binds a prompt without a provider turn id to the active turn before cleanup', () => { @@ -222,7 +149,7 @@ describe('codex turn lifecycle rows', () => { providerHandle: codexProviderHandle(THREAD_ID) }, now: () => 9_000, - stateDirectory: join(root, SESSION_ID) + stateDirectory: join(fixture.root, SESSION_ID) }) const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) const translator = createCodexJournalTranslator({ @@ -238,17 +165,7 @@ describe('codex turn lifecycle rows', () => { const appended = journal.readSince(before) expect(appended.ok && appended.rows).toEqual([ - expect.objectContaining({ - kind: 'item', - ts: 1_000, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'running', - userItemId: USER_ITEM_ID, - startedAt: 1_000 - } - }) + expect.objectContaining({ kind: 'outcome', seq: before.sequence + 1 }) ]) expect(journal.snapshot().items).toEqual([ expect.objectContaining({ @@ -313,307 +230,4 @@ describe('codex turn lifecycle rows', () => { requestedAt: 900 }) }) - - it('keeps the verdict when a send echoed after completion revises the settled row', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) - }) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) - ) - translator.handle( - notification( - 'item/started', - { - turn: { id: TURN_ID }, - item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } - }, - 2_100 - ) - ) - - // requestedAt distinguishes the post-echo revision from the original terminal row. - const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) - expect(lifecycle?.body).toMatchObject({ - kind: 'turn', - state: 'completed', - outcome: 'failure', - requestedAt: 900 - }) - }) - - it('carries the provider duration and the same user item onto the terminal row', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification( - 'turn/completed', - { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, - 4_500 - ) - ) - - expect(tap.rows.at(-1)).toEqual({ - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - outcome: 'success', - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 4_500, - durationMs: 3_250 - } - }) - }) - - it.each([ - ['interrupted', 'interrupted', 'cancellation'], - ['failed', 'completed', 'failure'], - ['someFutureStatus', 'completed', undefined], - ['inProgress', 'completed', undefined] - ] as const)( - 'maps a %s turn status to a %s lifecycle with outcome %s', - (status, state, outcome) => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) - - expect(tap.tombstones).toEqual([]) - expect(reduced(tap.rows)).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state, - ...(outcome ? { outcome } : {}), - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 2_000 - } - } - ]) - } - ) - - it('records no outcome for a turn end that named no status', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) - - const body = reduced(tap.rows).at(-1)?.body - expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) - expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() - }) - - it('stamps the host clock when a boundary arrives without a receipt time', () => { - const tap = recorder() - let clock = 10_000 - const translator = translatorFor(tap, () => (clock += 250)) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) - - expect(tap.rows.map((row) => row.body)).toMatchObject([ - { kind: 'turn', state: 'running', startedAt: 10_250 }, - { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } - ]) - }) - - it('writes only the end time, and no duration, when Codex reports neither', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) - - expect(tap.rows).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - userItemId: USER_ITEM_ID, - completedAt: 3_000 - } - } - ]) - }) - - it('replays an oversized backpressured notification with its original receipt time', async () => { - vi.useFakeTimers() - const connection = { - pauseReading: vi.fn(), - resumeReading: vi.fn() - } as unknown as CodexAppServerConnection - const translate = vi - .fn[0]['translate']>() - .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) - .mockReturnValue({ accepted: true }) - const retries = createCodexStructuredNotificationRetry({ - sessionFor: () => ({ connection, ended: false }) as CodexSession, - translate - }) - - expect( - retries.handle( - SESSION_ID, - 'turn/started', - { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, - 1_000, - -1 - ) - ).toEqual({ accepted: false, reason: 'backpressure' }) - await vi.advanceTimersByTimeAsync(50) - - expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) - expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) - expect(connection.resumeReading).not.toHaveBeenCalled() - }) - - it('restores historical turn rows with optional endpoints in milliseconds', () => { - const tap = recorder() - const translator = translatorFor(tap) - - expect( - translator.restoreThread(THREAD_ID, { - turns: [ - { - id: 'turn-done', - status: 'completed', - startedAt: 1_700_000_000, - completedAt: 1_700_000_042, - durationMs: 41_900, - items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] - }, - { - id: 'turn-cut', - status: 'interrupted', - startedAt: 1_700_000_100, - completedAt: 1_700_000_101, - items: [] - }, - { - id: 'turn-failed', - status: 'failed', - startedAt: 1_700_000_150, - completedAt: 1_700_000_152, - durationMs: 2_400, - items: [] - }, - { - id: 'turn-unplaced', - status: 'someFutureStatus', - startedAt: 1_700_000_170, - completedAt: 1_700_000_171, - items: [] - }, - { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, - { id: 'turn-untimed', status: 'completed', items: [] } - ] - }) - ).toEqual({ accepted: true }) - - expect(tap.rows).toEqual([ - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', - body: { - kind: 'turn', - turnId: 'turn-done', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-done:0', - startedAt: 1_700_000_000_000, - completedAt: 1_700_000_042_000, - durationMs: 41_900 - } - }, - expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', - body: { - kind: 'turn', - turnId: 'turn-cut', - state: 'interrupted', - outcome: 'cancellation', - userItemId: 'codex:thread-abc:turn-cut:0', - startedAt: 1_700_000_100_000, - completedAt: 1_700_000_101_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', - body: { - kind: 'turn', - turnId: 'turn-failed', - state: 'completed', - outcome: 'failure', - userItemId: 'codex:thread-abc:turn-failed:0', - startedAt: 1_700_000_150_000, - completedAt: 1_700_000_152_000, - durationMs: 2_400 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', - body: { - kind: 'turn', - turnId: 'turn-unplaced', - state: 'completed', - userItemId: 'codex:thread-abc:turn-unplaced:0', - startedAt: 1_700_000_170_000, - completedAt: 1_700_000_171_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', - body: { - kind: 'turn', - turnId: 'turn-open', - state: 'completed', - userItemId: 'codex:thread-abc:turn-open:0', - startedAt: 1_700_000_200_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', - body: { - kind: 'turn', - turnId: 'turn-untimed', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-untimed:0' - } - } - ]) - expect(tap.tombstones).toEqual([]) - }) - - it('restores no lifecycle rows without a session identity to key them by', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - primaryThreadId: () => THREAD_ID - }) - - translator.restoreThread(THREAD_ID, { - turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] - }) - - expect(tap.rows).toEqual([]) - }) }) diff --git a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts index 72e0a32e9e67..7f68e9bd03d1 100644 --- a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts +++ b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts @@ -11,10 +11,7 @@ import { agentSessionFailureFact } from '../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types' import { structuredRewindCut } from '../native-chat/agent-session-wire/structured-rewind-cut' -import { - applyJournalRow, - createJournalReducerState -} from '../native-chat/agent-session-journal/journal-reducer' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' export function registerCodexCatchUpEchoTests(input: { chat: typeof catchUpChat @@ -122,15 +119,8 @@ export function registerCodexCatchUpEchoTests(input: { await c.open([...native, outside]) expect(c.journal.snapshot()).toEqual(whole) expect(c.journal.queuedMessages.get('draft')).toEqual(draft) - const replay = c.journal.readSince({ epoch: c.journal.epoch, sequence: 0 }) - if (!replay.ok || !draft) { - throw new Error('missing replay fixture') - } - const state = createJournalReducerState(SESSION, c.journal.epoch) - for (const row of replay.rows) { - applyJournalRow(state, row) - } - expect(state.queue.cards.get('draft')).toEqual(draft) + const restored = restoreJournal(c.db, SESSION) + expect(restored?.state.queue.cards.get('draft')).toEqual(draft) }) it('keeps native display identity after a real retained cut and disk reopen', async () => { diff --git a/src/main/codex/codex-structured-thread-catch-up.test.ts b/src/main/codex/codex-structured-thread-catch-up.test.ts index c743325e6d8a..c635ac105f8b 100644 --- a/src/main/codex/codex-structured-thread-catch-up.test.ts +++ b/src/main/codex/codex-structured-thread-catch-up.test.ts @@ -1,459 +1,176 @@ -import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' import { registerCodexCatchUpEchoTests } from './codex-structured-thread-catch-up-echo.spec' - -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -import { - closeTestJournalHostDatabase, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' +import { expect, it } from 'vitest' import { createCodexJournalTranslator } from './codex-structured-journal-translation' -import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' -import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' -import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' -import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' -import { catchUpCodexThread } from './codex-structured-thread-catch-up' -const SESSION = 'session-codex-catch-up' -const THREAD = 'thread-abc' -const STARTED_AT = 1_700_000_000 +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` + const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } + await c.open([turn(1), outside]) + await c.reopen() + const items = c.journal.snapshot().items + const stored = items.find( + (item) => + item.body.kind === 'message' && + item.body.role === 'assistant' && + item.body.blocks.some((block) => block.type === 'text' && block.text === answer) + ) + expect(stored?.body).toEqual({ + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: answer }] + }) + const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) + expect(displayed).toContainEqual({ type: 'text', text: answer }) +}) -export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { - return { - id: `turn-${index}`, - status: 'completed', - itemsView: view, - startedAt: STARTED_AT + index * 100, - completedAt: STARTED_AT + index * 100 + 50, - items: [ - { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, - { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } - ] - } -} +it('adds the turns made outside the chat once, in order, after the chat rows', async () => { + const c = await chat({ now: 1_000 }) + + await c.open([turn(1)]) + expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) + + await c.open([turn(1), turn(2), turn(3)]) + const caughtUp = [ + 'user:ask 1', + 'assistant:answer 1', + '(continued-outside)', + 'user:ask 2', + 'assistant:answer 2', + 'user:ask 3', + 'assistant:answer 3' + ] + expect(c.texts()).toEqual(caughtUp) + + await c.open([turn(1), turn(2), turn(3)]) + expect(c.texts()).toEqual(caughtUp) + + // An external rewind preserves displayed rows and adds a notice. + await c.open([turn(1), turn(2), turn(4)]) + expect(c.texts().slice(caughtUp.length)).toEqual([ + '(continued-outside-rewound)', + 'user:ask 4', + 'assistant:answer 4' + ]) + + // Summary-only history cannot be imported. + await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) + expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) +}) -function codexWith(turns: Record[]) { - return { - request: async (method: string, params?: Record) => { - expect(method).toBe('thread/turns/list') - expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) - const newestFirst = turns.toReversed() - const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 - const data = newestFirst.slice(start, start + 2) - return { - data, - nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null - } +it('recovers an older gap behind newer native work after a failed read and restart', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const failed = { + request: async () => { + throw new Error('read failed') } } -} - -const journals = createTrackedJournalOpener() -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() + await c.open([turn(1), turn(2)], { connection: failed }) + const native = createCodexJournalTranslator({ + sink: c.deferred.sink, + sessionId: SESSION, + primaryThreadId: () => THREAD + }) + for (const [method, params] of [ + ['turn/started', { turn: { id: 'turn-3' } }], + [ + 'item/completed', + { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } + ], + ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] + ] as const) { + native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) } + await c.deferred.drained() + native.dispose() + const before = c.journal.snapshot().items + await c.reopen() + await c.open([turn(1), turn(2), turn(3)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) + await c.open([turn(1), turn(2), turn(3), turn(4)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) }) -export async function chat(clock: { now: number }) { - const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) - const journalOptions = { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - } satisfies AgentSessionJournalIdentity, - stateDirectory: root, - now: () => clock.now - } - let journal = await journals.open(journalOptions) - let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const publications: number[] = [] - const bind = () => - deferred.bind({ - journal, - fence: 1, - publish: () => { - publications.push(journal.snapshot().items.length) - } - }) - bind() - cleanups.push(async () => { - deferred.close() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) +it('uses the continued-outside notice after a receipt-only known turn', async () => { + const c = await chat({ now: 1_000 }) + const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } + await c.journal.appendSubmission({ + clientMessageId: 'receipt', + body, + payloadFingerprint: 'receipt', + fence: 1 }) - return { - get journal() { - return journal - }, - get deferred() { - return deferred - }, - root, - get db() { - return openTestJournalHostDatabase(root).db - }, - publications, - reopen: async () => { - deferred.close() - await journal.close() - await closeTestJournalHostDatabase(root) - journal = await journals.open(journalOptions) - deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - bind() - }, - open: async ( - turns: Record[], - options: Partial[0]> = {} - ) => { - await catchUpCodexThread({ - connection: codexWith(turns), - threadId: THREAD, - sessionId: SESSION, - sink: deferred.sink, - ...options - }) - return deferred.drained() - }, - texts: () => - journal.snapshot().items.flatMap((item) => { - if (item.body.kind === 'message') { - const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) - return [`${item.body.role}:${text.join('')}`] - } - return item.body.kind === 'status' && item.body.presentation - ? [`(${item.body.presentation})`] - : [] - }) - } -} - -describe('Codex chat catch-up', () => { - registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) - - it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` - const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } - await c.open([turn(1), outside]) - await c.reopen() - const items = c.journal.snapshot().items - const stored = items.find( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - item.body.blocks.some((block) => block.type === 'text' && block.text === answer) - ) - expect(stored?.body).toEqual({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: answer }] - }) - const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) - expect(displayed).toContainEqual({ type: 'text', text: answer }) + await c.journal.resolveDispatch({ + clientMessageId: 'receipt', + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, + fence: 1 }) + await c.open([turn(1), turn(2)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) +}) - it('adds the turns made outside the chat once, in order, after the chat rows', async () => { - const c = await chat({ now: 1_000 }) - - await c.open([turn(1)]) - expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) +it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const before = c.journal.snapshot() + const large = { + ...turn(2), + items: Array.from({ length: 600 }, (_, n) => ({ + type: 'agentMessage', + id: `item-${n}`, + text: `answer ${n}` + })) + } + const seq = c.journal.cursor().sequence + c.db.exec( + `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` + ) + expect((await c.open([turn(1), large])).ok).toBe(false) + expect(c.deferred.state().failed).toBe(true) + expect(c.journal.snapshot()).toEqual(before) + c.db.exec('DROP TRIGGER fail_later_partition') + await c.reopen() + expect(c.journal.snapshot()).toEqual(before) + c.publications.length = 0 + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) + expect(c.publications).toEqual([before.items.length + 602]) + await c.reopen() + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) +}) - await c.open([turn(1), turn(2), turn(3)]) - const caughtUp = [ - 'user:ask 1', - 'assistant:answer 1', - '(continued-outside)', - 'user:ask 2', - 'assistant:answer 2', - 'user:ask 3', - 'assistant:answer 3' +it('keeps rollback reasoning and message identities immutable across turns', async () => { + const c = await chat({ now: 1_000 }) + const withReasoning = (n: number) => ({ + ...turn(n), + items: [ + { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, + { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } ] - expect(c.texts()).toEqual(caughtUp) - - await c.open([turn(1), turn(2), turn(3)]) - expect(c.texts()).toEqual(caughtUp) - - // An external rewind preserves displayed rows and adds a notice. - await c.open([turn(1), turn(2), turn(4)]) - expect(c.texts().slice(caughtUp.length)).toEqual([ - '(continued-outside-rewound)', - 'user:ask 4', - 'assistant:answer 4' - ]) - - // Summary-only history cannot be imported. - await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) - expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) - }) - - it('recovers an older gap behind newer native work after a failed read and restart', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const failed = { - request: async () => { - throw new Error('read failed') - } - } - await c.open([turn(1), turn(2)], { connection: failed }) - const native = createCodexJournalTranslator({ - sink: c.deferred.sink, - sessionId: SESSION, - primaryThreadId: () => THREAD - }) - for (const [method, params] of [ - ['turn/started', { turn: { id: 'turn-3' } }], - [ - 'item/completed', - { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } - ], - ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] - ] as const) { - native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) - } - await c.deferred.drained() - native.dispose() - const before = c.journal.snapshot().items - await c.reopen() - await c.open([turn(1), turn(2), turn(3)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - await c.open([turn(1), turn(2), turn(3), turn(4)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) - }) - - it('uses the continued-outside notice after a receipt-only known turn', async () => { - const c = await chat({ now: 1_000 }) - const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } - await c.journal.appendSubmission({ - clientMessageId: 'receipt', - body, - payloadFingerprint: 'receipt', - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'receipt', - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, - fence: 1 - }) - await c.open([turn(1), turn(2)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - }) - - it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const before = c.journal.snapshot() - const large = { - ...turn(2), - items: Array.from({ length: 600 }, (_, n) => ({ - type: 'agentMessage', - id: `item-${n}`, - text: `answer ${n}` - })) - } - const seq = c.journal.cursor().sequence - c.db.exec( - `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` - ) - expect((await c.open([turn(1), large])).ok).toBe(false) - expect(c.deferred.state().failed).toBe(true) - expect(c.journal.snapshot()).toEqual(before) - c.db.exec('DROP TRIGGER fail_later_partition') - await c.reopen() - expect(c.journal.snapshot()).toEqual(before) - c.publications.length = 0 - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - expect(c.publications).toEqual([before.items.length + 602]) - await c.reopen() - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - }) - - it('keeps rollback reasoning and message identities immutable across turns', async () => { - const c = await chat({ now: 1_000 }) - const withReasoning = (n: number) => ({ - ...turn(n), - items: [ - { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, - { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } - ] - }) - await c.open([withReasoning(1)]) - const before = c.journal.snapshot().items - await c.open([withReasoning(2)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:answer 1', - 'assistant:answer 2' - ]) - const reasoning = c.journal - .snapshot() - .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') - expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) - expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) }) + await c.open([withReasoning(1)]) + const before = c.journal.snapshot().items + await c.open([withReasoning(2)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:answer 1', + 'assistant:answer 2' + ]) + const reasoning = c.journal + .snapshot() + .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') + expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) + expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) +}) - it('retains the original adoption cutoff through native rewind and disk recovery', async () => { - const clock = { now: 50_000 } - const c = await chat(clock) - let store = await openTestAgentSessionRecordStore(c.root) - const callerKey = 'catch-up-test' - await store.reserveOwner({ - sessionId: SESSION, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, - expectedFence: null, - spawnToken: 'fixture-only', - claimKeyId: 'fixture', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'fixture' }, - operation: { - callerKey, - operationId: '0000000050000-00000000000000000000000000000001', - fingerprint: 'create' - }, - now: clock.now - }) - await store.commitProcessIdentity({ - sessionId: SESSION, - fence: 1, - process: { - hostId: 'local', - pid: 424242, - processStartTimeMs: clock.now, - spawnToken: 'fixture-only' - }, - now: clock.now - }) - await store.proveOwner({ - sessionId: SESSION, - fence: 1, - link: { - linkId: 'adopted', - handle: codexProviderHandle(THREAD), - origin: 'adopted', - mintedAtFence: 1, - observedAt: clock.now - }, - now: clock.now - }) - const filePath = join(c.root, 'rollout.jsonl') - await writeFile( - filePath, - [ - { - timestamp: '1970-01-01T00:01:40.000Z', - type: 'event_msg', - payload: { type: 'user_message', message: 'old A ask' } - }, - { - timestamp: '1970-01-01T00:01:50.000Z', - type: 'event_msg', - payload: { type: 'agent_message', message: 'old A answer' } - } - ] - .map((line) => JSON.stringify(line)) - .join('\n') - ) - clock.now = 200_000 - expect( - await importLegacyTranscriptIntoJournal({ - journal: c.journal, - agent: 'codex', - sessionId: THREAD, - fence: 1, - options: { filePath } - }) - ).toMatchObject({ ok: true, imported: 2 }) - const original = c.journal.snapshot().items - const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) - await c.open([dated(100), dated(300)]) - const target = agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-300', - ordinal: 0 - }) - const operationId = '0000000500000-00000000000000000000000000000002' - await store.admitOperation({ - callerKey, - operationId, - fingerprint: 'rewind', - now: 500_000 - }) - await store.transitionHandoff(SESSION, (record) => ({ - ...record, - rewind: { - operationId, - callerKey, - itemId: target, - expectedEpoch: c.journal.epoch, - phase: 'provider-succeeded' - } - })) - clock.now = 500_000 - const deps = () => ({ store, logger: testEventSinkLogging().logger }) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - await c.reopen() - store = await openTestAgentSessionRecordStore(c.root) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') - expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:old A answer', - 'assistant:answer 250', - 'assistant:answer 600' - ]) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - const complete = c.journal.snapshot() - await c.reopen() - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.journal.snapshot()).toEqual(complete) - }) +export { chat, turn } from './codex-thread-catch-up-contract-test-fixture' - it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { - const c = await chat({ now: 200_000 }) - const kept = { - identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, - ownerFence: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'legacy' }] - } - } - await c.journal.replaceEpochItems('session_created', 1, [kept]) - await c.reopen() - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.open([turn(3)]) - expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) - }) -}) +registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) diff --git a/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts new file mode 100644 index 000000000000..15eb1de0a051 --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts @@ -0,0 +1,136 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect } from 'vitest' +import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { catchUpCodexThread } from './codex-structured-thread-catch-up' + +export const SESSION = 'session-codex-catch-up' + +export const THREAD = 'thread-abc' + +export const STARTED_AT = 1_700_000_000 + +export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { + return { + id: `turn-${index}`, + status: 'completed', + itemsView: view, + startedAt: STARTED_AT + index * 100, + completedAt: STARTED_AT + index * 100 + 50, + items: [ + { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, + { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } + ] + } +} + +export function codexWith(turns: Record[]) { + return { + request: async (method: string, params?: Record) => { + expect(method).toBe('thread/turns/list') + expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) + const newestFirst = turns.toReversed() + const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 + const data = newestFirst.slice(start, start + 2) + return { + data, + nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null + } + } + } +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) { + await cleanup() + } +}) + +export async function chat(clock: { now: number }) { + const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) + const journalOptions = { + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + } satisfies AgentSessionJournalIdentity, + stateDirectory: root, + now: () => clock.now + } + let journal = await journals.open(journalOptions) + let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const publications: number[] = [] + const bind = () => + deferred.bind({ + journal, + fence: 1, + publish: () => { + publications.push(journal.snapshot().items.length) + } + }) + bind() + cleanups.push(async () => { + deferred.close() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + return { + get journal() { + return journal + }, + get deferred() { + return deferred + }, + root, + get db() { + return openTestJournalHostDatabase(root).db + }, + publications, + reopen: async () => { + deferred.close() + await journal.close() + await closeTestJournalHostDatabase(root) + journal = await journals.open(journalOptions) + deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + bind() + }, + open: async ( + turns: Record[], + options: Partial[0]> = {} + ) => { + await catchUpCodexThread({ + connection: codexWith(turns), + threadId: THREAD, + sessionId: SESSION, + sink: deferred.sink, + ...options + }) + return deferred.drained() + }, + texts: () => + journal.snapshot().items.flatMap((item) => { + if (item.body.kind === 'message') { + const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) + return [`${item.body.role}:${text.join('')}`] + } + return item.body.kind === 'status' && item.body.presentation + ? [`(${item.body.presentation})`] + : [] + }) + } +} diff --git a/src/main/codex/codex-thread-catch-up-rewind.test.ts b/src/main/codex/codex-thread-catch-up-rewind.test.ts new file mode 100644 index 000000000000..bd145d5a57f7 --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-rewind.test.ts @@ -0,0 +1,160 @@ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' +import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' +import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' +import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' + +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +it('retains the original adoption cutoff through native rewind and disk recovery', async () => { + const clock = { now: 50_000 } + const c = await chat(clock) + let store = await openTestAgentSessionRecordStore(c.root) + const callerKey = 'catch-up-test' + await store.reserveOwner({ + sessionId: SESSION, + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' + }, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, + expectedFence: null, + spawnToken: 'fixture-only', + claimKeyId: 'fixture', + handoffOperationId: null, + probe: { outcome: 'indeterminate', reason: 'fixture' }, + operation: { + callerKey, + operationId: '0000000050000-00000000000000000000000000000001', + fingerprint: 'create' + }, + now: clock.now + }) + await store.commitProcessIdentity({ + sessionId: SESSION, + fence: 1, + process: { + hostId: 'local', + pid: 424242, + processStartTimeMs: clock.now, + spawnToken: 'fixture-only' + }, + now: clock.now + }) + await store.proveOwner({ + sessionId: SESSION, + fence: 1, + link: { + linkId: 'adopted', + handle: codexProviderHandle(THREAD), + origin: 'adopted', + mintedAtFence: 1, + observedAt: clock.now + }, + now: clock.now + }) + const filePath = join(c.root, 'rollout.jsonl') + await writeFile( + filePath, + [ + { + timestamp: '1970-01-01T00:01:40.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'old A ask' } + }, + { + timestamp: '1970-01-01T00:01:50.000Z', + type: 'event_msg', + payload: { type: 'agent_message', message: 'old A answer' } + } + ] + .map((line) => JSON.stringify(line)) + .join('\n') + ) + clock.now = 200_000 + expect( + await importLegacyTranscriptIntoJournal({ + journal: c.journal, + agent: 'codex', + sessionId: THREAD, + fence: 1, + options: { filePath } + }) + ).toMatchObject({ ok: true, imported: 2 }) + const original = c.journal.snapshot().items + const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) + await c.open([dated(100), dated(300)]) + const target = agentJournalItemKey({ + provider: 'codex', + threadId: THREAD, + turnId: 'turn-300', + ordinal: 0 + }) + const operationId = '0000000500000-00000000000000000000000000000002' + await store.admitOperation({ + callerKey, + operationId, + fingerprint: 'rewind', + now: 500_000 + }) + await store.transitionHandoff(SESSION, (record) => ({ + ...record, + rewind: { + operationId, + callerKey, + itemId: target, + expectedEpoch: c.journal.epoch, + phase: 'provider-succeeded' + } + })) + clock.now = 500_000 + const deps = () => ({ store, logger: testEventSinkLogging().logger }) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + await c.reopen() + store = await openTestAgentSessionRecordStore(c.root) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') + expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:old A answer', + 'assistant:answer 250', + 'assistant:answer 600' + ]) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + const complete = c.journal.snapshot() + await c.reopen() + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.journal.snapshot()).toEqual(complete) +}) + +it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { + const c = await chat({ now: 200_000 }) + const kept = { + identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, + ownerFence: 1, + body: { + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text: 'legacy' }] + } + } + await c.journal.replaceEpochItems('session_created', 1, [kept]) + await c.reopen() + await c.journal.appendItem( + { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + await c.open([turn(3)]) + expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) +}) diff --git a/src/main/codex/codex-turn-lifecycle-completion.test.ts b/src/main/codex/codex-turn-lifecycle-completion.test.ts new file mode 100644 index 000000000000..1bb894a9ad93 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-completion.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from 'vitest' +import { + readAgentJournalTurn, + readAgentJournalTurnOutcome +} from '../../shared/agent-session-turn-record' +import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' +import type { CodexSession } from './codex-structured-session-state' + +import { + LIFECYCLE_KEY, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + notification, + recorder, + reduced, + translatorFor +} from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('keeps the verdict when a send echoed after completion revises the settled row', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) + }) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) + ) + translator.handle( + notification( + 'item/started', + { + turn: { id: TURN_ID }, + item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } + }, + 2_100 + ) + ) + + // requestedAt distinguishes the post-echo revision from the original terminal row. + const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) + expect(lifecycle?.body).toMatchObject({ + kind: 'turn', + state: 'completed', + outcome: 'failure', + requestedAt: 900 + }) + }) + + it('carries the provider duration and the same user item onto the terminal row', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification( + 'turn/completed', + { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, + 4_500 + ) + ) + + expect(tap.rows.at(-1)).toEqual({ + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + outcome: 'success', + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 4_500, + durationMs: 3_250 + } + }) + }) + + it.each([ + ['interrupted', 'interrupted', 'cancellation'], + ['failed', 'completed', 'failure'], + ['someFutureStatus', 'completed', undefined], + ['inProgress', 'completed', undefined] + ] as const)( + 'maps a %s turn status to a %s lifecycle with outcome %s', + (status, state, outcome) => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) + + expect(tap.tombstones).toEqual([]) + expect(reduced(tap.rows)).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state, + ...(outcome ? { outcome } : {}), + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 2_000 + } + } + ]) + } + ) + + it('records no outcome for a turn end that named no status', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) + + const body = reduced(tap.rows).at(-1)?.body + expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) + expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() + }) + + it('stamps the host clock when a boundary arrives without a receipt time', () => { + const tap = recorder() + let clock = 10_000 + const translator = translatorFor(tap, () => (clock += 250)) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) + + expect(tap.rows.map((row) => row.body)).toMatchObject([ + { kind: 'turn', state: 'running', startedAt: 10_250 }, + { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } + ]) + }) + + it('writes only the end time, and no duration, when Codex reports neither', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) + + expect(tap.rows).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + userItemId: USER_ITEM_ID, + completedAt: 3_000 + } + } + ]) + }) + + it('replays an oversized backpressured notification with its original receipt time', async () => { + vi.useFakeTimers() + const connection = { + pauseReading: vi.fn(), + resumeReading: vi.fn() + } as unknown as CodexAppServerConnection + const translate = vi + .fn[0]['translate']>() + .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) + .mockReturnValue({ accepted: true }) + const retries = createCodexStructuredNotificationRetry({ + sessionFor: () => ({ connection, ended: false }) as CodexSession, + translate + }) + + expect( + retries.handle( + SESSION_ID, + 'turn/started', + { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, + 1_000, + -1 + ) + ).toEqual({ accepted: false, reason: 'backpressure' }) + await vi.advanceTimersByTimeAsync(50) + + expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) + expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) + expect(connection.resumeReading).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts new file mode 100644 index 000000000000..8726041f89ae --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts @@ -0,0 +1,92 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' + +export const SESSION_ID = 'session-1' + +export const THREAD_ID = 'thread-abc' + +export const TURN_ID = 'turn-1' + +export const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' + +export const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' + +export type Row = { key: string; body: AgentJournalItemBody } + +export function recorder() { + const rows: Row[] = [] + const tombstones: string[] = [] + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity: AgentJournalItemIdentity, body) => + rows.push({ key: agentJournalItemKey(identity), body }), + appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), + publish: () => {} + } + return { sink, rows, tombstones } +} + +export function reduced(rows: readonly Row[]): Row[] { + const latest = new Map() + for (const row of rows) { + latest.set(row.key, row) + } + return [...latest.values()] +} + +export function notification( + method: string, + params: unknown, + observedAt?: number +): CodexStructuredSessionEvent { + return { + type: 'notification', + sessionId: SESSION_ID, + threadId: THREAD_ID, + method, + params, + ...(observedAt !== undefined ? { observedAt } : {}) + } +} + +export function translatorFor(tap: ReturnType, now?: () => number) { + return createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + ...(now ? { now } : {}) + }) +} + +export const journals = createTrackedJournalOpener() + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + vi.useRealTimers() +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/codex/codex-turn-lifecycle-history.test.ts b/src/main/codex/codex-turn-lifecycle-history.test.ts new file mode 100644 index 000000000000..6ba26dc3b673 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-history.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' + +import { THREAD_ID, recorder, translatorFor } from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('restores historical turn rows with optional endpoints in milliseconds', () => { + const tap = recorder() + const translator = translatorFor(tap) + + expect( + translator.restoreThread(THREAD_ID, { + turns: [ + { + id: 'turn-done', + status: 'completed', + startedAt: 1_700_000_000, + completedAt: 1_700_000_042, + durationMs: 41_900, + items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] + }, + { + id: 'turn-cut', + status: 'interrupted', + startedAt: 1_700_000_100, + completedAt: 1_700_000_101, + items: [] + }, + { + id: 'turn-failed', + status: 'failed', + startedAt: 1_700_000_150, + completedAt: 1_700_000_152, + durationMs: 2_400, + items: [] + }, + { + id: 'turn-unplaced', + status: 'someFutureStatus', + startedAt: 1_700_000_170, + completedAt: 1_700_000_171, + items: [] + }, + { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, + { id: 'turn-untimed', status: 'completed', items: [] } + ] + }) + ).toEqual({ accepted: true }) + + expect(tap.rows).toEqual([ + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', + body: { + kind: 'turn', + turnId: 'turn-done', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-done:0', + startedAt: 1_700_000_000_000, + completedAt: 1_700_000_042_000, + durationMs: 41_900 + } + }, + expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', + body: { + kind: 'turn', + turnId: 'turn-cut', + state: 'interrupted', + outcome: 'cancellation', + userItemId: 'codex:thread-abc:turn-cut:0', + startedAt: 1_700_000_100_000, + completedAt: 1_700_000_101_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', + body: { + kind: 'turn', + turnId: 'turn-failed', + state: 'completed', + outcome: 'failure', + userItemId: 'codex:thread-abc:turn-failed:0', + startedAt: 1_700_000_150_000, + completedAt: 1_700_000_152_000, + durationMs: 2_400 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', + body: { + kind: 'turn', + turnId: 'turn-unplaced', + state: 'completed', + userItemId: 'codex:thread-abc:turn-unplaced:0', + startedAt: 1_700_000_170_000, + completedAt: 1_700_000_171_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', + body: { + kind: 'turn', + turnId: 'turn-open', + state: 'completed', + userItemId: 'codex:thread-abc:turn-open:0', + startedAt: 1_700_000_200_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', + body: { + kind: 'turn', + turnId: 'turn-untimed', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-untimed:0' + } + } + ]) + expect(tap.tombstones).toEqual([]) + }) + + it('restores no lifecycle rows without a session identity to key them by', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + primaryThreadId: () => THREAD_ID + }) + + translator.restoreThread(THREAD_ID, { + turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] + }) + + expect(tap.rows).toEqual([]) + }) +}) diff --git a/src/main/jsonl-rpc/timeline-lane.test.ts b/src/main/jsonl-rpc/timeline-lane.test.ts index 8ef584d1ac35..dc1cc3ce468a 100644 --- a/src/main/jsonl-rpc/timeline-lane.test.ts +++ b/src/main/jsonl-rpc/timeline-lane.test.ts @@ -116,6 +116,8 @@ describe('JSON-lines timeline admission', () => { await vi.advanceTimersByTimeAsync(250) await test.lane.drained() expect(test.lane.openTurnId).not.toBeNull() + // Close the journal's projection repair timer; leave the lane alive to detect retry leaks. + await test.journal.journal.close() expect(vi.getTimerCount()).toBe(0) }) diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json new file mode 100644 index 000000000000..2d28523c716f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json @@ -0,0 +1,456 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "rows": [ + "{\"v\":2,\"kind\":\"epoch\",\"epoch\":\"epoch-1\",\"seq\":1,\"fence\":0,\"ts\":1001,\"reason\":\"session_created\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"historyOrigin\":{\"version\":1,\"kind\":\"legacy_import\"}}", + "{\"v\":2,\"kind\":\"submission\",\"epoch\":\"epoch-1\",\"seq\":2,\"fence\":1,\"ts\":1002,\"clientMessageId\":\"send-1\",\"payloadFingerprint\":\"f1\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"handoverRecorded\":true,\"origin\":\"client\",\"options\":{\"model\":\"gpt-5\",\"effort\":\"high\",\"retired\":\"x\"}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":3,\"fence\":1,\"ts\":1003,\"clientMessageId\":\"send-1\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"carries\":[]}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":4,\"fence\":1,\"ts\":1004,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"running\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":5,\"fence\":1,\"ts\":1005,\"clientMessageId\":\"send-1\",\"state\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"answeredInTurn\":{\"turnItemId\":\"codex:thread-1:turn-1:0\",\"via\":\"start\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":6,\"fence\":1,\"ts\":1006,\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Reading\"},{\"type\":\"tool-call\",\"name\":\"Read\",\"input\":{\"path\":\"a.ts\"},\"callId\":\"call-1\"},{\"type\":\"tool-result\",\"output\":\"ok\",\"callId\":\"call-1\"}]}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":7,\"fence\":1,\"ts\":1007,\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\",\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"running\"}}", + "{\"v\":2,\"kind\":\"lifecycle-batch\",\"epoch\":\"epoch-1\",\"seq\":8,\"fence\":1,\"ts\":1008,\"settlementId\":\"settle-1\",\"mutations\":[{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":2,\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"completed\",\"endedAs\":\"completed\",\"exitCode\":0},\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\"},{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":2}]}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":9,\"fence\":1,\"ts\":1009,\"messageId\":\"card-1\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":1,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":9},\"options\":{\"model\":\"gpt-5\"}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":10,\"fence\":1,\"ts\":1010,\"messageId\":\"card-1\",\"change\":{\"op\":\"edited\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate both\"}]}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":11,\"fence\":1,\"ts\":1011,\"messageId\":\"card-2\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":11}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":12,\"fence\":1,\"ts\":1012,\"messageId\":\"card-2\",\"change\":{\"op\":\"moved\",\"position\":0}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":13,\"fence\":1,\"ts\":1013,\"itemId\":\"orca:stop-13\",\"revision\":1,\"stopEvent\":{\"reason\":\"user-stop\",\"turnId\":\"turn-1\",\"at\":1013,\"caller\":\"client\"}}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":14,\"fence\":1,\"ts\":1014,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":2,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"interrupted\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002,\"completedAt\":1014,\"contextUsage\":{\"window\":{\"tokens\":200000,\"capturedAt\":1014},\"used\":{\"kind\":\"estimate\",\"usage\":{\"inputTokens\":10,\"cacheCreationInputTokens\":0,\"cacheReadInputTokens\":0,\"outputTokens\":5},\"capturedAt\":1014}}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":15,\"fence\":1,\"ts\":1015,\"messageId\":\"card-2\",\"change\":{\"op\":\"held\",\"holdReason\":\"send_failed\"}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":16,\"fence\":1,\"ts\":1016,\"itemId\":\"orca:resume-16\",\"revision\":1,\"queueResume\":true}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":17,\"fence\":1,\"ts\":1017,\"itemId\":\"codex:thread-1:turn-2:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"approval\",\"title\":\"Run shell?\",\"detail\":null,\"options\":[{\"id\":\"yes\",\"label\":\"Yes\"}],\"subject\":{\"kind\":\"plan\",\"text\":\"Plan\"},\"resolution\":{\"state\":\"approved\",\"selectedOptionId\":\"yes\",\"resolvedBy\":\"client\",\"resolvedAt\":1017}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":18,\"fence\":1,\"ts\":1018,\"messageId\":\"card-1\",\"change\":{\"op\":\"withdrawn\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":19,\"fence\":1,\"ts\":1019,\"itemId\":\"codex:thread-1:turn-2:1\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"status\",\"text\":\"The agent stopped.\",\"failure\":{\"kind\":\"providerExited\",\"detail\":{\"text\":\"exit 1\",\"audience\":\"log\"}}}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-3:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-3\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":20,\"fence\":1,\"ts\":1020,\"ownerFence\":1,\"executionOwner\":2,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"item\",\"echoOf\":null,\"itemId\":\"codex:thread-1:turn-3:1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Echoed\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":21,\"fence\":1,\"ts\":1021,\"ownerFence\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-3:0\"}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-4\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":22,\"fence\":1,\"ts\":1022,\"ownerFence\":1,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":2,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":23,\"fence\":1,\"ts\":1023}", + "{\"kind\":\"queue\",\"messageId\":\"card-3\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":23}},\"v\":4,\"epoch\":\"epoch-1\",\"seq\":24,\"fence\":1,\"ts\":1024}", + "{\"kind\":\"submission\",\"clientMessageId\":\"send-2\",\"payloadFingerprint\":\"d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":25,\"fence\":1,\"ts\":1025,\"handoverRecorded\":true,\"queuedMessageId\":\"card-3\"}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":26,\"fence\":1,\"ts\":1026,\"turnScope\":{\"kind\":\"thread\"},\"carries\":[\"send-1\"]}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"rejected\",\"providerItemId\":null,\"reason\":\"provider_cancelled_before_start\",\"rejection\":{\"kind\":\"cancelled\"},\"answeredInTurn\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":27,\"fence\":1,\"ts\":1027}" + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 27, + "lastActivityAt": 1027, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 3, + "observedAt": 1003, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:0", + { + "itemId": "codex:thread-1:turn-1:0", + "revision": 2, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "interrupted", + "userItemId": "orca:send-1", + "startedAt": 1004, + "requestedAt": 1002, + "completedAt": 1014, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 1014 + }, + "used": { + "kind": "estimate", + "usage": { + "inputTokens": 10, + "cacheCreationInputTokens": 0, + "cacheReadInputTokens": 0, + "outputTokens": 5 + }, + "capturedAt": 1014 + } + } + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 2, + "body": { + "kind": "tool-call", + "name": "shell", + "input": { + "command": "ls" + }, + "callId": "call-2", + "state": "completed", + "endedAs": "completed", + "exitCode": 0 + }, + "sequence": 7, + "observedAt": 1007, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:0" + }, + "agentId": "child-1", + "producerKind": "agent" + } + ], + [ + "codex:thread-1:turn-2:0", + { + "itemId": "codex:thread-1:turn-2:0", + "revision": 1, + "body": { + "kind": "approval", + "title": "Run shell?", + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes" + } + ], + "subject": { + "kind": "plan", + "text": "Plan" + }, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "resolvedBy": "client", + "resolvedAt": 1017 + } + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-2:1", + { + "itemId": "codex:thread-1:turn-2:1", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent stopped.", + "failure": { + "kind": "providerExited", + "detail": { + "text": "exit 1", + "audience": "log" + } + } + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:0", + { + "itemId": "codex:thread-1:turn-3:0", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-3", + "state": "running" + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:1", + { + "itemId": "codex:thread-1:turn-3:1", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Echoed" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-3:0" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:0", 1], + ["codex:thread-1:turn-1:3", 1], + ["codex:thread-1:turn-2:0", 1], + ["codex:thread-1:turn-2:1", 1], + ["codex:thread-1:turn-3:0", 1], + ["codex:thread-1:turn-3:1", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-3:0", 2]], + "providerActivityAt": [ + [1, 1022], + [2, 1020] + ], + "tombstones": [ + ["codex:thread-1:turn-1:2", 2], + ["codex:thread-1:turn-4:0", 2] + ], + "removedTurnIds": ["turn-4"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f1", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1002, + "resolvedAt": 1005, + "submittedSequence": 2, + "handoverRecorded": true, + "acceptedSequence": 2, + "origin": "client", + "options": { + "model": "gpt-5", + "effort": "high" + }, + "handedOverAt": 1003 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "provider_cancelled_before_start", + "submittedAt": 1025, + "resolvedAt": 1027, + "submittedSequence": 25, + "handoverRecorded": true, + "acceptedSequence": 25, + "handedOverAt": 1026, + "rejection": { + "kind": "cancelled" + }, + "answeredInTurn": null + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-3:1", null]], + "appliedSettlementIds": ["settle-1"], + "derivedTurnScope": null, + "latestAcceptedTurnSequence": 2, + "queuePauseMarks": { + "latestStop": { + "sequence": 13, + "event": { + "reason": "user-stop", + "turnId": "turn-1", + "at": 1013, + "caller": "client" + } + }, + "resumedSequence": 16, + "reopenedSequence": 0 + }, + "stoppedHistoryCarried": [["send-2", ["send-1"]]], + "queuedHandOffPlaces": [ + [ + "send-2", + { + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-2"], + "queue": { + "revision": 8, + "cards": [ + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate both" + } + ] + }, + "fingerprint": "62f92d8004a31a5be6ee414930186d2097897cbbbb53e1e3607e6b2719b912f9", + "state": "withdrawn", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 9 + }, + "options": { + "model": "gpt-5" + } + } + ], + [ + "card-2", + { + "messageId": "card-2", + "position": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "waiting", + "holdReason": "send_failed", + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 11 + } + } + ], + [ + "card-3", + { + "messageId": "card-3", + "position": 2, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "fingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-2", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 23 + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import" + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json new file mode 100644 index 000000000000..1c8d4af930d2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json @@ -0,0 +1,1178 @@ +[ + [ + "items", + "\"item-0\"", + { + "itemId": "item-0", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-1\"", + { + "itemId": "item-1", + "revision": 1, + "body": { + "kind": "agent-start", + "dispatchId": "d", + "task": "do it", + "worker": { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-2\"", + { + "itemId": "item-2", + "revision": 1, + "body": { + "kind": "tool-call", + "name": "shell", + "input": {}, + "callId": "call-2", + "state": "running", + "endedAs": "interrupted", + "output": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + }, + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 1, + "durationMs": 2, + "webSearchResults": [] + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-3\"", + { + "itemId": "item-3", + "revision": 1, + "body": { + "kind": "diff", + "path": "a.ts", + "patch": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-4\"", + { + "itemId": "item-4", + "revision": 1, + "body": { + "kind": "approval", + "title": "Approve?", + "displayName": "Shell", + "description": "d", + "decisionReason": "r", + "blockedPath": "/b", + "matchedAskRule": { + "source": "settings", + "toolName": "Bash", + "ruleContent": "ls" + }, + "subject": { + "kind": "plan", + "text": "Plan", + "filePath": "/p" + }, + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes", + "description": "d" + } + ], + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-5\"", + { + "itemId": "item-5", + "revision": 1, + "body": { + "kind": "question", + "question": "Which?", + "options": [ + { + "id": "a", + "label": "A" + } + ], + "questions": [ + { + "id": "q1", + "question": "Which?", + "header": "H", + "multiSelect": false, + "options": [ + { + "id": "a", + "label": "A" + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "allowEmpty": true, + "multiline": true, + "initialValue": "", + "placeholder": "p" + } + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "multiline": false + }, + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-6\"", + { + "itemId": "item-6", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent could not start.", + "presentation": "notice", + "tone": "error", + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "turnLifecycle": { + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "threadGoal": { + "state": "set", + "goal": { + "objective": "o", + "status": "active", + "tokenBudget": null, + "tokensUsed": 1, + "timeUsedSeconds": 2, + "createdAt": 1, + "updatedAt": 2 + } + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-7\"", + { + "itemId": "item-7", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "submissions", + "\"send-1\"", + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "refused", + "rejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "submittedAt": 1, + "resolvedAt": 2, + "submittedSequence": 3, + "answeredInTurn": { + "turnItemId": "t", + "via": "start" + }, + "recovered": true, + "handoverRecorded": true, + "handedOverAt": 2, + "acceptedSequence": 4, + "queuedMessageId": "card-1", + "origin": "client", + "source": { + "kind": "agent" + }, + "keptAsQueuedMessageId": "card-1", + "options": { + "model": "m", + "effort": "high", + "personality": "p", + "fastMode": "true", + "serviceTier": "t" + } + } + ] + ], + [ + "queue.cards", + "\"card-1\"", + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "fingerprint": "f", + "state": "returned", + "holdReason": null, + "returnedReason": "refused", + "returnedRejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "m" + } + } + ] + ] +] diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json new file mode 100644 index 000000000000..4e400c0a4c2f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json @@ -0,0 +1,894 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "through": 21, + "marker": "{\"v\":5,\"kind\":\"outcomes\",\"epoch\":\"epoch-1\",\"seq\":1,\"ts\":1001}", + "outcomes": [ + [1, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [1, "$", "\"epoch\"", 1, "s0000000000000001:0000000000000001", "\"epoch-1\"", 0], + [1, "$", "\"highestFence\"", 1, "s0000000000000001:0000000000000005", "1", 0], + [ + 1, + "$", + "\"historyOrigin\"", + 1, + "s0000000000000001:0000000000000010", + "{\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"raw\":{\"version\":1,\"kind\":\"legacy_import\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"importedAt\":1001}}", + 0 + ], + [1, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "0", 0], + [1, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "0", 0], + [1, "$", "\"oldestSequence\"", 1, "s0000000000000001:0000000000000004", "1", 0], + [1, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":0}", 0], + [ + 1, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":null,\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [1, "$", "\"sessionId\"", 1, "s0000000000000001:0000000000000000", "\"session-1\"", 0], + [2, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":1}", 0], + [ + 2, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"waiting\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":null,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [3, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1003", 0], + [3, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":2}", 0], + [ + 3, + "itemFences", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000003", + "[\"orca:send-1\",1]", + 0 + ], + [ + 3, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":3,\"observedAt\":1003,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 3, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"dispatched\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":\"send-1\",\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [ + 3, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\"}]", + 0 + ], + [4, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1004", 0], + [ + 4, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 4, + "queuedHandOffPlaces", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000002", + "[\"send-1\",{\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}]", + 0 + ], + [ + 4, + "stoppedHistoryCarried", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000003", + "[\"send-1\",[\"stopped-2\",\"stopped-1\"]]", + 0 + ], + [ + 4, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [5, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1005", 0], + [5, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "3", 0], + [ + 5, + "aliases", + "\"codex:thread-1:turn-1:1\"", + 1, + "s0000000000000005:0000000000000002", + "[\"codex:thread-1:turn-1:1\",\"orca:send-1\"]", + 0 + ], + [ + 5, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 5, + "receipts", + "\"send-1\"", + 1, + "s0000000000000005:0000000000000003", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"cursor\":{\"epoch\":\"epoch-1\",\"sequence\":5},\"acceptedAt\":1005}]", + 0 + ], + [ + 5, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":1005,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [6, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1006", 0], + [ + 6, + "itemEchoes", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000002", + "[\"codex:thread-1:turn-1:2\"]", + 0 + ], + [ + 6, + "itemFences", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000001", + "[\"codex:thread-1:turn-1:2\",1]", + 0 + ], + [ + 6, + "items", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"echo\"}]},\"sequence\":6,\"observedAt\":1006,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [6, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1006]", 0], + [7, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1007", 0], + [ + 7, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 7, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"removed\"}]},\"sequence\":7,\"observedAt\":1007,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [7, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1007]", 0], + [8, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1008", 0], + [ + 8, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "null", + 1 + ], + [8, "items", "\"codex:thread-1:turn-1:3\"", 1, "s0000000000000007:0000000000000000", "null", 1], + [ + 8, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "[\"codex:thread-1:turn-1:3\",2]", + 0 + ], + [9, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1009", 0], + [ + 9, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [10, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1010", 0], + [ + 10, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [11, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1011", 0], + [ + 11, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":11,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [12, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1012", 0], + [ + 12, + "appliedSettlementIds", + "\"settlement-0\"", + 1, + "s0000000000000012:0000000000000003", + "[\"settlement-0\",\"settlement-0\"]", + 0 + ], + [ + 12, + "itemFences", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000001", + "[\"codex:thread-1:turn-1:4\",1]", + 0 + ], + [ + 12, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 0\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [12, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1012]", 0], + [13, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1013", 0], + [ + 13, + "appliedSettlementIds", + "\"settlement-1\"", + 1, + "s0000000000000013:0000000000000002", + "[\"settlement-1\",\"settlement-1\"]", + 0 + ], + [ + 13, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":2,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 1\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [13, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1013]", 0], + [14, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1014", 0], + [ + 14, + "appliedSettlementIds", + "\"settlement-2\"", + 1, + "s0000000000000014:0000000000000002", + "[\"settlement-2\",\"settlement-2\"]", + 0 + ], + [ + 14, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 2\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [14, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1014]", 0], + [ + 15, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:7\"", + 0 + ], + [15, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1015", 0], + [ + 15, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "[\"codex:thread-1:turn-1:7\",1]", + 0 + ], + [ + 15, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:7\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"removed-turn\",\"state\":\"running\"},\"sequence\":15,\"observedAt\":1015,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [15, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1015]", 0], + [16, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [16, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1016", 0], + [ + 16, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "null", + 1 + ], + [ + 16, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "null", + 1 + ], + [ + 16, + "removedTurnIds", + "\"removed-turn\"", + 1, + "s0000000000000016:0000000000000003", + "[\"removed-turn\",\"removed-turn\"]", + 0 + ], + [ + 16, + "tombstones", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000016:0000000000000000", + "[\"codex:thread-1:turn-1:7\",2]", + 0 + ], + [ + 17, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:5\"", + 0 + ], + [17, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1017", 0], + [ + 17, + "itemFences", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000001", + "[\"codex:thread-1:turn-1:5\",1]", + 0 + ], + [ + 17, + "items", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:5\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"open-turn\",\"state\":\"running\"},\"sequence\":17,\"observedAt\":1017,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [17, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1017]", 0], + [18, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1018", 0], + [ + 18, + "itemExecutionOwners", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000002", + "[\"codex:thread-1:turn-1:6\",2]", + 0 + ], + [ + 18, + "itemFences", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000001", + "[\"codex:thread-1:turn-1:6\",1]", + 0 + ], + [ + 18, + "items", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:6\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Working\"}]},\"sequence\":18,\"observedAt\":1018,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [18, "providerActivityAt", "2", 1, "s0000000000000018:0000000000000003", "[2,1018]", 0], + [19, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1019", 0], + [ + 19, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000002", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 19, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000001", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Recreated\"}]},\"sequence\":19,\"observedAt\":1019,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [19, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1019]", 0], + [ + 19, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "null", + 1 + ], + [20, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1020", 0], + [ + 20, + "itemFences", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000002", + "[\"orca:send-3\",1]", + 0 + ], + [ + 20, + "items", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000001", + "{\"itemId\":\"orca:send-3\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":20,\"observedAt\":1020,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 20, + "submissions", + "\"send-3\"", + 1, + "s0000000000000020:0000000000000000", + "[\"send-3\",{\"clientMessageId\":\"send-3\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1020,\"resolvedAt\":null,\"submittedSequence\":20}]", + 0 + ], + [21, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1021", 0], + [ + 21, + "itemFences", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000002", + "[\"orca:send-2\",1]", + 0 + ], + [ + 21, + "items", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000001", + "{\"itemId\":\"orca:send-2\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":21,\"observedAt\":1021,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 21, + "normalizedHandOffs", + "\"send-1\"", + 1, + "s0000000000000021:0000000000000099", + "[\"send-1\",\"send-1\"]", + 0 + ], + [ + 21, + "submissions", + "\"send-2\"", + 1, + "s0000000000000021:0000000000000000", + "[\"send-2\",{\"clientMessageId\":\"send-2\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1021,\"resolvedAt\":null,\"submittedSequence\":21}]", + 0 + ] + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 21, + "lastActivityAt": 1021, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:2", + { + "itemId": "codex:thread-1:turn-1:2", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "echo" + } + ] + }, + "sequence": 6, + "observedAt": 1006, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:4", + { + "itemId": "codex:thread-1:turn-1:4", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "progress 2" + } + ] + }, + "sequence": 12, + "observedAt": 1012, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:5", + { + "itemId": "codex:thread-1:turn-1:5", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "open-turn", + "state": "running" + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:6", + { + "itemId": "codex:thread-1:turn-1:6", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Working" + } + ] + }, + "sequence": 18, + "observedAt": 1018, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Recreated" + } + ] + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-3", + { + "itemId": "orca:send-3", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:2", 1], + ["codex:thread-1:turn-1:4", 1], + ["codex:thread-1:turn-1:5", 1], + ["codex:thread-1:turn-1:6", 1], + ["codex:thread-1:turn-1:3", 1], + ["orca:send-3", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-1:6", 2]], + "providerActivityAt": [ + [1, 1019], + [2, 1018] + ], + "tombstones": [["codex:thread-1:turn-1:7", 2]], + "removedTurnIds": ["removed-turn"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1003, + "resolvedAt": 1005, + "submittedSequence": 3, + "handoverRecorded": true, + "acceptedSequence": 3, + "queuedMessageId": "draft", + "origin": "client", + "handedOverAt": 1004 + } + ], + [ + "send-3", + { + "clientMessageId": "send-3", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1020, + "resolvedAt": null, + "submittedSequence": 20 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1021, + "resolvedAt": null, + "submittedSequence": 21 + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-1:2", null]], + "appliedSettlementIds": ["settlement-0", "settlement-1", "settlement-2"], + "derivedTurnScope": "codex:thread-1:turn-1:5", + "latestAcceptedTurnSequence": 3, + "queuePauseMarks": { + "latestStop": { + "sequence": 9, + "event": { + "reason": "user-stop", + "at": 1009 + } + }, + "resumedSequence": 0, + "reopenedSequence": 11, + "cleared": { + "operationId": "clear-1", + "messageIds": ["draft"], + "sequence": 10 + } + }, + "stoppedHistoryCarried": [["send-1", ["stopped-2", "stopped-1"]]], + "queuedHandOffPlaces": [ + [ + "send-1", + { + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-1"], + "queue": { + "revision": 2, + "cards": [ + [ + "draft", + { + "messageId": "draft", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-1", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "model-a" + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import", + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "importedAt": 1001 + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts new file mode 100644 index 000000000000..cb918aac427d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts @@ -0,0 +1,39 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' + +export function registerJournalApprovalRevisionValidationTests( + fixture: ReturnType +): void { + it('admits an answer on an exhausted approval without changing the saved item', async () => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision: Number.MAX_SAFE_INTEGER + 1, + body: fixture.pendingApproval() + } + ]) + const before = fixture.journal.snapshot().items[0] + const cursor = fixture.journal.cursor() + await expect( + fixture.journal.appendItem( + fixture.identity, + { + ...fixture.pendingApproval(), + kind: 'approval', + resolution: { + state: 'resolved', + selectedOptionId: null, + resolvedBy: 'user', + resolvedAt: 1_000 + } + }, + { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).resolves.toBeDefined() + expect(fixture.journal.cursor().sequence).toBe(cursor.sequence + 1) + expect(fixture.journal.snapshot().items[0]).toEqual(before) + await fixture.expectSendStillWritable() + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts new file mode 100644 index 000000000000..db8ebf9bb219 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts @@ -0,0 +1,125 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + readTestJournalRows +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const SESSION = 'atomic-settlement' + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + async function open(sessionId = SESSION) { + return journals.open({ + identity: { + sessionId, + workspaceId: 'folder-workspace', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function rows() { + return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( + (stored) => { + const parsed = parseJournalRow(stored.rowJson) + if (!parsed.ok) { + throw new Error('test row failed to parse') + } + return parsed.row + } + ) + } + + async function seedWork(count = 201) { + await journal.appendSubmission({ + clientMessageId: 'send', + payloadFingerprint: 'fingerprint', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, + fence: 7 + }) + const turn = await journal.appendItem( + { provider: 'orca', clientMessageId: 'turn' }, + { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + for (let index = 0; index < count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `call-${index}` }, + { + kind: 'tool-call', + name: 'Write', + input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, + state: 'running' + }, + { + fence: 7, + turnScope: { kind: 'turn', turnItemId: turn.itemId }, + agentId: 'child', + producerKind: 'agent' + } + ) + } + } + + function settle() { + return settleObservedExitForTest({ + journal, + sessionId: SESSION, + fence: 7, + settlementId: `exit:${SESSION}:7`, + verdict: { state: 'interrupted', completedAt: 1_000 }, + pendingSubmissionReason: 'provider_exited_before_acknowledgement', + showUnexpectedExitOutcome: true + }) + } + + return { + SESSION, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + rows, + seedWork, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts new file mode 100644 index 000000000000..426303ae98d4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts @@ -0,0 +1,107 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementOversizedTests( + fixture: ReturnType +): void { + it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { + const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } + await fixture.journal.appendItem( + identity, + { kind: 'status', text: 'remove me' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + const before = fixture.journal.cursor() + const input = { + settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + fence: 7, + recovered: true as const, + mutations: [{ kind: 'tombstone' as const, identity }] + } + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot().items).toEqual([]) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + expect(fixture.rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + }) + + it.each(['startup', 'stop'] as const)( + 'rolls back the %s submission verdict with its oversized item', + async (mode) => { + await fixture.journal.appendSubmission({ + clientMessageId: 'unanswered', + payloadFingerprint: 'unanswered', + fence: 7, + handoverRecorded: true, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } + }) + await fixture.journal.resolveDispatch({ + clientMessageId: 'unanswered', + state: 'pending', + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + if (mode === 'stop') { + await fixture.journal.appendStopEvent({ reason: 'user-stop' }, 7) + } + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId: 'oversized-call' }, + { + kind: 'tool-call', + name: 'Write', + input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + state: 'running' + }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 7, + settlementId: `${mode}:7`, + verdict: { state: 'interrupted' as const, completedAt: 1_000 }, + pendingSubmissionReason: 'owner exited', + showUnexpectedExitOutcome: mode === 'startup', + ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) + } + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = 'item' + BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) + expect(fixture.journal.snapshot()).toEqual(before) + expect(fixture.rows()).toEqual(diskBefore) + expect(published).toEqual([]) + database.db.exec('DROP TRIGGER reject_submission_settlement_item') + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.journal.submission('unanswered')).toMatchObject({ + dispatchState: 'rejected', + recovered: true, + rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) + expect(published).toEqual([fixture.journal.snapshot()]) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toHaveLength(1) + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts new file mode 100644 index 000000000000..2e2fe11e0e2e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts @@ -0,0 +1,250 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from './journal-row-builders' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementRollbackTests( + fixture: ReturnType +): void { + it.each(['item', 'lifecycle-batch'] as const)( + 'rolls back a later %s rejection, publishes nothing, then retries exactly once', + async (kind) => { + await fixture.seedWork() + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + const frames: AgentSessionSubscribeEvent[] = [] + const emittedStates: AgentJournalSnapshot[] = [] + const subscribers = new AgentSessionSubscribers() + subscribers.open({ + id: 'reader', + sessionId: fixture.SESSION, + journal: fixture.journal, + fence: 7, + cursor: before.cursor, + emit: (event) => { + frames.push(event) + emittedStates.push(fixture.journal.snapshot()) + } + }) + frames.length = 0 + emittedStates.length = 0 + fixture.journal.observeCommits(() => { + published.push(fixture.journal.snapshot()) + subscribers.publish(fixture.SESSION, fixture.journal) + }) + const sawEarlierInserts: number[] = [] + const transaction = database.transaction.bind(database) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + } catch (error) { + sawEarlierInserts.push(fixture.rows().length - diskBefore.length) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + throw error + } + }, + streamed, + committed + ) + ) + database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = '${kind}' + AND NEW.seq > ${before.cursor.sequence + 1} + BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) + + expect(await fixture.settle()).toMatchObject({ ok: false }) + expect(sawEarlierInserts[0]).toBeGreaterThan(0) + expect(fixture.rows()).toEqual(diskBefore) + expect(fixture.journal.cursor()).toEqual(before.cursor) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + + vi.restoreAllMocks() + + const other = await fixture.open('other-chat') + await expect( + other.appendSubmission({ + clientMessageId: 'unrelated', + payloadFingerprint: 'other', + fence: 0, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence: 2 }) + + database.db.exec('DROP TRIGGER reject_later_settlement') + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + }, + streamed, + committed + ) + ) + expect(await fixture.settle()).toMatchObject({ ok: true }) + vi.restoreAllMocks() + const settled = fixture.journal.snapshot() + expect(published).toEqual([settled]) + expect(frames.length).toBeGreaterThan(0) + expect( + emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) + ).toBe(true) + expect( + emittedStates.every((state) => + state.items.every( + (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' + ) + ) + ).toBe(true) + expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) + const frameCount = frames.length + expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const calls = settled.items.filter((item) => item.body.kind === 'tool-call') + expect(calls).toHaveLength(201) + expect( + calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toBe(true) + expect(calls[0]).toMatchObject({ + observedAt: 1_000, + agentId: 'child', + revision: 2, + body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.map((row) => row.kind)).toEqual([ + 'dispatch', + 'lifecycle-batch', + 'item', + 'lifecycle-batch', + 'lifecycle-batch' + ]) + expect(committed.every((row) => row.recovered)).toBe(true) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toEqual([settled]) + expect(frames).toHaveLength(frameCount) + await fixture.journal.close() + fixture.journal = await fixture.open() + expect(fixture.journal.snapshot()).toEqual(settled) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + } + ) + + it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { + await fixture.seedWork(2) + const calls = fixture.journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') + const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ + kind: 'item', + observedAt: index + 1, + identity: { provider: 'orca', clientMessageId: `call-${index}` }, + body: { + kind: 'tool-call', + name: 'Write', + state: 'failed', + endedAs: 'interrupted', + input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } + }, + turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE + })) + const input = { + settlementId: 'all-oversized:7', + fence: 7, + recovered: true as const, + mutations + } + const before = fixture.journal.cursor() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + await fixture.journal.appendLifecycleBatch(input) + const settled = fixture.journal.snapshot() + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 2) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.kind) + ).toEqual(['item', 'item']) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) + ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.ts) + ).toEqual([1, 2]) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.observedAt) + ).toEqual(calls.map((item) => item.observedAt)) + expect(published).toEqual([settled]) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(published).toEqual([settled]) + expect( + await fixture.journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: input.settlementId, + fence: input.fence, + recovered: true, + resolve: () => mutations + } + } + ]) + ).toEqual([false]) + expect(fixture.journal.snapshot()).toEqual(settled) + await fixture.journal.close() + fixture.journal = await fixture.open() + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + }) + + it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { + await fixture.seedWork(1) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 8, + acquisitionGeneration: 'new-generation', + deathEvidence: { + kind: 'exit-observed' as const, + ownerFence: 7, + observedAt: 1_000, + detail: '' + } + } + expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) + const settled = fixture.journal.snapshot() + expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts index 6c8f3f649897..7b84274b6385 100644 --- a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts @@ -1,430 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalSnapshot -} from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from './journal-row-builders' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES, parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { registerJournalAtomicSettlementRollbackTests } from './journal-atomic-settlement-rollback.spec' +import { registerJournalAtomicSettlementOversizedTests } from './journal-atomic-settlement-oversized.spec' export function registerJournalAtomicTerminalSettlementTests(): void { - const SESSION = 'atomic-settlement' - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - - async function open(sessionId = SESSION) { - return journals.open({ - identity: { - sessionId, - workspaceId: 'folder-workspace', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function rows() { - return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( - (stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - throw new Error('test row failed to parse') - } - return parsed.row - } - ) - } - - async function seedWork(count = 201) { - await journal.appendSubmission({ - clientMessageId: 'send', - payloadFingerprint: 'fingerprint', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, - fence: 7 - }) - const turn = await journal.appendItem( - { provider: 'orca', clientMessageId: 'turn' }, - { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - for (let index = 0; index < count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `call-${index}` }, - { - kind: 'tool-call', - name: 'Write', - input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, - state: 'running' - }, - { - fence: 7, - turnScope: { kind: 'turn', turnItemId: turn.itemId }, - agentId: 'child', - producerKind: 'agent' - } - ) - } - } - - function settle() { - return settleObservedExitForTest({ - journal, - sessionId: SESSION, - fence: 7, - settlementId: `exit:${SESSION}:7`, - verdict: { state: 'interrupted', completedAt: 1_000 }, - pendingSubmissionReason: 'provider_exited_before_acknowledgement', - showUnexpectedExitOutcome: true - }) - } - - describe('atomic terminal settlement', () => { - it.each(['item', 'lifecycle-batch'] as const)( - 'rolls back a later %s rejection, publishes nothing, then retries exactly once', - async (kind) => { - await seedWork() - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - const frames: AgentSessionSubscribeEvent[] = [] - const emittedStates: AgentJournalSnapshot[] = [] - const subscribers = new AgentSessionSubscribers() - subscribers.open({ - id: 'reader', - sessionId: SESSION, - journal, - fence: 7, - cursor: before.cursor, - emit: (event) => { - frames.push(event) - emittedStates.push(journal.snapshot()) - } - }) - frames.length = 0 - emittedStates.length = 0 - journal.observeCommits(() => { - published.push(journal.snapshot()) - subscribers.publish(SESSION, journal) - }) - const sawEarlierInserts: number[] = [] - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - } catch (error) { - sawEarlierInserts.push(rows().length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - throw error - } - }) - ) - database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = '${kind}' - AND NEW.seq > ${before.cursor.sequence + 1} - BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) - - expect(await settle()).toMatchObject({ ok: false }) - expect(sawEarlierInserts[0]).toBeGreaterThan(0) - expect(rows()).toEqual(diskBefore) - expect(journal.cursor()).toEqual(before.cursor) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - - vi.restoreAllMocks() - - const other = await open('other-chat') - await expect( - other.appendSubmission({ - clientMessageId: 'unrelated', - payloadFingerprint: 'other', - fence: 0, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence: 2 }) - - database.db.exec('DROP TRIGGER reject_later_settlement') - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - }) - ) - expect(await settle()).toMatchObject({ ok: true }) - vi.restoreAllMocks() - const settled = journal.snapshot() - expect(published).toEqual([settled]) - expect(frames.length).toBeGreaterThan(0) - expect( - emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) - ).toBe(true) - expect( - emittedStates.every((state) => - state.items.every( - (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' - ) - ) - ).toBe(true) - expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) - const frameCount = frames.length - expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const calls = settled.items.filter((item) => item.body.kind === 'tool-call') - expect(calls).toHaveLength(201) - expect( - calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toBe(true) - expect(calls[0]).toMatchObject({ - observedAt: 1_000, - agentId: 'child', - revision: 2, - body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.map((row) => row.kind)).toEqual([ - 'dispatch', - 'lifecycle-batch', - 'item', - 'lifecycle-batch', - 'lifecycle-batch' - ]) - expect(committed.every((row) => row.recovered)).toBe(true) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toEqual([settled]) - expect(frames).toHaveLength(frameCount) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - } - ) - - it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { - await seedWork(2) - const calls = journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') - const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ - kind: 'item', - observedAt: index + 1, - identity: { provider: 'orca', clientMessageId: `call-${index}` }, - body: { - kind: 'tool-call', - name: 'Write', - state: 'failed', - endedAs: 'interrupted', - input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } - }, - turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE - })) - const input = { - settlementId: 'all-oversized:7', - fence: 7, - recovered: true as const, - mutations - } - const before = journal.cursor() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - await journal.appendLifecycleBatch(input) - const settled = journal.snapshot() - expect(journal.cursor().sequence).toBe(before.sequence + 2) - expect( - rows() - .slice(-2) - .map((row) => row.kind) - ).toEqual(['item', 'item']) - expect( - settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) - ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) - expect( - rows() - .slice(-2) - .map((row) => row.ts) - ).toEqual([1, 2]) - expect( - settled.items - .filter((item) => item.body.kind === 'tool-call') - .map((item) => item.observedAt) - ).toEqual(calls.map((item) => item.observedAt)) - expect(published).toEqual([settled]) - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - expect(published).toEqual([settled]) - expect( - await journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: input.settlementId, - fence: input.fence, - recovered: true, - resolve: () => mutations - } - } - ]) - ).toEqual([false]) - expect(journal.snapshot()).toEqual(settled) - await journal.close() - journal = await open() - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - }) - - it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { - await seedWork(1) - const input = { - journal, - sessionId: SESSION, - fence: 8, - acquisitionGeneration: 'new-generation', - deathEvidence: { - kind: 'exit-observed' as const, - ownerFence: 7, - observedAt: 1_000, - detail: '' - } - } - expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) - const settled = journal.snapshot() - expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) - expect(journal.snapshot()).toEqual(settled) - expect(rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) - }) - - it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { - const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } - await journal.appendItem( - identity, - { kind: 'status', text: 'remove me' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - const before = journal.cursor() - const input = { - settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - fence: 7, - recovered: true as const, - mutations: [{ kind: 'tombstone' as const, identity }] - } - await journal.appendLifecycleBatch(input) - expect(journal.snapshot().items).toEqual([]) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - expect(rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) - await journal.appendLifecycleBatch(input) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - }) - - it.each(['startup', 'stop'] as const)( - 'rolls back the %s submission verdict with its oversized item', - async (mode) => { - await journal.appendSubmission({ - clientMessageId: 'unanswered', - payloadFingerprint: 'unanswered', - fence: 7, - handoverRecorded: true, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } - }) - await journal.resolveDispatch({ - clientMessageId: 'unanswered', - state: 'pending', - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - if (mode === 'stop') { - await journal.appendStopEvent({ reason: 'user-stop' }, 7) - } - await journal.appendItem( - { provider: 'orca', clientMessageId: 'oversized-call' }, - { - kind: 'tool-call', - name: 'Write', - input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - state: 'running' - }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const input = { - journal, - sessionId: SESSION, - fence: 7, - settlementId: `${mode}:7`, - verdict: { state: 'interrupted' as const, completedAt: 1_000 }, - pendingSubmissionReason: 'owner exited', - showUnexpectedExitOutcome: mode === 'startup', - ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) - } - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = 'item' - BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) - expect(journal.snapshot()).toEqual(before) - expect(rows()).toEqual(diskBefore) - expect(published).toEqual([]) - database.db.exec('DROP TRIGGER reject_submission_settlement_item') - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(journal.submission('unanswered')).toMatchObject({ - dispatchState: 'rejected', - recovered: true, - rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) - expect(published).toEqual([journal.snapshot()]) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toHaveLength(1) - } - ) - }) + const fixture = createFixture() + registerJournalAtomicSettlementRollbackTests(fixture) + registerJournalAtomicSettlementOversizedTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-cursor.ts b/src/main/native-chat/agent-session-journal/journal-cursor.ts index cb8021eba418..b95841701008 100644 --- a/src/main/native-chat/agent-session-journal/journal-cursor.ts +++ b/src/main/native-chat/agent-session-journal/journal-cursor.ts @@ -5,7 +5,7 @@ import type { AgentJournalResetReason } from '../../../shared/agent-session-journal-types' import type { JournalReadSince } from './journal-store-contracts' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' export type JournalCursorRange = { epoch: string @@ -22,6 +22,18 @@ export function sameJournalCursor(a: AgentJournalCursor, b: AgentJournalCursor): return a.epoch === b.epoch && a.sequence === b.sequence } +export function journalWroteBeforeOpen( + current: Pick, + openedThrough: AgentJournalCursor, + sequence: number | undefined +): boolean { + return ( + sequence !== undefined && + current.epoch === openedThrough.epoch && + sequence <= openedThrough.sequence + ) +} + /** Reload snapshots for epoch mismatches, rolled-back prefixes or compacted cursors. */ export function resolveJournalResume( range: JournalCursorRange, @@ -58,7 +70,7 @@ export function findSequenceGap( export function readJournalSince( source: { state: { epoch: string; lastSequence: number; oldestSequence: number } - rowsAfter: (afterSequence: number) => JournalRow[] + rowsAfter: (afterSequence: number) => JournalReadRow[] }, cursor: AgentJournalCursor, currentCursor: () => AgentJournalCursor diff --git a/src/main/native-chat/agent-session-journal/journal-damage.test.ts b/src/main/native-chat/agent-session-journal/journal-damage.test.ts index 6117f56cf4e5..0d2b062decb8 100644 --- a/src/main/native-chat/agent-session-journal/journal-damage.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-damage.test.ts @@ -1,7 +1,7 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody, @@ -9,7 +9,7 @@ import { type AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type Database from '../../sqlite/sync-database' +import Database from '../../sqlite/sync-database' import type { openAgentSessionJournal } from './journal-store-factory' import { createTrackedJournalOpener, @@ -20,6 +20,7 @@ import { deleteTestJournalRow, SAVED_BY_NEWER_ORCA } from './journal-host-database-test-support' +import { journalOpenRefusalError } from './journal-open-failure' const IDENTITY: AgentSessionJournalIdentity = { sessionId: 'session-1', @@ -35,7 +36,7 @@ const UNLOADABLE = { let root: string let clock = 1_000 -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -141,17 +142,71 @@ describe('a damaged chat', () => { }) }) - it("reads past damage to a newer build's row, which fails the load as a newer Orca's instead", async () => { - await writeChat() - await withJournalDatabase((db) => { - updateTestJournalRowJson(db, IDENTITY.sessionId, 3, '}{') - const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } - updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) + it.each([1, 3])( + "reads past damage at row %i to a newer build's row, which fails the load as a newer Orca's instead", + async (damaged) => { + await writeChat() + await withJournalDatabase((db) => { + updateTestJournalRowJson(db, IDENTITY.sessionId, damaged, '}{') + const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } + updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) + }) + const before = await storedRows() + + await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(await storedRows()).toEqual(before) + } + ) +}) + +describe('a chat whose saved state cannot be read right now', () => { + const outcomes = createTrackedJournalOpener() + afterEach(async () => { + vi.restoreAllMocks() + await outcomes.closeAll() + }) + + it('refuses the open as unavailable on a transient read error, and the next open loads it', async () => { + const options = { + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + } + const journal = await outcomes.open(options) + await journal.appendItem(item(0), body('kept'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.close() + let failures = 1 + const prepare = Database.prototype.prepare + vi.spyOn(Database.prototype, 'prepare').mockImplementation(function ( + this: Database, + sql: string + ) { + if (failures > 0 && sql.includes('FROM journal_outcomes')) { + failures -= 1 + throw Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR', errcode: 10 }) + } + return prepare.call(this, sql) }) - const before = await storedRows() - await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) - expect(await storedRows()).toEqual(before) + // As on main, the storage error reaches the host, which reports "unavailable, try again". + const failure = await outcomes.open(options).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject({ code: 'ERR_SQLITE_ERROR' }) + expect(journalOpenRefusalError(failure)).toMatchObject({ + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + expect(failures).toBe(0) + const reopened = await outcomes.open(options) + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([body('kept')]) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-database.ts b/src/main/native-chat/agent-session-journal/journal-database.ts index c5be4fbb6768..2efa705074de 100644 --- a/src/main/native-chat/agent-session-journal/journal-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-database.ts @@ -1,5 +1,6 @@ // Read user_version before persistent pragmas/DDL: even enabling WAL mutates newer databases. +import { ensureJournalOutcomeTables } from './journal-outcome-format' import Database from '../../sqlite/sync-database' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' import { @@ -72,6 +73,7 @@ export function openJournalDatabase(dbPath: string): OpenJournalDatabase { // Additive tables must exist on every writable open, even when version migration returns early. ensureQueuedMessagesTable(probe) ensureCommandReceiptsTable(probe) + ensureJournalOutcomeTables(probe) ensureAgentSessionAttachmentClaimTables(probe) hardenSqliteDatabaseFiles(dbPath) transferred = true diff --git a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts index 5b4236e1d1c1..52ff383f538c 100644 --- a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts +++ b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts @@ -12,6 +12,16 @@ import { isAgentSessionContextClear } from '../../../shared/agent-session-contex export class JournalDerivedTurnScope { private openTurnItemId: string | null = null + snapshot(): string | null { + return this.openTurnItemId + } + + static restore(openTurnItemId: string | null): JournalDerivedTurnScope { + const scope = new JournalDerivedTurnScope() + scope.openTurnItemId = openTurnItemId + return scope + } + scopeFor(body: AgentJournalItemBody): AgentJournalTurnScope { return this.openTurnItemId === null || readAgentJournalTurn(body) ? AGENT_JOURNAL_THREAD_SCOPE diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts index 2d58733db126..c9b1e731e42f 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts @@ -36,8 +36,9 @@ export class JournalEpochController { } ) {} - start(reason: AgentJournalEpochReason, fence: number): void { + start(reason: AgentJournalEpochReason, fence: number, expectedEpoch: string | null): void { publishNewEpoch({ + expectedEpoch, database: this.deps.database(), identity: this.deps.identity, epoch: this.deps.mintEpoch(), @@ -53,7 +54,7 @@ export class JournalEpochController { roll(reason: AgentJournalEpochReason, fence: number): Promise { return this.deps.serialize(() => { assertJournalWritable(this.deps.readOnly(), this.deps.identity.sessionId) - this.start(reason, fence) + this.start(reason, fence, this.deps.state().epoch) return this.deps.cursor() }) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts new file mode 100644 index 000000000000..cf08e0b4c138 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { JournalHostDatabase } from './journal-host-database' +import { replaceJournalEpoch } from './journal-epoch-replacement' +import type { JournalLoad } from './journal-open' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + const PEER: AgentSessionJournalIdentity = { + ...IDENTITY, + sessionId: 'session-peer', + providerHandle: codexProviderHandle('thread-peer') + } + + let root: string + + let clock = 1_000 + + let database: JournalHostDatabase + + const journals = createTrackedJournalOpener() + + function now(): number { + clock += 1 + return clock + } + + function storedRows(sessionId: string, epoch: string): number { + return Number( + database.db + .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch)?.total + ) + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function replace(input: { + items: Parameters[0]['items'] + onPublished?: (loaded: JournalLoad) => void + }): void { + replaceJournalEpoch({ + database, + identity: IDENTITY, + reason: 'legacy_import', + fence: 1, + items: input.items, + queuePause: { lifted: false, liveStop: null, reopened: false }, + queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, + now, + mintEpoch: () => `epoch-${clock}`, + onPublished: input.onPublished ?? (() => undefined) + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) + clock = 1_000 + database = openTestJournalHostDatabase(root) + }) + + afterEach(async () => { + try { + await database.close() + } catch {} + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function legacyInputs(count: number) { + const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await existing.close() + const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] + for (let n = 0; n < count; n++) { + const id = randomUUID() + const path = join( + attachmentReferences.agentSessionAttachmentStoreRoot(root), + id, + 'source.txt' + ) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'queued source') + const body: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] + } + database.db + .prepare(`INSERT INTO queued_messages + (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) + .run( + IDENTITY.sessionId, + `queue-${n}`, + n + 1, + JSON.stringify(body), + agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), + n % 2 ? 'returned' : 'waiting', + n % 2 ? null : 'send_failed', + n % 2 ? 'refused before' : null, + n % 2 ? `old-${n}` : null + ) + files.push({ id, path, body }) + } + return files + } + + return { + IDENTITY, + PEER, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get database() { + return database + }, + set database(value: typeof database) { + database = value + }, + item, + journals, + legacyInputs, + now, + replace, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storedRows + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts new file mode 100644 index 000000000000..a6f3e29b6837 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts @@ -0,0 +1,229 @@ +import type { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import { describe, expect, it, vi } from 'vitest' +import type { JournalLoad } from './journal-open' +import type { AgentSessionJournal } from './journal-store' +import { readJournalSessionEpoch } from './journal-row-table' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function registerJournalEpochReplacementReceiptsTests( + fixture: ReturnType +): void { + describe('journal epoch replacement', () => { + it('publishes one observable replacement', () => { + const published: JournalLoad[] = [] + + fixture.replace({ + items: [ + { + identity: fixture.item(1), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ], + onPublished: (loaded) => published.push(loaded) + }) + + expect(published).toHaveLength(1) + const epoch = readJournalSessionEpoch(fixture.database.db, fixture.IDENTITY.sessionId) + expect(epoch).toBe(published[0]?.state.epoch) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, epoch ?? '')).toBe(1) + expect(published[0]?.state.lastSequence).toBe(2) + }) + + it.each([ + [ + 'a replace', + (journal: AgentSessionJournal) => + journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ]) + ], + ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] + ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const peer = await fixture.journals.open({ + identity: fixture.PEER, + stateDirectory: fixture.root + }) + const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(fixture.item(1), { kind: 'status', text: 'old' }, scope) + await journal.appendItem(fixture.item(2), { kind: 'status', text: 'older' }, scope) + await peer.appendItem(fixture.item(1), { kind: 'status', text: 'peer' }, scope) + const before = journal.epoch + + await retire(journal) + + expect(journal.epoch).not.toBe(before) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, before)).toBe(0) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, journal.epoch)).toBe(1) + expect(fixture.storedRows(fixture.PEER.sessionId, peer.epoch)).toBe(1) + }) + }) + + it.each([ + ['replace', 1], + ['replace', 10], + ['roll', 1], + ['roll', 10] + ] as const)( + 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', + async (mode, count) => { + const files = await fixture.legacyInputs(count) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const { db } = fixture.database + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(0) + const cards = () => + journal.queuedMessages + .list() + .map(({ messageId, body, state, holdReason, returnedReason }) => ({ + messageId, + body, + state, + holdReason, + returnedReason + })) + const before = cards() + const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } + await journal.appendClaimingAttachments( + goal, + { ...files[0].body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + await (mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1)) + expect(extraction).toHaveBeenCalledTimes(count) + expect(insertion).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(cards()).toEqual(before) + process.stdout.write( + `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(count) + if (mode === 'replace') { + const card = journal.queuedMessages.get('queue-0') + if (!card) { + throw new Error('missing carried card') + } + await journal.appendSubmission({ + clientMessageId: 'pending', + payloadFingerprint: card.fingerprint, + body: card.body, + fence: 1, + handoverRecorded: true, + queuedMessageId: card.messageId + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + extraction.mockClear() + insertion.mockClear() + acquired.mockClear() + await journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: card.body, + ownerFence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ]) + expect(extraction).toHaveBeenCalledTimes(count + 2) + expect(insertion).toHaveBeenCalledTimes(count + 2) + expect(acquired).toHaveBeenCalledTimes(count + 2) + expect(journal.submission('pending')).toMatchObject({ + dispatchState: 'pending', + handoverRecorded: true, + queuedMessageId: 'queue-0' + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) + process.stdout.write( + `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + await fixture.journals.closeAll() + const reopened = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + fixture.database = openTestJournalHostDatabase(fixture.root) + expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( + before.map((card) => card.body) + ) + for (const file of files) { + expect(markUnclaimedUploadForSweep(fixture.database.db, file.id, 1)).toBe(false) + expect(await readFile(file.path, 'utf8')).toBe('queued source') + } + } + ) + + it.each(['replace', 'roll'] as const)( + 'finalizes %s queue ownership only after COMMIT and before fallible publication', + async (mode) => { + const [file] = await fixture.legacyInputs(1) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + for (const phase of ['rollback', 'publication'] as const) { + const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } + await journal.appendClaimingAttachments( + goal, + { ...file.body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const retire = () => + mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1) + if (phase === 'rollback') { + const transaction = fixture.database.transaction.bind(fixture.database) + vi.spyOn(fixture.database, 'transaction').mockImplementationOnce((run) => + transaction((db) => { + run(db) + throw new Error('rollback epoch') + }) + ) + await expect(retire()).rejects.toThrow('rollback epoch') + } else { + journal.observeCommits(() => { + throw new Error('publication failed') + }) + await expect(retire()).rejects.toThrow('publication failed') + journal.observeCommits(() => {}) + } + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + fixture.database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(phase === 'rollback' ? 0 : 1) + expect(journal.queuedMessages.list()).toHaveLength(1) + } + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts index 7d5b142e04ef..b76b12c0b030 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts @@ -1,327 +1,7 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' - -import { mkdtemp, rm, mkdir, writeFile, readFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import type { JournalHostDatabase } from './journal-host-database' -import { replaceJournalEpoch } from './journal-epoch-replacement' -import type { JournalLoad } from './journal-open' -import type { AgentSessionJournal } from './journal-store' -import { readJournalSessionEpoch } from './journal-row-table' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' - -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' -import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { registerJournalEpochReplacementReceiptsTests } from './journal-epoch-replacement-receipts.spec' export function registerJournalEpochReplacementTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - const PEER: AgentSessionJournalIdentity = { - ...IDENTITY, - sessionId: 'session-peer', - providerHandle: codexProviderHandle('thread-peer') - } - - let root: string - let clock = 1_000 - let database: JournalHostDatabase - const journals = createTrackedJournalOpener() - - function now(): number { - clock += 1 - return clock - } - - function storedRows(sessionId: string, epoch: string): number { - return Number( - database.db - .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') - .get(sessionId, epoch)?.total - ) - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function replace(input: { - items: Parameters[0]['items'] - onPublished?: (loaded: JournalLoad) => void - }): void { - replaceJournalEpoch({ - database, - identity: IDENTITY, - reason: 'legacy_import', - fence: 1, - items: input.items, - queuePause: { lifted: false, liveStop: null, reopened: false }, - queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, - now, - mintEpoch: () => `epoch-${clock}`, - onPublished: input.onPublished ?? (() => undefined) - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) - clock = 1_000 - database = openTestJournalHostDatabase(root) - }) - - afterEach(async () => { - try { - await database.close() - } catch {} - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('journal epoch replacement', () => { - it('publishes one observable replacement', () => { - const published: JournalLoad[] = [] - - replace({ - items: [ - { identity: item(1), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ], - onPublished: (loaded) => published.push(loaded) - }) - - expect(published).toHaveLength(1) - const epoch = readJournalSessionEpoch(database.db, IDENTITY.sessionId) - expect(epoch).toBe(published[0]?.state.epoch) - expect(readTestJournalRows(database.db, IDENTITY.sessionId, epoch ?? '')).toHaveLength(2) - }) - - it.each([ - [ - 'a replace', - (journal: AgentSessionJournal) => - journal.replaceEpochItems('legacy_import', 1, [ - { identity: item(9), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ]) - ], - ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] - ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const peer = await journals.open({ identity: PEER, stateDirectory: root }) - const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(1), { kind: 'status', text: 'old' }, scope) - await journal.appendItem(item(2), { kind: 'status', text: 'older' }, scope) - await peer.appendItem(item(1), { kind: 'status', text: 'peer' }, scope) - const before = journal.epoch - - await retire(journal) - - expect(journal.epoch).not.toBe(before) - expect(storedRows(IDENTITY.sessionId, before)).toBe(0) - expect(storedRows(IDENTITY.sessionId, journal.epoch)).toBe(journal.cursor().sequence) - expect(storedRows(PEER.sessionId, peer.epoch)).toBe(2) - }) - }) - - async function legacyInputs(count: number) { - const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) - await existing.close() - const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] - for (let n = 0; n < count; n++) { - const id = randomUUID() - const path = join( - attachmentReferences.agentSessionAttachmentStoreRoot(root), - id, - 'source.txt' - ) - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'queued source') - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] - } - database.db - .prepare(`INSERT INTO queued_messages - (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) - .run( - IDENTITY.sessionId, - `queue-${n}`, - n + 1, - JSON.stringify(body), - agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), - n % 2 ? 'returned' : 'waiting', - n % 2 ? null : 'send_failed', - n % 2 ? 'refused before' : null, - n % 2 ? `old-${n}` : null - ) - files.push({ id, path, body }) - } - return files - } - - it.each([ - ['replace', 1], - ['replace', 10], - ['roll', 1], - ['roll', 10] - ] as const)( - 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', - async (mode, count) => { - const files = await legacyInputs(count) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const { db } = database - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(0) - const cards = () => - journal.queuedMessages - .list() - .map(({ messageId, body, state, holdReason, returnedReason }) => ({ - messageId, - body, - state, - holdReason, - returnedReason - })) - const before = cards() - const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } - await journal.appendClaimingAttachments( - goal, - { ...files[0].body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - await (mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1)) - expect(extraction).toHaveBeenCalledTimes(count) - expect(insertion).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(cards()).toEqual(before) - process.stdout.write( - `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(count) - if (mode === 'replace') { - const card = journal.queuedMessages.get('queue-0') - if (!card) { - throw new Error('missing carried card') - } - await journal.appendSubmission({ - clientMessageId: 'pending', - payloadFingerprint: card.fingerprint, - body: card.body, - fence: 1, - handoverRecorded: true, - queuedMessageId: card.messageId - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - extraction.mockClear() - insertion.mockClear() - acquired.mockClear() - await journal.replaceEpochItems('legacy_import', 1, [ - { - identity: item(9), - body: card.body, - ownerFence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) - expect(extraction).toHaveBeenCalledTimes(count + 2) - expect(insertion).toHaveBeenCalledTimes(count + 2) - expect(acquired).toHaveBeenCalledTimes(count + 2) - expect(journal.submission('pending')).toMatchObject({ - dispatchState: 'pending', - handoverRecorded: true, - queuedMessageId: 'queue-0' - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) - process.stdout.write( - `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - await journals.closeAll() - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: root }) - database = openTestJournalHostDatabase(root) - expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( - before.map((card) => card.body) - ) - for (const file of files) { - expect(markUnclaimedUploadForSweep(database.db, file.id, 1)).toBe(false) - expect(await readFile(file.path, 'utf8')).toBe('queued source') - } - } - ) - - it.each(['replace', 'roll'] as const)( - 'finalizes %s queue ownership only after COMMIT and before fallible publication', - async (mode) => { - const [file] = await legacyInputs(1) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - for (const phase of ['rollback', 'publication'] as const) { - const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } - await journal.appendClaimingAttachments( - goal, - { ...file.body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const retire = () => - mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1) - if (phase === 'rollback') { - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementationOnce((run) => - transaction((db) => { - run(db) - throw new Error('rollback epoch') - }) - ) - await expect(retire()).rejects.toThrow('rollback epoch') - } else { - journal.observeCommits(() => { - throw new Error('publication failed') - }) - await expect(retire()).rejects.toThrow('publication failed') - journal.observeCommits(() => {}) - } - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(phase === 'rollback' ? 0 : 1) - expect(journal.queuedMessages.list()).toHaveLength(1) - } - } - ) + const fixture = createFixture() + registerJournalEpochReplacementReceiptsTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts index 3b8f78660396..c39a1fbbbadf 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts @@ -1,3 +1,5 @@ +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalItemEchoFields, journalItemEchoRestatement, @@ -43,12 +45,11 @@ import { import type { JournalQueuePauseRestatement } from './queued-message-pause' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' -import { assertJournalFence } from './journal-write-guards' +import { AgentSessionJournalError, assertJournalFence } from './journal-write-guards' import type { JournalOperationReceipt } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -65,6 +66,8 @@ export type JournalReplacementItem = AgentJournalProducerLinkage & { executionOwner?: number } +/** Survivors are restated from the open chat. That loses nothing another build wrote: a chat holding + * a key this build does not declare refuses to open, so no handle can reach here. */ export function replaceJournalEpoch(input: { database: JournalHostDatabase identity: AgentSessionJournalIdentity @@ -192,34 +195,47 @@ export function replaceJournalEpoch(input: { const { sessionId } = input.identity const receipt = input.receipt?.({ epoch, sequence: state.lastSequence }) const claimsCommitted: (() => void)[] = [] - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const row of rows) { - insertJournalRow(db, sessionId, row) - const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null - if ( - body?.kind === 'message' && - body.role === 'user' && - !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) - ) { - const commit = input.claimAttachments?.(db, body, false) - if (commit) { - claimsCommitted.push(commit) + state.oldestSequence = 1 + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + // The new epoch was built from the live one; refuse if another write replaced it meanwhile. + if (input.previous && retired !== input.previous.epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + for (const row of rows) { + const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null + if ( + body?.kind === 'message' && + body.role === 'user' && + !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) + ) { + const commit = input.claimAttachments?.(db, body, false) + if (commit) { + claimsCommitted.push(commit) + } } } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, epoch) + receipt?.write(db) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing ownership bookkeeping, before the fallible publication. + const state = publication.adopt() + claimsCommitted.forEach((commit) => commit()) + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, epoch) - receipt?.write(db) - }) - claimsCommitted.forEach((commit) => commit()) - input.queue.receipt.committed() + ) - // Adopt the committed epoch immediately; later failures must not leave writers targeting deleted rows. - state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) receipt?.committed() } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts index feca4c4d0064..615f622972ed 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts @@ -1,5 +1,7 @@ // Delete and replace epochs atomically; retaining superseded rows would grow history without bound. +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' @@ -10,11 +12,11 @@ import { buildJournalQueueRow } from './journal-queue-events' import type { JournalQueueRestatement } from './journal-queued-messages' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' +import { AgentSessionJournalError } from './journal-write-guards' export function publishNewEpoch(input: { database: JournalHostDatabase @@ -25,6 +27,8 @@ export function publishNewEpoch(input: { now: number /** Unhanded cards wait again; replacement submissions may relink them. */ queue: JournalQueueRestatement + /** The epoch the caller built from (null: none yet); a different stored epoch refuses. */ + expectedEpoch?: string | null /** Adopt committed state before fallible follow-up work. */ onPublished: (loaded: JournalLoad) => void }): void { @@ -32,7 +36,6 @@ export function publishNewEpoch(input: { kind: 'epoch', reason: input.reason, providerHandle: agentSessionJournalProviderHandle(input.identity), - // Body-free epoch rows must remain readable by older hosts. v: journalRowSchemaVersion([]), epoch: input.epoch, seq: 1, @@ -51,20 +54,29 @@ export function publishNewEpoch(input: { rows.push(card) } } - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const each of rows) { - insertJournalRow(db, sessionId, each) - } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, input.epoch) - }) - - // Adopt committed state before fallible work can leave writers targeting the deleted epoch. - input.queue.receipt.committed() state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + if (input.expectedEpoch !== undefined && retired !== input.expectedEpoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, input.epoch) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing queue bookkeeping, before the fallible publication. + const state = publication.adopt() + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) + } + ) } diff --git a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts index 46108f549c0c..93d11ac3a22c 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts @@ -1,10 +1,18 @@ // Share one connection per test profile to match production host ownership. import { resolve } from 'node:path' +import { randomUUID } from 'node:crypto' +import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' +import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' import { JournalHostDatabase } from './journal-host-database' -import { replayJournal, type JournalLoad } from './journal-open' +import { fields } from './journal-state-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { decodeJournalOutcome, type JournalOutcome } from './journal-outcome-codec' +import { applyJournalRow } from './journal-reducer' +import { restoreJournal, type JournalLoad } from './journal-open' import { serializeJournalRow, type JournalRow } from './journal-row-schema' import { + insertJournalRow, iterateJournalEpochRows, publishJournalSessionEpoch, readJournalSessionEpoch, @@ -50,15 +58,23 @@ export type TrackedJournalOpener = { closeAll: () => Promise } -export function createTrackedJournalOpener(): TrackedJournalOpener { +export function createTrackedJournalOpener( + fixture: { legacyInputs?: boolean } = {} +): TrackedJournalOpener { const journals: AgentSessionJournal[] = [] return { open: async ({ stateDirectory, ...options }) => { + if (fixture.legacyInputs) { + seedLegacyTestJournal(openTestJournalHostDatabase(stateDirectory), options) + } const { openAgentSessionJournal } = await import('./journal-store-factory') const journal = await openAgentSessionJournal({ ...options, database: openTestJournalHostDatabase(stateDirectory) }) + if (fixture.legacyInputs) { + pinTestJournalInputMode(journal) + } journals.push(journal) return journal }, @@ -73,6 +89,33 @@ export function createTrackedJournalOpener(): TrackedJournalOpener { } } +/** Input-parser fixtures explicitly found an epoch in the shipped input format. */ +export function seedLegacyTestJournal( + database: JournalHostDatabase, + options: Omit +): void { + if ( + database.readOnly || + readJournalSessionEpoch(database.db, options.identity.sessionId) !== null + ) { + return + } + const epoch = options.mintEpoch?.() ?? randomUUID() + database.transaction((db) => { + publishJournalSessionEpoch(db, options.identity, epoch) + insertTestJournalRow(db, options.identity.sessionId, { + kind: 'epoch', + v: journalRowSchemaVersion([]), + epoch, + seq: 1, + fence: 0, + ts: options.now?.() ?? Date.now(), + reason: 'session_created', + providerHandle: agentSessionJournalProviderHandle(options.identity) + }) + }) +} + export const SAVED_BY_NEWER_ORCA = { refusal: { code: 'agent_session_journal_unreadable', @@ -81,7 +124,7 @@ export const SAVED_BY_NEWER_ORCA = { } export function loadTestJournal(stateDirectory: string, sessionId: string): JournalLoad | null { - return replayJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) + return restoreJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) } function liveEpoch(db: Database.Database, sessionId: string): string { @@ -153,3 +196,67 @@ export function deleteTestJournalRow(db: Database.Database, sessionId: string, s seq ) } + +/** Read current canonical contributions in commit order for persisted-outcome assertions. */ +export function readTestJournalOutcomes( + db: Database.Database, + sessionId: string +): JournalOutcome[] { + const epoch = readJournalSessionEpoch(db, sessionId) + const source = epoch && journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return [] + } + return db + .prepare(`SELECT seq, field, entry_key, format, ordinal, value_json, deleted FROM journal_outcomes + WHERE generation = ? ORDER BY seq, field, entry_key`) + .all(source.generation) + .map(decodeJournalOutcome) +} + +export function readTestQueueChanges( + db: Database.Database, + sessionId: string +): { + messageId: string + op: string + returned: boolean +}[] { + const seen = new Set() + return readTestJournalOutcomes(db, sessionId).flatMap((value) => { + if (value.field !== 'queue.cards') { + return [] + } + if (value.deleted) { + return [{ messageId: String(JSON.parse(value.key)), op: 'withdrawn', returned: false }] + } + const [messageId, card] = fields.queue.shape.cards.element.parse(JSON.parse(value.json)) + const first = !seen.has(messageId) + seen.add(messageId) + return [ + { messageId, op: first ? 'queued' : card.state, returned: first && card.state === 'returned' } + ] + }) +} + +/** Input fixtures stand for a chat an older build wrote and goes on writing: writes to its input + * epoch stay input rows, as that build's writer stored them, so the input reader meets writer-made + * rows. An epoch this build founds (rollover, replacement) is written as this build writes it. */ +export function pinTestJournalInputMode(journal: AgentSessionJournal): void { + const projection = journal['projection'] + const prepare = projection.prepare.bind(projection) + projection.prepare = (db, rows, savedAt) => { + const state = journal['state'] + if (journalOutcomeSource(db, state.sessionId, state.epoch)) { + return prepare(db, rows, savedAt) + } + for (const row of rows) { + insertJournalRow(db, state.sessionId, row, savedAt) + } + return () => { + for (const row of rows) { + applyJournalRow(state, row, savedAt) + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts index f7392afec747..3da49ac632d6 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts @@ -46,7 +46,7 @@ export function registerJournalHostDatabaseTests(): void { } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -55,11 +55,11 @@ export function registerJournalHostDatabaseTests(): void { /** Deferred foreign-key failures leave COMMIT open, exercising shared-connection rollback recovery. */ function failCommits(db: Database.Database): () => void { db.exec(`CREATE TEMP TABLE commit_probe_parent (id INTEGER PRIMARY KEY); -CREATE TEMP TABLE commit_probe_child ( - parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED -); -CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows -BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) + CREATE TEMP TABLE commit_probe_child ( + parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED + ); + CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows + BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) return () => db.exec('DROP TRIGGER temp.commit_probe') } @@ -89,10 +89,10 @@ BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) args: [ '-e', `const { DatabaseSync } = require('node:sqlite') -const db = new DatabaseSync(process.argv[1]) -db.exec('BEGIN IMMEDIATE') -process.stdout.write('holding') -setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, + const db = new DatabaseSync(process.argv[1]) + db.exec('BEGIN IMMEDIATE') + process.stdout.write('holding') + setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, journalDatabasePath(root) ], timeoutMs: 30_000 diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.ts b/src/main/native-chat/agent-session-journal/journal-host-database.ts index 62ab838f54ef..c35b06c11a87 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.ts @@ -60,12 +60,17 @@ export class JournalHostDatabase { } /** Streamed text may lose only its trailing suffix on OS crash; the next FULL commit makes it durable. */ - transaction(run: (db: Database.Database) => T, streamed = false): T { + transaction( + run: (db: Database.Database) => T, + streamed = false, + committed?: (result: T) => void + ): T { const db = this.db if (!streamed) { const result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) this.checkpoint?.afterCommit() return result } @@ -76,6 +81,7 @@ export class JournalHostDatabase { result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) } finally { if (!db.isTransaction) { db.pragma('synchronous = FULL') diff --git a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts index c574811413f6..6c76e730fd75 100644 --- a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts @@ -39,7 +39,7 @@ export function registerJournalItemProvenanceTests(): void { let root: string let database: JournalHostDatabase - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts index 1c7b2f5be36a..f02e0ddf071d 100644 --- a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts @@ -26,7 +26,7 @@ export function registerJournalLifecycleBatchAppenderTests(): void { } const SESSION = 'repeated-items' - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string let journal: AgentSessionJournal const options = () => ({ diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts new file mode 100644 index 000000000000..21693b1221df --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts @@ -0,0 +1,197 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readdir } from 'node:fs/promises' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + boundInlineText, + boundPayload, + JOURNAL_RUNNING_PREVIEW_LIMITS +} from './journal-payload-bounds' +import type { AgentSessionJournal } from './journal-store' + +export function registerJournalLifecycleBoundaryTests( + fixture: ReturnType +): void { + describe('bounds', () => { + it('marks a clipped payload instead of dropping bytes silently', () => { + const limits = { inlineHeadBytes: 16 } + const bounded = boundPayload('x'.repeat(4_096), limits) + expect(bounded.truncated).toBe(true) + expect(bounded.head).toHaveLength(16) + expect(bounded.byteLength).toBe(4_096) + expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') + }) + + it('never splits a multi-byte character across the bound', () => { + const limits = { inlineHeadBytes: 4 } + // Three-byte characters expose UTF-8 splits. + const bounded = boundPayload('日本語テスト', limits) + expect(bounded.head).toBe('日') + expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) + }) + + it('leaves a payload inside the bound untouched', () => { + const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) + expect(bounded.truncated).toBe(false) + expect(bounded.head).toBe('small') + expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') + }) + }) + + describe('lifecycle batches', () => { + it('deduplicates concurrent submissions before appending a second row', async () => { + const journal = await fixture.open() + const input = { + settlementId: 'concurrent-settlement', + fence: 1, + mutations: [ + { + kind: 'item' as const, + identity: fixture.item(1), + body: fixture.body('settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + } + + const [first, replay] = await Promise.all([ + journal.appendLifecycleBatch(input), + journal.appendLifecycleBatch(input) + ]) + + expect([replay, first.sequence]).toEqual([first, 2]) + }) + + it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { + const journal = await fixture.open() + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const settled = await journal.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(1), + body: fixture.body('tool settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: { provider: 'orca', clientMessageId: 'exit-status' }, + body: { kind: 'status', text: 'Provider exited' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + const atSettlement = journal + .snapshot() + .items.filter((entry) => entry.sequence === settled.sequence) + expect(atSettlement).toHaveLength(2) + expect( + journal + .snapshot() + .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') + ).toBe(false) + await journal.close() + + const reopened = await fixture.open() + const beforeReplay = reopened.cursor() + const replay = await reopened.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(9), + body: fixture.body('must not appear'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(replay).toEqual(beforeReplay) + expect( + reopened + .snapshot() + .items.some( + (entry) => + entry.body.kind === 'message' && + entry.body.blocks.some( + (block) => block.type === 'text' && block.text === 'must not appear' + ) + ) + ).toBe(false) + }) + }) + + describe('on-disk layout', () => { + it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { + const journal: AgentSessionJournal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(await readdir(fixture.root)).toContain('agent-session-journal.db') + expect(await readdir(fixture.root)).not.toContain('agent-session-journal') + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + expect( + db.prepare("SELECT value_json FROM journal_outcomes WHERE field = 'items'").get() + ?.value_json + ).toContain('"kind":"message"') + expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ + epoch: journal.epoch + }) + }) + }) + }) + + describe('what a handle found on disk when it opened', () => { + const submission = (clientMessageId: string) => ({ + clientMessageId, + payloadFingerprint: 'fp', + body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, + fence: 1, + handoverRecorded: true as const + }) + + it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { + const earlier = await fixture.open() + await earlier.appendItem(fixture.item(1), fixture.body('one'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await earlier.appendSubmission(submission('earlier')) + await earlier.close() + + const journal = await fixture.open() + const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') + expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) + + await journal.resolveDispatch({ + clientMessageId: 'earlier', + state: 'unknown', + reason: 'unconfirmed from an earlier host', + fence: 1 + }) + // Epochs restart sequences, so later rows can fall below the old open cursor. + await journal.replaceEpochItems('handle_forked', 1, []) + await journal.appendSubmission(submission('later')) + const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') + expect(later?.acceptedSequence).toBeLessThanOrEqual(2) + expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts new file mode 100644 index 000000000000..6f1a72ca78f8 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts @@ -0,0 +1,185 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { journalOutcomeSource } from './journal-outcome-format' +import { sweepJournalOutcomePage } from './journal-outcome-cleanup' +import type { AgentSessionJournal } from './journal-store' +import { JournalWriteProjection } from './journal-write-projection' + +// An existing chat this build has written to holds old input rows, the marker and records. Rewind, +// replacement and rollover found an outcome-only epoch from what the open chat holds, delete the +// retired epoch's rows whole inside that transaction, as main does, and leave its records to the +// runner's sweep; a refused replacement leaves the mixed chat as it was. +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-mixed-replacement', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const FENCE = 1 +const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } +const item = (ordinal: number): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal +}) +const status = (text: string): AgentJournalItemBody => ({ kind: 'status', text }) +const message = (text: string) => ({ + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text }] +}) + +let root: string +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-mixed-replacement-')) + // Every commit restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const db = () => openTestJournalHostDatabase(root).db +const rowsOfEpoch = (epoch: string) => + db().prepare('SELECT seq, row_json FROM journal_rows WHERE epoch = ? ORDER BY seq').all(epoch) +const recordsOf = (generation: number) => + db().prepare('SELECT * FROM journal_outcomes WHERE generation = ? ORDER BY seq').all(generation) + +/** Old rows (items 0 and 1, a waiting card, a user Stop), then this build's records (item 0 + * revised, item 2, a second card). */ +async function mixedChat(): Promise { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const earlier = await older.open({ identity: IDENTITY, stateDirectory: root }) + await earlier.appendItem(item(0), status('first'), scope) + await earlier.appendItem(item(1), status('second'), scope) + await earlier.queuedMessages.insert({ messageId: 'card-old', body: message('old card') }) + await earlier.appendStopEvent({ reason: 'user-stop' }, FENCE) + await older.closeAll() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await journal.appendItem(item(0), status('first, revised'), scope) + await journal.appendItem(item(2), status('third'), scope) + await journal.queuedMessages.insert({ messageId: 'card-new', body: message('new card') }) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch) + expect(source?.prefix).toBeGreaterThan(0) + return journal +} + +/** What a user sees of the chat: its items, sends, queue and pause. */ +function seen(journal: AgentSessionJournal) { + return { + items: journal.snapshot().items.map((entry) => entry.body), + cards: journal.queuedMessages.list().map((card) => [card.messageId, card.body, card.state]), + stop: journal.queuedMessages.userStopInForce()?.event.reason ?? null + } +} + +async function reopened() { + await journals.closeAll() + return seen(await journals.open({ identity: IDENTITY, stateDirectory: root })) +} + +function expectRetiredWhole(retired: { epoch: string; generation: number }, live: string) { + expect(rowsOfEpoch(retired.epoch)).toEqual([]) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, live) + // The new epoch is outcome-only: its rows hold only the marker. + expect(source?.prefix).toBe(0) + expect(rowsOfEpoch(live).map((row) => JSON.parse(String(row.row_json)).kind)).toEqual([ + 'outcomes' + ]) + expect(recordsOf(retired.generation).length).toBeGreaterThan(0) + const database = openTestJournalHostDatabase(root) + while (sweepJournalOutcomePage(database)) { + // Sweeps one bounded page per transaction. + } + expect(recordsOf(retired.generation)).toEqual([]) + expect(recordsOf(source!.generation).length).toBeGreaterThan(0) +} + +it.each(['rewind', 'replacement'] as const)( + 'a %s of a mixed chat keeps what the user kept and deletes the retired epoch whole', + async (path) => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const kept = [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(2), body: status('third'), ownerFence: FENCE } + ] + await journal.replaceEpochItems( + path === 'rewind' ? 'handle_forked' : 'legacy_import', + FENCE, + kept + ) + const live = seen(journal) + expect(live).toEqual({ + items: [status('first, revised'), status('third')], + cards: [ + ['card-old', message('old card'), 'waiting'], + ['card-new', message('new card'), 'waiting'] + ], + stop: 'user-stop' + }) + const epoch = journal.epoch + expect(epoch).not.toBe(retired.epoch) + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) + } +) + +it('a rollover of a mixed chat keeps its queue and deletes the retired epoch whole', async () => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const before = seen(journal) + await journal.rollEpoch('unreconcilable_prefix', FENCE) + const live = seen(journal) + expect(live).toEqual({ ...before, items: [], stop: null }) + const epoch = journal.epoch + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) +}) + +it('a refused replacement of a mixed chat leaves its rows, records and state as they were', async () => { + const journal = await mixedChat() + const rows = liveTestJournalRows(db(), IDENTITY.sessionId) + const records = db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all() + const before = seen(journal) + const unreadable: AgentJournalItemBody = { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'Bash', input: null, callId: ' ' }] + } + await expect( + journal.replaceEpochItems('handle_forked', FENCE, [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(5), body: unreadable, ownerFence: FENCE } + ]) + ).rejects.toMatchObject({ code: 'journal_row_rejected' }) + expect(liveTestJournalRows(db(), IDENTITY.sessionId)).toEqual(rows) + expect(db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all()).toEqual(records) + expect(seen(journal)).toEqual(before) + expect(await reopened()).toEqual(before) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-open.ts b/src/main/native-chat/agent-session-journal/journal-open.ts index bd1561b4e510..35a2d5932919 100644 --- a/src/main/native-chat/agent-session-journal/journal-open.ts +++ b/src/main/native-chat/agent-session-journal/journal-open.ts @@ -1,5 +1,10 @@ // Replay live epochs without rewriting history; damage/newer rows fail load and remain on disk. +import { journalOutcomeSource } from './journal-outcome-format' +import { readJournalOutcomes } from './journal-outcome-table' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' +import { readJournalOutcomeGroups, type JournalReadRow } from './journal-read-row' +import { AgentSessionJournalError } from './journal-write-guards' import type Database from '../../sqlite/sync-database' import { applyJournalRow, @@ -11,7 +16,7 @@ import { readJournalRowsAfter, readJournalSessionEpoch } from './journal-row-table' -import { parseJournalRow, type JournalRow } from './journal-row-schema' +import { parseJournalRow } from './journal-row-schema' const FIRST_JOURNAL_SEQUENCE = 1 @@ -33,23 +38,78 @@ export function replayJournal(db: Database.Database, sessionId: string): Journal if (epoch === null) { return null } - const fold = startJournalRowFold({ sessionId, epoch }) - for (const entry of iterateJournalEpochRows(db, sessionId, epoch)) { - if (!fold.add(entry)) { + return foldJournalFromState(db, createJournalReducerState(sessionId, epoch)) +} + +/** The read is synchronous, like main's replay: it blocks once for one chat's saved records (its + * frozen input prefix, then each outcome key's newest record), and nothing can interleave with it. + * Admission comes first, so a newer chat is never folded. */ +export function restoreJournal(db: Database.Database, sessionId: string): JournalLoad | null { + const epoch = readJournalSessionEpoch(db, sessionId) + if (epoch === null) { + return null + } + const empty = createJournalReducerState(sessionId, epoch) + try { + const source = journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return foldJournalFromState(db, empty) + } + let baseline: JournalReducerState | undefined + if (source.prefix > 0) { + const prefix = foldJournalFromState(db, empty, source.prefix) + if (prefix.newer || prefix.damage || prefix.state.lastSequence !== source.prefix) { + const gap = { sequence: prefix.state.lastSequence + 1, cause: 'sequence-gap' as const } + return { ...prefix, damage: prefix.newer ? null : (prefix.damage ?? gap) } + } + baseline = prefix.state + } + const state = readJournalOutcomes(db, sessionId, epoch, source, baseline) + return { state, newer: null, damage: null } + } catch (error) { + if (error instanceof AgentSessionJournalError && error.code === 'journal_read_only') { + return { state: empty, newer: { sequence: 1 }, damage: null } + } + // Only stored content this build rejects is damage; a storage error stays retryable, as on main. + if (error instanceof JournalOutcomeDecodeError) { + return { state: empty, newer: null, damage: { sequence: 1, cause: 'unparseable-row' } } + } + throw error + } +} + +/** Folds input rows as main does, up to `through` when the epoch's outcome records follow them. */ +function foldJournalFromState( + db: Database.Database, + state: JournalReducerState, + through = Number.POSITIVE_INFINITY +): JournalLoad { + const { sessionId, epoch, lastSequence } = state + const fold = startJournalRowFold({ sessionId, epoch }, state) + for (const entry of iterateJournalEpochRows( + db, + sessionId, + epoch, + lastSequence === 0 ? Number.MIN_SAFE_INTEGER : lastSequence + )) { + if (entry.seq > through || !fold.add(entry)) { break } } return fold.finish() } -export function startJournalRowFold(input: { sessionId: string; epoch: string }): { +/** untilDamage stops at the first damage, for callers that only ask whether a fold publishes. */ +export function startJournalRowFold( + input: { sessionId: string; epoch: string; untilDamage?: boolean }, + state = createJournalReducerState(input.sessionId, input.epoch) +): { add: (entry: { seq: number; rowJson: string; ts?: number }) => boolean finish: () => JournalLoad } { - const state = createJournalReducerState(input.sessionId, input.epoch) - let expectedSequence = FIRST_JOURNAL_SEQUENCE + let expectedSequence = state.lastSequence + 1 let damage: JournalDamage | null = null - let anchored = false + let anchored = state.lastSequence > 0 let newer: { sequence: number } | null = null let empty = true @@ -98,7 +158,7 @@ export function startJournalRowFold(input: { sessionId: string; epoch: string }) : { sequence: FIRST_JOURNAL_SEQUENCE, cause: 'no-epoch-row' as const }) return { state, newer, damage: newer ? null : found } } - return { add, finish } + return { add: input.untilDamage ? (entry) => add(entry) && damage === null : add, finish } } export function journalRowsAfterReader( @@ -106,25 +166,46 @@ export function journalRowsAfterReader( sessionId: string, epoch: string, limit?: number -): (afterSequence: number) => JournalRow[] { +): (afterSequence: number) => JournalReadRow[] { return (afterSequence) => readJournalRowsAfterCursor(db, sessionId, epoch, afterSequence, limit) } -/** Stop replay at the first unreadable row; never serve a partial tail beyond it. */ +/** Stop replay at the first unreadable row; never serve a partial tail beyond it. A chat with an + * input prefix pages its rows, then its outcome groups, each sequence exactly once. */ export function readJournalRowsAfterCursor( db: Database.Database, sessionId: string, epoch: string, afterSequence: number, limit?: number -): JournalRow[] { - const rows: JournalRow[] = [] - for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - break +): JournalReadRow[] { + const source = journalOutcomeSource(db, sessionId, epoch) + const prefix = source ? source.prefix : Number.POSITIVE_INFINITY + const rows: JournalReadRow[] = [] + if (afterSequence < prefix) { + for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { + const parsed = stored.seq <= prefix ? parseJournalRow(stored.rowJson) : null + if (!parsed?.ok) { + // An unreadable prefix row ends the page; outcome groups never skip past it. + return parsed ? rows : [...rows, ...groupsAfter(prefix)] + } + rows.push(parsed.row) + } + if (!source || (limit !== undefined && rows.length >= limit)) { + return rows } - rows.push(parsed.row) } - return rows + return [...rows, ...groupsAfter(Math.max(afterSequence, prefix))] + + function groupsAfter(after: number): JournalReadRow[] { + return source + ? readJournalOutcomeGroups( + db, + epoch, + source, + after, + limit === undefined ? undefined : limit - rows.length + ) + : [] + } } diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts new file mode 100644 index 000000000000..c26a964c286a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts @@ -0,0 +1,157 @@ +// One sweeper per database deletes retired epochs' records in the background. Opens and sends never +// wait for it: a retired generation is one no current epoch names, so no read reaches its records. + +import type { JournalHostDatabase } from './journal-host-database' +import type Database from '../../sqlite/sync-database' + +const FIRST_PASS_MS = 60_000 +const PASS_INTERVAL_MS = 6 * 60 * 60_000 +const sweepPositions = new WeakMap() +type SweptDatabase = Pick + +/** A retired epoch's records go with it, as main deletes a retired epoch's rows: every generation + * the chat's current epoch no longer names is swept, one bounded page per transaction. */ +export function sweepJournalOutcomePage( + database: Pick +): boolean { + return database.transaction((db) => { + const after = sweepPositions.get(db) ?? 0 + const candidates = db + .prepare(`SELECT a.generation FROM journal_outcome_generations a LEFT JOIN journal_outcome_epochs e + ON e.session_id = a.session_id AND e.epoch = a.epoch AND e.generation = a.generation + WHERE e.session_id IS NULL AND a.generation > ? ORDER BY a.generation LIMIT 32`) + .all(after) + for (const { generation } of candidates) { + if (typeof generation !== 'number') { + continue + } + sweepPositions.set(db, generation) + const removed = db + .prepare(`DELETE FROM journal_outcomes WHERE rowid IN ( + SELECT rowid FROM journal_outcomes WHERE generation = ? LIMIT 32)`) + .run(generation) + if (removed.changes === 0) { + db.prepare('DELETE FROM journal_outcome_generations WHERE generation = ?').run(generation) + continue + } + // One bounded data page per transaction, even with many retired generations. The next page + // resumes at this generation, so it never rescans the live ones before it. + sweepPositions.set(db, generation - 1) + return true + } + if (candidates.length === 32) { + return true + } + sweepPositions.delete(db) + return false + }) +} + +export type JournalPace = { work: (unit: () => T) => T; rest: () => Promise } + +/** A 10% duty cycle for background deletion only: a chat open or a send is never charged. */ +export function createJournalPace( + now: () => number, + delay: (ms: number) => Promise +): JournalPace { + let worked = 0 + return { + work(unit: () => T): T { + const start = now() + try { + return unit() + } finally { + worked += now() - start + } + }, + async rest(): Promise { + const ms = worked >= 25 ? worked * 9 : 0 + if (ms > 0) { + worked = 0 + } + await delay(ms) + } + } +} + +/** Sweeps a minute after launch, then every six hours; a failed pass is retried by the next one. */ +export class JournalOutcomeSweeper { + private readonly pace: JournalPace + private running: Promise | null = null + private timer: ReturnType | null = null + private stopped = false + + constructor( + private readonly deps: { + database: () => SweptDatabase | null + now?: () => number + delay?: (ms: number) => Promise + onError?: (error: unknown) => void + } + ) { + this.pace = createJournalPace(deps.now ?? (() => performance.now()), deps.delay ?? delay) + } + + start(): this { + this.schedule(FIRST_PASS_MS) + return this + } + + stop(): void { + this.stopped = true + this.clearTimer() + } + + pass(): Promise { + this.running ??= this.run().finally(() => { + this.running = null + this.schedule(PASS_INTERVAL_MS) + }) + return this.running + } + + private async run(): Promise { + for (;;) { + const database = this.current() + if (!database || !this.pace.work(() => sweepJournalOutcomePage(database))) { + return + } + await this.pace.rest() + } + } + + private schedule(ms: number): void { + if (this.stopped) { + return + } + this.clearTimer() + this.timer = setTimeout(() => { + this.timer = null + void this.pass().catch((error: unknown) => this.deps.onError?.(error)) + }, ms) + unref(this.timer) + } + + private clearTimer(): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + } + + private current(): SweptDatabase | null { + const database = this.deps.database() + return this.stopped || !database || database.isClosed || database.readOnly ? null : database + } +} + +function delay(ms: number): Promise { + return new Promise((resolve) => unref(setTimeout(resolve, ms))) +} + +/** Mobile test programs type global timers as numbers; Node timers may release the event loop. */ +function unref(timer: unknown): void { + if (typeof timer === 'object' && timer && 'unref' in timer && typeof timer.unref === 'function') { + timer.unref() + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts new file mode 100644 index 000000000000..4f7ee7e222d9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts @@ -0,0 +1,199 @@ +import { z } from 'zod' +import type { SqliteRow } from '../../sqlite/sqlite-statement' +import type { JournalReducerState } from './journal-reducer' +import type { JournalEntryChange } from './journal-transition-collections' +import { journalEntryJson, journalStateScalars } from './journal-state-layout' +import { + admitOutcomeFormat1, + JOURNAL_OUTCOME_FORMAT_1, + type AdmittedOutcome +} from './journal-outcome-format-1' +import { decodeOutcomeFormat1Onto } from './journal-outcome-format-1-decode' +import { AgentSessionJournalError } from './journal-write-guards' + +export type JournalOutcome = { + seq: number + field: string + key: string + format: number + ordinal: string + json: string + deleted: boolean +} + +/** A key first written over a frozen input prefix keeps the place the prefix gave it. */ +export const JOURNAL_PREFIX_ORDINAL = 'b' + +/** Stored outcome content this build rejects; storage errors never become this, so they stay + * retryable, as main's replay keeps them. */ +export class JournalOutcomeDecodeError extends Error { + override readonly name = 'JournalOutcomeDecodeError' +} + +const scalars = (state: JournalReducerState): Record => + z.record(z.string(), z.unknown()).parse(JSON.parse(journalStateScalars(state))) + +/** Encoding freezes a sequence's contributions before the next input can mutate the draft; + * `untracked` reads each changed value as it stands, not through the draft's tracking. */ +export function encodeJournalOutcomes( + state: JournalReducerState, + changes: readonly JournalEntryChange[], + before: Record, + untracked: (key: string, value: unknown) => unknown +): { values: Omit[]; scalars: Record } { + const next = scalars(state) + const values = changes.map((entry) => ({ + seq: state.lastSequence, + field: entry.path, + key: JSON.stringify(entry.key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: entry.deleted + ? 'null' + : entry.path === 'items' + ? JSON.stringify(entry.value, untracked) + : journalEntryJson(entry.key, entry.value, untracked), + deleted: entry.deleted + })) + for (const [key, value] of Object.entries(next)) { + // The sequence is the record's own, and the epoch's coverage on read; it is never stored. + if (key !== 'lastSequence' && JSON.stringify(value) !== JSON.stringify(before[key])) { + values.push({ + seq: state.lastSequence, + field: '$', + key: JSON.stringify(key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: JSON.stringify(value), + deleted: false + }) + } + } + for (const value of values) { + // A reducer field format 1 has no home for needs a new outcome format, never a silent change. + if (admitOutcomeFormat1(value) === 'unknown') { + throw new Error(`journal outcome format 1 does not store ${value.field} ${value.key}`) + } + } + return { values, scalars: next } +} + +export function journalOutcomeScalars(state: JournalReducerState): Record { + return scalars(state) +} + +/** Admits one stored record or refuses the chat: a newer format or field as newer, anything else as + * damage. */ +export function decodeJournalOutcome(row: SqliteRow): JournalOutcome { + return admitJournalOutcome(row).value +} + +function admitJournalOutcome(row: SqliteRow): { value: JournalOutcome; admitted: AdmittedOutcome } { + return decodingOutcome(() => { + if ( + typeof row.seq !== 'number' || + !Number.isSafeInteger(row.seq) || + row.seq < 1 || + typeof row.field !== 'string' || + typeof row.entry_key !== 'string' || + typeof row.format !== 'number' || + !Number.isSafeInteger(row.format) || + row.format < 1 || + typeof row.ordinal !== 'string' || + !/^(b|s\d{16}:\d{16})$/.test(row.ordinal) || + typeof row.value_json !== 'string' || + (row.deleted !== 0 && row.deleted !== 1) + ) { + throw new Error('invalid journal outcome') + } + const value = { + seq: row.seq, + field: row.field, + key: row.entry_key, + format: row.format, + ordinal: row.ordinal, + json: row.value_json, + deleted: row.deleted === 1 + } + const admitted = + value.format === JOURNAL_OUTCOME_FORMAT_1 ? admitOutcomeFormat1(value) : 'unknown' + if (admitted === 'unknown') { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer outcome') + } + return { value, admitted } + }) +} + +/** A pure decode: a newer writer's record is refused as newer, anything else it throws is damage. */ +export function decodingOutcome(decode: () => T): T { + try { + return decode() + } catch (error) { + if (error instanceof AgentSessionJournalError || error instanceof JournalOutcomeDecodeError) { + throw error + } + throw new JournalOutcomeDecodeError('invalid journal outcome', { cause: error }) + } +} + +type Newest = AdmittedOutcome & Pick + +/** Last-write-wins per key, deletions included, so the tail can remove values from a frozen prefix; + * order comes from the canonical log. */ +export class JournalOutcomeFold { + private readonly values = new Map>() + /** Admits one stored record and keeps its value as admission parsed it, not its text. */ + add(row: SqliteRow): Pick { + const { value, admitted } = admitJournalOutcome(row) + let field = this.values.get(value.field) + if (!field) { + field = new Map() + this.values.set(value.field, field) + } + field.set(value.key, { ordinal: value.ordinal, deleted: value.deleted, ...admitted }) + return value + } + + /** Applies the latest values over `baseline` (the folded input prefix) or over the scalars alone: + * a deletion removes, a prefix-ordinal value replaces in place, and every other value takes its + * canonical place after the prefix. Each record was admitted as format 1 on read. A prefix-ordinal + * value the prefix does not hold is still the key's newest value and is appended rather than + * refusing the chat; that can only happen if the prefix is read differently from how it was + * written, which the marker's rule forbids (`JOURNAL_OUTCOME_MARKER_VERSION`). */ + finish( + sessionId: string, + epoch: string, + through: number, + baseline?: JournalReducerState + ): JournalReducerState { + const scalars: [string, unknown][] = [ + ...[...(this.values.get('$')?.values() ?? [])].map((value): [string, unknown] => [ + String(value.entryKey), + value.kept + ]), + ['lastSequence', through] + ] + const decode = decodingOutcome(() => decodeOutcomeFormat1Onto(scalars, baseline)) + for (const [field, entries] of this.values) { + if (field === '$') { + continue + } + // Canonical ordinals compare bytewise, as SQLite's BINARY collation orders them; the prefix + // ordinal sorts before every appended one. + const ordered = [...entries.values()].sort((a, b) => (a.ordinal < b.ordinal ? -1 : 1)) + for (const value of ordered) { + decodingOutcome(() => { + if (value.deleted || value.ordinal !== JOURNAL_PREFIX_ORDINAL) { + decode.remove(field, value.entryKey) + } + if (!value.deleted) { + decode.entry(field, value.kept) + } + }) + } + } + const state = decode.finish() + if (state.sessionId !== sessionId || state.epoch !== epoch) { + throw new JournalOutcomeDecodeError('invalid journal outcome coverage') + } + return state + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts new file mode 100644 index 000000000000..a7495a6274d8 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import { JournalDerivedTurnScope } from './journal-derived-turn-scope' +import { + outcomeFormat1StoredScalars, + outcomeFormat1StrictScalars +} from './journal-outcome-format-1' + +// Part of frozen outcome format 1: builds reducer state from its stored scalars and keyed entries. +// Every value arrives as admission parsed it and walked it strictly, so these views only type it. + +type JournalStateDecode = { + entry: (path: string, entry: unknown) => void + remove: (path: string, key: unknown) => void + finish: () => JournalReducerState +} + +type Target = { + set: (entry: unknown) => void + remove: (key: unknown) => void +} + +/** Applies admitted scalars and entries onto `baseline`, or onto a new chat state when the scalars + * are complete. A map or set entry for an existing key replaces it in place. */ +export function decodeOutcomeFormat1Onto( + scalars: readonly [string, unknown][], + baseline?: JournalReducerState +): JournalStateDecode { + const state = baseline ?? createJournalReducerState('', '') + if (!baseline) { + outcomeFormat1StrictScalars.parse(Object.fromEntries(scalars)) + } + for (const [key, value] of scalars) { + applyScalar(state, key, value) + } + const targets = collectionTargets(state) + const target = (path: string): Target => { + const found = targets.get(path) + if (!found) { + throw new Error('unknown saved journal collection') + } + return found + } + return { + entry: (path, entry) => target(path).set(entry), + remove: (path, key) => target(path).remove(key), + finish: () => state + } +} + +// Live Stop settlement belongs to its process; only the row-derived pause facts are stored, so a +// stored value decodes as it is. +export function durableQueuePauseMarks( + marks: JournalReducerState['queuePauseMarks'] +): JournalReducerState['queuePauseMarks'] { + const stop = marks.latestStop + return { ...marks, latestStop: stop && { sequence: stop.sequence, event: stop.event } } +} + +const f = outcomeFormat1StoredScalars.shape +const admittedPauseMarks = z.custom() +const admittedHistoryOrigin = z.custom() + +function applyScalar(state: JournalReducerState, key: string, value: unknown): void { + switch (key) { + case 'sessionId': + state.sessionId = f.sessionId.parse(value) + return + case 'epoch': + state.epoch = f.epoch.parse(value) + return + case 'lastSequence': + state.lastSequence = f.lastSequence.parse(value) + return + case 'lastActivityAt': + state.lastActivityAt = f.lastActivityAt.parse(value) + return + case 'oldestSequence': + state.oldestSequence = f.oldestSequence.parse(value) + return + case 'highestFence': + state.highestFence = f.highestFence.parse(value) + return + case 'derivedTurnScope': + state.derivedTurnScope = JournalDerivedTurnScope.restore(f.derivedTurnScope.parse(value)) + return + case 'latestAcceptedTurnSequence': + state.latestAcceptedTurnSequence = f.latestAcceptedTurnSequence.parse(value) + return + case 'queuePauseMarks': + state.queuePauseMarks = admittedPauseMarks.parse(value) + return + case 'queue': + state.queue.revision = f.queue.parse(value).revision + return + case 'historyOrigin': + state.historyOrigin = admittedHistoryOrigin.parse(value) + return + default: + throw new Error('unknown saved journal scalar') + } +} + +const isString = (key: unknown): key is string => typeof key === 'string' +const isNumber = (key: unknown): key is number => typeof key === 'number' + +function collectionTargets(state: JournalReducerState): Map { + const map = (target: Map, isKey: (key: unknown) => key is K): Target => { + const admitted = z.custom<[K, V]>() + return { + set: (entry) => { + const [key, value] = admitted.parse(entry) + target.set(key, value) + }, + remove: (key) => { + if (isKey(key)) { + target.delete(key) + } + } + } + } + const member = z.custom<[string, string]>() + const set = (target: Set): Target => ({ + set: (entry) => { + target.add(member.parse(entry)[0]) + }, + remove: (key) => { + if (isString(key)) { + target.delete(key) + } + } + }) + const item = z.custom() + const echo = z.custom<[string] | [string, unknown]>() + const items = state.items + return new Map([ + [ + 'items', + { + set: (entry) => { + const value = item.parse(entry) + items.set(value.itemId, value) + }, + remove: (key) => { + if (isString(key)) { + items.delete(key) + } + } + } + ], + ['itemFences', map(state.itemFences, isString)], + ['itemExecutionOwners', map(state.itemExecutionOwners, isString)], + ['providerActivityAt', map(state.providerActivityAt, isNumber)], + ['tombstones', map(state.tombstones, isString)], + ['removedTurnIds', set(state.removedTurnIds)], + ['submissions', map(state.submissions, isString)], + ['receipts', map(state.receipts, isString)], + ['aliases', map(state.aliases, isString)], + [ + 'itemEchoes', + { + set: (entry) => { + const value = echo.parse(entry) + state.itemEchoes.set(value[0], value[1]) + }, + remove: (key) => { + if (isString(key)) { + state.itemEchoes.delete(key) + } + } + } + ], + ['appliedSettlementIds', set(state.appliedSettlementIds)], + ['stoppedHistoryCarried', map(state.stoppedHistoryCarried, isString)], + ['queuedHandOffPlaces', map(state.queuedHandOffPlaces, isString)], + ['normalizedHandOffs', set(state.normalizedHandOffs)], + ['queue.cards', map(state.queue.cards, isString)] + ]) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts new file mode 100644 index 000000000000..42a60bf90cfe --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts @@ -0,0 +1,201 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + closeTestJournalHostDatabases, + insertTestJournalRowJson, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + admitOutcomeFormat1, + OUTCOME_FORMAT_1_COLLECTIONS, + outcomeFormat1EntryParsers, + outcomeFormat1Fields, + outcomeFormat1Scalars +} from './journal-outcome-format-1' + +// Rows a format-1 build wrote, checked in as data: this build must read them, and every later one. +const fixture = z + .object({ + sessionId: z.string(), + epoch: z.string(), + through: z.number(), + marker: z.string(), + outcomes: z.array( + z.tuple([z.number(), z.string(), z.string(), z.number(), z.string(), z.string(), z.number()]) + ), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-outcome-format-1.json', import.meta.url), 'utf8') + ) + ) +const { sessionId, epoch } = fixture +const GENERATION = 7 + +let root: string +let database: JournalHostDatabase +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-format-1-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, sessionId, epoch) + insertTestJournalRowJson(db, sessionId, 1, fixture.marker) + db.prepare(`INSERT INTO journal_outcome_generations (generation, session_id, epoch) + VALUES (?, ?, ?)`).run(GENERATION, sessionId, epoch) + db.prepare(`INSERT INTO journal_outcome_epochs + (session_id, epoch, generation, format, through_seq, prefix_seq) VALUES (?, ?, ?, 1, ?, 0)`).run( + sessionId, + epoch, + GENERATION, + fixture.through + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const outcome of fixture.outcomes) { + insert.run(GENERATION, ...outcome) + } + }) +}) +afterEach(async () => { + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +function restored(): JournalReducerState { + const loaded = restoreJournal(database.db, sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing fixture chat') + } + return loaded.state +} + +it('reads the checked-in format-1 outcomes into the same chat, every field and scalar included', () => { + // Every field and scalar has records here; a field or scalar added later adds its own records. + expect(OUTCOME_FORMAT_1_COLLECTIONS).toEqual([ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' + ]) + const scalars = Object.keys(outcomeFormat1Scalars.shape) + expect(scalars).toEqual([ + 'sessionId', + 'epoch', + 'lastSequence', + 'lastActivityAt', + 'oldestSequence', + 'highestFence', + 'derivedTurnScope', + 'latestAcceptedTurnSequence', + 'queuePauseMarks', + 'historyOrigin', + 'queue' + ]) + const stored = fixture.outcomes + expect(new Set(stored.map(([, field]) => field))).toEqual( + new Set(['$', ...OUTCOME_FORMAT_1_COLLECTIONS]) + ) + // The sequence is never stored: it is the epoch's coverage. + expect( + new Set(stored.filter(([, field]) => field === '$').map(([, , key]) => JSON.parse(key))) + ).toEqual(new Set(scalars.filter((scalar) => scalar !== 'lastSequence'))) + expect(stored.some(([, , , , , , deleted]) => deleted === 1)).toBe(true) + + const state = restored() + expect(plain(state)).toEqual(fixture.expected) + // An echo declared undefined stays present without a value. + const echoes = [...state.itemEchoes] + expect(echoes).toHaveLength(1) + expect(echoes[0]?.[1]).toBeUndefined() +}) + +function insertOutcome(field: string, key: string, json: string, format = 1): void { + database.db + .prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, 's0000000000000021:0000000000000099', ?, 0)`) + .run(GENERATION, fixture.through, field, key, format, json) +} + +const newer = { newer: { sequence: 1 }, damage: null } + +it('refuses a field format 1 does not define as written by a newer Orca', () => { + insertOutcome('futureField', '"k"', '["k",1]') + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +it('refuses a record of a newer format even when the epoch summary was not raised', () => { + insertOutcome('receipts', '"client-9"', '["client-9",{}]', 2) + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +// Every key format 1 declares, at every depth, checked in as data: each must keep admitting and +// decoding as stored. Adding an optional key adds to this corpus; nothing here is edited in place. +const values = z + .array(z.tuple([z.enum(['items', 'submissions', 'queue.cards']), z.string(), z.unknown()])) + .parse( + JSON.parse( + readFileSync( + new URL('./__fixtures__/journal-outcome-format-1-values.json', import.meta.url), + 'utf8' + ) + ) + ) + +it('admits and decodes every declared shape as stored, and refuses one key more as newer', () => { + for (const [field, key, value] of values) { + const json = JSON.stringify(value) + expect(admitOutcomeFormat1({ field, key, json, deleted: false })).toEqual({ + entryKey: JSON.parse(key), + kept: value + }) + const decoded = + field === 'items' + ? outcomeFormat1Fields.items.element.parse(value) + : outcomeFormat1EntryParsers[field].parse(value) + expect(decoded).toEqual(value) + } + const [, key, item] = values[0] ?? [] + const newer = JSON.stringify(item).replace('"orcaStop":{', '"orcaStop":{"later":1,') + expect(admitOutcomeFormat1({ field: 'items', key: key ?? '', json: newer, deleted: false })).toBe( + 'unknown' + ) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts new file mode 100644 index 000000000000..b748cde210cb --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts @@ -0,0 +1,273 @@ +import { z } from 'zod' +import { AgentJournalTurnScopeSchema } from '../../../shared/agent-session-journal-schemas' +import { AgentSessionExecutionOptionsSchema } from '../../../shared/agent-session-execution-options' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import type { JournalReducerState } from './journal-reducer' +import type { JournalHistoryOrigin } from './journal-history-origin' +import type { JournalStopEvent } from './journal-row-schema' +import { + storedFailureFact, + storedItem, + storedMessageBody, + storedProviderHandle, + storedSubmission +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Outcome format 1. A record keeps this meaning whatever the reducer becomes, and a build refuses a +// record holding a key it does not declare. So an added optional key needs no new format; a changed +// meaning, a removed or renamed key, a loosened type or a changed record key does, with its own +// records and decoder beside these. Its fields copy reducer bookkeeping, so changing what one of +// those means is a format change too. The golden fixture must keep decoding. +export const JOURNAL_OUTCOME_FORMAT_1 = 1 + +const number = z.number().finite() +const cursor = z.object({ epoch: z.string(), sequence: number }) +const place = z.object({ + sequence: number, + observedAt: number, + turnScope: AgentJournalTurnScopeSchema.optional() +}) +const pauseMarks = z.object({ + cleared: z + .object({ + sequence: number, + operationId: z.string(), + messageIds: z.array(z.string()), + lifted: z.literal(true).optional() + }) + .optional(), + latestStop: z + .object({ + sequence: number, + event: z.object({ + reason: z.string(), + at: number, + turnId: z.string().optional(), + caller: z.string().optional() + }) + }) + .nullable(), + resumedSequence: number, + reopenedSequence: number +}) +const card = z.object({ + messageId: z.string(), + position: number, + body: storedMessageBody, + fingerprint: z.string(), + state: z.enum(['waiting', 'dispatched', 'returned', 'withdrawn']), + holdReason: z.string().nullable(), + returnedReason: z.string().nullable(), + returnedRejection: storedFailureFact.nullable(), + consumedAs: z.string().nullable(), + queuedAt: cursor.nullable(), + options: AgentSessionExecutionOptionsSchema.optional() +}) +const receipt = z.object({ + clientMessageId: z.string(), + providerItemId: z.string(), + cursor, + acceptedAt: number +}) +const entry = (value: V) => z.tuple([z.string(), value]) +// Set members are stored as [value, value], as a Set's entries() yields them. +const member = (value: z.ZodString) => + z.tuple([value, value]).refine(([key, stored]) => key === stored) + +/** What format 1 stores, as declared; reads admit values only through their strict forms. */ +export const outcomeFormat1Stored = { + items: storedItem, + itemFences: entry(number), + itemExecutionOwners: entry(number), + providerActivityAt: z.tuple([number, number]), + tombstones: entry(number), + removedTurnIds: member(z.string()), + submissions: entry(storedSubmission), + receipts: entry(receipt), + aliases: entry(z.string()), + itemEchoes: z.union([z.tuple([z.string()]), z.tuple([z.string(), z.unknown()])]), + appliedSettlementIds: member(z.string()), + stoppedHistoryCarried: entry(z.array(z.string())), + queuedHandOffPlaces: entry(place), + normalizedHandOffs: member(z.string()), + 'queue.cards': entry(card) +} +export const outcomeFormat1StoredScalars = z.object({ + sessionId: z.string(), + epoch: z.string(), + lastSequence: z.number().int().nonnegative(), + lastActivityAt: number, + oldestSequence: number, + highestFence: number, + derivedTurnScope: z.string().nullable(), + latestAcceptedTurnSequence: number, + queuePauseMarks: pauseMarks, + historyOrigin: z.object({ providerHandle: storedProviderHandle, raw: z.unknown() }).nullable(), + queue: z.object({ revision: number }) +}) + +/** Keyed collections, in the order the golden fixture pins. */ +export const OUTCOME_FORMAT_1_COLLECTIONS = [ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' +] as const satisfies readonly (keyof typeof outcomeFormat1Stored)[] + +function checked(schema: z.ZodType): z.ZodType { + // SAFETY: the strict schema admits only keys the type declares (checked at the end of this file); + // decoding keeps the stored value as it is. + const strict = strictStorage(schema) + return z.custom((value) => strict.safeParse(value).success) +} + +type State = JournalReducerState +type Stored = F extends Map ? [K, V] : F extends Set ? [T, T] : never +type Cards = State['queue']['cards'] +const s = outcomeFormat1Stored +const scalar = outcomeFormat1StoredScalars.shape + +/** Typed views of the stored schemas for decoding admitted records into reducer state. */ +export const outcomeFormat1EntryParsers = { + itemFences: checked>(s.itemFences), + itemExecutionOwners: checked>(s.itemExecutionOwners), + providerActivityAt: checked>(s.providerActivityAt), + tombstones: checked>(s.tombstones), + removedTurnIds: checked>(s.removedTurnIds), + submissions: checked>(s.submissions), + receipts: checked>(s.receipts), + aliases: checked>(s.aliases), + itemEchoes: checked<[string] | [string, unknown]>(s.itemEchoes), + appliedSettlementIds: checked>(s.appliedSettlementIds), + stoppedHistoryCarried: checked>(s.stoppedHistoryCarried), + queuedHandOffPlaces: checked>(s.queuedHandOffPlaces), + normalizedHandOffs: checked>(s.normalizedHandOffs), + 'queue.cards': checked>(s['queue.cards']) +} +const p = outcomeFormat1EntryParsers +export const outcomeFormat1Fields = { + ...outcomeFormat1StoredScalars.shape, + items: z.array(checked(s.items)), + itemFences: z.array(p.itemFences), + itemExecutionOwners: z.array(p.itemExecutionOwners), + providerActivityAt: z.array(p.providerActivityAt), + tombstones: z.array(p.tombstones), + removedTurnIds: z.array(p.removedTurnIds), + submissions: z.array(p.submissions), + receipts: z.array(p.receipts), + aliases: z.array(p.aliases), + itemEchoes: z.array(p.itemEchoes), + appliedSettlementIds: z.array(p.appliedSettlementIds), + queuePauseMarks: checked(scalar.queuePauseMarks), + stoppedHistoryCarried: z.array(p.stoppedHistoryCarried), + queuedHandOffPlaces: z.array(p.queuedHandOffPlaces), + normalizedHandOffs: z.array(p.normalizedHandOffs), + queue: z.object({ revision: number, cards: z.array(p['queue.cards']) }), + historyOrigin: checked(scalar.historyOrigin) +} +export const outcomeFormat1Scalars = outcomeFormat1StoredScalars.extend({ + queuePauseMarks: outcomeFormat1Fields.queuePauseMarks, + historyOrigin: outcomeFormat1Fields.historyOrigin +}) + +/** The scalars as a whole, strict: a chat with no input prefix holds every one. */ +export const outcomeFormat1StrictScalars = strictStorage(outcomeFormat1StoredScalars) +const strictly = (schemas: Record) => + new Map(Object.entries(schemas).map(([field, schema]) => [field, strictStorage(schema)])) +const collections = strictly(outcomeFormat1Stored) +const scalars = strictly(outcomeFormat1StoredScalars.shape) + +/** A record's key and value as admission parsed and checked them; decoding takes them as they are. */ +export type AdmittedOutcome = { readonly entryKey: unknown; readonly kept: unknown } + +/** Admission: a field, scalar, key or union tag format 1 does not declare, at any depth, is a newer + * writer's ('unknown'); content failing a declared type is damage and throws. An admitted value is + * decoded as stored, never re-encoded through the schema, and never parsed or walked again. */ +export function admitOutcomeFormat1(value: { + field: string + key: string + json: string + deleted: boolean +}): 'unknown' | AdmittedOutcome { + const key: unknown = JSON.parse(value.key) + const schema = + value.field === '$' + ? typeof key === 'string' + ? scalars.get(key) + : undefined + : collections.get(value.field) + if (!schema) { + return 'unknown' + } + if (value.field === '$' ? value.deleted : typeof key !== 'string' && typeof key !== 'number') { + throw new Error('invalid journal outcome key') + } + if (value.deleted) { + return value.json === 'null' ? { entryKey: key, kept: null } : 'unknown' + } + const kept: unknown = JSON.parse(value.json) + const verdict = storageVerdict(schema, kept) + if (verdict !== 'stored') { + if (verdict === 'newer') { + return 'unknown' + } + throw new Error('invalid journal outcome value') + } + const storedKey = value.field === '$' ? key : value.field === 'items' ? itemId(kept) : first(kept) + if (storedKey !== key) { + throw new Error('mismatched journal outcome key') + } + return { entryKey: key, kept } +} + +function itemId(value: unknown): unknown { + return typeof value === 'object' && value !== null && 'itemId' in value ? value.itemId : undefined +} + +function first(value: unknown): unknown { + return Array.isArray(value) ? value[0] : undefined +} + +type Collection = (typeof OUTCOME_FORMAT_1_COLLECTIONS)[number] +type StoredIn = F extends 'items' + ? AgentJournalRenderItem + : F extends 'queue.cards' + ? Stored + : F extends keyof State + ? Stored + : never +type Marks = State['queuePauseMarks'] +// Live Stop settlement is never stored (durableQueuePauseMarks). +type StoredMarks = Omit & { + latestStop: { sequence: number; event: JournalStopEvent } | null +} +type Scalars = z.output +export type OutcomeFormat1DeclaresEveryKey = [ + StorageDeclaresAll< + { + [F in Collection]: UndeclaredStorageKeys< + StoredIn, + z.output<(typeof outcomeFormat1Stored)[F]> + > + }[Collection] + >, + StorageDeclaresAll>, + StorageDeclaresAll> +] diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts new file mode 100644 index 000000000000..cfc7cb54ca6d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts @@ -0,0 +1,148 @@ +import type Database from '../../sqlite/sync-database' +import { readJournalSessionEpoch } from './journal-row-table' +import { AgentSessionJournalError } from './journal-write-guards' +import { JOURNAL_OUTCOME_FORMAT_1 } from './journal-outcome-format-1' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' + +/** The newest record format this build reads, and the one it writes. Each stored record carries its + * own format; older formats keep their frozen decoders and are never rewritten. */ +export const JOURNAL_OUTCOME_FORMAT = JOURNAL_OUTCOME_FORMAT_1 +/** Builds before outcome records refuse a row of this version wherever it sits in the epoch. + * Under this version, how the input rows before the marker fold into keys and values is frozen: the + * tail's records were written over that reading. A build that reads old rows into different keys or + * values must key the new reading off a new marker version; a prefix key read twice under two + * names, or a key the tail deleted coming back, is never intended behavior. */ +export const JOURNAL_OUTCOME_MARKER_VERSION = 5 +/** `prefix` counts the epoch's frozen input rows; the marker row sits right after them and outcome + * records start at its sequence. `format` is the highest record format the epoch holds. */ +export type JournalOutcomeSource = { + generation: number + through: number + format: number + prefix: number +} + +export function ensureJournalOutcomeTables(db: Database.Database): void { + db.exec(`CREATE TABLE IF NOT EXISTS journal_outcome_generations ( + generation INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, epoch TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcome_epochs ( + session_id TEXT PRIMARY KEY, epoch TEXT NOT NULL, generation INTEGER NOT NULL, + format INTEGER NOT NULL, through_seq INTEGER NOT NULL, prefix_seq INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcomes ( + generation INTEGER NOT NULL, seq INTEGER NOT NULL, field TEXT NOT NULL, + entry_key TEXT NOT NULL, format INTEGER NOT NULL, ordinal TEXT NOT NULL, + value_json TEXT NOT NULL, deleted INTEGER NOT NULL, + PRIMARY KEY (generation, seq, field, entry_key) + ); + CREATE INDEX IF NOT EXISTS journal_outcome_keys ON journal_outcomes + (generation, field, entry_key, seq DESC)`) +} + +/** Every owning mutation calls this inside its transaction, before changing the epoch. Null means + * an input-only epoch, read as main reads it; a format this build does not know refuses as newer. */ +export function journalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string +): JournalOutcomeSource | null { + if (readJournalSessionEpoch(db, sessionId) !== epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + const source = db + .prepare( + `SELECT generation, format, through_seq, prefix_seq FROM journal_outcome_epochs + WHERE session_id = ? AND epoch = ?` + ) + .get(sessionId, epoch) + if (!source) { + return null + } + const { generation, format, through_seq: through, prefix_seq: prefix } = source + if ( + typeof generation !== 'number' || + typeof format !== 'number' || + typeof through !== 'number' || + typeof prefix !== 'number' + ) { + throw new JournalOutcomeDecodeError('invalid journal outcome source') + } + if (format > JOURNAL_OUTCOME_FORMAT) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer outcome format') + } + // Only the marker follows the prefix: a row after it is no row this build writes. + const [marker, after] = db + .prepare(`SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq > ? + ORDER BY seq LIMIT 2`) + .all(sessionId, epoch, prefix) + if (after) { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer row') + } + const version = marker?.seq === prefix + 1 ? markerVersion(marker.row_json) : null + if (typeof version === 'number' && version > JOURNAL_OUTCOME_MARKER_VERSION) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer marker') + } + if (version !== JOURNAL_OUTCOME_MARKER_VERSION) { + throw new JournalOutcomeDecodeError('missing journal outcome marker') + } + return { generation, format, through, prefix } +} + +function markerVersion(json: unknown): unknown { + try { + const parsed: unknown = typeof json === 'string' ? JSON.parse(json) : null + return typeof parsed === 'object' && parsed !== null && 'v' in parsed ? parsed.v : null + } catch { + return null + } +} + +/** Starts an epoch's outcome records after `prefix` input rows, which stay byte for byte. The marker + * is appended, never written over an existing row, in the transaction of the first outcome. */ +export function startJournalOutcomeLog( + db: Database.Database, + sessionId: string, + epoch: string, + prefix: number, + savedAt: number +): JournalOutcomeSource { + const tip = db + .prepare('SELECT MAX(seq) AS seq FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch) + if ((tip?.seq ?? 0) !== prefix) { + throw new Error('journal outcome log would not start at the input tip') + } + const generation = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run(sessionId, epoch).lastInsertRowid + ) + const seq = prefix + 1 + db.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ).run( + sessionId, + epoch, + seq, + savedAt, + JSON.stringify({ v: JOURNAL_OUTCOME_MARKER_VERSION, kind: 'outcomes', epoch, seq, ts: savedAt }) + ) + db.prepare( + `INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(session_id) DO UPDATE SET epoch = excluded.epoch, generation = excluded.generation, + format = excluded.format, through_seq = excluded.through_seq, prefix_seq = excluded.prefix_seq` + ).run(sessionId, epoch, generation, JOURNAL_OUTCOME_FORMAT, prefix, prefix) + return { generation, format: JOURNAL_OUTCOME_FORMAT, through: prefix, prefix } +} + +/** Coverage advances with each write; the required format only ever rises. */ +export function advanceJournalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string, + through: number +): void { + db.prepare(`UPDATE journal_outcome_epochs SET through_seq = ?, format = MAX(format, ?) + WHERE session_id = ? AND epoch = ?`).run(through, JOURNAL_OUTCOME_FORMAT, sessionId, epoch) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts new file mode 100644 index 000000000000..be60e4ad4c4f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts @@ -0,0 +1,800 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import type { SqliteStatement } from '../../sqlite/sqlite-statement' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS, type JournalRow } from './journal-row-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { JournalOutcomeSweeper, sweepJournalOutcomePage } from './journal-outcome-cleanup' +import { JOURNAL_NEWEST_OUTCOME_SQL } from './journal-outcome-table' +import { readJournalOutcomeGroups } from './journal-read-row' +import { applyJournalRow, type JournalReducerState } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import { encodeJournalState } from './journal-state-codec' +import type * as RowStorage from './journal-storage-row-schema' +import type * as Strict from './journal-storage-strict' +import type * as OutcomeFormat1 from './journal-outcome-format-1' +import type * as Transition from './journal-reducer-transition' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' + +// N/10N contracts: each counts statements (prepare and exec), rows read and rows and bytes +// written, never time, and requires the same work for a chat ten times larger. + +// Admission's own work: strict walks of input rows and of outcome records, counted at the calls, +// and every strict walk at all, counted at each strict schema storage builds. +const admission = vi.hoisted(() => ({ rows: 0, records: 0, walks: 0 })) +vi.mock('./journal-storage-strict', async (original) => { + const actual = await original() + // A schema storage cannot close further comes back as it is, so one instance can recur. + const counted = new WeakSet>() + return { + ...actual, + strictStorage: (schema: Parameters[0]) => { + const strict = actual.strictStorage(schema) + if (counted.has(strict)) { + return strict + } + counted.add(strict) + const walk = strict.safeParse.bind(strict) + Object.defineProperty(strict, 'safeParse', { + value: (...input: Parameters) => { + admission.walks += 1 + return walk(...input) + } + }) + return strict + } + } +}) +vi.mock('./journal-storage-row-schema', async (original) => { + const actual = await original() + return { + ...actual, + journalRowDeclaresMore: (row: unknown) => { + admission.rows += 1 + return actual.journalRowDeclaresMore(row) + } + } +}) +vi.mock('./journal-outcome-format-1', async (original) => { + const actual = await original() + return { + ...actual, + admitOutcomeFormat1: (value: Parameters[0]) => { + admission.records += 1 + return actual.admitOutcomeFormat1(value) + } + } +}) +// Every draft transition a write or a replacement folds through, to count the nodes it reaches. +const transitions = vi.hoisted(() => { + const opened: { tracked: () => number }[] = [] + return opened +}) +vi.mock('./journal-reducer-transition', async (original) => { + const actual = await original() + return { + ...actual, + isolateJournalTransition: (...input: Parameters) => { + const transition = actual.isolateJournalTransition(...input) + transitions.push(transition) + return transition + } + } +}) +const N = 40 +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const providerItemId = agentJournalItemKey({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal: 1 +}) +const WRITTEN = { + journal_rows: 'row_json', + journal_outcomes: 'value_json' +} as const +const TRANSACTION = /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/ + +let root: string +const rigs: ReturnType[] = [] +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-scaling-')) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +const message = (text: string, role: 'user' | 'assistant' = 'user'): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +const send = (seq: number, clientMessageId: string, handoverRecorded?: true): JournalRow => ({ + ...base(seq), + kind: 'submission', + clientMessageId, + body: message(clientMessageId), + providerHandle, + ...(handoverRecorded ? { handoverRecorded } : {}), + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, message(clientMessageId)) +}) +const revision = + (itemId: string, body: Extract['body'], value: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'item', + itemId, + revision: value, + body + }) +const plan = (text: string) => ({ + kind: 'status' as const, + text, + providerFrame: { + provider: 'codex', + kind: 'notification:turn/plan/updated', + payload: { head: text, byteLength: text.length, digest: 'd'.repeat(64), truncated: false } + } +}) + +/** `size` accepted sends with their statuses and queue cards, then one handed-over send. */ +function historyOf(size: number, everyCard = false): JournalRow[] { + const rows: JournalRow[] = [projectionEpochRow] + for (let index = 0; index < size; index++) { + rows.push(send(rows.length + 1, `earlier-${index}`)) + rows.push({ + ...base(rows.length + 1), + kind: 'dispatch', + clientMessageId: `earlier-${index}`, + state: 'accepted', + providerItemId: `provider-${index}`, + reason: null + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: `status-${index}`, + revision: 1, + body: { kind: 'status', text: `Status ${index}` } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `waiting-${index}`, + change: { + op: 'queued', + body: message(`waiting-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length } + } + }) + const outcomes = everyCard + ? ([ + ['dispatched', { attempt: `attempt-${index}` }], + ['returned', { returned: { reason: 'refused' } }] + ] as const) + : [] + for (const [state, outcome] of outcomes) { + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `${state}-${index}`, + change: { + op: 'queued', + body: message(`${state}-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length }, + ...outcome + } + }) + } + } + rows.push(send(rows.length + 1, 'send', true)) + return rows +} + +function databaseFor(label: string): JournalHostDatabase { + return openTestJournalHostDatabase(join(root, label)) +} + +function outcomeChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedOutcomeRows(database, historyOf(size))) + rigs.push(rig) + return { database, rig } +} + +/** Counts every statement, the rows each table returns, and the rows and bytes each table takes. */ +function watch(database: JournalHostDatabase) { + const triggers = Object.entries(WRITTEN).flatMap(([table, column]) => + ['INSERT', 'UPDATE', 'DELETE'].map((op) => { + const bytes = op === 'DELETE' ? '0' : `length(CAST(NEW.${column} AS BLOB))` + return `CREATE TEMP TRIGGER IF NOT EXISTS count_${table}_${op} AFTER ${op} ON ${table} + BEGIN INSERT INTO scaling_writes VALUES ('${table} ${op}', ${bytes}); END;` + }) + ) + database.db.exec( + `CREATE TEMP TABLE IF NOT EXISTS scaling_writes (target TEXT, bytes INTEGER); ${triggers.join('\n')}` + ) + database.db.exec('DELETE FROM scaling_writes') + const statements: string[] = [] + const read = new Map() + const prepare = database.db.prepare.bind(database.db) + const exec = database.db.exec.bind(database.db) + vi.spyOn(database.db, 'exec').mockImplementation((sql: string) => { + if (!TRANSACTION.test(sql.trim())) { + statements.push(sql) + } + exec(sql) + }) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + statements.push(sql) + const statement = prepare(sql) + const table = /\bFROM\s+(journal_\w+)/.exec(sql)?.[1] ?? 'other' + const count = (rows: number): void => { + read.set(table, (read.get(table) ?? 0) + rows) + } + const counted: SqliteStatement = { + all: (...parameters) => { + const rows = statement.all(...parameters) + count(rows.length) + return rows + }, + get: (...parameters) => { + const row = statement.get(...parameters) + count(row ? 1 : 0) + return row + }, + run: (...parameters) => statement.run(...parameters), + iterate: function* (...parameters) { + for (const row of statement.iterate(...parameters)) { + count(1) + yield row + } + }, + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return counted + }) + return { + rowsRead: (table: string) => read.get(table) ?? 0, + take: () => { + const writes = prepare( + 'SELECT target, COUNT(*) AS n, SUM(bytes) AS bytes FROM scaling_writes GROUP BY target ORDER BY target' + ) + .all() + .map((row) => [String(row.target), Number(row.n), Number(row.bytes)] as const) + exec('DELETE FROM scaling_writes') + const work = { + statements: [...statements], + read: Object.fromEntries([...read].sort()), + writes: writes.map(([target, n]) => [target, n]), + bytes: writes.reduce((sum, [, , bytes]) => sum + bytes, 0) + } + statements.length = 0 + read.clear() + return work + }, + stop: () => vi.restoreAllMocks() + } +} + +function expectSameWork( + small: ReturnType['take']>, + large: ReturnType['take']> +): void { + expect(large.statements).toStrictEqual(small.statements) + expect(large.read).toStrictEqual(small.read) + expect(large.writes).toStrictEqual(small.writes) + // Only the digits of the larger chat's sequence numbers differ. + expect(Math.abs(large.bytes - small.bytes)).toBeLessThanOrEqual(64) +} + +it('appends a streamed revision, a Codex plan update and an acceptance with the same work at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `append-${size}`) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + await rig.writer.enqueue(revision('plan', plan('Plan 1'), 1)) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision('plan', plan('Plan 2'), 2)) + const planned = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + expect(rig.state().submissions.get('send')?.dispatchState).toBe('accepted') + return { streamed, planned, accepted } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const key of ['streamed', 'planned', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The item's record alone: the sequence is the epoch's coverage, never a record. + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) +}) + +/** One settlement row creating `size` status items. */ +const batchOf = + (size: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'lifecycle-batch', + settlementId: `batch-${size}`, + mutations: Array.from({ length: size }, (_, index) => ({ + kind: 'item' as const, + itemId: `batch-${index}`, + revision: 1, + body: { kind: 'status' as const, text: `Batch ${index}` } + })) + }) + +it('encodes a settlement batch with the same work per mutation up to the mutation cap', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(N, `batch-${size}`) + const watched = watch(database) + const stringify = vi.spyOn(JSON, 'stringify') + await rig.writer.enqueue(batchOf(size)) + const calls = stringify.mock.calls.length + const work = watched.take() + watched.stop() + expect(rig.state().items.has(`batch-${size - 1}`)).toBe(true) + return { calls, statements: work.statements.length } + } + // Schemas compile on their first parse; that one-time work is not the batch's. + await measure(10) + const few = await measure(20) + const more = await measure(110) + const most = await measure(MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS) + // Linear in the batch: each further 90 mutations add the same work. + expect(most.calls - more.calls).toBe(more.calls - few.calls) + expect(most.statements).toBe(few.statements) +}) + +/** A tool call whose structured input holds `size` nested objects, as a large multi-edit does. */ +const toolCall = (size: number) => ({ + kind: 'tool-call' as const, + name: 'edit', + input: { + edits: Array.from({ length: size }, (_, index) => ({ path: `file-${index}`, at: { index } })) + }, + state: 'running' as const +}) + +it("encodes a structured tool call's revisions without reading its input through the draft, at N and 10N nested objects", async () => { + const measure = async (size: number) => { + const { rig } = outcomeChat(N, `tool-${size}`) + // The draft's copy-on-write proxies read through Reflect.get; plain reads never call it. + const reads = vi.spyOn(Reflect, 'get') + await rig.writer.enqueue(revision('tool', toolCall(size), 1)) + const first = reads.mock.calls.length + reads.mockClear() + await rig.writer.enqueue(revision('tool', toolCall(size), 2)) + const next = reads.mock.calls.length + reads.mockRestore() + expect(rig.state().items.get('tool')?.body).toEqual(toolCall(size)) + return { first, next } + } + expect(await measure(10 * N)).toStrictEqual(await measure(N)) +}) + +/** A chat this build wrote, holding `size` live items and `size` waiting queue cards. */ +async function liveChat(size: number, label: string) { + const stateDirectory = join(root, label) + const journal = await journals.open({ + identity: { + sessionId, + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory, + // A fixed clock: a timestamp that moves mid-chat would change which rows touch the activity time. + now: () => 10_000 + }) + const kept = Array.from({ length: size }, (_, ordinal) => ({ + identity: { provider: 'codex' as const, threadId: 'thread-1', turnId: 'turn-1', ordinal }, + body: { kind: 'status' as const, text: `Status ${ordinal}` }, + ownerFence: 1 + })) + for (const { identity, body } of kept) { + await journal.appendItem(identity, body, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await journal.queuedMessages.insert({ + messageId: `card-${identity.ordinal}`, + body: message(`card ${identity.ordinal}`) + }) + } + return { journal, kept, database: openTestJournalHostDatabase(stateDirectory) } +} + +// Rewind, replacement and rollover restate the live chat in one transaction, as main does: the +// epoch's rows are built by one fold and its records by a second through the draft. Both stay +// linear: the statements are fixed, and rows read, rows written and draft nodes grow by the same +// amount for each restated item and card. +it.each(['rewind', 'replacement', 'rollover'] as const)( + 'publishes a %s of a chat with the same work per restated item at N, 2N and 11N', + async (path) => { + const measure = async (size: number) => { + const { journal, kept, database } = await liveChat(size, `${path}-${size}`) + const watched = watch(database) + transitions.length = 0 + await (path === 'rollover' + ? journal.rollEpoch('unreconcilable_prefix', 1) + : journal.replaceEpochItems(path === 'rewind' ? 'handle_forked' : 'legacy_import', 1, kept)) + const work = watched.take() + watched.stop() + expect(journal.snapshot().items).toHaveLength(path === 'rollover' ? 0 : size) + expect(journal.queuedMessages.list()).toHaveLength(size) + const counts = new Map([ + ...Object.entries(work.read).map(([table, rows]): [string, number] => [ + `read ${table}`, + rows + ]), + ...work.writes.map(([target, rows]): [string, number] => [`${target}`, Number(rows)]), + ['draft nodes', transitions.reduce((sum, transition) => sum + transition.tracked(), 0)] + ]) + return { statements: work.statements, counts } + } + // A chat's first item and card start collections an empty chat lacks, so the line is taken + // between non-empty chats: 10N more restated items cost ten times what N more do. + const base = await measure(N) + const small = await measure(2 * N) + const large = await measure(11 * N) + expect(large.statements).toStrictEqual(small.statements) + expect([...large.counts.keys()]).toStrictEqual([...small.counts.keys()]) + for (const [counted, value] of large.counts) { + const from = base.counts.get(counted) ?? 0 + expect({ counted, grown: value - from }).toStrictEqual({ + counted, + grown: 10 * ((small.counts.get(counted) ?? 0) - from) + }) + } + expect(large.counts.get('draft nodes')).toBeGreaterThan(small.counts.get('draft nodes') ?? 0) + } +) + +/** Distinct keys the chat's records hold, live, deleted and scalar alike. */ +function outcomeKeys(database: JournalHostDatabase): number { + return Number( + database.db + .prepare('SELECT COUNT(*) AS n FROM (SELECT DISTINCT field, entry_key FROM journal_outcomes)') + .get()?.n + ) +} + +it("opens a new chat reading each key's newest record once, the same with N and 10N superseded revisions", async () => { + const measure = async (revisions: number) => { + const { database, rig } = outcomeChat(N, `open-${revisions}`) + for (let index = 1; index <= revisions; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const records = database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { database, work, records: Number(records), keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + // Anti-vacuous: the larger chat holds 9N more superseded revisions of one key. + expect(large.records - small.records).toBe(9 * N) + expect(large.keys).toBe(small.keys) + expectSameWork(small.work, large.work) + // One record per key; of the chat's rows only the marker, which its outcome summary must agree with. + expect(small.work.read).toStrictEqual({ + journal_outcome_epochs: 1, + journal_outcomes: small.keys, + journal_rows: 1, + journal_sessions: 2 + }) + // Each read is one seek down the key index from the last key: no scan, no sort, no revision walk. + const plan = small.database.db + .prepare(`EXPLAIN QUERY PLAN ${JOURNAL_NEWEST_OUTCOME_SQL}`) + .all(1, '', '', 1) + .map((row) => String(row.detail)) + expect(plan).toEqual([ + 'SEARCH journal_outcomes USING INDEX journal_outcome_keys (generation=? AND (field,entry_key)>(?,?))' + ]) +}) + +/** An existing chat of `size` sends in its input rows, then three writes as outcome records. */ +async function prefixChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedProjectionRows(database, historyOf(size))) + rigs.push(rig) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + const first = watched.take() + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + return { database, rig, first, streamed, accepted } +} + +it('writes to an existing chat without reading its prefix, the same at N and 10N', async () => { + const small = await prefixChat(N, 'prefix-append-small') + const large = await prefixChat(10 * N, 'prefix-append-large') + for (const key of ['first', 'streamed', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The first write appends the marker, then the item's record and the two scalars it changed. + expect(small.first.writes).toStrictEqual([ + ['journal_outcomes INSERT', 3], + ['journal_rows INSERT', 1] + ]) + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) + expect(large.rig.state().submissions.get('send')?.dispatchState).toBe('accepted') +}) + +it("opens an existing chat reading main's prefix rows and each tail key's newest record, at N and 10N", async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `prefix-open-${size}`) + // The tail's one streamed item takes `size` more revisions: superseded, never read. + for (let index = 3; index < size + 3; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { work, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const { work, prefix, keys } of [small, large]) { + // The prefix rows main folds, plus the marker: checked against the outcome summary, and met + // again on the prefix's last page. + expect(work.read.journal_rows).toBe(prefix + 2) + expect(work.read.journal_outcomes).toBe(keys) + } + expect(large.keys).toBe(small.keys) +}) + +/** The text of each keyed record an open decodes: every key's newest live record. */ +function newestEntries(database: JournalHostDatabase) { + const rows = database.db + .prepare( + `SELECT value_json FROM journal_outcomes o WHERE field <> '$' AND deleted = 0 AND seq = + (SELECT MAX(seq) FROM journal_outcomes WHERE generation = o.generation AND field = o.field + AND entry_key = o.entry_key)` + ) + .all() + return { texts: new Set(rows.map((row) => String(row.value_json))), records: rows.length } +} + +// Admission is linear in what is read, with a constant of one: one strict walk per input row read +// (main parses each row once; this adds the walk), one per outcome record read or written. Decoding +// takes each record as admission parsed it: no record is parsed or walked twice. +it('admits each row and record an existing chat reads or writes once, at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `admission-${size}`) + const entries = newestEntries(database) + const watched = watch(database) + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + const parses = vi.spyOn(JSON, 'parse') + restoreJournal(database.db, sessionId) + const parsed = parses.mock.calls.filter(([text]) => entries.texts.has(text)).length + parses.mockRestore() + const open = { ...admission, parsed, entries: entries.records, read: watched.take().read } + admission.rows = 0 + const page = readJournalRowsAfterCursor(database.db, sessionId, epoch, 0, 100) + const paged = { walks: admission.rows, rows: page.filter((row) => row.kind !== 'outcome') } + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + await rig.writer.enqueue(revision('answer', message('z'.repeat(4_096), 'assistant'), 3)) + const written = { ...admission, writes: watched.take().writes } + watched.stop() + return { open, paged, written, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + for (const { open, paged, written, prefix, keys } of [await measure(N), await measure(10 * N)]) { + // The marker is read twice (source check, last prefix page) and walked never. + expect(open.read.journal_rows).toBe(prefix + 2) + expect(open.rows).toBe(prefix) + expect(open.records).toBe(keys) + expect(open.walks).toBe(open.rows + open.records) + expect(open.entries).toBeGreaterThan(0) + expect(open.parsed).toBe(open.entries) + expect(paged.rows).toHaveLength(100) + expect(paged.walks).toBe(100) + // The written row's read-back, and each record the write inserts. + expect(written.rows).toBe(1) + expect(written.writes).toStrictEqual([['journal_outcomes INSERT', written.records]]) + expect(written.walks).toBe(written.rows + written.records) + } +}) + +it('runs a sweep pass with nothing to retire without reading history at N and 10N', async () => { + const measure = async (size: number) => { + const { database } = outcomeChat(size, `idle-${size}`) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: async () => {} }) + const watched = watch(database) + await sweeper.pass() + sweeper.stop() + const work = watched.take() + watched.stop() + return work + } + const small = await measure(N) + for (const table of ['journal_rows', 'journal_outcomes']) { + expect(small.read[table] ?? 0).toBe(0) + } + expectSameWork(small, await measure(10 * N)) +}) + +it('sweeps a retired generation one bounded page per transaction at N and 10N', () => { + const measure = (size: number) => { + const { database } = outcomeChat(size, `sweep-${size}`) + // A replacement generation retires the published one. + database.db.exec(`INSERT INTO journal_outcome_generations (session_id, epoch) + VALUES ('${sessionId}', '${epoch}')`) + database.db.exec(`UPDATE journal_outcome_epochs SET generation = + (SELECT MAX(generation) FROM journal_outcome_generations)`) + const watched = watch(database) + expect(sweepJournalOutcomePage(database)).toBe(true) + const work = watched.take() + watched.stop() + return work + } + const small = measure(N) + expect(small.writes).toStrictEqual([['journal_outcomes DELETE', 32]]) + expectSameWork(small, measure(10 * N)) +}) + +it('sweeps a retired generation numbered after N and 10N live chats without rescanning them per page', () => { + const measure = (chats: number) => { + const database = databaseFor(`sweep-chats-${chats}`) + database.transaction((db) => { + const generation = db.prepare( + 'INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)' + ) + const live = db.prepare('INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, 1, 1, 0)') + for (let index = 0; index < chats; index++) { + const id = Number(generation.run(`chat-${index}`, epoch).lastInsertRowid) + live.run(`chat-${index}`, epoch, id) + } + const retired = Number(generation.run('gone', 'gone-epoch').lastInsertRowid) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < 100; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) + // Each page's candidate scan walks the generations above its position in order, so the live + // ones it passes are those numbered above that position. + const positions: number[] = [] + const prepare = database.db.prepare.bind(database.db) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + const statement = prepare(sql) + if (!sql.includes('LEFT JOIN journal_outcome_epochs')) { + return statement + } + const recorded: SqliteStatement = { + all: (...parameters) => { + positions.push(Number(parameters[0])) + return statement.all(...parameters) + }, + get: (...parameters) => statement.get(...parameters), + run: (...parameters) => statement.run(...parameters), + iterate: (...parameters) => statement.iterate(...parameters), + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return recorded + }) + while (sweepJournalOutcomePage(database)) { + // One bounded page per call. + } + vi.mocked(database.db.prepare).mockRestore() + const passed = database.db.prepare( + 'SELECT COUNT(*) AS n FROM journal_outcome_epochs WHERE generation > ?' + ) + return positions.map((position) => Number(passed.get(position)?.n)) + } + const small = measure(N) + const large = measure(10 * N) + // Four record pages and the page that drops the generation row; only a pass's first page walks + // the live chats, as an idle pass does. + expect(small).toEqual([N, 0, 0, 0, 0]) + expect(large).toEqual([10 * N, 0, 0, 0, 0]) +}) + +it('catches a wire client up from outcomes reading only the groups it asks for at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `wire-${size}`) + const after = rig.state().lastSequence + for (let index = 0; index < 3; index++) { + await rig.writer.enqueue( + revision('answer', message(`Answer ${index}`, 'assistant'), index + 1) + ) + } + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcomes') + } + const watched = watch(database) + expect(readJournalOutcomeGroups(database.db, epoch, source, after, 200)).toHaveLength(3) + const work = watched.take() + watched.stop() + return work + } + expectSameWork(await measure(N), await measure(10 * N)) +}) + +/** Reducer nodes the draft reaches to fold `row` onto `state`, without adopting it. */ +const trackedNodes = (state: JournalReducerState, row: JournalRow) => + isolateJournalTransition(state, (draft) => applyJournalRow(draft, row, row.ts)).tracked() + +it("folds a streamed revision and an acceptance through the draft with only main's scans growing at N and 10N", () => { + const measure = (size: number) => { + const database = databaseFor(`draft-${size}`) + const state = seedOutcomeRows(database, historyOf(size, true)) + const next = state.lastSequence + 1 + const live = { + items: state.items.size, + submissions: state.submissions.size, + cards: state.queue.cards.size, + returned: [...state.queue.cards.values()].filter((card) => card.state === 'returned').length, + streamed: trackedNodes( + state, + revision('answer', message('y'.repeat(4_096), 'assistant'), 2)(next, 10_000) + ), + accepted: trackedNodes(state, revision(providerItemId, message('send'), 1)(next, 10_000)) + } + return live + } + const small = measure(N) + const large = measure(10 * N) + const grown = (key: keyof typeof small) => large[key] - small[key] + // Main's reducer scans these on the same rows; the draft adds one node per value it reaches. + // A streamed revision's only growing term is the queue card scan: each card, and each returned + // card's body. + const cardScan = grown('cards') + grown('returned') + expect(cardScan).toBeGreaterThan(0) + expect(grown('streamed')).toBe(cardScan) + // An echo also reads every item with its body (context-clear and echo lookups) and every + // submission to find its send. + expect(grown('accepted')).toBe(2 * grown('items') + grown('submissions') + cardScan) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts new file mode 100644 index 000000000000..0acb87d871cd --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts @@ -0,0 +1,131 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { restoreJournal } from './journal-open' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { JournalOutcomeSweeper } from './journal-outcome-cleanup' + +// The production sweeper over a real database, on its own timers. +const epoch = 'epoch-1' +const base = (seq: number) => ({ v: 4, epoch, seq, ts: 1_000 + seq, fence: 1 }) +const epochRow: JournalRow = { + ...base(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} +const item: JournalRow = { + ...base(2), + kind: 'item', + itemId: 'kept', + revision: 1, + body: { kind: 'status', text: 'kept' } +} + +let root: string +let database: JournalHostDatabase +const sweepers: JournalOutcomeSweeper[] = [] +beforeEach(async () => { + vi.useFakeTimers() + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-sweeper-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, 'live', epoch) + publishJournalOutcomeEpoch(db, 'live', epoch, [epochRow, item]) + }) +}) +afterEach(async () => { + sweepers.splice(0).forEach((sweeper) => sweeper.stop()) + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function started(onError = vi.fn()) { + const rests = vi.fn(async () => {}) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: rests, onError }) + sweepers.push(sweeper.start()) + return { rests, onError } +} + +/** A generation no epoch names any more, as a replacement leaves it, holding `keys` records. */ +function retire(keys: number): void { + database.transaction((db) => { + const retired = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < keys; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) +} + +const retiredRecords = () => + database.db + .prepare(`SELECT COUNT(*) AS n FROM journal_outcomes + WHERE generation NOT IN (SELECT generation FROM journal_outcome_epochs)`) + .get()?.n + +it('sweeps a retired generation a minute after launch in paced pages, keeping the live chat', async () => { + retire(100) + const { rests } = started() + await vi.advanceTimersByTimeAsync(59_999) + expect(retiredRecords()).toBe(100) + await vi.advanceTimersByTimeAsync(1) + expect(retiredRecords()).toBe(0) + // Four 32-record pages and the generation row, each its own transaction with a rest after it. + expect(rests.mock.calls.length).toBeGreaterThanOrEqual(4) + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(1) + expect(restoreJournal(database.db, 'live')?.state.items.has('kept')).toBe(true) +}) + +it('retries a failed pass at the next periodic pass, and runs none after it stops', async () => { + retire(10) + const failure = Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR' }) + vi.spyOn(database, 'transaction').mockImplementationOnce(() => { + throw failure + }) + const { onError } = started() + await vi.advanceTimersByTimeAsync(60_000) + expect(onError).toHaveBeenCalledWith(failure) + expect(retiredRecords()).toBe(10) + await vi.advanceTimersByTimeAsync(6 * 60 * 60_000) + expect(retiredRecords()).toBe(0) + retire(10) + sweepers.forEach((sweeper) => sweeper.stop()) + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retiredRecords()).toBe(10) +}) + +it('rests nine times as long as each page worked, holding the sweep to a 10% duty cycle', async () => { + retire(100) + // Every page takes 30 ms on the sweeper's clock. + let clock = 0 + const rests = vi.fn(async (_ms: number) => {}) + const sweeper = new JournalOutcomeSweeper({ + database: () => database, + now: () => (clock += 30), + delay: rests + }) + sweepers.push(sweeper) + await sweeper.pass() + expect(retiredRecords()).toBe(0) + // Four record pages, each followed by its rest; the last page finds nothing more to do. + expect(rests.mock.calls).toEqual([[270], [270], [270], [270]]) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-table.ts b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts new file mode 100644 index 000000000000..fb5c563037b2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts @@ -0,0 +1,99 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalReducerState } from './journal-reducer' +import { applyJournalRow } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import type { JournalRow } from './journal-row-schema' +import { journalRowReadBack } from './journal-row-table' +import { + encodeJournalOutcomes, + journalOutcomeScalars, + JournalOutcomeFold, + JOURNAL_PREFIX_ORDINAL +} from './journal-outcome-codec' +import type { JournalOutcomeSource } from './journal-outcome-format' + +// The key index orders each key's records newest first, so a range seek past the last key read lands +// on the next key's newest record: one indexed seek per key, whatever its revisions number. +export const JOURNAL_NEWEST_OUTCOME_SQL = `SELECT seq, field, entry_key, format, ordinal, value_json, + deleted FROM journal_outcomes WHERE generation = ? AND (field, entry_key) > (?, ?) AND seq <= ? + ORDER BY field, entry_key, seq DESC LIMIT 1` + +/** Folds each key's newest record, deletions included, over `baseline`, the chat's folded input + * prefix when it has one. Superseded revisions are never read: they no longer shape the chat. */ +export function readJournalOutcomes( + db: Database.Database, + sessionId: string, + epoch: string, + source: JournalOutcomeSource, + baseline?: JournalReducerState +): JournalReducerState { + const newest = db.prepare(JOURNAL_NEWEST_OUTCOME_SQL) + const fold = new JournalOutcomeFold() + let after = { field: '', key: '' } + for (;;) { + const row = newest.get(source.generation, after.field, after.key, source.through) + if (!row) { + return fold.finish(sessionId, epoch, source.through, baseline) + } + const value = fold.add(row) + after = { field: value.field, key: value.key } + } +} + +/** Runs inside the receipt transaction and only inserts: no record is ever updated or rewritten. A + * row the reader would reject is refused, as an input insert refuses it; the caller rolls back. */ +export function persistJournalOutcomeRows( + db: Database.Database, + state: JournalReducerState, + source: Pick, + rows: readonly JournalRow[], + savedAt?: number +): { state: JournalReducerState; adopt: () => JournalReducerState } { + let scalar = state.lastSequence === 0 ? {} : journalOutcomeScalars(state) + const transition = isolateJournalTransition(state, () => undefined) + const previous = db.prepare(`SELECT ordinal, deleted FROM journal_outcomes + WHERE generation = ? AND field = ? AND entry_key = ? ORDER BY seq DESC LIMIT 1`) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const row of rows) { + // Folding what a reload reads keeps live state equal to it: an annotation the reader drops as + // unusable never reaches the model, so it is never refused by the strict record encoder. + const { stored } = journalRowReadBack(state.sessionId, row) + applyJournalRow(transition.state, stored, savedAt ?? row.ts) + const changes = transition.changes(true) + // Only this row's own transition is recorded, never a snapshot of a prefix value it left alone. + const encoded = encodeJournalOutcomes(transition.state, changes, scalar, transition.untracked) + scalar = encoded.scalars + for (const [index, value] of encoded.values.entries()) { + // Each change's record is at its own index; the scalar records after them match no change. + const change = changes.at(index) + const kept = previous.get(source.generation, value.field, value.key) + // A new or re-created key takes its place in the row's touch order, as the live map does; a + // key that existed before this row keeps its place, which for a key only the frozen prefix + // held is the prefix's own order. + const ordinal = change?.reinsert + ? appended(row.seq, index) + : kept?.deleted === 0 && typeof kept.ordinal === 'string' + ? kept.ordinal + : !kept && source.prefix > 0 && change + ? JOURNAL_PREFIX_ORDINAL + : appended(row.seq, index) + insert.run( + source.generation, + value.seq, + value.field, + value.key, + value.format, + ordinal, + value.json, + Number(value.deleted) + ) + } + } + return { state: transition.state, adopt: transition.adopt } +} + +function appended(seq: number, index: number): string { + return `s${String(seq).padStart(16, '0')}:${String(index).padStart(16, '0')}` +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts new file mode 100644 index 000000000000..0584008e80e6 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts @@ -0,0 +1,126 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readAgentSessionHistory } from '../agent-session-wire/agent-session-history-page' +import { projectJournalBatch } from '../agent-session-wire/agent-session-journal-batch' +import { readJournalOutcomeGroups } from './journal-read-row' +import { journalOutcomeSource } from './journal-outcome-format' +import { + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionBase as base, + seedOutcomeRows +} from './journal-projection-test-support' +import type { JournalRow } from './journal-row-schema' + +const journals = createTrackedJournalOpener() +let root: string +const identity = { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} as const +const item = (id: string) => ({ provider: 'orca', clientMessageId: id }) as const +afterEach(async () => { + await journals.closeAll() + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +it('keeps sparse sequence groups whole across catch-up, lookahead, history limits and byte shrinking', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-wire-')) + const database = openTestJournalHostDatabase(root) + const rows: JournalRow[] = [projectionEpochRow] + for (let seq = 2; seq <= 30; seq++) { + rows.push({ + ...base(seq), + kind: 'item', + itemId: 'legacy', + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } + }) + } + seedOutcomeRows(database, rows) + const journal = await journals.open({ identity, stateDirectory: root }) + const before = { epoch, sequence: 1 } + const old = journal.readSince(before) + if (!old.ok) { + throw new Error('dense read failed') + } + const expected = projectJournalBatch({ + rows: old.rows, + snapshot: journal.snapshot(), + afterSequence: 1 + }) + // Retention keeps a key's first and latest records, leaving whole sequences without any. + database.db.prepare('DELETE FROM journal_outcomes WHERE seq BETWEEN 3 AND 29').run() + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcome records') + } + const sparse = readJournalOutcomeGroups(database.db, epoch, source, 1) + expect(sparse.length).toBeLessThan(old.rows.length) + expect( + projectJournalBatch({ rows: sparse, snapshot: journal.snapshot(), afterSequence: 1 }) + ).toEqual(expected) + const cursor = journal.cursor() + await journal.appendLifecycleBatch({ + settlementId: 'whole-group', + fence: 1, + mutations: ['one', 'two'].map((id) => ({ + kind: 'item', + identity: item(id), + body: { kind: 'status', text: id }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + })) + }) + await journal.appendItem( + item('later'), + { kind: 'status', text: 'later' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const first = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor, + limit: 1 + }) + expect(first).toMatchObject({ + ok: true, + page: { + hasNewer: true, + items: [{ body: { text: 'one' } }, { body: { text: 'two' } }], + window: { nextCursor: { sequence: cursor.sequence + 1 } } + } + }) + if (!first.ok) { + throw new Error('first group missing') + } + const second = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 1 + }) + expect(second).toMatchObject({ + ok: true, + page: { hasNewer: false, items: [{ body: { text: 'later' } }] } + }) + const bounded = readAgentSessionHistory( + journal, + { sessionId, direction: 'after', cursor, limit: 5 }, + { reader: { budgetBytes: 1, form: (value) => ({ item: value, bytes: 100 }) } } + ) + expect(bounded).toMatchObject({ ok: false, reset: 'cursor_compacted' }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-write.ts b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts new file mode 100644 index 000000000000..79959c7d1b11 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts @@ -0,0 +1,46 @@ +import type Database from '../../sqlite/sync-database' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { + advanceJournalOutcomeSource, + journalOutcomeSource, + startJournalOutcomeLog +} from './journal-outcome-format' +import { persistJournalOutcomeRows } from './journal-outcome-table' + +/** Every write stores outcome records, and nothing else: they are the saved chat. An input-only epoch + * keeps its rows as they are and starts its records here, after them. */ +export function prepareJournalOutcomeWrite( + db: Database.Database, + live: JournalReducerState, + rows: readonly JournalRow[], + savedAt: number +): { adopt: () => JournalReducerState } { + const source = + journalOutcomeSource(db, live.sessionId, live.epoch) ?? + startJournalOutcomeLog(db, live.sessionId, live.epoch, live.lastSequence, savedAt) + if (source.through !== live.lastSequence) { + throw new Error('journal outcome writer has stale coverage') + } + const transition = persistJournalOutcomeRows(db, live, source, rows, savedAt) + advanceJournalOutcomeSource(db, live.sessionId, live.epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} + +/** Epoch builders use the same transition encoder; the epoch's journal rows hold only its marker. */ +export function publishJournalOutcomeEpoch( + db: Database.Database, + sessionId: string, + epoch: string, + rows: readonly JournalRow[] +): { adopt: () => JournalReducerState } { + const first = rows[0] + if (!first || first.seq !== 1 || first.kind !== 'epoch') { + throw new Error('missing founding epoch') + } + const source = startJournalOutcomeLog(db, sessionId, epoch, 0, first.ts) + const initial = createJournalReducerState(sessionId, epoch) + const transition = persistJournalOutcomeRows(db, initial, source, rows) + advanceJournalOutcomeSource(db, sessionId, epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} diff --git a/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts new file mode 100644 index 000000000000..397f0ba2dec9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts @@ -0,0 +1,173 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + liveTestJournalRows +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { parseJournalRow } from './journal-row-schema' +import type { JournalRow } from './journal-row-schema' +import { publishNewEpoch } from './journal-epoch-rollover' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + seedProjectionRows, + seedOutcomeRows, + projectionWriter, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +const rigs: ReturnType[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-prefix-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) +const item = (seq: number, itemId = 'stream'): JournalRow => ({ + ...base(seq), + kind: 'item', + itemId, + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } +}) + +const tombstone = (seq: number, itemId: string): JournalRow => ({ + ...base(seq), + kind: 'tombstone', + itemId, + revision: seq +}) + +it("keeps an existing chat's rows byte for byte, starts its records after one appended marker, and reopens prefix plus records as live", async () => { + // A prefix holding a, b, c, d; then b changes in place, a is deleted, c is deleted and recreated, + // and e is new: the live map reads b, d, c, e. + seedProjectionRows(database, [ + projectionEpochRow, + ...['a', 'b', 'c', 'd'].map((id, index) => item(index + 2, id)) + ]) + const original = liveTestJournalRows(database.db, sessionId) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + // The first record holds only the row's own transition, never a snapshot of the prefix. + expect( + database.db + .prepare(`SELECT field, entry_key, ordinal FROM journal_outcomes + WHERE field != '$'`) + .all() + ).toEqual([{ field: 'items', entry_key: '"b"', ordinal: 'b' }]) + for (const row of [ + (seq: number) => tombstone(seq, 'a'), + (seq: number) => tombstone(seq, 'c'), + (seq: number) => item(seq, 'c'), + (seq: number) => item(seq, 'e') + ]) { + await rig.writer.enqueue((seq, ts) => ({ ...row(seq), ts })) + } + + const rows = liveTestJournalRows(database.db, sessionId) + expect(rows.slice(0, original.length)).toEqual(original) + expect(rows).toHaveLength(original.length + 1) + // Shipped readers refuse the marker wherever it sits; it was never written over a row. + expect(rows.at(-1)?.seq).toBe(original.length + 1) + expect(parseJournalRow(rows.at(-1)!.rowJson)).toEqual({ ok: false, unreadable: true }) + expect([...rig.state().items.keys()]).toEqual(['b', 'd', 'c', 'e']) + expectProjectionMatches(database, rig.state()) + + // Catch-up pages the prefix rows, then the record groups, each sequence once. + const read = (after: number, limit?: number) => + readJournalRowsAfterCursor(database.db, sessionId, epoch, after, limit).map((row) => row.seq) + expect(read(0)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + expect(read(3, 4)).toEqual([4, 5, 6, 7]) + expect(read(5, 2)).toEqual([6, 7]) + expect(read(7)).toEqual([8, 9, 10]) +}) + +it('keeps a record that updated a prefix key when a later prefix fold no longer yields that key', async () => { + seedProjectionRows(database, [projectionEpochRow, item(2, 'a'), item(3, 'b')]) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'c'), ts })) + // A later reducer reads the old row for b as another item: the prefix no longer holds b. + database.db + .prepare('UPDATE journal_rows SET row_json = ? WHERE session_id = ? AND seq = 3') + .run(JSON.stringify({ ...item(3, 'renamed'), revision: 3 }), sessionId) + const restored = restoreJournal(database.db, sessionId) + expect(restored).toMatchObject({ newer: null, damage: null }) + // b keeps its newest value, appended after the prefix and before the tail's own keys. + expect([...restored!.state.items.keys()]).toEqual(['a', 'renamed', 'b', 'c']) + expect(restored!.state.items.get('b')).toEqual(rig.state().items.get('b')) +}) + +it('fences opens and every writer before mutation, while the old parser refuses the founding row', async () => { + const state = seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const anchor = liveTestJournalRows(database.db, sessionId)[0] + expect(anchor && parseJournalRow(anchor.rowJson)).toEqual({ ok: false, unreadable: true }) + const rig = projectionWriter(database, state) + rigs.push(rig) + database.db.prepare('UPDATE journal_outcome_epochs SET format = 99').run() + expect(restoreJournal(database.db, sessionId)).toMatchObject({ + newer: { sequence: 1 }, + damage: null + }) + const before = database.db + .prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key') + .all() + await expect(rig.writer.enqueue((seq) => item(seq))).rejects.toMatchObject({ + code: 'journal_read_only' + }) + expect( + database.db.prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key').all() + ).toEqual(before) + expect(rig.state()).toBe(state) + // Missing remains distinct from unsupported for ACP's resume and loss-warning decisions. + expect(restoreJournal(database.db, 'missing-session')).toBeNull() +}) + +// The check runs inside the publishing transaction, against the epoch the caller last saw. +it('refuses to publish a new epoch over one the caller did not see, writing nothing', () => { + seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const before = database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all() + const committed = vi.fn() + expect(() => + publishNewEpoch({ + database, + identity: { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + epoch: 'replacement', + reason: 'handle_forked', + fence: 2, + now: 20_000, + expectedEpoch: 'an-epoch-replaced-meanwhile', + queue: { cards: [], receipt: { write: () => {}, committed } }, + onPublished: committed + }) + ).toThrow(expect.objectContaining({ code: 'journal_row_rejected' })) + expect(committed).not.toHaveBeenCalled() + expect(database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all()).toEqual(before) + expect(restoreJournal(database.db, sessionId)?.state.epoch).toBe(epoch) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts new file mode 100644 index 000000000000..f1d7d36c9308 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts @@ -0,0 +1,158 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { encodeJournalState } from './journal-state-codec' +import { JournalStopMarks } from './journal-stop-marks' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +let rig: ReturnType | undefined +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-failure-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + rig?.queue.markClosed() + await rig?.queue.drain() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +// The records, the epoch's coverage and the receipt are one write: any failure among them, or at +// COMMIT, refuses the send as main's row insert does, and the live chat adopts nothing. +it('adopts nothing on an outcome, coverage, receipt, outer-abort or COMMIT failure', async () => { + const user: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'Continue' }] + } + const state = seedOutcomeRows(database, [ + projectionEpochRow, + { + ...base(2), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_002 } + } + ]) + rig = projectionWriter(database, state) + const writer = rig.writer + const stops = new JournalStopMarks({ state: rig.state }) + const settle = stops.beginSettle(true) + const send = + (id: string) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'submission', + clientMessageId: id, + body: user, + providerHandle: { kind: 'codex', threadId: 'thread-1' }, + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, user) + }) + database.db.exec('CREATE TABLE test_receipts (seq INTEGER)') + const receipt = { + write: (db: JournalHostDatabase['db'], row?: JournalRow) => { + db.prepare('INSERT INTO test_receipts VALUES (?)').run(row?.seq ?? 0) + }, + committed: vi.fn() + } + await expect(writer.enqueue(send('preserved'), receipt)).resolves.toMatchObject({ seq: 3 }) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(rig.state().submissions.has('preserved')).toBe(true) + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, rig.state()) + const saved = encodeJournalState(rig.state()) + const live = rig.state() + const scenarios = [ + [ + 'outcome', + `CREATE TRIGGER failure BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'coverage', + `CREATE TRIGGER failure BEFORE UPDATE ON journal_outcome_epochs BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'receipt', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'outer', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ROLLBACK, 'failure'); END` + ] + ] as const + for (const [name, sql] of scenarios) { + database.db.exec(sql) + await expect(writer.enqueue(send(name), receipt)).rejects.toThrow('failure') + database.db.exec('DROP TRIGGER failure') + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, live) + } + const exec = database.db.exec.bind(database.db) + const spy = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('injected boundary failure') + } + exec(sql) + }) + await expect(writer.enqueue(send('commit'), receipt)).rejects.toThrow('injected boundary failure') + spy.mockRestore() + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(stops.latest()?.settle).toBe(settle) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(database.db.prepare('SELECT COUNT(*) AS n FROM test_receipts').get()?.n).toBe(1) + expectProjectionMatches(database, live) + const first = rig.state().lastSequence + 1 + await writer.enqueueRows(() => [ + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'queued', body: user, position: 1, queuedAt: { epoch, sequence: seq } } + }), + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'held', holdReason: 'edited' } + }) + ]) + const contributions = database.db + .prepare(`SELECT seq, value_json FROM journal_outcomes + WHERE field = 'queue.cards' AND seq >= ? ORDER BY seq`) + .all(first) + expect( + contributions.map((entry) => + typeof entry.value_json === 'string' ? JSON.parse(entry.value_json)[1].holdReason : undefined + ) + ).toEqual([null, 'edited']) + expectProjectionMatches(database, rig.state()) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts new file mode 100644 index 000000000000..a34403606155 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts @@ -0,0 +1,250 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + codexProviderHandle, + claudeProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { createClaudeJournalTranslator } from '../../claude/claude-structured-journal-translation' +import { createCodexJournalTranslator } from '../../codex/codex-structured-journal-translation' +import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { restoreJournal } from './journal-open' +import { applyJournalRow, renderJournalState } from './journal-reducer' +import { + expectProjectionMatches, + projectionBase, + projectionEpochRow, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' + +const sessionId = 'session-1' +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() +const disposals: (() => void)[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-projection-streams-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + for (const dispose of disposals.splice(0)) { + dispose() + } + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const claudeCapture = z.object({ + kind: z.string(), + at: z.number(), + frame: z.record(z.string(), z.unknown()).optional() +}) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) +function lines(path: URL): unknown[] { + return readFileSync(path, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +it.each(['claude', 'codex'] as const)( + 'projects every commit of a captured %s stream, revisions and Stop settlement', + async (agent) => { + let at = 1_000 + const identity: AgentSessionJournalIdentity = { + sessionId, + workspaceId: 'workspace', + hostId: 'host', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) + } + const journal = await journals.open({ identity, stateDirectory: root, now: () => at }) + const expected = restoreJournal(database.db, sessionId)!.state + let commits = 0 + let planRevisions = 0 + journal.observeCommits((rows) => { + if (!rows?.length) { + return + } + for (const row of rows) { + applyJournalRow(expected, row, at) + } + commits++ + planRevisions += rows.filter( + (row) => + row.kind === 'item' && + row.body.kind === 'status' && + row.body.providerFrame?.kind === 'notification:turn/plan/updated' + ).length + const saved = restoreJournal(database.db, sessionId)?.state + expect(saved?.lastSequence).toBe(journal.cursor().sequence) + if (!saved) { + throw new Error('missing saved chat') + } + expectProjectionMatches(database, expected) + expect(renderJournalState(saved)).toStrictEqual(journal.snapshot()) + }) + const failed = vi.fn() + const sink = createDeferredStructuredAgentSessionEventSink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + disposals.push(() => sink.close()) + sink.bind({ journal, fence: 1, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = Array.from(pending) + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + if (agent === 'claude') { + const translator = createClaudeJournalTranslator({ sink: sink.sink, schedule }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../claude/__fixtures__/claude-adapter-capture-miss.jsonl', import.meta.url) + ).map((line) => claudeCapture.parse(line)) + for (const record of capture) { + if (!record.frame) { + continue + } + at = 1_000 + record.at + translator.handle({ type: 'message', sessionId, message: record.frame, observedAt: at }) + await flush(translator) + } + } else { + const translator = createCodexJournalTranslator({ sink: sink.sink, schedule, now: () => at }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../codex/__fixtures__/codex-app-server-turn-endings.jsonl', import.meta.url) + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(capture.length).toBeGreaterThan(0) + let threadId = 'thread-1' + let turnId = 'turn-1' + for (const record of capture) { + at = 1_000 + record.t + if (typeof record.params.threadId === 'string') { + threadId = record.params.threadId + } + if (record.method === 'turn/started') { + const turn = z.object({ id: z.string() }).parse(record.params.turn) + turnId = turn.id + } + if (record.method === 'turn/completed') { + for (const status of ['inProgress', 'completed']) { + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: 'turn/plan/updated', + params: { threadId, turnId, plan: [{ step: 'Verify saved state', status }] } + }) + await flush(translator) + } + } + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: at + }) + await flush(translator) + } + expect(planRevisions).toBeGreaterThanOrEqual(2) + } + expect(failed).not.toHaveBeenCalled() + // Most codex capture records write no row; it commits three times. + expect(commits).toBeGreaterThanOrEqual(agent === 'claude' ? 6 : 3) + const stoppedTurn = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + await journal.appendItem( + stoppedTurn, + { kind: 'turn', turnId: 'stop-turn', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, 1) + const settle = journal.stopMarks.beginSettle(true) + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: 1, + mutations: [ + { + kind: 'item', + identity: stoppedTurn, + body: { kind: 'turn', turnId: 'stop-turn', state: 'interrupted', completedAt: at + 1 }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(journal.stopMarks.latest()?.settle).toBe(settle) + journal.stopMarks.settled(settle) + expect( + restoreJournal(database.db, sessionId)?.state.appliedSettlementIds.has('stop-settlement') + ).toBe(true) + } +) + +// One row may remove an item, add another, then re-create the first above its tombstone: the +// re-created item moves after the new one, live and saved alike, whether the first came from the +// chat's records or from its frozen input prefix. +it.each(['written', 'over a prefix'] as const)( + 'keeps live order for a key deleted and re-created around a new key in one %s row', + async (path) => { + const item = (itemId: string, revision: number) => ({ + kind: 'item' as const, + itemId, + revision, + body: { kind: 'status' as const, text: `${itemId} ${revision}` } + }) + const first: JournalRow = { ...projectionBase(2), ...item('x', 1) } + const batch: JournalRow = { + ...projectionBase(3), + kind: 'lifecycle-batch', + settlementId: 'reorder', + mutations: [{ kind: 'tombstone', itemId: 'x', revision: 2 }, item('y', 1), item('x', 3)] + } + const rig = projectionWriter( + database, + path === 'written' + ? seedOutcomeRows(database, [projectionEpochRow, first]) + : seedProjectionRows(database, [projectionEpochRow, first]) + ) + await rig.writer.enqueue((seq, ts) => ({ ...batch, seq, ts })) + expect([...rig.state().items.keys()]).toEqual(['y', 'x']) + expectProjectionMatches(database, rig.state()) + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts new file mode 100644 index 000000000000..a26b438c72ac --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts @@ -0,0 +1,96 @@ +import { expect } from 'vitest' +import type { JournalHostDatabase } from './journal-host-database' +import { JournalRowWriter } from './journal-row-writer' +import { JournalWriteQueue } from './journal-write-queue' +import { JournalWriteProjection } from './journal-write-projection' +import { + applyJournalRow, + createJournalReducerState, + type JournalReducerState +} from './journal-reducer' +import { restoreJournal } from './journal-open' +import { encodeJournalState } from './journal-state-codec' +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { insertTestJournalRow, publishTestJournalEpoch } from './journal-host-database-test-support' +import type { JournalRow } from './journal-row-schema' + +export const projectionSessionId = 'session-1' +export const projectionEpoch = 'epoch-1' +export const projectionBase = (seq: number) => ({ + v: 4, + epoch: projectionEpoch, + seq, + ts: 1_000 + seq, + fence: 1 +}) +export const projectionEpochRow: JournalRow = { + ...projectionBase(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} + +export function seedProjectionRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const state = createJournalReducerState(projectionSessionId, projectionEpoch) + database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + for (const row of rows) { + insertTestJournalRow(db, projectionSessionId, row) + applyJournalRow(state, row) + } + }) + return state +} + +export function seedOutcomeRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const publication = database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + return publishJournalOutcomeEpoch(db, projectionSessionId, projectionEpoch, rows) + }) + return publication.adopt() +} + +export function projectionWriter(database: JournalHostDatabase, initial: JournalReducerState) { + let state = initial + const queue = new JournalWriteQueue(state.sessionId) + const projection = new JournalWriteProjection({ + database, + state: () => state, + adopt: (next) => { + state = next + } + }) + const writer = new JournalRowWriter({ + database: () => database, + sessionId: state.sessionId, + now: () => 10_000, + serialize: (run) => queue.serialize(run), + readOnly: () => false, + highestFence: () => state.highestFence, + nextSequence: () => state.lastSequence + 1, + prepare: (db, rows, savedAt) => projection.prepare(db, rows, savedAt), + commit: () => undefined + }) + return { writer, projection, state: () => state, queue } +} + +export function expectProjectionMatches( + database: JournalHostDatabase, + state: JournalReducerState +): void { + const source = journalOutcomeSource(database.db, state.sessionId, state.epoch) + if (!source) { + throw new Error('expected canonical outcomes') + } + const restored = restoreJournal(database.db, state.sessionId) + expect(restored?.damage).toBeNull() + expect(restored?.newer).toBeNull() + expect(restored && encodeJournalState(restored.state)).toStrictEqual(encodeJournalState(state)) +} diff --git a/src/main/native-chat/agent-session-journal/journal-read-row.ts b/src/main/native-chat/agent-session-journal/journal-read-row.ts new file mode 100644 index 000000000000..8ee6c981084a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-read-row.ts @@ -0,0 +1,51 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalRow } from './journal-row-schema' +import type { JournalOutcomeSource } from './journal-outcome-format' + +/** In-process change index only; the public wire still contains items and submissions. */ +export type JournalOutcomeReadRow = { + kind: 'outcome' + epoch: string + seq: number + itemIds: string[] + submissionIds: string[] +} +export type JournalReadRow = JournalRow | JournalOutcomeReadRow + +/** LIMIT counts logical sequences, never the independently compactable physical contributions. */ +export function readJournalOutcomeGroups( + db: Database.Database, + epoch: string, + source: JournalOutcomeSource, + after: number, + limit?: number +): JournalOutcomeReadRow[] { + const groups = db + .prepare(`SELECT DISTINCT seq FROM journal_outcomes + WHERE generation = ? AND seq > ? AND seq <= ? ORDER BY seq LIMIT ?`) + .all(source.generation, after, source.through, limit ?? -1) + const touched = db.prepare(`SELECT field, entry_key FROM journal_outcomes + WHERE generation = ? AND seq = ? AND field IN ('items', 'submissions') ORDER BY field, entry_key`) + return groups.map(({ seq }) => { + if (typeof seq !== 'number') { + throw new Error('invalid journal outcome group') + } + const itemIds: string[] = [] + const submissionIds: string[] = [] + for (const entry of touched.iterate(source.generation, seq)) { + if (typeof entry.entry_key !== 'string') { + throw new Error('invalid journal outcome key') + } + const key: unknown = JSON.parse(entry.entry_key) + if (typeof key !== 'string') { + throw new Error('invalid journal public outcome key') + } + if (entry.field === 'items') { + itemIds.push(key) + } else { + submissionIds.push(key) + } + } + return { kind: 'outcome', epoch, seq, itemIds, submissionIds } + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts index 1441989c61f3..f9ed75c5e54f 100644 --- a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts @@ -134,12 +134,11 @@ it.each(['claude', 'codex'] as const)( if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + const durable = reopened.snapshot().items.filter((item) => item.sequence > cursor.sequence) + expect(durable[0]?.body).toMatchObject({ kind: 'status', text: 'before' }) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + durable.findIndex((item) => item.body.kind === 'tool-call' && item.body.state === 'completed') ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) @@ -211,12 +210,18 @@ it('hands an ACP omitted-field completion to SQLite before root exit with a bloc if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + // The call began before the cursor, so its revision keeps that place; the held writes' own + // groups still show the status landing first and the completion after it. + const touched = replay.rows.map((row) => (row.kind === 'outcome' ? row.itemIds : [])) + const items = reopened.snapshot().items + const status = items.find((item) => item.body.kind === 'status' && item.body.text === 'before') + const call = items.find( + (item) => item.body.kind === 'tool-call' && item.body.callId === 'sleep-1' + ) + expect(touched[0]).toEqual([status?.itemId]) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + touched.findIndex((ids) => call !== undefined && ids.includes(call.itemId)) ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) diff --git a/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts new file mode 100644 index 000000000000..ca9ce22b4f8a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts @@ -0,0 +1,272 @@ +// Track writes through objects, iterators and collection entries; finalize only after COMMIT. + +import type { JournalReducerState } from './journal-reducer' +import { + JournalDraftMap, + JournalDraftSet, + type JournalDraftAccess, + type JournalEntryChange +} from './journal-transition-collections' + +type DraftNode = { + value: object + /** What the draft holds now: the copy once written, else the object itself. */ + current: () => object + finish: () => object + listen: (changed: () => void) => void +} + +class JournalDraft { + private readonly originals = new WeakMap() + private readonly proxies = new WeakMap() + private readonly collections: (JournalDraftMap | JournalDraftSet)[] = + [] + private readonly assigned = new WeakSet() + private readonly pending: (() => void)[] = [] + private readonly resolved = new WeakMap() + /** Objects and collections the fold reached; scaling tests pin how this grows with chat size. */ + nodes = 0 + + readonly access: JournalDraftAccess = { + wrap: (value, changed, path) => this.wrap(value, changed, path), + assign: (value) => { + if (typeof value === 'object' && value !== null) { + this.assigned.add(value) + } + }, + finish: (value) => this.resolve(value), + defer: (apply) => this.pending.push(apply) + } + + wrap(value: T, changed: () => void, path: string): T { + if (typeof value !== 'object' || value === null) { + return value + } + const node = this.proxies.get(value) ?? this.originals.get(value) ?? this.track(value, path) + node.listen(changed) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a node's draft (overlay collection or copy-on-write proxy) has the interface of the object it isolates. + return node.value as T + } + + private track(value: T, path: string): DraftNode { + this.nodes += 1 + const listeners = new Set<() => void>() + let dirty = false + let notifying = false + const mark = (): void => { + dirty = true + if (notifying) { + return + } + // A batch consumes changes after each row; later mutations must notify again. + notifying = true + try { + for (const notify of listeners) { + notify() + } + } finally { + notifying = false + } + } + const listen = (notify: () => void): void => { + listeners.add(notify) + if (dirty) { + notify() + } + } + let node: DraftNode + if (value instanceof Map || value instanceof Set) { + const collection = + value instanceof Map + ? new JournalDraftMap(value, this.access, mark, path) + : new JournalDraftSet(value, this.access, mark, path) + this.collections.push(collection) + node = { + value: collection, + current: () => collection, + finish: () => collection.finish(), + listen + } + } else { + let copy: object | undefined + const current = (): object => copy ?? value + const writable = (): object => { + const next = + copy ?? + (Array.isArray(value) + ? [...value] + : Object.assign(Object.create(Object.getPrototypeOf(value)), value)) + copy = next + return next + } + const assignedKeys = new Set() + const target = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value)) + const proxy = new Proxy(target, { + get: (_target, key, receiver) => + this.wrap( + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: only Reflect.get forwards a raw string|symbol key with the proxy receiver. + Reflect.get(current(), key, receiver), + mark, + path ? `${path}.${String(key)}` : String(key) + ), + has: (_target, key) => Reflect.has(current(), key), + ownKeys: () => Reflect.ownKeys(current()), + getOwnPropertyDescriptor: (_target, key) => { + const descriptor = Reflect.getOwnPropertyDescriptor(current(), key) + return ( + descriptor && { ...descriptor, configurable: key !== 'length' || !Array.isArray(value) } + ) + }, + set: (_target, key, next) => { + const before = Reflect.getOwnPropertyDescriptor(current(), key) + if (!before || !Object.is(before.value, next)) { + this.access.assign(next) + assignedKeys.add(key) + Reflect.set(writable(), key, next) + mark() + } + return true + }, + deleteProperty: (_target, key) => { + if (Object.hasOwn(current(), key)) { + Reflect.deleteProperty(writable(), key) + mark() + } + return true + }, + defineProperty: (_target, key, descriptor) => { + this.access.assign(descriptor.value) + assignedKeys.add(key) + Reflect.defineProperty(writable(), key, descriptor) + mark() + return true + } + }) + node = { + value: proxy, + current, + finish: () => { + if (!dirty && !this.assigned.has(value)) { + return value + } + const result = writable() + const keys = Reflect.ownKeys(result) + for (const key of keys) { + const child: unknown = Reflect.getOwnPropertyDescriptor(result, key)?.value + if (assignedKeys.has(key) || this.assigned.has(value) || this.tracks(child)) { + Reflect.set(result, key, this.finish(child)) + } + } + // Holders of reducer objects across commits keep reading the live object, so apply the + // committed copy to it, keeping the key order in-place mutation would have left. + const previous = Reflect.ownKeys(value) + const reordered = + !Array.isArray(value) && previous.some((key, index) => key !== keys[index]) + for (const key of previous) { + if (reordered || !Object.hasOwn(result, key)) { + Reflect.deleteProperty(value, key) + } + } + for (const key of keys) { + Reflect.set(value, key, Reflect.getOwnPropertyDescriptor(result, key)?.value) + } + return value + }, + listen + } + } + this.originals.set(value, node) + this.proxies.set(node.value, node) + return node + } + + changes(reset = false): JournalEntryChange[] { + return this.collections.flatMap((collection) => collection.changes(reset)) + } + + /** Reads a draft value as it stands without tracking it, so serializing a changed value reaches + * no proxy trap and adds no node. */ + untracked(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + return (this.proxies.get(value) ?? this.originals.get(value))?.current() ?? value + } + + adopt(value: T): T { + const result = this.resolve(value) + for (const apply of this.pending) { + apply() + } + return result + } + + private resolve(value: T): T { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: finishing returns the value itself or the live object its draft stands for, so its type is unchanged. + return this.finish(value) as T + } + + private tracks(value: unknown): boolean { + return ( + typeof value === 'object' && + value !== null && + (this.originals.has(value) || this.proxies.has(value)) + ) + } + + private finish(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + const previous = this.resolved.get(value) + if (previous) { + return previous + } + const node = this.proxies.get(value) ?? this.originals.get(value) + if (node) { + const result = node.finish() + this.resolved.set(value, result) + this.resolved.set(node.value, result) + return result + } + this.resolved.set(value, value) + if (value instanceof Map || value instanceof Set) { + return value + } + // Values created during the fold may hold drafts introduced by spread or destructuring. + for (const key of Reflect.ownKeys(value)) { + const child: unknown = Reflect.getOwnPropertyDescriptor(value, key)?.value + const finished = this.finish(child) + if (finished !== child) { + Reflect.set(value, key, finished) + } + } + return value + } +} + +/** Fold onto a draft of `state`; the live state changes only when `adopt` runs after COMMIT. */ +export function isolateJournalTransition( + state: JournalReducerState, + fold: (draft: JournalReducerState) => T +): { + state: JournalReducerState + result: T + changes: (reset?: boolean) => JournalEntryChange[] + /** A `JSON.stringify` replacer giving each draft value as it stands, untracked. */ + untracked: (key: string, value: unknown) => unknown + adopt: () => JournalReducerState + tracked: () => number +} { + const draft = new JournalDraft() + const candidate = draft.wrap(state, () => undefined, '') + const result = fold(candidate) + return { + state: candidate, + result, + changes: (reset) => draft.changes(reset), + untracked: (_key, value) => draft.untracked(value), + adopt: () => draft.adopt(candidate), + tracked: () => draft.nodes + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts index ccc43a7d6352..a420b05262c8 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts @@ -59,7 +59,7 @@ export function registerJournalRowContextUsageTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const open = () => journals.open({ @@ -123,7 +123,7 @@ export function registerJournalRowContextUsageTests(): void { try { const rowJson = liveTestJournalRows(opened.db, IDENTITY.sessionId)[1]?.rowJson ?? '' const future = JSON.parse(rowJson) - future.body.contextUsage = { used: { kind: 'measured-later', tokens: 'many' } } + future.body.contextUsage = { used: { kind: 'unknown', capturedAt: 'later' } } updateTestJournalRowJson(opened.db, IDENTITY.sessionId, 2, JSON.stringify(future)) } finally { await opened.close() diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts index c58ab5eb60d8..f3de0cb71201 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts @@ -15,7 +15,7 @@ export function registerJournalRowSchemaVersionTests(): void { // Inspect raw rows: upcasting hides the version older readers would see on disk. describe('journal row schema versions', () => { let root = '' - const opener = createTrackedJournalOpener() + const opener = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-row-version-')) diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts index 8016f61aa29b..83c2dbd5f370 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts @@ -196,12 +196,16 @@ describe('journal row validation', () => { ).toBe(false) }) - it('keeps forward compatibility for open string fields and unknown block types', () => { + it('keeps open string fields readable and refuses an unknown block type as newer', () => { const item = (body: unknown) => ({ ...BASE, kind: 'item', itemId: 'i-1', revision: 1, body }) - // Renderers skip unknown block types without dereferencing their fields. + // A saved row's block types are closed: a newer one refuses as a newer Orca's. expect( - parse(item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] })) - ).toBe(true) + parseJournalRow( + JSON.stringify( + item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] }) + ) + ) + ).toEqual({ ok: false, unreadable: true }) expect( parse(item({ kind: 'message', role: 'narrator', blocks: [{ type: 'text', text: 'hi' }] })) ).toBe(true) @@ -217,8 +221,7 @@ describe('journal row validation', () => { selectedOptionId: null, resolvedBy: null, resolvedAt: null - }, - futureField: 'ignored' + } }) ) ).toBe(true) @@ -425,8 +428,8 @@ describe('producer linkage on the persisted row', () => { expect(parsed.ok).toBe(true) }) - it('reads the same row with linkage put INSIDE a prompt option, ignoring the key there', () => { - // Legacy strict prompt bodies rejected unknown keys; linkage must stay on the row base. + it("refuses the same row with linkage put INSIDE a prompt option as a newer Orca's", () => { + // A key a prompt option does not declare is a newer build's; linkage stays on the row base. const smuggled = { ...BASE, v: 3, @@ -440,9 +443,7 @@ describe('producer linkage on the persisted row', () => { resolution } } - const parsed = parseJournalRow(JSON.stringify(smuggled)) - expect(parsed.ok && parsed.row.kind === 'item' && parsed.row.body).toEqual(smuggled.body) - expect(parsed.ok && 'agentId' in parsed.row).toBe(false) + expect(parseJournalRow(JSON.stringify(smuggled))).toEqual({ ok: false, unreadable: true }) }) }) @@ -523,8 +524,7 @@ it.each([ worker: { ...startWorker, party: { ...startWorker.party, orcaSessionId: 'invalid' } }, senders: [] }, - { worker: null, senders: [] }, - { worker: { futureIdentity: 'new shape' }, senders: [] } + { worker: null, senders: [] } ])('replays open worker metadata without damaging task/core: $worker', ({ worker, senders }) => { const body = { kind: 'agent-start', dispatchId: 'dispatch', task: ' Full task\r\nEND ', worker } const parsed = parseJournalRow( diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.ts index bee5568d212a..24dd927fe9ad 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.ts @@ -22,6 +22,7 @@ import { import { isJournalTag } from '../../../shared/agent-session-journal-open-union' import type { StructuredAgentSessionStopCause } from '../agent-session-wire/structured-agent-session-stop-cause' import { dropUnusableRowAnnotations } from './journal-row-unusable-annotations' +import { journalRowDeclaresMore } from './journal-storage-row-schema' import { journalQueueRowContent, type JournalQueueRow } from './journal-queue-events' /** Put additive annotations on the base: older strict prompt bodies reject unknown keys. */ @@ -208,7 +209,14 @@ export function parseJournalRow(line: string): JournalRowParse { if (version === null || !Number.isInteger(version) || version < 1) { return { ok: false, unreadable: false } } - if (version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION) { + // A key or tag this build does not declare in a row of a kind it reads is refused as newer before + // it can be normalized away and the row's value restated without it. + if ( + version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION || + (typeof record.kind === 'string' && + KNOWN_ROW_KINDS.has(record.kind) && + journalRowDeclaresMore(record)) + ) { return { ok: false, unreadable: true } } const upcast = upcastRow(record, version) diff --git a/src/main/native-chat/agent-session-journal/journal-row-table.ts b/src/main/native-chat/agent-session-journal/journal-row-table.ts index bc01a932345b..fda3f14708a6 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-table.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-table.ts @@ -35,8 +35,19 @@ export function insertJournalRow( row: JournalRow, savedAt = row.ts ): number { + const { rowJson } = journalRowReadBack(sessionId, row) + // The table timestamp records the save; the JSON timestamp can remain pinned to item start. + db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) + return Buffer.byteLength(rowJson, 'utf8') +} + +/** Rejects a row the reader would not read back before it can break the next load, and returns the + * row the reader sees: without the annotations it drops as unusable. */ +export function journalRowReadBack( + sessionId: string, + row: JournalRow +): { rowJson: string; stored: JournalRow } { const rowJson = serializeJournalRow(row) - // Reject unreadable rows before they can break the next load; the caller rolls back. const readBack = parseJournalRow(rowJson) if (!readBack.ok || readBack.row.seq !== row.seq) { throw new AgentSessionJournalError( @@ -44,9 +55,7 @@ export function insertJournalRow( `the ${row.kind} row for ${sessionId} would not read back, so it was not written` ) } - // The table timestamp records the save; the JSON timestamp can remain pinned to item start. - db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) - return Buffer.byteLength(rowJson, 'utf8') + return { rowJson, stored: readBack.row } } // Page fetches release read snapshots before reduction so WAL checkpoints are not blocked. @@ -55,9 +64,10 @@ const EPOCH_ROW_PAGE_SIZE = 128 export function* iterateJournalEpochRows( db: Database.Database, sessionId: string, - epoch: string + epoch: string, + afterSequence = Number.MIN_SAFE_INTEGER ): Generator { - let afterSeq = Number.MIN_SAFE_INTEGER + let afterSeq = afterSequence for (;;) { const page = readJournalRowsAfter(db, sessionId, epoch, afterSeq, EPOCH_ROW_PAGE_SIZE) yield* page diff --git a/src/main/native-chat/agent-session-journal/journal-row-writer.ts b/src/main/native-chat/agent-session-journal/journal-row-writer.ts index a2905157b30c..40941b40b633 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-writer.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-writer.ts @@ -47,6 +47,7 @@ export type JournalRowWriterDeps = { readOnly: () => boolean highestFence: () => number nextSequence: () => number + prepare?: (db: Database.Database, rows: readonly JournalRow[], savedAt: number) => () => void commit: (rows: readonly JournalRow[], savedAt: number) => void /** Streamed-text-only revisions may skip per-commit fsync; settlement makes them durable. */ streamedTextRevision?: (row: JournalRow) => boolean @@ -65,14 +66,19 @@ export class JournalRowWriter { const row = build(this.deps.nextSequence(), savedAt) assertJournalFence(row.fence, this.deps.highestFence()) const receipt = typeof prepareReceipt === 'function' ? prepareReceipt([row]) : prepareReceipt + const streamed = !receipt && this.streamed([row]) this.deps.database().transaction( (db) => { - insertJournalRow(db, this.deps.sessionId, row, savedAt) + if (!this.deps.prepare) { + insertJournalRow(db, this.deps.sessionId, row, savedAt) + } + const adopt = this.deps.prepare?.(db, [row], savedAt) receipt?.write(db, row) + return adopt }, - !receipt && this.streamed([row]) + streamed, + (adopt) => adopt?.() ) - // Adopt durable sequence state before fallible work: nonthrowing receipt ledger, then fold. receipt?.committed() this.deps.commit([row], savedAt) return row @@ -105,14 +111,20 @@ export class JournalRowWriter { assertJournalFence(row.fence, this.deps.highestFence()) } const receipt = typeof prepareReceipt === 'function' ? prepareReceipt(rows) : prepareReceipt + const streamed = !receipt && this.streamed(rows) this.deps.database().transaction( (db) => { - for (const row of rows) { - insertJournalRow(db, this.deps.sessionId, row, ts) + if (!this.deps.prepare) { + for (const row of rows) { + insertJournalRow(db, this.deps.sessionId, row, ts) + } } + const adopt = this.deps.prepare?.(db, rows, ts) receipt?.write(db, receiptRow?.(rows)) + return adopt }, - !receipt && this.streamed(rows) + streamed, + (adopt) => adopt?.() ) receipt?.committed() this.deps.commit(rows, ts) diff --git a/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts new file mode 100644 index 000000000000..3d1a2f6404d9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts @@ -0,0 +1,246 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + agentJournalItemKey, + agentJournalSubmissionKey +} from '../../../shared/agent-session-journal-item-key' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { SQLITE_TABLE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-storage-dispositions' +import { + MAX_JOURNAL_APPLIED_SETTLEMENT_IDS, + renderJournalState, + type JournalReducerState +} from './journal-reducer' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { restoreJournal } from './journal-open' +import type { JournalRow } from './journal-row-schema' +import type { JournalHostDatabase } from './journal-host-database' + +const identity: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const epoch = 'epoch-1' +const text = ( + value: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) +const base = (seq: number) => ({ v: 4, epoch, seq, fence: 1, ts: 1_000 + seq }) +const itemId = (ordinal: number) => + agentJournalItemKey({ provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }) +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-saved-state-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function write(rows: readonly JournalRow[]): JournalReducerState { + const result = database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, epoch) + return publishJournalOutcomeEpoch(db, identity.sessionId, epoch, rows) + }) + return result.adopt() +} + +function requireState(state: JournalReducerState | null | undefined): JournalReducerState { + expect(state).toBeTruthy() + if (!state) { + throw new Error('missing journal state') + } + return state +} + +function expectSameState(actual: JournalReducerState, expected: JournalReducerState): void { + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + const actualFields: Record = { ...actual } + const expectedFields: Record = { ...expected } + for (const [field, right] of Object.entries(expectedFields)) { + const left = actualFields[field] + if ( + (left instanceof Map && right instanceof Map) || + (left instanceof Set && right instanceof Set) + ) { + expect([...left]).toStrictEqual([...right]) + } else if (field === 'queue') { + expect([...actual.queue.cards]).toStrictEqual([...expected.queue.cards]) + expect(actual.queue.revision).toBe(expected.queue.revision) + } else if (field === 'derivedTurnScope') { + expect(actual.derivedTurnScope.snapshot()).toBe(expected.derivedTurnScope.snapshot()) + } else { + expect(left).toStrictEqual(right) + } + } + expect(renderJournalState(actual)).toStrictEqual(renderJournalState(expected)) +} + +it('round trips the complete replayed reducer, including insertion order and valueless echoes', () => { + for (const table of [ + 'journal_rows', + 'journal_sessions', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations' + ]) { + expect( + database.db + .prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = ?") + .get(table) + ).toEqual({ name: table }) + expect(SQLITE_TABLE_DISPOSITIONS[`agent-session-journal.${table}`]).toMatchObject({ + disposition: 'not-applicable', + item: 52 + }) + } + const user = text('Please investigate', 'user') + const rows: JournalRow[] = [ + { ...base(1), kind: 'epoch', reason: 'legacy_import', providerHandle }, + { + ...base(2), + kind: 'queue', + messageId: 'draft', + change: { + op: 'queued', + body: user, + position: 1, + queuedAt: { epoch, sequence: 2 }, + options: { model: 'model-a' } + } + }, + { + ...base(3), + kind: 'submission', + clientMessageId: 'send-1', + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle, + handoverRecorded: true, + queuedMessageId: 'draft', + origin: 'client' + }, + { + ...base(4), + kind: 'dispatch', + clientMessageId: 'send-1', + state: 'pending', + providerItemId: null, + reason: null, + carries: ['stopped-2', 'stopped-1'] + }, + { ...base(5), kind: 'item', itemId: itemId(1), revision: 1, body: user }, + { + ...base(6), + kind: 'item', + itemId: itemId(2), + revision: 1, + body: text('echo'), + // A declaration without a known original, as the writers store it (JSON keeps no undefined). + echoOf: null + }, + { ...base(7), kind: 'item', itemId: itemId(3), revision: 1, body: text('removed') }, + { ...base(8), kind: 'tombstone', itemId: itemId(3), revision: 2 }, + { + ...base(9), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_009 } + }, + { + ...base(10), + kind: 'tombstone', + itemId: 'clear', + revision: 1, + queueClear: { operationId: 'clear-1', messageIds: ['draft'] } + }, + { ...base(11), kind: 'tombstone', itemId: 'reopen', revision: 1, queueReopen: true } + ] + for (let index = 0; index < MAX_JOURNAL_APPLIED_SETTLEMENT_IDS + 2; index++) { + rows.push({ + ...base(rows.length + 1), + kind: 'lifecycle-batch', + settlementId: `settlement-${index}`, + mutations: [ + { kind: 'item', itemId: itemId(4), revision: index + 1, body: text(`progress ${index}`) } + ] + }) + } + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(7), + revision: 1, + body: { kind: 'turn', turnId: 'removed-turn', state: 'running' } + }) + rows.push({ ...base(rows.length + 1), kind: 'tombstone', itemId: itemId(7), revision: 2 }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(5), + revision: 1, + body: { kind: 'turn', turnId: 'open-turn', state: 'running' } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(6), + revision: 1, + executionOwner: 2, + body: text('Working') + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(3), + revision: 3, + body: text('Recreated') + }) + for (const clientMessageId of ['send-3', 'send-2']) { + rows.push({ + ...base(rows.length + 1), + kind: 'submission', + clientMessageId, + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle + }) + } + const state = write(rows) + expect(state.items.has(agentJournalSubmissionKey('send-1'))).toBe(true) + expect(state.itemEchoes.has(itemId(2))).toBe(true) + expect(state.itemEchoes.get(itemId(2))).toBeNull() + expect([...state.appliedSettlementIds][0]).toBe('settlement-2') + expect(state.derivedTurnScope.snapshot()).toBe(itemId(5)) + const restored = requireState(restoreJournal(database.db, identity.sessionId)?.state) + expectSameState(restored, state) + expect(restored.derivedTurnScope.scopeFor(text('next'))).toEqual({ + kind: 'turn', + turnItemId: itemId(5) + }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts new file mode 100644 index 000000000000..8121483857d5 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts @@ -0,0 +1,286 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + agentJournalItemKey, + boundJournalKeyComponent, + MAX_JOURNAL_KEY_COMPONENT_CHARS +} from '../../../shared/agent-session-journal-item-key' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { AgentSessionJournalError } from './journal-store' +import { + openTestJournalHostDatabase, + liveTestJournalRows, + deleteTestJournalRow, + seedLegacyTestJournal, + pinTestJournalInputMode +} from './journal-host-database-test-support' + +export function registerJournalSequenceReplayTests( + fixture: ReturnType +): void { + describe('sequences', () => { + it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { + const journal = await fixture.open() + const results = await Promise.all( + Array.from({ length: 25 }, (_unused, index) => + journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ) + ) + const sequences = results.map((result) => result.cursor.sequence) + expect(new Set(sequences).size).toBe(25) + expect(sequences.slice().sort((a, b) => a - b)).toEqual( + Array.from({ length: 25 }, (_unused, index) => index + 2) + ) + }) + + it('serializes revisions of one item so the last write wins deterministically', async () => { + const journal = await fixture.open() + const results = await Promise.all([ + journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('c'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ]) + expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) + expect(journal.snapshot().items).toHaveLength(1) + expect(journal.snapshot().items[0]?.revision).toBe(3) + }) + + it('visits reduced items at their creation sequence without promoting an older revision', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const latest = await journal.appendItem(fixture.item(1), fixture.body('second'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('first revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const visited: { itemId: string; sequence: number }[] = [] + + journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) + + expect(visited).toEqual([ + { itemId: agentJournalItemKey(fixture.item(0)), sequence: 2 }, + { itemId: latest.itemId, sequence: latest.cursor.sequence } + ]) + }) + + it('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { + const journal = await fixture.open() + const turnItem = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `turn-lifecycle:${turnId}` + }) + const rendered = (): string | null => + activeStructuredAgentSessionTurnId(journal.snapshot().items) + const bothAgreeOn = async (turnId: string | null): Promise => { + expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) + expect(rendered()).toBe(turnId) + } + + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem(fixture.item(0), fixture.body('work'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await bothAgreeOn('turn-1') + + // Revisions retain creation position. + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'completed' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn(null) + + await journal.appendItem( + turnItem('turn-2'), + { kind: 'turn', turnId: 'turn-2', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn('turn-2') + }) + + it('preserves an oversized identity and its raw digest-form mimic across reopen', async () => { + const oversizedTurnId = 'a'.repeat(MAX_JOURNAL_KEY_COMPONENT_CHARS + 1) + const digestFormMimic = boundJournalKeyComponent(oversizedTurnId) + const identityFor = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId, + ordinal: 0 + }) + const oversizedIdentity = identityFor(oversizedTurnId) + const mimicIdentity = identityFor(digestFormMimic) + const journal = await fixture.open() + + const oversized = await journal.appendItem(oversizedIdentity, fixture.body('oversized'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const mimic = await journal.appendItem(mimicIdentity, fixture.body('mimic'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(oversized.itemId).not.toBe(mimic.itemId) + expect([oversized.revision, mimic.revision]).toEqual([1, 1]) + + const reopened = await fixture.open() + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('oversized'), + fixture.body('mimic') + ]) + + await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) + const afterTombstoneReopen = await fixture.open() + expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('mimic') + ]) + }) + }) + + describe('fences', () => { + it('rejects an append from a writer behind the journal', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await expect( + journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ).rejects.toBeInstanceOf(AgentSessionJournalError) + }) + + it('keeps accepting appends after a rejected one', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal + .appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + .catch(() => undefined) + await journal.appendItem(fixture.item(2), fixture.body('c'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('a'), + fixture.body('c') + ]) + }) + }) + + describe('replay', () => { + it('reopens to the same render model the live writer held', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('a2'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendTombstone(fixture.item(1), { fence: 1 }) + const live = journal.snapshot() + + const reopened = await fixture.open() + expect(reopened.snapshot()).toEqual(live) + }) + + it('serves a resume from a cursor and refuses one from a stale epoch', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const cursor = journal.cursor() + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const resumed = journal.readSince(cursor) + expect(resumed.ok && resumed.rows).toHaveLength(1) + + await journal.rollEpoch('handle_forked', 2) + expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) + }) + + it('rebuilds from a clean epoch after a rollover', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.rollEpoch('unreconcilable_prefix', 2) + expect(journal.snapshot().items).toHaveLength(0) + + const reopened = await fixture.open() + expect(reopened.epoch).toBe(journal.epoch) + expect(reopened.snapshot().items).toHaveLength(0) + }) + + it('refuses a journal with a gap and keeps every row', async () => { + seedLegacyTestJournal(openTestJournalHostDatabase(fixture.root), { + identity: fixture.IDENTITY, + now: fixture.tick + }) + const journal = await fixture.open() + pinTestJournalInputMode(journal) + for (let index = 0; index < 4; index += 1) { + await journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + deleteTestJournalRow(db, fixture.IDENTITY.sessionId, 3) + }) + + await expect(fixture.open()).rejects.toMatchObject({ + refusal: { details: { reason: 'journalCorrupt' } } + }) + await fixture.withJournalDatabase(fixture.root, (db) => { + const rows = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) + }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-codec.ts b/src/main/native-chat/agent-session-journal/journal-state-codec.ts new file mode 100644 index 000000000000..2263f74089cf --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-codec.ts @@ -0,0 +1,45 @@ +import type { JournalReducerState } from './journal-reducer' +import { durableQueuePauseMarks } from './journal-outcome-format-1-decode' + +/** The whole chat in a comparable form, insertion order included: a restore must equal live. */ +export function encodeJournalState(state: JournalReducerState): { + stateJson: string + items: { itemId: string; itemJson: string; ordinal: number }[] +} { + const stored = { + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + itemFences: [...state.itemFences], + itemExecutionOwners: [...state.itemExecutionOwners], + providerActivityAt: [...state.providerActivityAt], + tombstones: [...state.tombstones], + removedTurnIds: [...state.removedTurnIds], + submissions: [...state.submissions], + receipts: [...state.receipts], + aliases: [...state.aliases], + itemEchoes: [...state.itemEchoes].map(([key, value]) => + value === undefined ? [key] : [key, value] + ), + appliedSettlementIds: [...state.appliedSettlementIds], + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: durableQueuePauseMarks(state.queuePauseMarks), + stoppedHistoryCarried: [...state.stoppedHistoryCarried], + queuedHandOffPlaces: [...state.queuedHandOffPlaces], + normalizedHandOffs: [...state.normalizedHandOffs], + queue: { revision: state.queue.revision, cards: [...state.queue.cards] }, + historyOrigin: state.historyOrigin + } satisfies Record, unknown> + return { + stateJson: JSON.stringify(stored), + items: [...state.items].map(([itemId, item], ordinal) => ({ + itemId, + itemJson: JSON.stringify(item), + ordinal + })) + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-layout.ts b/src/main/native-chat/agent-session-journal/journal-state-layout.ts new file mode 100644 index 000000000000..2f589dfe4a14 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-layout.ts @@ -0,0 +1,82 @@ +import type { JournalReducerState } from './journal-reducer' + +// Every reducer field has a storage home; queue splits its revision from its keyed cards. +export const journalStateLayout = { + sessionId: 'scalar', + epoch: 'scalar', + lastSequence: 'scalar', + lastActivityAt: 'scalar', + oldestSequence: 'scalar', + highestFence: 'scalar', + items: 'items', + itemFences: 'map', + itemExecutionOwners: 'map', + providerActivityAt: 'map', + tombstones: 'map', + removedTurnIds: 'set', + submissions: 'map', + receipts: 'map', + aliases: 'map', + itemEchoes: 'map', + appliedSettlementIds: 'set', + derivedTurnScope: 'scalar', + latestAcceptedTurnSequence: 'scalar', + queuePauseMarks: 'scalar', + stoppedHistoryCarried: 'map', + queuedHandOffPlaces: 'map', + normalizedHandOffs: 'set', + queue: 'queue', + historyOrigin: 'scalar' +} as const satisfies Record + +type ScalarKey = { + [K in keyof typeof journalStateLayout]: (typeof journalStateLayout)[K] extends 'scalar' | 'queue' + ? K + : never +}[keyof typeof journalStateLayout] + +type Collection = { path: string; entries: Iterable<[unknown, unknown]> } + +export function journalStateScalars(state: JournalReducerState): string { + const stop = state.queuePauseMarks.latestStop + return JSON.stringify({ + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: { + ...state.queuePauseMarks, + latestStop: stop && { sequence: stop.sequence, event: stop.event } + }, + queue: { revision: state.queue.revision }, + historyOrigin: state.historyOrigin + } satisfies Record) +} + +export function journalStateCollections(state: JournalReducerState): Collection[] { + return Object.entries(state).flatMap(([path, value]) => { + if (value instanceof Map) { + return [{ path, entries: value }] + } + if (value instanceof Set) { + return [{ path, entries: value.entries() }] + } + if (path === 'queue') { + return [{ path: 'queue.cards', entries: state.queue.cards }] + } + return [] + }) +} + +/** Entry tuples preserve an undefined echo declaration without turning it into null. */ +export function journalEntryJson( + key: unknown, + value: unknown, + replacer?: (key: string, value: unknown) => unknown +): string { + return JSON.stringify(value === undefined ? [key] : [key, value], replacer) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-schema.ts b/src/main/native-chat/agent-session-journal/journal-state-schema.ts new file mode 100644 index 000000000000..426acf5973f4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-schema.ts @@ -0,0 +1,6 @@ +import type { z } from 'zod' +import type { JournalReducerState } from './journal-reducer' +import { outcomeFormat1Fields } from './journal-outcome-format-1' + +// Every reducer key needs an explicit stored representation in the format this build writes. +export const fields = outcomeFormat1Fields satisfies Record diff --git a/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts new file mode 100644 index 000000000000..b4b9512a66c6 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts @@ -0,0 +1,277 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase, + publishTestJournalEpoch, + SAVED_BY_NEWER_ORCA, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { admitOutcomeFormat1 } from './journal-outcome-format-1' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { storedFailureFact, storedProviderHandle } from './journal-storage-schema' +import type { UndeclaredStorageKeys } from './journal-storage-strict' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + journalEntryJson, + journalStateCollections, + journalStateScalars +} from './journal-state-layout' +import { readStoredQueuedMessageRow } from './queued-message-stored-row' + +// Admission keeps the in-memory chat within what this build declares on every path a saved value +// takes into it, so restating that chat on a new epoch never drops a newer build's key. + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +let root: string +let clock = 1_000 +const inputs = createTrackedJournalOpener({ legacyInputs: true }) +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-storage-admission-')) +}) +afterEach(async () => { + await inputs.closeAll() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function open(opener: typeof journals) { + return opener.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + }) +} + +function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +async function writeItems(opener: typeof journals, ordinals: number[]): Promise { + const journal = await open(opener) + for (const ordinal of ordinals) { + await journal.appendItem( + item(ordinal), + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `item ${ordinal}` }] }, + SCOPE + ) + } + await opener.closeAll() + return journal.epoch +} + +const db = () => openTestJournalHostDatabase(root).db + +/** Every saved byte of the chat database: a refusal writes none of it. */ +function savedBytes(): unknown { + const tables = db() + .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) + .all() + .map(({ name }) => String(name)) + return tables.map((table) => [table, db().prepare(`SELECT * FROM "${table}"`).all()]) +} + +/** Adds a key no build declares inside an item's first text block, as a newer build would. */ +function withLaterKey(json: string): string { + return json.replace('"type":"text",', '"type":"text","emphasis":"strong",') +} + +it("refuses a newer build's record with an undeclared nested key before adopting it, writes nothing, and starts no epoch", async () => { + await writeItems(journals, [0, 1, 2]) + const database = openTestJournalHostDatabase(root) + const source = db().prepare('SELECT generation, through_seq FROM journal_outcome_epochs').get() + const generation = Number(source?.generation) + const through = Number(source?.through_seq) + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: null, damage: null }) + + // The newer build revises item 2 with a key this build does not declare. + const itemId = 'codex:thread-1:turn-1:2' + const latest = db() + .prepare(`SELECT value_json FROM journal_outcomes WHERE field = 'items' AND entry_key = ? + ORDER BY seq DESC LIMIT 1`) + .get(JSON.stringify(itemId)) + const revised = withLaterKey(String(latest?.value_json)) + const next = through + 1 + const ordinal = (index: number) => + `s${String(next).padStart(16, '0')}:${String(index).padStart(16, '0')}` + database.transaction((write) => { + const insert = write.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, 1, ?, ?, 0)`) + insert.run(generation, next, 'items', JSON.stringify(itemId), ordinal(0), revised) + write.prepare('UPDATE journal_outcome_epochs SET through_seq = ?').run(next) + }) + const before = savedBytes() + + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: { sequence: 1 } }) + // No handle exists for a refused chat, so nothing can replace, roll over or rewind its epoch. + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) +}) + +it.each([ + ['alone', []], + ['with outcome records after it', [2]] +])( + 'refuses a chat whose frozen input row holds an undeclared key before folding it, %s', + async (_name, later) => { + await writeItems(inputs, [0, 1]) + if (later.length > 0) { + await writeItems(journals, later) + expect(db().prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n).not.toBe(0) + } + const row = liveTestJournalRows(db(), IDENTITY.sessionId).find((stored) => stored.seq === 2) + updateTestJournalRowJson(db(), IDENTITY.sessionId, 2, withLaterKey(row?.rowJson ?? '')) + const before = savedBytes() + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) + } +) + +it('leaves a legacy queued card whose saved body holds an undeclared key on disk, never adopted', () => { + const body = { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'later' }] } + const row = (saved: unknown) => ({ + message_id: 'card-1', + position: 1, + body_json: JSON.stringify(saved), + fingerprint: 'f', + state: 'waiting', + hold_reason: null, + returned_reason: null, + returned_rejection: null, + consumed_as: null, + queued_epoch: 'epoch-1', + queued_sequence: 2, + options_json: '{"model":"m","later":"x"}' + }) + // Options keep their legacy meaning: a choice this build does not use is ignored. + expect(readStoredQueuedMessageRow(row(body))).toMatchObject({ messageId: 'card-1', body }) + expect(readStoredQueuedMessageRow(row(body))?.options).toEqual({ model: 'm' }) + const later = { ...body, blocks: [{ type: 'text', text: 'later', emphasis: 'strong' }] } + expect(readStoredQueuedMessageRow(row(later))).toBeNull() +}) + +// Input rows as builds before outcome records wrote them, checked in with the chat they fold into; +// rows 20-27 are v1.4.245's own writes. Every keyed collection holds data, so a reducer change that +// reads them differently fails here: version the prefix fold, never edit this. +const prefix = z + .object({ + sessionId: z.string(), + epoch: z.string(), + rows: z.array(z.string()), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-input-prefix.json', import.meta.url), 'utf8') + ) + ) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +it('folds the checked-in input rows into the same chat, every value of which storage declares', () => { + const database = openTestJournalHostDatabase(root) + database.transaction((write) => { + publishTestJournalEpoch(write, prefix.sessionId, prefix.epoch) + for (const [index, json] of prefix.rows.entries()) { + insertTestJournalRowJson(write, prefix.sessionId, index + 1, json, 1_001 + index) + } + }) + const loaded = restoreJournal(db(), prefix.sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing prefix chat') + } + expect(plain(loaded.state)).toEqual(prefix.expected) + const collections = journalStateCollections(loaded.state) + expect(collections.filter(({ entries }) => [...entries].length === 0)).toEqual([]) + expect(collections.length).toBeGreaterThanOrEqual(15) + // What restating this chat on a new epoch would store, admitted as this build stores it. + const stored = [ + ...Object.entries(JSON.parse(journalStateScalars(loaded.state))).map(([key, value]) => ({ + field: '$', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...[...loaded.state.items].map(([key, value]) => ({ + field: 'items', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...journalStateCollections(loaded.state).flatMap(({ path, entries }) => + [...(path === 'items' ? [] : entries)].map(([key, value]) => ({ + field: path, + key: JSON.stringify(key), + json: journalEntryJson(key, value) + })) + ) + ] + expect(stored.length).toBeGreaterThan(20) + for (const value of stored) { + expect(admitOutcomeFormat1({ ...value, deleted: false })).toEqual({ + entryKey: JSON.parse(value.key), + kept: JSON.parse(value.json) + }) + } +}) + +function declared(): Undeclared | undefined { + return undefined +} + +it('compiles only when storage declares every key a persisted type holds, at any depth', () => { + type Stored = z.output + type Later = AgentSessionFailureFact & { retry?: { later?: number } } + expect(declared>()).toBeUndefined() + // @ts-expect-error `retry.later` is a key the stored failure fact does not declare + expect(declared>()).toBeUndefined() +}) + +it('reads an open string such as an agent type as a value, and still refuses a key beside it', () => { + type Stored = z.output + type Later = AgentSessionJournalProviderHandle & { host?: string } + expect( + declared>() + ).toBeUndefined() + // @ts-expect-error `host` is a key the stored provider handle does not declare + expect(declared>()).toBeUndefined() +}) diff --git a/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts new file mode 100644 index 000000000000..49c4ab4c9a5c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts @@ -0,0 +1,143 @@ +import { z } from 'zod' +import { + AgentJournalProducerLinkageFields, + AgentJournalTurnScopeSchema +} from '../../../shared/agent-session-journal-schemas' +import type { JournalRow } from './journal-row-schema' +import { + storedFailureFact, + storedItemBody, + storedMessageBody, + storedProviderHandle +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Every key an input row may hold. Only builds before outcome records wrote input rows, so a key +// this build does not declare is refused before main's reader normalizes it away; values keep +// main's checks (scalars here are unchecked), and execution options keep their legacy meaning of +// ignoring keys this build does not use. + +const value = z.unknown().optional() +const envelope = { + v: value, + epoch: value, + seq: value, + fence: value, + ts: value, + recovered: value, + turnScope: AgentJournalTurnScopeSchema.optional(), + ...AgentJournalProducerLinkageFields +} +const provenance = { ownerFence: value, executionOwner: value, echoOf: value } +const legacyOptions = z.record(z.string(), z.unknown()).optional() + +const itemMutation = { + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody, + turnScope: AgentJournalTurnScopeSchema.optional(), + observedAt: value, + ...provenance, + ...AgentJournalProducerLinkageFields +} +const tombstoneMutation = { kind: z.literal('tombstone'), itemId: value, revision: value } + +const queueChange = z.discriminatedUnion('op', [ + z.object({ + op: z.literal('queued'), + body: storedMessageBody, + position: value, + queuedAt: z.object({ epoch: value, sequence: value }).nullable(), + holdReason: value, + options: legacyOptions, + attempt: value, + returned: z.object({ reason: value, rejection: storedFailureFact.optional() }).optional() + }), + z.object({ op: z.literal('edited'), body: storedMessageBody }), + z.object({ op: z.literal('moved'), position: value }), + z.object({ op: z.literal('held'), holdReason: value }), + z.object({ op: z.literal('withdrawn') }) +]) + +const storedRow = z.discriminatedUnion('kind', [ + z.object({ + ...envelope, + kind: z.literal('epoch'), + reason: value, + providerHandle: storedProviderHandle, + historyOrigin: value + }), + z.object({ + ...envelope, + ...provenance, + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody + }), + z.object({ + ...envelope, + kind: z.literal('tombstone'), + itemId: value, + revision: value, + stopEvent: z.object({ reason: value, turnId: value, at: value, caller: value }).optional(), + queueResume: value, + queueReopen: value, + queueReopenSince: value, + queueClear: z + .object({ operationId: value, messageIds: z.array(value), lifted: value }) + .optional(), + retireSubmission: value + }), + z.object({ + ...envelope, + kind: z.literal('submission'), + clientMessageId: value, + payloadFingerprint: value, + providerHandle: storedProviderHandle, + body: storedMessageBody, + handoverRecorded: value, + queuedMessageId: value, + origin: value, + source: z.object({ kind: value }).optional(), + options: legacyOptions + }), + z.object({ + ...envelope, + kind: z.literal('dispatch'), + clientMessageId: value, + state: value, + providerItemId: value, + reason: value, + carries: z.array(value).optional(), + rejection: storedFailureFact.optional(), + keptAsQueuedMessageId: value, + answeredInTurn: z.object({ turnItemId: value, via: value }).nullable().optional() + }), + z.object({ + ...envelope, + kind: z.literal('lifecycle-batch'), + settlementId: value, + mutations: z.array( + z.discriminatedUnion('kind', [z.object(itemMutation), z.object(tombstoneMutation)]) + ) + }), + z.object({ ...envelope, kind: z.literal('queue'), messageId: value, change: queueChange }) +]) +const strictRow = strictStorage(storedRow) + +/** True when an input row holds a key or union tag this build does not declare; main's reader + * judges every value. */ +export function journalRowDeclaresMore(row: unknown): boolean { + return storageVerdict(strictRow, row) === 'newer' +} + +export type JournalRowsAreDeclared = StorageDeclaresAll< + UndeclaredStorageKeys> +> diff --git a/src/main/native-chat/agent-session-journal/journal-storage-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts new file mode 100644 index 000000000000..55e40bed92a9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import { + AgentJournalKnownSchemas, + AgentJournalRenderItemSchema +} from '../../../shared/agent-session-journal-schemas' +import { AgentJournalSubmissionSchema } from '../../../shared/agent-session-journal-submission-schema' +import { AgentSessionFailureFactSchema } from '../../../shared/agent-session-failure-fact-schema' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../shared/agent-session-journal-types' +import type { StorageDeclaresAll, UndeclaredStorageKeys } from './journal-storage-strict' + +// What saved outcomes declare beyond the wire's open schemas, which read only the keys their +// readers use: the shared definitions are reused and completed here. A persisted type gaining a key +// fails the checks at the end of this file until the key is declared; an added optional key needs +// no new format. Keys newly declared here are optional and loosely typed, since only their +// presence decides whether this build understands a value. + +const [ + textBlock, + toolCallBlock, + toolResultBlock, + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +] = AgentJournalKnownSchemas.blocks +const [ + messageBody, + agentStartBody, + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody, + turnBody +] = AgentJournalKnownSchemas.bodies + +const text = z.string().optional() +const count = z.number().optional() +const argumentProblem = z.object({ agent: z.string(), option: z.string(), problem: z.string() }) + +const refusalDetails = z.object({ + reason: text, + ownerVerdict: text, + rewindReason: text, + account: text, + argumentProblem: argumentProblem.optional(), + agent: text, + agentInstallation: z + .object({ agent: z.string(), installedVersion: z.string(), minimumVersion: z.string() }) + .optional(), + codexInstallation: z + .object({ installedVersion: z.string().nullable(), minimumVersion: z.string() }) + .optional(), + currentFence: count, + currentRevision: count, + resolution: AgentJournalKnownSchemas.resolution.optional(), + owner: z.object({ sessionId: z.string(), workspaceId: z.string() }).optional() +}) + +export const storedFailureFact = AgentSessionFailureFactSchema.extend({ + account: text, + refusal: z.object({ code: z.string().min(1), details: refusalDetails.optional() }).optional(), + attachment: z.object({ reason: z.string(), limit: count }).optional(), + retry: z + .object({ error: text, status: count, cause: text, attempt: count, maxRetries: count }) + .optional(), + usageLimit: z.object({ window: text, resetsAt: count }).optional(), + neverReachedAgent: z.literal(true).optional(), + backgroundStop: text, + requestTimeout: z.object({ method: z.string(), timeoutMs: z.number() }).optional() +}) + +// A sender's reader salvages any value of a known key, so only the keys are storage's to close. +const salvaged = z.unknown().optional() +const sender = z.object({ + party: z + .object({ address: salvaged, terminalHandle: salvaged, orcaSessionId: salvaged }) + .nullable() + .optional(), + name: salvaged, + relation: salvaged +}) +const orchestration = z.discriminatedUnion('message', [ + z.object({ + message: z.literal('mail-notice'), + mailbox: salvaged, + dispatchId: salvaged, + messages: z + .array(z.object({ messageId: salvaged, runId: salvaged, from: salvaged })) + .nullable() + .optional() + }), + z.object({ message: z.literal('task'), runId: salvaged, taskId: salvaged, dispatchId: salvaged }) +]) +const messageSource = z.object({ + kind: salvaged, + senders: z.array(sender.nullable()).nullable().optional(), + orchestration: orchestration.nullable().optional() +}) + +const block = z.discriminatedUnion('type', [ + textBlock.extend({ + contextClear: z + .object({ operationId: z.string(), afterFence: z.number(), clearedAt: z.number() }) + .optional(), + failure: storedFailureFact.optional(), + orcaStop: z.object({ cause: z.string(), turnItemId: text }).optional(), + usageLimitTurnItemId: text + }), + toolCallBlock.extend({ state: text, endedAs: text }), + toolResultBlock.extend({ + callId: text, + editPatch: z + .object({ + filePath: text, + hunks: z.array( + z.object({ + oldStart: z.number(), + oldLines: z.number(), + newStart: z.number(), + newLines: z.number(), + lines: z.array(z.string()) + }) + ) + }) + .optional(), + fullOutputItemId: text + }), + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +]) + +export const storedMessageBody = messageBody.extend({ + blocks: z.array(block), + from: messageSource.nullable().optional() +}) + +export const storedItemBody = z.discriminatedUnion('kind', [ + storedMessageBody, + agentStartBody.extend({ worker: sender.nullable().optional() }), + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody.extend({ + failure: storedFailureFact.optional(), + turnLifecycle: turnBody.omit({ kind: true }).optional() + }), + turnBody +]) + +export const storedProviderHandle = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('codex'), threadId: z.string() }), + z.object({ kind: z.literal('claude'), sessionId: z.string(), leafUuid: z.string().nullable() }), + z.object({ kind: z.literal('opaque'), agent: z.string(), value: z.string() }) +]) + +export const storedItem = AgentJournalRenderItemSchema.extend({ body: storedItemBody }) + +export const storedSubmission = AgentJournalSubmissionSchema.extend({ + rejection: storedFailureFact.optional(), + acceptedSequence: count, + origin: z.enum(['client', 'host']).optional() +}) + +export type StoredValuesAreDeclared = [ + StorageDeclaresAll>>, + StorageDeclaresAll< + UndeclaredStorageKeys> + >, + StorageDeclaresAll< + UndeclaredStorageKeys> + > +] diff --git a/src/main/native-chat/agent-session-journal/journal-storage-strict.ts b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts new file mode 100644 index 000000000000..d01a2d594d9c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts @@ -0,0 +1,131 @@ +import { z } from 'zod' +import { + isJournalOpenUnionFallback, + isJournalTag +} from '../../../shared/agent-session-journal-open-union' +import type { AgentJournalUnknownKind } from '../../../shared/agent-session-journal-types' + +// The wire reads a peer's or an older build's value openly. A saved value is different: a build +// that kept a key it does not declare would restate the value without it, so storage refuses the +// chat instead. Only key and union-tag sets are closed; string vocabularies keep the wire's +// fallbacks, and `z.unknown()` stays an opaque value carried whole. + +/** The strict form of a declared schema: objects refuse undeclared keys, open unions refuse + * unknown tags. Checks are kept; a schema kind storage cannot close fails at load. */ +export function strictStorage(schema: z.core.$ZodType): z.ZodType { + if (schema instanceof z.ZodObject) { + const shape = Object.fromEntries( + Object.entries(schema.shape).map(([key, value]) => [key, strictStorage(value)]) + ) + return schema.clone({ ...schema.def, shape, catchall: z.never() }) + } + if (schema instanceof z.ZodUnion) { + const options = schema.options.filter((option) => !isJournalOpenUnionFallback(option)) + const [known] = options + // An open union is its known arms and a fallback that kept the tags storage refuses. + return known && options.length === 1 && schema.options.length === 2 + ? strictStorage(known) + : schema.clone({ ...schema.def, options: options.map(strictStorage) }) + } + if (schema instanceof z.ZodOptional) { + return strictStorage(schema.unwrap()).optional() + } + if (schema instanceof z.ZodNullable) { + return strictStorage(schema.unwrap()).nullable() + } + if (schema instanceof z.ZodArray) { + return schema.clone({ ...schema.def, element: strictStorage(schema.element) }) + } + if (schema instanceof z.ZodTuple) { + const { items, rest } = schema.def + return schema.clone({ + ...schema.def, + items: items.map(strictStorage), + rest: rest && strictStorage(rest) + }) + } + if (schema instanceof z.ZodRecord) { + return schema.clone({ ...schema.def, valueType: strictStorage(schema.def.valueType) }) + } + if ( + schema instanceof z.ZodString || + schema instanceof z.ZodNumber || + schema instanceof z.ZodBoolean || + schema instanceof z.ZodLiteral || + schema instanceof z.ZodEnum || + schema instanceof z.ZodNull || + schema instanceof z.ZodUnknown + ) { + return schema + } + throw new Error(`saved journal storage cannot close a ${schema._zod.def.type} schema`) +} + +/** `newer` when the value holds a key or union tag this build does not declare; `damage` when it + * fails a type this build declares, a blank tag included. */ +export function storageVerdict(schema: z.ZodType, value: unknown): 'stored' | 'newer' | 'damage' { + const parsed = schema.safeParse(value) + if (parsed.success) { + return 'stored' + } + return parsed.error.issues.some((issue) => undeclared(issue, value)) ? 'newer' : 'damage' +} + +// A union's issues locate values relative to the union's own input. +function undeclared(issue: z.core.$ZodIssue, input: unknown): boolean { + if (issue.code === 'unrecognized_keys') { + return true + } + if (issue.code !== 'invalid_union') { + return false + } + const at = issue.path.reduce(child, input) + if (issue.discriminator !== undefined && issue.errors.length === 0) { + return isJournalTag(at) + } + return issue.errors.some((errors) => errors.some((inner) => undeclared(inner, at))) +} + +function child(value: unknown, key: PropertyKey): unknown { + return typeof value === 'object' && value !== null + ? Object.entries(value).find(([name]) => name === String(key))?.[1] + : undefined +} + +type Get = K extends keyof O ? O[K] : never +type At = A extends unknown ? Get : never +type TagKeys = Exclude< + { [K in keyof S]: S[K] extends string ? (string extends S[K] ? never : K) : never }[keyof S], + undefined +> +// The storage arm a value of type T is stored under: the one whose required literal tags it has. +type Arm = S extends object + ? { [K in TagKeys & keyof T]: Get } extends { [K in TagKeys & keyof T]: Get } + ? S + : never + : never +type Keys = A extends unknown ? keyof A : never +type ArmKeys = [A] extends [never] + ? 'a value no storage arm declares' + : + | Exclude> + | { [K in keyof T & Keys]: UndeclaredStorageKeys> }[keyof T & Keys] + +/** Keys of a persisted type, at any depth and in any union member, that its storage schema's + * output `S` leaves undeclared; `never` when it declares them all. An unknown-kind value never + * reaches storage: admission refuses it. A primitive holds no keys; it is settled before `object` + * because an open or branded string (`AgentType`'s `string & {}`) is assignable to `object`. */ +export type UndeclaredStorageKeys = T extends { readonly kind: AgentJournalUnknownKind } + ? never + : T extends string | number | boolean | bigint | symbol | null | undefined + ? never + : T extends readonly (infer E)[] + ? [Extract] extends [never] + ? 'an array storage does not declare' + : UndeclaredStorageKeys[number]> + : T extends object + ? ArmKeys> + : never + +/** Compiles only when every persisted key is declared. */ +export type StorageDeclaresAll = Undeclared diff --git a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts index f43deaf96058..bbce643d73ac 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts @@ -37,6 +37,7 @@ export type JournalStoreHost = { readOnly: () => boolean cursor: () => AgentJournalCursor adopt: (loaded: JournalLoad) => void + prepare: NonNullable[0]['prepare']> commit: (rows: readonly JournalRow[], savedAt: number) => void journal: () => AgentSessionJournal enqueue: JournalRowWriter['enqueue'] @@ -99,6 +100,7 @@ export function createJournalStoreCollaborators(host: JournalStoreHost): Journal readOnly: host.readOnly, highestFence: () => host.state().highestFence, nextSequence: () => host.state().lastSequence + 1, + prepare: host.prepare, commit: host.commit, streamedTextRevision: (row) => isJournalStreamedTextRevision(host.state(), row) }) diff --git a/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts new file mode 100644 index 000000000000..1eaa5c37879f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts @@ -0,0 +1,99 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { openAgentSessionJournal } from './journal-store-factory' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type Database from '../../sqlite/sync-database' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + let root: string + + let clock = 1_000 + + function tick(): number { + clock += 1 + return clock + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function body(value: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } + } + + const journals = createTrackedJournalOpener() + + async function open(overrides: Partial[0]> = {}) { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => `epoch-${clock}`, + ...overrides + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function withJournalDatabase( + stateDirectory: string, + run: (db: Database.Database) => void + ): Promise { + const opened = openTestJournalHostDatabase(stateDirectory) + try { + run(opened.db) + } finally { + await opened.close() + } + } + + return { + IDENTITY, + body, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + item, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + tick, + withJournalDatabase + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts index dcc49ac670bb..1c76b6217c50 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts @@ -16,7 +16,7 @@ import type { AgentSessionMessageSource } from '../../../shared/agent-session/ag import type { AgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' import type { JournalHostDatabase } from './journal-host-database' import type { JournalLifecycleMutationInput } from './journal-row-builders' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' import type { JournalReducerState } from './journal-reducer' import type { JournalRowWriter } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -30,7 +30,7 @@ export type AgentSessionJournalOptions = { } export type JournalReadSince = - | { ok: true; rows: JournalRow[]; cursor: AgentJournalCursor } + | { ok: true; rows: JournalReadRow[]; cursor: AgentJournalCursor } | { ok: false; reset: AgentJournalResetReason } export type ResolveDispatchInput = { diff --git a/src/main/native-chat/agent-session-journal/journal-store-restore.ts b/src/main/native-chat/agent-session-journal/journal-store-restore.ts index d4b5e917a781..3fc0a1a1b835 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-restore.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-restore.ts @@ -1,6 +1,6 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { JournalEpochController } from './journal-epoch-controller' -import { replayJournal } from './journal-open' +import { restoreJournal } from './journal-open' import { journalOpenRefusalError } from './journal-open-failure' import type { JournalStoreHost } from './journal-store-collaborators' import { openJournalStoreState } from './journal-store-open' @@ -19,10 +19,13 @@ export async function restoreJournalStore( ) ) } + // Unpaced and charged to no maintenance budget: background work alone pays its duty cycle. + const loaded = restoreJournal(database.db, host.identity.sessionId) return openJournalStoreState({ sessionId: host.identity.sessionId, - replay: () => replayJournal(database.db, host.identity.sessionId), - start: () => collaborators.epochController.start('session_created', 0), + replay: () => loaded, + start: () => + collaborators.epochController.start('session_created', 0, loaded?.state.epoch ?? null), adopt: host.adopt, // Recovery revisions must not count as new provider output. appendItem: (identity, body, fence) => diff --git a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts index 08a5ee6eebf3..4d6328536217 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts @@ -35,7 +35,7 @@ export function registerJournalStoreSchemaTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function tick(): number { clock += 1 diff --git a/src/main/native-chat/agent-session-journal/journal-store.spec.ts b/src/main/native-chat/agent-session-journal/journal-store.spec.ts index a274117bcf51..314795f2b934 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.spec.ts @@ -1,511 +1,9 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, readdir, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - agentJournalItemKey, - boundJournalKeyComponent, - MAX_JOURNAL_KEY_COMPONENT_CHARS -} from '../../../shared/agent-session-journal-item-key' -import { - boundInlineText, - boundPayload, - JOURNAL_RUNNING_PREVIEW_LIMITS -} from './journal-payload-bounds' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { AgentSessionJournalError, type AgentSessionJournal } from './journal-store' -import type { openAgentSessionJournal } from './journal-store-factory' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - liveTestJournalRows, - deleteTestJournalRow -} from './journal-host-database-test-support' -import type Database from '../../sqlite/sync-database' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createFixture } from './journal-store-contract-test-fixture' +import { registerJournalSequenceReplayTests } from './journal-sequence-replay.spec' +import { registerJournalLifecycleBoundaryTests } from './journal-lifecycle-boundaries.spec' export function registerJournalStoreTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - let root: string - let clock = 1_000 - - function tick(): number { - clock += 1 - return clock - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function body(value: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } - } - - const journals = createTrackedJournalOpener() - - async function open(overrides: Partial[0]> = {}) { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => `epoch-${clock}`, - ...overrides - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('sequences', () => { - it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { - const journal = await open() - const results = await Promise.all( - Array.from({ length: 25 }, (_unused, index) => - journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - ) - ) - const sequences = results.map((result) => result.cursor.sequence) - expect(new Set(sequences).size).toBe(25) - expect(sequences.slice().sort((a, b) => a - b)).toEqual( - Array.from({ length: 25 }, (_unused, index) => index + 2) - ) - }) - - it('serializes revisions of one item so the last write wins deterministically', async () => { - const journal = await open() - const results = await Promise.all([ - journal.appendItem(item(0), body('a'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('b'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('c'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ]) - expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) - expect(journal.snapshot().items).toHaveLength(1) - expect(journal.snapshot().items[0]?.revision).toBe(3) - }) - - it('visits reduced items at their creation sequence without promoting an older revision', async () => { - const journal = await open() - await journal.appendItem(item(0), body('first'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const latest = await journal.appendItem(item(1), body('second'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('first revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const visited: { itemId: string; sequence: number }[] = [] - - journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) - - expect(visited).toEqual([ - { itemId: agentJournalItemKey(item(0)), sequence: 2 }, - { itemId: latest.itemId, sequence: latest.cursor.sequence } - ]) - }) - - it('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { - const journal = await open() - const turnItem = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `turn-lifecycle:${turnId}` - }) - const rendered = (): string | null => - activeStructuredAgentSessionTurnId(journal.snapshot().items) - const bothAgreeOn = async (turnId: string | null): Promise => { - expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) - expect(rendered()).toBe(turnId) - } - - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem(item(0), body('work'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await bothAgreeOn('turn-1') - - // Revisions retain creation position. - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'completed' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn(null) - - await journal.appendItem( - turnItem('turn-2'), - { kind: 'turn', turnId: 'turn-2', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn('turn-2') - }) - - it('preserves an oversized identity and its raw digest-form mimic across reopen', async () => { - const oversizedTurnId = 'a'.repeat(MAX_JOURNAL_KEY_COMPONENT_CHARS + 1) - const digestFormMimic = boundJournalKeyComponent(oversizedTurnId) - const identityFor = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'codex', - threadId: 'thread-1', - turnId, - ordinal: 0 - }) - const oversizedIdentity = identityFor(oversizedTurnId) - const mimicIdentity = identityFor(digestFormMimic) - const journal = await open() - - const oversized = await journal.appendItem(oversizedIdentity, body('oversized'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const mimic = await journal.appendItem(mimicIdentity, body('mimic'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(oversized.itemId).not.toBe(mimic.itemId) - expect([oversized.revision, mimic.revision]).toEqual([1, 1]) - - const reopened = await open() - expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ - body('oversized'), - body('mimic') - ]) - - await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) - const afterTombstoneReopen = await open() - expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ - body('mimic') - ]) - }) - }) - - describe('fences', () => { - it('rejects an append from a writer behind the journal', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await expect( - journal.appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).rejects.toBeInstanceOf(AgentSessionJournalError) - }) - - it('keeps accepting appends after a rejected one', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal - .appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - .catch(() => undefined) - await journal.appendItem(item(2), body('c'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([body('a'), body('c')]) - }) - }) - - describe('replay', () => { - it('reopens to the same render model the live writer held', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('a2'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendTombstone(item(1), { fence: 1 }) - const live = journal.snapshot() - - const reopened = await open() - expect(reopened.snapshot()).toEqual(live) - }) - - it('serves a resume from a cursor and refuses one from a stale epoch', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const resumed = journal.readSince(cursor) - expect(resumed.ok && resumed.rows).toHaveLength(1) - - await journal.rollEpoch('handle_forked', 2) - expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) - }) - - it('rebuilds from a clean epoch after a rollover', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.rollEpoch('unreconcilable_prefix', 2) - expect(journal.snapshot().items).toHaveLength(0) - - const reopened = await open() - expect(reopened.epoch).toBe(journal.epoch) - expect(reopened.snapshot().items).toHaveLength(0) - }) - - it('refuses a journal with a gap and keeps every row', async () => { - const journal = await open() - for (let index = 0; index < 4; index += 1) { - await journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - await journal.close() - await withJournalDatabase(root, (db) => { - deleteTestJournalRow(db, IDENTITY.sessionId, 3) - }) - - await expect(open()).rejects.toMatchObject({ - refusal: { details: { reason: 'journalCorrupt' } } - }) - await withJournalDatabase(root, (db) => { - const rows = liveTestJournalRows(db, IDENTITY.sessionId) - expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) - }) - }) - }) - - describe('bounds', () => { - it('marks a clipped payload instead of dropping bytes silently', () => { - const limits = { inlineHeadBytes: 16 } - const bounded = boundPayload('x'.repeat(4_096), limits) - expect(bounded.truncated).toBe(true) - expect(bounded.head).toHaveLength(16) - expect(bounded.byteLength).toBe(4_096) - expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') - }) - - it('never splits a multi-byte character across the bound', () => { - const limits = { inlineHeadBytes: 4 } - // Three-byte characters expose UTF-8 splits. - const bounded = boundPayload('日本語テスト', limits) - expect(bounded.head).toBe('日') - expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) - }) - - it('leaves a payload inside the bound untouched', () => { - const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) - expect(bounded.truncated).toBe(false) - expect(bounded.head).toBe('small') - expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') - }) - }) - - describe('lifecycle batches', () => { - it('deduplicates concurrent submissions before appending a second row', async () => { - const journal = await open() - const input = { - settlementId: 'concurrent-settlement', - fence: 1, - mutations: [ - { - kind: 'item' as const, - identity: item(1), - body: body('settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - } - - const [first, replay] = await Promise.all([ - journal.appendLifecycleBatch(input), - journal.appendLifecycleBatch(input) - ]) - - expect([replay, first.sequence]).toEqual([first, 2]) - }) - - it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { - const journal = await open() - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const settled = await journal.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('tool settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: { provider: 'orca', clientMessageId: 'exit-status' }, - body: { kind: 'status', text: 'Provider exited' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - const atSettlement = journal - .snapshot() - .items.filter((entry) => entry.sequence === settled.sequence) - expect(atSettlement).toHaveLength(2) - expect( - journal - .snapshot() - .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') - ).toBe(false) - await journal.close() - - const reopened = await open() - const beforeReplay = reopened.cursor() - const replay = await reopened.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(9), - body: body('must not appear'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(replay).toEqual(beforeReplay) - expect( - reopened - .snapshot() - .items.some( - (entry) => - entry.body.kind === 'message' && - entry.body.blocks.some( - (block) => block.type === 'text' && block.text === 'must not appear' - ) - ) - ).toBe(false) - }) - }) - - describe('on-disk layout', () => { - it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { - const journal: AgentSessionJournal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(await readdir(root)).toContain('agent-session-journal.db') - expect(await readdir(root)).not.toContain('agent-session-journal') - await journal.close() - await withJournalDatabase(root, (db) => { - expect(liveTestJournalRows(db, IDENTITY.sessionId)[1]?.rowJson).toContain('"kind":"item"') - expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ - epoch: journal.epoch - }) - }) - }) - }) - - async function withJournalDatabase( - stateDirectory: string, - run: (db: Database.Database) => void - ): Promise { - const opened = openTestJournalHostDatabase(stateDirectory) - try { - run(opened.db) - } finally { - await opened.close() - } - } - - describe('what a handle found on disk when it opened', () => { - const submission = (clientMessageId: string) => ({ - clientMessageId, - payloadFingerprint: 'fp', - body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, - fence: 1, - handoverRecorded: true as const - }) - - it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { - const earlier = await open() - await earlier.appendItem(item(1), body('one'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await earlier.appendSubmission(submission('earlier')) - await earlier.close() - - const journal = await open() - const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') - expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) - - await journal.resolveDispatch({ - clientMessageId: 'earlier', - state: 'unknown', - reason: 'unconfirmed from an earlier host', - fence: 1 - }) - // Epochs restart sequences, so later rows can fall below the old open cursor. - await journal.replaceEpochItems('handle_forked', 1, []) - await journal.appendSubmission(submission('later')) - const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') - expect(later?.acceptedSequence).toBeLessThanOrEqual(2) - expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) - }) - }) + const fixture = createFixture() + registerJournalSequenceReplayTests(fixture) + registerJournalLifecycleBoundaryTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-store.ts b/src/main/native-chat/agent-session-journal/journal-store.ts index 100b7957486c..b46f2987f3cc 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -1,5 +1,6 @@ // Each session owns its fold and queue; all statements use the host's shared database connection. +import { JournalWriteProjection } from './journal-write-projection' import type { AgentJournalDispatchRejection } from '../../../shared/agent-session-failure-words' import { randomUUID } from 'node:crypto' import { createJournalPublicReader } from './journal-public-read' @@ -22,7 +23,7 @@ import { newestStructuredAgentSessionTurnBySequence, runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/structured-agent-session-live-turn' -import { readJournalSince } from './journal-cursor' +import { journalWroteBeforeOpen, readJournalSince } from './journal-cursor' import type { JournalHostDatabase } from './journal-host-database' import { journalRowsAfterReader } from './journal-open' import { @@ -31,7 +32,6 @@ import { rejectJournalQueuedSubmissions } from './journal-pending-submission-recovery' import { - applyJournalRow, createJournalReducerState, resolveJournalItemId, type JournalReducerState @@ -65,8 +65,6 @@ export class AgentSessionJournal { private readonly goalAttachments: JournalCollaborators['goalAttachments'] private readonly identity: AgentSessionJournalIdentity private readonly database: JournalHostDatabase - private readonly now: () => number - private readonly mintEpoch: () => string private state: JournalReducerState private readonly readPublic = createJournalPublicReader() @@ -81,6 +79,7 @@ export class AgentSessionJournal { private readonly submissionWriter: JournalCollaborators['submissionWriter'] private readonly stepWriter: JournalCollaborators['stepWriter'] private readonly restore: () => Promise + private readonly projection: JournalWriteProjection /** Queued cards never count as owed work. */ readonly queuedMessages: JournalCollaborators['queuedMessages'] readonly stopMarks: JournalCollaborators['stopMarks'] @@ -90,14 +89,19 @@ export class AgentSessionJournal { constructor(options: AgentSessionJournalOptions) { this.identity = options.identity this.database = options.database - this.now = options.now ?? (() => Date.now()) - this.mintEpoch = options.mintEpoch ?? randomUUID this.state = createJournalReducerState(options.identity.sessionId, '') this.queue = new JournalWriteQueue(options.identity.sessionId) + this.projection = new JournalWriteProjection({ + database: this.database, + state: () => this.state, + adopt: (state) => { + this.state = state + } + }) const collaborators = createJournalStoreCollaborators({ identity: this.identity, - now: this.now, - mintEpoch: this.mintEpoch, + now: options.now ?? (() => Date.now()), + mintEpoch: options.mintEpoch ?? randomUUID, serialize: (run) => this.queue.serialize(run), database: () => this.database, state: () => this.state, @@ -107,11 +111,10 @@ export class AgentSessionJournal { this.state = loaded.state this.onCommitted?.() }, - commit: (rows, savedAt) => { - for (const row of rows) { - applyJournalRow(this.state, row, savedAt) - } + prepare: (db, rows, savedAt) => this.projection.prepare(db, rows, savedAt), + commit: (rows) => { this.onCommitted?.(rows) + this.projection.verify() }, notifyCommitted: () => this.onCommitted?.([]), journal: () => this, @@ -141,11 +144,7 @@ export class AgentSessionJournal { /** Only rows from this handle's opening epoch can predate the open. */ wroteBeforeOpen(sequence: number | undefined): boolean { - return ( - sequence !== undefined && - this.state.epoch === this.openedThrough.epoch && - sequence <= this.openedThrough.sequence - ) + return journalWroteBeforeOpen(this.state, this.openedThrough, sequence) } /** Fallback reopen boundary until its mark is written; each new handle marks again. */ diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts new file mode 100644 index 000000000000..60aa6928d8b5 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts @@ -0,0 +1,78 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { journalPragmaNumber } from './journal-database' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) +}) + +afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) + +export function openJournal(sessionId = 'stream') { + return journals.open({ + stateDirectory: root, + identity: { + sessionId, + workspaceId: 'folder', + hostId: 'local', + agent: 'grok', + providerHandle: null + } + }) +} + +export function commitLevels() { + const { db } = openTestJournalHostDatabase(root) + const levels: number[] = [] + const exec = db.exec.bind(db) + vi.spyOn(db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + levels.push(journalPragmaNumber(db, 'synchronous')) + } + exec(sql) + }) + return levels +} + +export async function uploadedInput() { + const id = randomUUID() + const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'retained input') + return { id, body: text('user', formatNativeChatFileReference(path)) } +} + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts new file mode 100644 index 000000000000..368cd08aa7e2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts @@ -0,0 +1,238 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import type { JournalOperationReceipt } from './journal-row-writer' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' + +it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { + const journal = await openJournal() + const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } + let release = () => {} + const barrier = new Promise((resolve) => { + release = resolve + }) + const held = journal.readInOrder(() => barrier) + const levels = commitLevels() + const preceding = journal.appendItem(identity, text('assistant', 'first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const resolve = vi.fn(() => { + expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) + return { identity, body: text('assistant', 'second') } + }) + const following = journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + release() + await Promise.all([held, preceding, following]) + expect(resolve).toHaveBeenCalledTimes(1) + expect(levels).toEqual([2, 1]) + levels.length = 0 + const empty = vi.fn(() => null) + expect( + await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + ).toBeNull() + expect(empty).toHaveBeenCalledTimes(1) + expect(levels).toEqual([]) + + const { db } = openTestJournalHostDatabase(fixture.root) + db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') + const write = vi.fn((connection, row) => { + if (!row) { + throw new Error('missing receipt target') + } + connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) + }) + const committed = vi.fn(() => + expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) + ) + const result = await journal.appendItem( + identity, + text('assistant', 'durable receipt'), + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, + { write, committed } + ) + expect(levels).toEqual([2]) + expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( + result.cursor.sequence + ) + expect(write).toHaveBeenCalledTimes(1) + expect(committed).toHaveBeenCalledTimes(1) + const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) + for (const mode of ['ordinary', 'planned', 'step'] as const) { + const body = text('assistant', `${huge}${mode}`) + const plan = vi.fn(() => [ + { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ]) + levels.length = 0 + if (mode === 'ordinary') { + await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) + } + if (mode === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: mode, + fence: 1, + plan: () => ({ mutations: plan(), dispatches: [] }) + }) + } + if (mode === 'step') { + await journal.appendSteps([ + { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } + ]) + } + expect(plan).toHaveBeenCalledTimes(1) + expect(levels).toEqual([1]) + expect(journal.snapshot().items[0]?.body).toEqual(body) + } + levels.length = 0 + expect( + await journal.appendSteps([ + { + kind: 'item', + resolve: () => null, + options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } + ]) + ).toEqual([false]) + await journal.appendPlannedLifecycleBatch({ + settlementId: 'empty', + fence: 1, + plan: () => ({ mutations: [], dispatches: [] }) + }) + expect(levels).toEqual([]) + await journal.appendLifecycleBatch({ + settlementId: 'envelope', + fence: 1, + mutations: [ + { + kind: 'item', + identity, + body: text('assistant', 'settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(levels).toEqual([2]) +}) + +it.each([1, 10])( + 'protects %i actual independent inputs per writer without visiting prior history', + async (count) => { + const journal = await openJournal() + const other = await openJournal('other') + for (let n = 0; n < 10 * count; n++) { + const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } + await journal.appendItem(identity, text('user', 'old'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await other.appendItem(identity, text('user', 'unrelated'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const { db } = openTestJournalHostDatabase(fixture.root) + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + const levels = commitLevels() + for (const writer of [ + 'direct', + 'resolved', + 'step', + 'batch', + 'planned', + 'submission', + 'queue' + ] as const) { + insertion.mockClear() + extraction.mockClear() + acquired.mockClear() + levels.length = 0 + for (let n = 0; n < count; n++) { + const { id, body } = await uploadedInput() + const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } + const resolve = vi.fn(() => ({ identity, body })) + if (writer === 'direct') { + await journal.appendItem(identity, body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + if (writer === 'resolved') { + await journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'step') { + await journal.appendSteps([ + { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } + ]) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'batch') { + await journal.appendLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] + }) + } + if (writer === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + plan: () => ({ + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], + dispatches: [] + }) + }) + } + if (writer === 'submission') { + await journal.appendSubmission({ + clientMessageId: identity.clientMessageId, + payloadFingerprint: 'fp', + body, + fence: 1, + origin: 'host' + }) + } + if (writer === 'queue') { + await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) + } + expect( + db + .prepare( + 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' + ) + .all(id, 'stream') + ).toHaveLength(1) + } + expect(insertion).toHaveBeenCalledTimes(count) + expect(extraction).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(levels).toEqual(Array(count).fill(2)) + process.stdout.write( + `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts index 9c6911fcc9df..826a480b6f3e 100644 --- a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts @@ -1,50 +1,26 @@ -import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { codexImageItemBody } from '../../codex/codex-image-item-translation' import { journalPragmaNumber } from './journal-database' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from './journal-host-database-test-support' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' import { openAgentSessionJournal } from './journal-store-factory' - import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' import { testEventSinkLogging } from '../agent-session-wire/structured-agent-session-logger-test-support' import { createProviderTimelineAssembler } from '../agent-session-timeline/provider-timeline-assembler' import { providerTimelineSink } from '../agent-session-timeline/provider-timeline-plan' -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import type { JournalOperationReceipt } from './journal-row-writer' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) -}) -afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ - kind: 'message', - role, - blocks: [{ type: 'text', text: value }] -}) +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' it('keeps image and goal transitions FULL, streams text at NORMAL, and restores FULL', async () => { - const database = openTestJournalHostDatabase(root) + const database = openTestJournalHostDatabase(fixture.root) const levels: number[] = [] database.transaction((db) => levels.push(journalPragmaNumber(db, 'synchronous')), true) levels.push(journalPragmaNumber(database.db, 'synchronous')) @@ -121,7 +97,7 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores turnScope: AGENT_JOURNAL_THREAD_SCOPE }) database.db.exec( - "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_rows BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" + "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" ) await expect( journal.appendSteps([ @@ -146,40 +122,6 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores await journal.close() }) -function openJournal(sessionId = 'stream') { - return journals.open({ - stateDirectory: root, - identity: { - sessionId, - workspaceId: 'folder', - hostId: 'local', - agent: 'grok', - providerHandle: null - } - }) -} - -function commitLevels() { - const { db } = openTestJournalHostDatabase(root) - const levels: number[] = [] - const exec = db.exec.bind(db) - vi.spyOn(db, 'exec').mockImplementation((sql) => { - if (sql === 'COMMIT') { - levels.push(journalPragmaNumber(db, 'synchronous')) - } - exec(sql) - }) - return levels -} - -async function uploadedInput() { - const id = randomUUID() - const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'retained input') - return { id, body: text('user', formatNativeChatFileReference(path)) } -} - it.each([1, 10])( 'commits %i real assembler windows at NORMAL with no attachment effects', async (count) => { @@ -234,7 +176,9 @@ it.each([1, 10])( expect(journal.snapshot().items[0]?.body).toEqual( text('assistant', 'hello '.repeat(count + 1)) ) - expect(journalPragmaNumber(openTestJournalHostDatabase(root).db, 'synchronous')).toBe(2) + expect(journalPragmaNumber(openTestJournalHostDatabase(fixture.root).db, 'synchronous')).toBe( + 2 + ) process.stdout.write( `pr34654-stream-contract ${JSON.stringify({ count, levels, extractions: extraction.mock.calls.length, acquired: acquired.mock.calls.length })}\n` ) @@ -259,226 +203,3 @@ it.each([1, 10])( } } ) - -it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { - const journal = await openJournal() - const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } - let release = () => {} - const barrier = new Promise((resolve) => { - release = resolve - }) - const held = journal.readInOrder(() => barrier) - const levels = commitLevels() - const preceding = journal.appendItem(identity, text('assistant', 'first'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const resolve = vi.fn(() => { - expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) - return { identity, body: text('assistant', 'second') } - }) - const following = journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - release() - await Promise.all([held, preceding, following]) - expect(resolve).toHaveBeenCalledTimes(1) - expect(levels).toEqual([2, 1]) - levels.length = 0 - const empty = vi.fn(() => null) - expect( - await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).toBeNull() - expect(empty).toHaveBeenCalledTimes(1) - expect(levels).toEqual([]) - - const { db } = openTestJournalHostDatabase(root) - db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') - const write = vi.fn((connection, row) => { - if (!row) { - throw new Error('missing receipt target') - } - connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) - }) - const committed = vi.fn(() => - expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) - ) - const result = await journal.appendItem( - identity, - text('assistant', 'durable receipt'), - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, - { write, committed } - ) - expect(levels).toEqual([2]) - expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( - result.cursor.sequence - ) - expect(write).toHaveBeenCalledTimes(1) - expect(committed).toHaveBeenCalledTimes(1) - const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) - for (const mode of ['ordinary', 'planned', 'step'] as const) { - const body = text('assistant', `${huge}${mode}`) - const plan = vi.fn(() => [ - { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ]) - levels.length = 0 - if (mode === 'ordinary') { - await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) - } - if (mode === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: mode, - fence: 1, - plan: () => ({ mutations: plan(), dispatches: [] }) - }) - } - if (mode === 'step') { - await journal.appendSteps([ - { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } - ]) - } - expect(plan).toHaveBeenCalledTimes(1) - expect(levels).toEqual([1]) - expect(journal.snapshot().items[0]?.body).toEqual(body) - } - levels.length = 0 - expect( - await journal.appendSteps([ - { - kind: 'item', - resolve: () => null, - options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - } - ]) - ).toEqual([false]) - await journal.appendPlannedLifecycleBatch({ - settlementId: 'empty', - fence: 1, - plan: () => ({ mutations: [], dispatches: [] }) - }) - expect(levels).toEqual([]) - await journal.appendLifecycleBatch({ - settlementId: 'envelope', - fence: 1, - mutations: [ - { - kind: 'item', - identity, - body: text('assistant', 'settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(levels).toEqual([2]) -}) - -it.each([1, 10])( - 'protects %i actual independent inputs per writer without visiting prior history', - async (count) => { - const journal = await openJournal() - const other = await openJournal('other') - for (let n = 0; n < 10 * count; n++) { - const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } - await journal.appendItem(identity, text('user', 'old'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await other.appendItem(identity, text('user', 'unrelated'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - const { db } = openTestJournalHostDatabase(root) - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - const levels = commitLevels() - for (const writer of [ - 'direct', - 'resolved', - 'step', - 'batch', - 'planned', - 'submission', - 'queue' - ] as const) { - insertion.mockClear() - extraction.mockClear() - acquired.mockClear() - levels.length = 0 - for (let n = 0; n < count; n++) { - const { id, body } = await uploadedInput() - const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } - const resolve = vi.fn(() => ({ identity, body })) - if (writer === 'direct') { - await journal.appendItem(identity, body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - if (writer === 'resolved') { - await journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'step') { - await journal.appendSteps([ - { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } - ]) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'batch') { - await journal.appendLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] - }) - } - if (writer === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - plan: () => ({ - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], - dispatches: [] - }) - }) - } - if (writer === 'submission') { - await journal.appendSubmission({ - clientMessageId: identity.clientMessageId, - payloadFingerprint: 'fp', - body, - fence: 1, - origin: 'host' - }) - } - if (writer === 'queue') { - await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) - } - expect( - db - .prepare( - 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' - ) - .all(id, 'stream') - ).toHaveLength(1) - } - expect(insertion).toHaveBeenCalledTimes(count) - expect(extraction).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(levels).toEqual(Array(count).fill(2)) - process.stdout.write( - `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - } -) diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts index ceb85ed1f50f..e4ee0d11e88e 100644 --- a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts @@ -1,402 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { - createTrackedJournalOpener, - insertTestJournalRowJson, - liveTestJournalRows, - openTestJournalHostDatabase -} from './journal-host-database-test-support' -import { parseJournalRow, type JournalRow } from './journal-row-schema' -import * as rowTable from './journal-row-table' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-terminal-validation-test-fixture' +import { registerJournalTerminalTimeValidationTests } from './journal-terminal-time-validation.spec' +import { registerJournalApprovalRevisionValidationTests } from './journal-approval-revision-validation.spec' export function registerJournalTerminalSettlementValidationTests(): void { - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } - - async function open() { - return journals.open({ - identity: { - sessionId: 'validation', - workspaceId: 'folder', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function settle(observedAt = 1_000, lastProvenAliveAt?: number) { - return settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'validation', - fence: 8, - acquisitionGeneration: 'replacement', - deathEvidence: { - kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', - detail: '', - ownerFence: 7, - observedAt, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - } - }) - } - - async function expectSendStillWritable() { - const sequence = journal.cursor().sequence + 1 - await expect( - journal.appendSubmission({ - clientMessageId: 'new-send', - payloadFingerprint: 'new', - fence: 8, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence }) - } - - async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { - const { db } = openTestJournalHostDatabase(root) - for (const [index, input] of inputs.entries()) { - const json = JSON.stringify({ - v: 3, - kind: 'item', - epoch: journal.epoch, - seq: index + 2, - ts: 900, - fence: 7, - revision: 1, - ...input, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(parseJournalRow(json).ok).toBe(true) - insertTestJournalRowJson(db, 'validation', index + 2, json, 900) - } - await journal.close() - journal = await open() - } - - it.each([ - ['zero exit time', 0, undefined], - ['zero renewal time', 1_000, 0] - ] as const)( - 'ends an untimed turn with %s and still permits a fresh send', - async (_name, observedAt, lastProvenAliveAt) => { - await journal.appendItem( - identity, - { kind: 'turn', turnId: 'old', state: 'running' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - await settle(observedAt, lastProvenAliveAt) - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted' - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await expectSendStillWritable() - } - ) - - it.each([{ kind: 'tool-call' }, { providerTurnId: '' }])( - 'ends a readable legacy extension %j using a valid turn rewrite', - async (extension) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - body: { - kind: 'status', - text: 'working', - turnLifecycle: { turnId: 'old', state: 'running', ...extension } - } - } - ]) - await settle() - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted', - completedAt: 1_000 - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( - 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', - async (revision) => { - await expectUnadvanceableItemUntouched({ - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - }) - await expectSendStillWritable() - } - ) - - async function expectUnadvanceableItemUntouched(saved: { - itemId: string - revision: number - body: unknown - }) { - await saveOldItems([ - saved, - { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, - { itemId: 'orca:approval', body: pendingApproval() } - ]) - const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const commits = vi.fn() - journal.observeCommits(commits) - await expect(settle()).resolves.toBeGreaterThan(0) - expect(commits).toHaveBeenCalledTimes(1) - expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) - expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) - expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - const settled = journal.snapshot() - await settle() - expect(journal.snapshot()).toEqual(settled) - expect(commits).toHaveBeenCalledTimes(1) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - } - - it('revises the original legacy long prompt key and still permits a fresh send', async () => { - const oldKey = `orca:${'x'.repeat(1025)}` - await saveOldItems([{ itemId: oldKey, body: pendingApproval() }]) - await settle() - expect(journal.snapshot().items).toHaveLength(1) - expect(journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'approval')).toHaveLength(1) - await expectSendStillWritable() - }) - - function pendingApproval() { - return { - kind: 'approval', - title: 'Allow?', - detail: null, - options: [], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - } - } - - function expectRewriteTimes(value: unknown) { - if (typeof value !== 'object' || value === null) { - return - } - for (const [key, field] of Object.entries(value)) { - if (key.endsWith('At') && field !== null && field !== undefined) { - expect(typeof field).toBe('number') - expect(Number.isFinite(field)).toBe(true) - expect(field).toBeGreaterThan(0) - } - expectRewriteTimes(field) - } - } - - it.each([ - ['untimed exit', 0, undefined], - ['untimed renewal', 1_000, 0], - ['timed exit', 1_000, undefined] - ] as const)( - 'builds admitted settlement rows preserving extensions without invalid known times for %s', - async (_name, observedAt, lastProvenAliveAt) => { - const long = 'x'.repeat(1025) - const running = { turnId: 'old', state: 'running' } - const laterContextUsage = { - window: { tokens: 100, capturedAt: 1, laterWindowField: true }, - used: { kind: 'unknown', capturedAt: 1, laterUsedField: true }, - laterUsageField: { kept: true } - } - const extensionBodies = [ - { ...running, kind: 'tool-call' }, - { ...running, providerTurnId: '' }, - { ...running, providerTurnId: 42 }, - { ...running, providerTurnId: null }, - { ...running, contextUsage: { window: { tokens: -1 } } }, - { ...running, contextUsage: 'extension' }, - { - ...running, - providerTurnId: 'provider', - contextUsage: laterContextUsage - }, - { ...running, laterField: { kind: 'tool-call' } } - ] - const inputs = [ - ...extensionBodies.map((turnLifecycle, index) => ({ - itemId: `orca:extension-${index}`, - body: { kind: 'status', text: 'working', turnLifecycle } - })), - { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, - { - itemId: 'orca:timed', - body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } - }, - { - itemId: 'orca:last-advanceable', - revision: Number.MAX_SAFE_INTEGER - 1, - body: { kind: 'turn', ...running } - }, - { itemId: `orca:${long}`, body: pendingApproval() }, - { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, - { - itemId: `codex:thread:${long}:0`, - body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } - }, - { - itemId: `legacy:codex:session:${long}`, - body: { kind: 'tool-call', name: 'shell', state: 'running' } - }, - { itemId: 'future-provider:opaque%ZZ', body: pendingApproval() }, - { itemId: 'orca:%78', body: pendingApproval() }, - { itemId: '', body: pendingApproval() }, - { - itemId: `orca:${long}oversized`, - body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } - } - ] - await saveOldItems(inputs) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const rows: JournalRow[] = [] - const insert = rowTable.insertJournalRow - vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { - expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) - const bodies = - row.kind === 'item' - ? [row.body] - : row.kind === 'lifecycle-batch' - ? row.mutations.flatMap((mutation) => - mutation.kind === 'item' ? [mutation.body] : [] - ) - : [] - for (const body of bodies) { - expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) - expectRewriteTimes(body) - } - rows.push(row) - return insert(database, sessionId, row) - }) - await settle(observedAt, lastProvenAliveAt) - expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) - expect( - rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) - ).toBe(true) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - for (const input of inputs) { - const body = journal.itemBody(input.itemId) - expect(body).toBeDefined() - expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') - if (body?.kind === 'approval') { - expect(body.resolution.state).toBe('cancelled') - } - if (body?.kind === 'message') { - expect(body.state).toBe('completed') - } - if (body?.kind === 'tool-call') { - expect(body.state).toBe('failed') - } - } - expect(journal.itemBody('orca:extension-7')).toHaveProperty('laterField', { - kind: 'tool-call' - }) - expect(journal.itemBody('orca:extension-6')).toHaveProperty('contextUsage', laterContextUsage) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - expect(journal.snapshot().items).toHaveLength(inputs.length + 1) - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await journal.close() - journal = await open() - for (const input of inputs) { - expect(journal.itemBody(input.itemId)).toEqual( - ended.items.find((item) => item.itemId === input.itemId)?.body - ) - } - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( - 'advances readable saved revision %s using the existing integer admission', - async (revision) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - } - ]) - await settle() - expect(journal.snapshot().items[0]).toMatchObject({ - revision: Math.max(revision, 0) + 1, - body: { state: 'interrupted' } - }) - await expectSendStillWritable() - } - ) - - it('admits an answer on an exhausted approval without changing the saved item', async () => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision: Number.MAX_SAFE_INTEGER + 1, - body: pendingApproval() - } - ]) - const before = journal.snapshot().items[0] - const cursor = journal.cursor() - await expect( - journal.appendItem( - identity, - { - ...pendingApproval(), - kind: 'approval', - resolution: { - state: 'resolved', - selectedOptionId: null, - resolvedBy: 'user', - resolvedAt: 1_000 - } - }, - { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - ).resolves.toBeDefined() - expect(journal.cursor().sequence).toBe(cursor.sequence + 1) - expect(journal.snapshot().items[0]).toEqual(before) - await expectSendStillWritable() - }) + const fixture = createFixture() + registerJournalTerminalTimeValidationTests(fixture) + registerJournalApprovalRevisionValidationTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts new file mode 100644 index 000000000000..bb9930a0d2ef --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts @@ -0,0 +1,219 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow, type JournalRow } from './journal-row-schema' +import * as rowTable from './journal-row-table' + +export function registerJournalTerminalTimeValidationTests( + fixture: ReturnType +): void { + it.each([ + ['zero exit time', 0, undefined], + ['zero renewal time', 1_000, 0] + ] as const)( + 'ends an untimed turn with %s and still permits a fresh send', + async (_name, observedAt, lastProvenAliveAt) => { + await fixture.journal.appendItem( + fixture.identity, + { kind: 'turn', turnId: 'old', state: 'running' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted' + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.expectSendStillWritable() + } + ) + + it.each([{ providerTurnId: '' }])( + 'ends a readable legacy extension %j using a valid turn rewrite', + async (extension) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + body: { + kind: 'status', + text: 'working', + turnLifecycle: { turnId: 'old', state: 'running', ...extension } + } + } + ]) + await fixture.settle() + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted', + completedAt: 1_000 + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( + 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', + async (revision) => { + await fixture.expectUnadvanceableItemUntouched({ + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + }) + await fixture.expectSendStillWritable() + } + ) + + it('revises the original legacy long prompt key and still permits a fresh send', async () => { + const oldKey = `orca:${'x'.repeat(1025)}` + await fixture.saveOldItems([{ itemId: oldKey, body: fixture.pendingApproval() }]) + await fixture.settle() + expect(fixture.journal.snapshot().items).toHaveLength(1) + expect(fixture.journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) + expect( + fixture.journal.snapshot().items.filter((item) => item.body.kind === 'approval') + ).toHaveLength(1) + await fixture.expectSendStillWritable() + }) + + it.each([ + ['untimed exit', 0, undefined], + ['untimed renewal', 1_000, 0], + ['timed exit', 1_000, undefined] + ] as const)( + 'builds admitted settlement rows preserving extensions without invalid known times for %s', + async (_name, observedAt, lastProvenAliveAt) => { + const long = 'x'.repeat(1025) + const running = { turnId: 'old', state: 'running' } + const extensionBodies = [ + { ...running, providerTurnId: '' }, + { ...running, providerTurnId: 42 }, + { ...running, providerTurnId: null }, + { ...running, contextUsage: { window: { tokens: -1 } } }, + { ...running, contextUsage: 'extension' } + ] + const inputs = [ + ...extensionBodies.map((turnLifecycle, index) => ({ + itemId: `orca:extension-${index}`, + body: { kind: 'status', text: 'working', turnLifecycle } + })), + { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, + { + itemId: 'orca:timed', + body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } + }, + { + itemId: 'orca:last-advanceable', + revision: Number.MAX_SAFE_INTEGER - 1, + body: { kind: 'turn', ...running } + }, + { itemId: `orca:${long}`, body: fixture.pendingApproval() }, + { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, + { + itemId: `codex:thread:${long}:0`, + body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } + }, + { + itemId: `legacy:codex:session:${long}`, + body: { kind: 'tool-call', name: 'shell', state: 'running' } + }, + { itemId: 'future-provider:opaque%ZZ', body: fixture.pendingApproval() }, + { itemId: 'orca:%78', body: fixture.pendingApproval() }, + { itemId: '', body: fixture.pendingApproval() }, + { + itemId: `orca:${long}oversized`, + body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } + } + ] + await fixture.saveOldItems(inputs) + const { db } = openTestJournalHostDatabase(fixture.root) + const history = liveTestJournalRows(db, 'validation') + const rows: JournalRow[] = [] + const insert = rowTable.insertJournalRow + vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { + expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) + const bodies = + row.kind === 'item' + ? [row.body] + : row.kind === 'lifecycle-batch' + ? row.mutations.flatMap((mutation) => + mutation.kind === 'item' ? [mutation.body] : [] + ) + : [] + for (const body of bodies) { + expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) + fixture.expectRewriteTimes(body) + } + rows.push(row) + return insert(database, sessionId, row) + }) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) + expect( + rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) + ).toBe(true) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + for (const input of inputs) { + const body = fixture.journal.itemBody(input.itemId) + expect(body).toBeDefined() + expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') + if (body?.kind === 'approval') { + expect(body.resolution.state).toBe('cancelled') + } + if (body?.kind === 'message') { + expect(body.state).toBe('completed') + } + if (body?.kind === 'tool-call') { + expect(body.state).toBe('failed') + } + } + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + expect(fixture.journal.snapshot().items).toHaveLength(inputs.length + 1) + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.journal.close() + fixture.journal = await fixture.open() + for (const input of inputs) { + expect(fixture.journal.itemBody(input.itemId)).toEqual( + ended.items.find((item) => item.itemId === input.itemId)?.body + ) + } + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( + 'advances readable saved revision %s using the existing integer admission', + async (revision) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + } + ]) + await fixture.settle() + expect(fixture.journal.snapshot().items[0]).toMatchObject({ + revision: Math.max(revision, 0) + 1, + body: { state: 'interrupted' } + }) + await fixture.expectSendStillWritable() + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts new file mode 100644 index 000000000000..6ce38691e5f6 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts @@ -0,0 +1,177 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } + + async function open() { + return journals.open({ + identity: { + sessionId: 'validation', + workspaceId: 'folder', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function settle(observedAt = 1_000, lastProvenAliveAt?: number) { + return settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'validation', + fence: 8, + acquisitionGeneration: 'replacement', + deathEvidence: { + kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', + detail: '', + ownerFence: 7, + observedAt, + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) + } + }) + } + + async function expectSendStillWritable() { + const sequence = journal.cursor().sequence + 1 + await expect( + journal.appendSubmission({ + clientMessageId: 'new-send', + payloadFingerprint: 'new', + fence: 8, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence }) + } + + async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { + const { db } = openTestJournalHostDatabase(root) + for (const [index, input] of inputs.entries()) { + const json = JSON.stringify({ + v: 3, + kind: 'item', + epoch: journal.epoch, + seq: index + 2, + ts: 900, + fence: 7, + revision: 1, + ...input, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(parseJournalRow(json).ok).toBe(true) + insertTestJournalRowJson(db, 'validation', index + 2, json, 900) + } + await journal.close() + journal = await open() + } + + async function expectUnadvanceableItemUntouched(saved: { + itemId: string + revision: number + body: unknown + }) { + await saveOldItems([ + saved, + { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, + { itemId: 'orca:approval', body: pendingApproval() } + ]) + const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) + const { db } = openTestJournalHostDatabase(root) + const history = liveTestJournalRows(db, 'validation') + const commits = vi.fn() + journal.observeCommits(commits) + await expect(settle()).resolves.toBeGreaterThan(0) + expect(commits).toHaveBeenCalledTimes(1) + expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) + expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) + expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + const settled = journal.snapshot() + await settle() + expect(journal.snapshot()).toEqual(settled) + expect(commits).toHaveBeenCalledTimes(1) + await journal.close() + journal = await open() + expect(journal.snapshot()).toEqual(settled) + } + + function pendingApproval() { + return { + kind: 'approval', + title: 'Allow?', + detail: null, + options: [], + resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } + } + } + + function expectRewriteTimes(value: unknown) { + if (typeof value !== 'object' || value === null) { + return + } + for (const [key, field] of Object.entries(value)) { + if (key.endsWith('At') && field !== null && field !== undefined) { + expect(typeof field).toBe('number') + expect(Number.isFinite(field)).toBe(true) + expect(field).toBeGreaterThan(0) + } + expectRewriteTimes(field) + } + } + + return { + expectRewriteTimes, + expectSendStillWritable, + expectUnadvanceableItemUntouched, + identity, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + pendingApproval, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + saveOldItems, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-transition-collections.ts b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts new file mode 100644 index 000000000000..1fcdfd69c557 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts @@ -0,0 +1,269 @@ +// Overlay collections leave the live containers untouched until their transaction commits. + +export type JournalEntryChange = { + path: string + key: unknown + deleted: boolean + reinsert: boolean + value: unknown +} + +export type JournalDraftAccess = { + wrap: (value: T, changed: () => void, path: string) => T + assign: (value: unknown) => void + finish: (value: T) => T + defer: (apply: () => void) => void +} + +export class JournalDraftMap extends Map { + private readonly writes = new Map() + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Map, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + + override has(key: K): boolean { + return this.inserted.has(key) || (!this.removed.has(key) && this.source.has(key)) + } + + override get(key: K): V | undefined { + return this.has(key) ? this.draft(key) : undefined + } + + override set(key: K, value: V): this { + if (!this.has(key)) { + this.inserted.add(key) + this.recreated.add(key) + // A (re)created key moves to the end of both orders, as the live map's re-insert does. + this.touched.delete(key) + this.pending.delete(key) + } + this.access.assign(value) + this.writes.set(key, value) + this.touch(key) + return this + } + + override delete(key: K): boolean { + if (!this.has(key)) { + return false + } + if (this.source.has(key)) { + this.removed.add(key) + } + this.inserted.delete(key) + this.recreated.delete(key) + this.writes.delete(key) + this.touch(key) + return true + } + + override clear(): void { + for (const key of this.keys()) { + this.delete(key) + } + } + + override *keys(): MapIterator { + for (const key of this.source.keys()) { + if (!this.removed.has(key)) { + yield key + } + } + yield* this.inserted + } + + override *values(): MapIterator { + for (const key of this.keys()) { + yield this.draft(key) + } + } + + override *entries(): MapIterator<[K, V]> { + for (const key of this.keys()) { + yield [key, this.draft(key)] + } + } + + override [Symbol.iterator](): MapIterator<[K, V]> { + return this.entries() + } + + override forEach(callback: (value: V, key: K, map: Map) => void, thisArg?: unknown): void { + for (const [key, value] of this) { + callback.call(thisArg, value, key, this) + } + } + + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: this.get(key) + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + + finish(): Map { + const changes = [...this.touched].map((key) => ({ + key, + reinsert: this.inserted.has(key), + kept: this.has(key) ? { value: this.access.finish(this.draft(key)) } : null + })) + this.access.defer(() => { + for (const { key, reinsert, kept } of changes) { + if (!kept || reinsert) { + this.source.delete(key) + } + if (kept) { + this.source.set(key, kept.value) + } + } + }) + return this.source + } + + /** Only for present keys; a present entry may hold undefined. */ + private draft(key: K): V { + const stored = this.writes.has(key) ? this.writes.get(key) : this.source.get(key) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: callers pass only keys has() reports present, so the stored value is a V even when V includes undefined. + return this.access.wrap(stored as V, () => this.touch(key), `${this.path}.*`) + } + + private touch(key: K): void { + this.touched.add(key) + this.pending.add(key) + this.changed() + } +} + +export class JournalDraftSet extends Set { + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Set, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + override has(value: T): boolean { + return this.inserted.has(value) || (!this.removed.has(value) && this.source.has(value)) + } + override add(value: T): this { + if (!this.has(value)) { + this.inserted.add(value) + this.recreated.add(value) + this.pending.delete(value) + this.pending.add(value) + this.touched.delete(value) + this.touched.add(value) + this.changed() + } + return this + } + override delete(value: T): boolean { + if (!this.has(value)) { + return false + } + if (this.source.has(value)) { + this.removed.add(value) + } + this.inserted.delete(value) + this.recreated.delete(value) + this.pending.add(value) + this.touched.add(value) + this.changed() + return true + } + override clear(): void { + for (const value of this) { + this.delete(value) + } + } + override *values(): SetIterator { + for (const value of this.source) { + if (!this.removed.has(value)) { + yield value + } + } + yield* this.inserted + } + override keys(): SetIterator { + return this.values() + } + override *entries(): SetIterator<[T, T]> { + for (const value of this.values()) { + yield [value, value] + } + } + override [Symbol.iterator](): SetIterator { + return this.values() + } + override forEach(callback: (value: T, key: T, set: Set) => void, thisArg?: unknown): void { + for (const value of this) { + callback.call(thisArg, value, value, this) + } + } + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: key + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + finish(): Set { + const changes = [...this.touched].map((value) => ({ + value, + deleted: !this.has(value), + reinsert: this.inserted.has(value) + })) + this.access.defer(() => { + for (const { value, deleted, reinsert } of changes) { + if (deleted || reinsert) { + this.source.delete(value) + } + if (!deleted) { + this.source.add(value) + } + } + }) + return this.source + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts index a4e0a9dc771c..c9c2119b2307 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts @@ -32,7 +32,7 @@ export function registerJournalUnknownContentTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-content-')) @@ -116,36 +116,26 @@ export function registerJournalUnknownContentTests(): void { expect(stored()).toEqual(written) } - /** Verify writable downgrade compatibility without rewriting stored rows. */ - async function expectWritableAndKept( - written: { seq: number; rowJson: string }[], - itemId: string - ) { - const journal = await open() - expect(journal.snapshot().items.some((entry) => entry.itemId === itemId)).toBe(true) - await journal.appendItem(item(5), { kind: 'status', text: 'taken' }, SCOPE) - await journals.closeAll() - expect(stored().slice(0, written.length)).toEqual(written) - } - - describe("a newer build's body kind, kept and writable", () => { + // An input row's union tags are closed like its keys: a newer kind refuses the chat before main's + // reader could keep it undrawn and this build restate the chat without it. + describe("a newer build's body kind", () => { it.each([ ['an item body of a newer kind', NEWER_BODY], ['a plan subject of a newer kind', { ...PLAN_APPROVAL, subject: { kind: 'diff' } }] - ])('keeps %s and stays writable', async (_name, body) => { + ])('fails the load on %s and keeps the row', async (_name, body) => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', body) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:2') + await expectNewerAndKept(written) }) - it('keeps a lifecycle mutation whose body is a newer kind, and stays writable', async () => { + it('fails the load on a lifecycle mutation whose body is a newer kind', async () => { const { written } = await journalWith((epoch) => [ batchRow(epoch, [ { kind: 'item', itemId: 'codex:thread-1:turn-1:4', revision: 1, body: NEWER_BODY } ]) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:4') + await expectNewerAndKept(written) }) }) @@ -230,7 +220,7 @@ export function registerJournalUnknownContentTests(): void { }) describe("a turn's context usage of a newer shape", () => { - it('is dropped like an unusable annotation: the chat stays writable and keeps the row', async () => { + it('fails the load and keeps the row', async () => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', { kind: 'turn', @@ -239,14 +229,7 @@ export function registerJournalUnknownContentTests(): void { contextUsage: { used: { kind: 'measured', capturedAt: 1 } } }) ]) - const journal = await open() - expect(journal.snapshot().items[2]?.body).toEqual({ - kind: 'turn', - turnId: 'turn-1', - state: 'completed' - }) - await journals.closeAll() - expect(stored()).toEqual(written) + await expectNewerAndKept(written) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts index d55230b105fc..fee7bcd7a47d 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts @@ -13,6 +13,7 @@ import { import { closeTestJournalHostDatabase, createTrackedJournalOpener, + deleteTestJournalRow, insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, @@ -39,7 +40,7 @@ export function registerJournalUnknownRowKindTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-kind-')) @@ -58,14 +59,14 @@ export function registerJournalUnknownRowKindTests(): void { return journal.snapshot().items.map((entry) => entry.itemId) } + function rowEnvelope(epoch: string, seq: number) { + return { v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, epoch, seq, fence: 1, ts: 5_000 + seq } + } + function newerRow(epoch: string, seq: number, extra: Record = {}) { return { - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + ...rowEnvelope(epoch, seq), kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: 5_000 + seq, payload: { said: 'by a newer build', seq }, ...extra } @@ -82,10 +83,7 @@ export function registerJournalUnknownRowKindTests(): void { await journals.closeAll() const { db } = openTestJournalHostDatabase(root) edit((seq, json) => { - db.prepare('DELETE FROM journal_rows WHERE session_id = ? AND seq = ?').run( - IDENTITY.sessionId, - seq - ) + deleteTestJournalRow(db, IDENTITY.sessionId, seq) insertTestJournalRowJson(db, IDENTITY.sessionId, seq, json, 5_000 + seq) }) await closeTestJournalHostDatabase(root) @@ -198,7 +196,7 @@ export function registerJournalUnknownRowKindTests(): void { it('reads a known kind that fails its own checks as malformed', () => { const parsed = parseJournalRow( - JSON.stringify({ ...newerRow('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) + JSON.stringify({ ...rowEnvelope('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) ) expect(parsed).toEqual({ ok: false, unreadable: false }) }) @@ -265,7 +263,12 @@ export function registerJournalUnknownRowKindTests(): void { ['a later', 9] ])('fails the load and is kept when it names %s one', async (_name, seq) => { const epoch = await journalWithOneItem() - const tombstone = { ...newerRow(epoch, seq), kind: 'tombstone', itemId: 'gone', revision: 1 } + const tombstone = { + ...rowEnvelope(epoch, seq), + kind: 'tombstone', + itemId: 'gone', + revision: 1 + } await expect(restartAfter((put) => put(3, JSON.stringify(tombstone)))).rejects.toMatchObject( UNLOADABLE ) diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts new file mode 100644 index 000000000000..8d1155259b2b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts @@ -0,0 +1,195 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { + AgentMessageSource, + AgentSessionMessageSource +} from '../../../shared/agent-session/agent-session-message-source' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { holdUnsentSends, type UnsentSendHold } from './journal-unsent-send-hold' +import type { AgentSessionJournal } from './journal-store' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + updateTestJournalRowJson +} from './journal-host-database-test-support' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-held', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { + surface: 'rejection' + }) + + const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { + surface: 'rejection' + }) + + let root: string + + let clock = 1_000 + + let epochs = 0 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprint(body: AgentJournalMessageItem): string { + return structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body } + }) + } + + async function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${(epochs += 1)}` + }) + } + + function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { + return holdUnsentSends(journal, { fence: 0, hold: settle }) + } + + const MAIL_SOURCE: AgentMessageSource = { + kind: 'agent', + senders: [ + { + party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, + name: null + } + ], + orchestration: { + message: 'mail-notice', + mailbox: 'agent:worker', + dispatchId: null, + messages: [] + } + } + + async function accept( + journal: AgentSessionJournal, + id: string, + fields: { + body?: AgentJournalMessageItem + origin?: 'client' | 'host' + source?: AgentSessionMessageSource + } = {} + ): Promise { + const body = fields.body ?? message(`text of ${id}`) + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: fingerprint(body), + body, + fence: 0, + handoverRecorded: true, + ...(fields.origin ? { origin: fields.origin } : {}), + ...(fields.source ? { source: fields.source } : {}) + }) + } + + async function afterRestart( + write: (journal: AgentSessionJournal) => Promise + ): Promise { + const earlier = await open() + await write(earlier) + await earlier.close() + return open() + } + + async function storeSubmissionSourceAs( + journal: AgentSessionJournal, + id: string, + source: unknown + ): Promise { + await journal.close() + const seq = journal.submission(id)?.submittedSequence + const { db } = openTestJournalHostDatabase(root) + const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) + if (!stored) { + throw new Error(`no stored row for ${id}`) + } + const row: unknown = JSON.parse(stored.rowJson) + updateTestJournalRowJson( + db, + IDENTITY.sessionId, + stored.seq, + JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) + ) + } + + function cardOrder(journal: AgentSessionJournal): string[] { + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => card.messageId) + } + + beforeEach(async () => { + epochs = 0 + root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) + }) + + afterEach(async () => { + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) + }) + + return { + CHAT_CLOSED, + HOST_RESTARTED, + IDENTITY, + MAIL_SOURCE, + accept, + afterRestart, + cardOrder, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + fingerprint, + hold, + journals, + message, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storeSubmissionSourceAs + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts new file mode 100644 index 000000000000..27ca1cdc49b9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts @@ -0,0 +1,160 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' + +export function registerJournalUnsentSendHoldQueueTests( + fixture: ReturnType +): void { + describe('where kept sends go in the queue', () => { + it.each([ + { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, + { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } + ])( + 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', + async ({ origin, order }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'H', + body: fixture.message('H') + }) + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await earlier.appendSubmission( + { + clientMessageId: 'H-handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('H')), + body: fixture.message('H'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'H', expect: 'waiting' } + ) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(order) + } + ) + + it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { + const interrupted = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + // Simulate a crash after keeping A at a stale position but before settling B. + await interrupted.resolveDispatch( + { + clientMessageId: 'A', + state: 'rejected', + ...fixture.HOST_RESTARTED, + fence: 0, + recovered: true, + keptAsQueuedMessageId: 'A' + }, + () => + interrupted.queuedMessages.plan([ + { + messageId: 'A', + change: { + op: 'queued', + body: fixture.message('text of A'), + queuedAt: { + epoch: 'epoch-1', + sequence: interrupted.submission('A')!.acceptedSequence! + }, + position: 5 + } + } + ]) + ) + await interrupted.close() + const journal = await fixture.open() + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['A', 'B', 'C']) + }) + }) + + describe('a close of the chat', () => { + it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.hold(journal, { cause: 'chatClosed' }) + + expect(fixture.cardOrder(journal)).toEqual(['person']) + expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) + for (const id of ['person', 'mail']) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.CHAT_CLOSED + }) + } + }) + + it('settles only what `which` names, leaving a later send queued', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal, { + cause: 'chatClosed', + which: (submission) => submission.clientMessageId === 'before' + }) + + expect(fixture.cardOrder(journal)).toEqual(['before']) + expect(journal.submission('after')?.dispatchState).toBe('pending') + }) + }) + + describe('the order kept cards stand in', () => { + it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + for (const id of ['m1', 'm2', 'm3']) { + await fixture.accept(earlier, id, { origin: 'host', source: fixture.MAIL_SOURCE }) + } + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + await journal.rollEpoch('handle_forked', 0) + await fixture.accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await journal.close() + const reopened = await fixture.open() + await fixture.hold(reopened) + + expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( + reopened.queuedMessages.get('B')?.queuedAt?.epoch + ) + expect(fixture.cardOrder(reopened)).toEqual(['A', 'B']) + }) + }) + + describe('the source a send records', () => { + it('is folded from the row; a row without one folds without it', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'without', { origin: 'client' }) + const folded: AgentJournalSubmission | undefined = journal.submission('with-source') + expect(folded?.source).toEqual({ kind: 'user' }) + expect(journal.submission('without')).not.toHaveProperty('source') + }) + + it('keeps only the kind of an agent’s source, never its senders', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await journal.close() + const reopened = await fixture.open() + expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) + expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts new file mode 100644 index 000000000000..7b219bb78fca --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts @@ -0,0 +1,176 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' +import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' +import { unsentSendKeptAsCard } from './journal-unsent-send-hold' + +export function registerJournalUnsentSendHoldRecoveryTests( + fixture: ReturnType +): void { + describe('which sends an earlier host process left unsent are kept', () => { + it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'legacy-client', { origin: 'client' }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) + await journal.close() + const reopened = await fixture.open() + for (const id of ['person', 'launch', 'legacy-client']) { + expect(reopened.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED, + keptAsQueuedMessageId: id + }) + expect(reopened.queuedMessages.get(id)).toMatchObject({ + state: 'waiting', + holdReason: null, + body: fixture.message(`text of ${id}`), + fingerprint: fixture.fingerprint(fixture.message(`text of ${id}`)), + queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } + }) + } + }) + + it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { + const image: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [ + { type: 'text', text: 'look' }, + { type: 'image-ref', path: '/tmp/attachment.png' } + ] + } + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.accept(earlier, 'dispatch', { origin: 'host' }) + await fixture.accept(earlier, 'continuation', { origin: 'host' }) + await fixture.accept(earlier, 'compact', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: structuredAgentSessionCompactBody() + }) + await fixture.accept(earlier, 'image', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: image + }) + await fixture.accept(earlier, 'legacy-host', { origin: 'host' }) + await fixture.accept(earlier, 'no-origin') + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toEqual([]) + for (const id of [ + 'mail', + 'dispatch', + 'continuation', + 'compact', + 'image', + 'legacy-host', + 'no-origin' + ]) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED + }) + expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') + } + }) + + it.each([ + { by: 'Send now', origin: 'client' as const }, + { by: 'the queue', origin: 'host' as const } + ])( + 'a card’s own hand-off by $by returns its card, and makes no second one', + async ({ origin }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'card', + body: fixture.message('card text') + }) + await earlier.appendSubmission( + { + clientMessageId: 'handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('card text')), + body: fixture.message('card text'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'card', expect: 'waiting' } + ) + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toHaveLength(1) + expect(journal.queuedMessages.get('card')).toMatchObject({ + state: 'waiting', + consumedAs: null, + holdReason: null + }) + expect(journal.queuedMessages.get('handoff')).toBeNull() + } + ) + + it('leaves alone what this process accepted', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal) + expect(journal.submission('mine')?.dispatchState).toBe('pending') + expect(journal.queuedMessages.list()).toEqual([]) + }) + + it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { + const body = fixture.message('x') + expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() + }) + + it('never keeps a source kind this build does not know, whatever its origin', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'future', + payloadFingerprint: fixture.fingerprint(fixture.message('from a newer build')), + body: fixture.message('from a newer build'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) + }) + expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) + }) + + it('never keeps a send whose stored source has no readable kind', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'unreadable', + payloadFingerprint: fixture.fingerprint(fixture.message('unreadable')), + body: fixture.message('unreadable'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'unreadable', {}) + }) + expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts index 670c42114d5c..b898e59cd3c3 100644 --- a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts @@ -1,477 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { - AgentJournalMessageItem, - AgentJournalSubmission, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - USER_MESSAGE_SOURCE, - type AgentMessageSource, - type AgentSessionMessageSource -} from '../../../shared/agent-session/agent-session-message-source' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' -import { - holdUnsentSends, - unsentSendKeptAsCard, - type UnsentSendHold -} from './journal-unsent-send-hold' -import type { AgentSessionJournal } from './journal-store' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from './journal-host-database-test-support' +import { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { registerJournalUnsentSendHoldRecoveryTests } from './journal-unsent-send-hold-recovery.spec' +import { registerJournalUnsentSendHoldQueueTests } from './journal-unsent-send-hold-queue.spec' export function registerJournalUnsentSendHoldTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-held', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { - surface: 'rejection' - }) - const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { - surface: 'rejection' - }) - - let root: string - let clock = 1_000 - let epochs = 0 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprint(body: AgentJournalMessageItem): string { - return structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body } - }) - } - - async function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => (clock += 1), - mintEpoch: () => `epoch-${(epochs += 1)}` - }) - } - - function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { - return holdUnsentSends(journal, { fence: 0, hold: settle }) - } - - const MAIL_SOURCE: AgentMessageSource = { - kind: 'agent', - senders: [ - { - party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, - name: null - } - ], - orchestration: { - message: 'mail-notice', - mailbox: 'agent:worker', - dispatchId: null, - messages: [] - } - } - - async function accept( - journal: AgentSessionJournal, - id: string, - fields: { - body?: AgentJournalMessageItem - origin?: 'client' | 'host' - source?: AgentSessionMessageSource - } = {} - ): Promise { - const body = fields.body ?? message(`text of ${id}`) - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: fingerprint(body), - body, - fence: 0, - handoverRecorded: true, - ...(fields.origin ? { origin: fields.origin } : {}), - ...(fields.source ? { source: fields.source } : {}) - }) - } - - async function afterRestart( - write: (journal: AgentSessionJournal) => Promise - ): Promise { - const earlier = await open() - await write(earlier) - await earlier.close() - return open() - } - - function storeSubmissionSourceAs( - journal: AgentSessionJournal, - id: string, - source: unknown - ): void { - const seq = journal.submission(id)?.submittedSequence - const { db } = openTestJournalHostDatabase(root) - const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) - if (!stored) { - throw new Error(`no stored row for ${id}`) - } - const row: unknown = JSON.parse(stored.rowJson) - updateTestJournalRowJson( - db, - IDENTITY.sessionId, - stored.seq, - JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) - ) - } - - function cardOrder(journal: AgentSessionJournal): string[] { - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => card.messageId) - } - - beforeEach(async () => { - epochs = 0 - root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) - }) - - afterEach(async () => { - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) - }) - - describe('which sends an earlier host process left unsent are kept', () => { - it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'legacy-client', { origin: 'client' }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) - await journal.close() - const reopened = await open() - for (const id of ['person', 'launch', 'legacy-client']) { - expect(reopened.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED, - keptAsQueuedMessageId: id - }) - expect(reopened.queuedMessages.get(id)).toMatchObject({ - state: 'waiting', - holdReason: null, - body: message(`text of ${id}`), - fingerprint: fingerprint(message(`text of ${id}`)), - queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } - }) - } - }) - - it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { - const image: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'look' }, - { type: 'image-ref', path: '/tmp/attachment.png' } - ] - } - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await accept(earlier, 'dispatch', { origin: 'host' }) - await accept(earlier, 'continuation', { origin: 'host' }) - await accept(earlier, 'compact', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: structuredAgentSessionCompactBody() - }) - await accept(earlier, 'image', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: image - }) - await accept(earlier, 'legacy-host', { origin: 'host' }) - await accept(earlier, 'no-origin') - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toEqual([]) - for (const id of [ - 'mail', - 'dispatch', - 'continuation', - 'compact', - 'image', - 'legacy-host', - 'no-origin' - ]) { - expect(journal.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED - }) - expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') - } - }) - - it.each([ - { by: 'Send now', origin: 'client' as const }, - { by: 'the queue', origin: 'host' as const } - ])( - 'a card’s own hand-off by $by returns its card, and makes no second one', - async ({ origin }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'card', - body: message('card text') - }) - await earlier.appendSubmission( - { - clientMessageId: 'handoff', - payloadFingerprint: fingerprint(message('card text')), - body: message('card text'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'card', expect: 'waiting' } - ) - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toHaveLength(1) - expect(journal.queuedMessages.get('card')).toMatchObject({ - state: 'waiting', - consumedAs: null, - holdReason: null - }) - expect(journal.queuedMessages.get('handoff')).toBeNull() - } - ) - - it('leaves alone what this process accepted', async () => { - const journal = await open() - await accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal) - expect(journal.submission('mine')?.dispatchState).toBe('pending') - expect(journal.queuedMessages.list()).toEqual([]) - }) - - it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { - const body = message('x') - expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() - }) - - it('never keeps a source kind this build does not know, whatever its origin', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'future', - payloadFingerprint: fingerprint(message('from a newer build')), - body: message('from a newer build'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) - }) - expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) - }) - - it('never keeps a send whose stored source has no readable kind', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'unreadable', - payloadFingerprint: fingerprint(message('unreadable')), - body: message('unreadable'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'unreadable', {}) - }) - expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) - }) - }) - - describe('where kept sends go in the queue', () => { - it.each([ - { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, - { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } - ])( - 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', - async ({ origin, order }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'H', - body: message('H') - }) - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await earlier.appendSubmission( - { - clientMessageId: 'H-handoff', - payloadFingerprint: fingerprint(message('H')), - body: message('H'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'H', expect: 'waiting' } - ) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(order) - } - ) - - it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { - const interrupted = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - // Simulate a crash after keeping A at a stale position but before settling B. - await interrupted.resolveDispatch( - { - clientMessageId: 'A', - state: 'rejected', - ...HOST_RESTARTED, - fence: 0, - recovered: true, - keptAsQueuedMessageId: 'A' - }, - () => - interrupted.queuedMessages.plan([ - { - messageId: 'A', - change: { - op: 'queued', - body: message('text of A'), - queuedAt: { - epoch: 'epoch-1', - sequence: interrupted.submission('A')!.acceptedSequence! - }, - position: 5 - } - } - ]) - ) - await interrupted.close() - const journal = await open() - await hold(journal) - - expect(cardOrder(journal)).toEqual(['A', 'B', 'C']) - }) - }) - - describe('a close of the chat', () => { - it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { - const journal = await open() - await accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await hold(journal, { cause: 'chatClosed' }) - - expect(cardOrder(journal)).toEqual(['person']) - expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) - for (const id of ['person', 'mail']) { - expect(journal.submission(id)).toMatchObject({ dispatchState: 'rejected', ...CHAT_CLOSED }) - } - }) - - it('settles only what `which` names, leaving a later send queued', async () => { - const journal = await open() - await accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal, { - cause: 'chatClosed', - which: (submission) => submission.clientMessageId === 'before' - }) - - expect(cardOrder(journal)).toEqual(['before']) - expect(journal.submission('after')?.dispatchState).toBe('pending') - }) - }) - - describe('the order kept cards stand in', () => { - it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { - const journal = await afterRestart(async (earlier) => { - for (const id of ['m1', 'm2', 'm3']) { - await accept(earlier, id, { origin: 'host', source: MAIL_SOURCE }) - } - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - await journal.rollEpoch('handle_forked', 0) - await accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await journal.close() - const reopened = await open() - await hold(reopened) - - expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( - reopened.queuedMessages.get('B')?.queuedAt?.epoch - ) - expect(cardOrder(reopened)).toEqual(['A', 'B']) - }) - }) - - describe('the source a send records', () => { - it('is folded from the row; a row without one folds without it', async () => { - const journal = await open() - await accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'without', { origin: 'client' }) - const folded: AgentJournalSubmission | undefined = journal.submission('with-source') - expect(folded?.source).toEqual({ kind: 'user' }) - expect(journal.submission('without')).not.toHaveProperty('source') - }) - - it('keeps only the kind of an agent’s source, never its senders', async () => { - const journal = await open() - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await journal.close() - const reopened = await open() - expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) - expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') - }) - }) + const fixture = createFixture() + registerJournalUnsentSendHoldRecoveryTests(fixture) + registerJournalUnsentSendHoldQueueTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-write-projection.ts b/src/main/native-chat/agent-session-journal/journal-write-projection.ts new file mode 100644 index 000000000000..842ef5e00d2b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-write-projection.ts @@ -0,0 +1,77 @@ +import { isDeepStrictEqual } from 'node:util' +import type Database from '../../sqlite/sync-database' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { prepareJournalOutcomeWrite } from './journal-outcome-write' +import { encodeJournalState } from './journal-state-codec' +import { restoreJournal } from './journal-open' + +// A full restore per check: development samples each chat so long streams stay responsive. +const DEVELOPMENT_VERIFY_INTERVAL_MS = 60_000 + +/** Writes outcome records with each append and adopts their transition once the write commits. */ +export class JournalWriteProjection { + /** Projection tests check the equality invariant after every commit and throw on divergence. */ + static verifyEachCommit = false + + private verifiedAt = Number.NEGATIVE_INFINITY + + constructor( + private readonly deps: { + database: JournalHostDatabase + state: () => JournalReducerState + adopt: (state: JournalReducerState) => void + } + ) {} + + /** The callback is invoked only after the outer transaction has committed. */ + prepare(db: Database.Database, rows: readonly JournalRow[], savedAt: number): () => void { + const transition = prepareJournalOutcomeWrite(db, this.deps.state(), rows, savedAt) + return () => this.deps.adopt(transition.adopt()) + } + + /** Runs after commit notification, never in the adopt path. */ + verify(): void { + if (JournalWriteProjection.verifyEachCommit) { + this.checkEquivalent() + return + } + const now = performance.now() + if ( + process.env.NODE_ENV !== 'development' || + now - this.verifiedAt < DEVELOPMENT_VERIFY_INTERVAL_MS + ) { + return + } + this.verifiedAt = now + try { + this.checkEquivalent() + } catch (error) { + logJournalVerifyFailure(this.deps.state().sessionId, error) + } + } + + /** Every saved form (input fold, prefix plus records, or records alone) must restore the live + * state. */ + private checkEquivalent(): void { + const live = this.deps.state() + const loaded = restoreJournal(this.deps.database.db, live.sessionId) + if ( + !loaded || + loaded.damage || + loaded.newer || + !isDeepStrictEqual(encodeJournalState(loaded.state), encodeJournalState(live)) + ) { + throw new Error('journal saved state differs from live state') + } + } +} + +function logJournalVerifyFailure(sessionId: string, error: unknown): void { + try { + console.warn('[agent-session-journal] saved chat differs from live chat', { sessionId, error }) + } catch { + // Diagnostics never turn a development check into a rejected send. + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts new file mode 100644 index 000000000000..38e922d0c5f7 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts @@ -0,0 +1,193 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { + createTrackedJournalOpener, + liveTestJournalRows, + readTestJournalOutcomes, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import { fields } from './journal-state-schema' +import type { AgentSessionJournal } from './journal-store' +import { queuePauseHolding } from './queued-message-pause' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-p', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + let root: string + + let clock = 1_000 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprintOf(text: string): string { + return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) + } + + function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => ++clock, + mintEpoch: () => `epoch-${clock}` + }) + } + + function queueDraft(journal: AgentSessionJournal, messageId: string) { + return journal.queuedMessages.insert({ messageId, body: message(messageId) }) + } + + function clearContext(journal: AgentSessionJournal) { + return journal.context.clear( + { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, + { write: () => {}, committed: () => {} } + ) + } + + async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: `fp-${id}`, + body: message(id), + fence: 0, + handoverRecorded: true + }) + if (accept) { + await acceptTurn(journal, id) + } + } + + function acceptTurn(journal: AgentSessionJournal, id: string) { + return journal.resolveDispatch({ + clientMessageId: id, + state: 'accepted', + providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, + fence: 0 + }) + } + + function userStop(journal: AgentSessionJournal) { + return journal.appendStopEvent({ reason: 'user-stop' }, 0) + } + + function reason(journal: AgentSessionJournal): string | null { + return journal.queuedMessages.pauses()[0]?.reason ?? null + } + + function held(journal: AgentSessionJournal): [string, boolean][] { + const pauses = journal.queuedMessages.pauses() + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) + } + + function stopEvents(): unknown[] { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + // An outcome epoch (every replaced one) stores the Stop as pause marks, not as an input row. + const marks = readTestJournalOutcomes(db, IDENTITY.sessionId).filter( + (value) => value.field === '$' && value.key === JSON.stringify('queuePauseMarks') + ) + if (marks.length > 0) { + const stop = fields.queuePauseMarks.parse(JSON.parse(marks.at(-1)!.json)).latestStop + return stop ? [stop.event] : [] + } + return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { + const parsed = parseJournalRow(stored.rowJson) + return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent + ? [parsed.row.stopEvent] + : [] + }) + } finally { + db.close() + } + } + + function rewriteRows(keys: Record): void { + const db = new Database(journalDatabasePath(root)) + try { + for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { + const rewrite = keys[stored.seq] + if (rewrite) { + const row: Record = JSON.parse(stored.rowJson) + row[rewrite[0]] = rewrite[1] + updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) + } + } + } finally { + db.close() + } + } + + function pauseTables(): number { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + return db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") + .all().length + } finally { + db.close() + } + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + return { + IDENTITY, + acceptTurn, + clearContext, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + fingerprintOf, + held, + journals, + message, + open, + pauseTables, + queueDraft, + reason, + rewriteRows, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + stopEvents, + turn, + userStop + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts new file mode 100644 index 000000000000..7c54d574f6a4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + deriveQueuePauses, + nextSendableQueuedCard, + queuePauseHolding, + resumableQueuePause +} from './queued-message-pause' + +export function registerQueuedMessagePauseHeldCardsTests(): void { + describe('which cards the pauses in force hold', () => { + type Card = Parameters[1] & { messageId: string } + + function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { + const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } + const base = { state: 'waiting', holdReason: null } + return { messageId, ...base, queuedAt, ...fields } + } + + /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ + function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { + return deriveQueuePauses({ + epoch: 'epoch-1', + marks: { + latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, + resumedSequence: 0, + reopenedSequence: 0, + ...(clearedIds + ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } + : {}) + }, + latestAcceptedTurnSequence: 0, + cards, + reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null + }) + } + + function holding( + cards: readonly Card[], + stopped?: number, + opened?: number + ): [string, string | null][] { + const pauses = pausesOver(cards, stopped, opened) + return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + } + + it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { + const cards = [ + card('unrecorded', 5, { queuedAt: null }), + // Epoch precedence outranks raw sequence values. + card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), + card('after', 5) + ] + expect(holding(cards)).toEqual([ + ['unrecorded', 'stopped'], + ['before-rewind', 'stopped'], + ['after', null] + ]) + }) + + it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { + const after = card('after', 5) + expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ + 'stopped', + 'restarted' + ]) + expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) + expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() + expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) + }) + + it("a card names the first pause holding it, and the header names the first held card's", () => { + const cards = [card('before', 3), card('after', 5)] + expect(holding(cards, 5, 6)).toEqual([ + ['before', 'stopped'], + ['after', 'restarted'] + ]) + expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') + }) + + it('a card from before the open waits in order, and so do the cards behind it', () => { + const cards = [card('kept', 1), card('behind', 2)] + expect(holding(cards, 0, 4)).toEqual([ + ['kept', 'restarted'], + ['behind', 'restarted'] + ]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() + }) + + it('a card held on its own from before the open starts no reopen pause', () => { + const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] + expect(pausesOver(cards, 0, 4)).toEqual([]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') + }) + + it("a /clear's pause that holds nothing never hides a reopen's", () => { + const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] + const pauses = pausesOver(cards, 0, 4, ['cleared']) + expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) + expect( + cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + ).toEqual([ + ['cleared', null], + ['typed', 'restarted'] + ]) + expect(nextSendableQueuedCard(pauses, cards)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts index 9b161a0611d5..5592a1259681 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts @@ -1,725 +1,11 @@ -// Derive pauses from journal rows; never maintain a second stored pause state. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import Database from '../../sqlite/sync-database' -import { journalDatabasePath } from './journal-host-database' -import { - createTrackedJournalOpener, - liveTestJournalRows, - updateTestJournalRowJson -} from './journal-host-database-test-support' -import { QueuedMessageNotConsumableError } from './queued-message-consume-error' -import { applyJournalRow, createJournalReducerState } from './journal-reducer' -import { parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' -import { - deriveQueuePauses, - nextSendableQueuedCard, - queuePauseHolding, - resumableQueuePause -} from './queued-message-pause' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { createFixture } from './queued-message-pause-contract-test-fixture' +import { registerQueuedMessageStopPauseTests } from './queued-message-stop-pause.spec' +import { registerQueuedMessageReopenPauseTests } from './queued-message-reopen-pause.spec' +import { registerQueuedMessagePauseHeldCardsTests } from './queued-message-pause-held-cards.spec' export function registerQueuedMessagePauseTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-p', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - - let root: string - let clock = 1_000 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprintOf(text: string): string { - return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) - } - - function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => ++clock, - mintEpoch: () => `epoch-${clock}` - }) - } - - function queueDraft(journal: AgentSessionJournal, messageId: string) { - return journal.queuedMessages.insert({ messageId, body: message(messageId) }) - } - - function clearContext(journal: AgentSessionJournal) { - return journal.context.clear( - { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, - { write: () => {}, committed: () => {} } - ) - } - - async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: `fp-${id}`, - body: message(id), - fence: 0, - handoverRecorded: true - }) - if (accept) { - await acceptTurn(journal, id) - } - } - - function acceptTurn(journal: AgentSessionJournal, id: string) { - return journal.resolveDispatch({ - clientMessageId: id, - state: 'accepted', - providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, - fence: 0 - }) - } - - function userStop(journal: AgentSessionJournal) { - return journal.appendStopEvent({ reason: 'user-stop' }, 0) - } - - function reason(journal: AgentSessionJournal): string | null { - return journal.queuedMessages.pauses()[0]?.reason ?? null - } - - function held(journal: AgentSessionJournal): [string, boolean][] { - const pauses = journal.queuedMessages.pauses() - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) - } - - function stopEvents(): unknown[] { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent - ? [parsed.row.stopEvent] - : [] - }) - } finally { - db.close() - } - } - - function rewriteRows(keys: Record): void { - const db = new Database(journalDatabasePath(root)) - try { - for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { - const rewrite = keys[stored.seq] - if (rewrite) { - const row: Record = JSON.parse(stored.rowJson) - row[rewrite[0]] = rewrite[1] - updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) - } - } - } finally { - db.close() - } - } - - function pauseTables(): number { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return db - .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") - .all().length - } finally { - db.close() - } - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe("the queue's pause, derived from the journal", () => { - it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { - let journal = await open() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await queueDraft(journal, 'draft-1') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { - const journal = await open() - await turn(journal, 'before-stop', false) - await userStop(journal) - // Late acceptance of a pre-Stop send cannot lift the pause. - await acceptTurn(journal, 'before-stop') - expect(reason(journal)).toBe('stopped') - await turn(journal, 'mail', false) - expect(reason(journal)).toBe('stopped') - await acceptTurn(journal, 'mail') - expect(reason(journal)).toBeNull() - }) - - it('a later Stop is the latest, and a Resume row lifts it', async () => { - const journal = await open() - await userStop(journal) - await turn(journal, 'typed') - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it('a card kept by /clear stays paused until Resume in the same journal', async () => { - let journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - expect(reason(journal)).toBe('cleared') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('cleared') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - expect(pauseTables()).toBe(0) - }) - - it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'launch', false) - expect(reason(journal)).toBe('cleared') - await acceptTurn(journal, 'launch') - expect(reason(journal)).toBeNull() - }) - - it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { - const journal = await open() - await turn(journal, 'typed') - await journal.appendStopEvent( - { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, - 0 - ) - const db = new Database(journalDatabasePath(root), { readonly: true }) - const stored = liveTestJournalRows(db, IDENTITY.sessionId) - db.close() - const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') - expect(parsed).toMatchObject({ - ok: true, - row: { - kind: 'tombstone', - stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } - } - }) - if (!parsed.ok || parsed.row.kind !== 'tombstone') { - throw new Error('expected a tombstone row') - } - expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) - // Older readers ignore the annotation and remove a nonexistent item. - const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row - const state = createJournalReducerState(IDENTITY.sessionId, parsed.row.epoch) - for (const row of stored.slice(0, -1)) { - const earlier = parseJournalRow(row.rowJson) - if (earlier.ok) { - applyJournalRow(state, earlier.row) - } - } - const items = [...state.items.keys()] - const submissions = [...state.submissions.keys()] - applyJournalRow(state, asOlderBuildReadsIt) - expect([...state.items.keys()]).toEqual(items) - expect([...state.submissions.keys()]).toEqual(submissions) - }) - - it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { - let journal = await open() - await queueDraft(journal, 'held') - const corrupted = async ( - append: Promise<{ sequence: number }>, - key: string, - value: unknown - ) => { - const { sequence } = await append - await journal.close() - rewriteRows({ [sequence]: [key, value] }) - journal = await open() - } - const malformed = [null, 'stopped', { at: 1 }] - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBeNull() - } - await userStop(journal) - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBe('stopped') - } - await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - await userStop(journal) - const consume = (id: string, automatic: boolean) => - journal.appendSubmission( - { - clientMessageId: id, - payloadFingerprint: fingerprintOf('draft-1'), - body: message('draft-1'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'draft-1', - expect: 'waiting', - ...(automatic ? { yieldsToPause: true as const } : {}) - } - ) - await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.submission('drain-1')).toBeUndefined() - expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') - await consume('send-now-1', false) - expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') - }) - - it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { - const journal = await open() - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBe('stopped') - await turn(journal, 'typed') - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const reason of ['user-close', 'host-stop', 'evict'] as const) { - await journal.appendStopEvent({ reason }, 0) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. - await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) - expect(reason(journal)).toBeNull() - }) - - it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const later of ['host-stop', 'evict', 'user-close'] as const) { - await userStop(journal) - expect(held(journal)).toEqual([['draft-1', true]]) - await journal.appendStopEvent({ reason: later }, 0) - expect(reason(journal)).toBeNull() - expect(held(journal)).toEqual([['draft-1', false]]) - } - }) - - it("a person's Stop with no later Stop event is not lifted", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - // Eviction rows must describe ended work or they would incorrectly lift this pause. - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it('the restated Stop is the same event: its reason, turn, caller and time', async () => { - const journal = await open() - await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) - const stopped = stopEvents() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(stopEvents()).toEqual(stopped) - expect(stopped).toEqual([ - { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } - ]) - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'typed')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'typed') - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - }) - }) - - describe('which cards a pause holds', () => { - it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { - let journal = await open() - await queueDraft(journal, 'before') - await userStop(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - await journal.close() - journal = await open() - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - }) - - it('a steer the Stop withdrew comes back in its own place, and is held', async () => { - const journal = await open() - await queueDraft(journal, 'steered') - await journal.appendSubmission( - { - clientMessageId: 'send-now-1', - payloadFingerprint: fingerprintOf('steered'), - body: message('steered'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'steered', expect: 'waiting' } - ) - await userStop(journal) - await queueDraft(journal, 'after') - await journal.resolveDispatch({ - clientMessageId: 'send-now-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), - fence: 0 - }) - expect(held(journal)).toEqual([ - ['steered', true], - ['after', false] - ]) - }) - - it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - await queueDraft(journal, 'newer') - await expect( - journal.appendSubmission( - { - clientMessageId: 'drain-newer', - payloadFingerprint: fingerprintOf('newer'), - body: message('newer'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'newer', - expect: 'waiting', - yieldsToPause: true - } - ) - ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') - }) - - it("'cleared' holds the cards already queued, not one typed after it", async () => { - const journal = await open() - await queueDraft(journal, 'carried-1') - await queueDraft(journal, 'carried-2') - await clearContext(journal) - await queueDraft(journal, 'typed-here') - expect(held(journal)).toEqual([ - ['carried-1', true], - ['carried-2', true], - ['typed-here', false] - ]) - }) - }) - - describe("a reopen's pause", () => { - /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ - async function reopen( - journal: AgentSessionJournal, - failMark = false - ): Promise { - await journal.close() - const reopened = await open() - if (failMark) { - vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) - await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') - } else { - await reopened.markQueueReopen(0) - } - return reopened - } - - it('holds the cards queued before the reopen, never one queued after its mark', async () => { - let journal = await open() - await queueDraft(journal, 'before') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - expect(reason(journal)).toBe('restarted') - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'carry-on')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('%s after the reopen lifts it', async (_name, lift) => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - }) - - it('a turn the agent has not accepted yet lifts nothing', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await turn(journal, 'carry-on', false) - expect(reason(journal)).toBe('restarted') - }) - - it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { - let journal = await open() - await queueDraft(journal, 'in-flight') - await journal.appendSubmission( - { - clientMessageId: 'drain-1', - payloadFingerprint: fingerprintOf('in-flight'), - body: message('in-flight'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'in-flight', expect: 'waiting' } - ) - journal = await reopen(journal) - await journal.resolveDispatch({ - clientMessageId: 'drain-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { - surface: 'rejection' - }), - fence: 0 - }) - expect(held(journal)).toEqual([['in-flight', true]]) - }) - - it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { - const journal = await open() - await queueDraft(journal, 'kept') - const stopped = journal.cursor().sequence + 1 - await turn(journal, 'later') - await journal.markQueueReopen(0, stopped) - expect(reason(journal)).toBeNull() - - const reopened = await reopen(journal) - expect(reason(reopened)).toBe('restarted') - await reopened.markQueueReopen(0, stopped) - expect(reason(reopened)).toBe('restarted') - }) - - it('a reopen with no waiting card writes nothing', async () => { - let journal = await open() - await turn(journal, 'earlier') - const before = journal.cursor() - journal = await reopen(journal) - expect(journal.cursor()).toEqual(before) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([['after', false]]) - }) - - it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - }) - - it('without a mark the open itself is where the pause begins', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal, true) - expect(held(journal)).toEqual([['before', true]]) - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - }) - - it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { - let journal = await open() - const db = new Database(journalDatabasePath(root)) - for (const [position, id, stored] of [ - [1, 'was-kept', 'kept'], - [2, 'was-stopped', 'stopped'], - [3, 'failed', 'send_failed'] - ] as const) { - db.prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason) - VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` - ).run(IDENTITY.sessionId, id, position, JSON.stringify(message(id)), stored) - } - db.close() - journal = await reopen(journal) - expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ - ['was-kept', null], - ['was-stopped', null], - ['failed', 'send_failed'] - ]) - expect(held(journal)).toEqual([ - ['was-kept', true], - ['was-stopped', true], - ['failed', false] - ]) - }) - }) - - describe('which cards the pauses in force hold', () => { - type Card = Parameters[1] & { messageId: string } - - function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { - const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } - const base = { state: 'waiting', holdReason: null } - return { messageId, ...base, queuedAt, ...fields } - } - - /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ - function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { - return deriveQueuePauses({ - epoch: 'epoch-1', - marks: { - latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, - resumedSequence: 0, - reopenedSequence: 0, - ...(clearedIds - ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } - : {}) - }, - latestAcceptedTurnSequence: 0, - cards, - reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null - }) - } - - function holding( - cards: readonly Card[], - stopped?: number, - opened?: number - ): [string, string | null][] { - const pauses = pausesOver(cards, stopped, opened) - return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - } - - it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { - const cards = [ - card('unrecorded', 5, { queuedAt: null }), - // Epoch precedence outranks raw sequence values. - card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), - card('after', 5) - ] - expect(holding(cards)).toEqual([ - ['unrecorded', 'stopped'], - ['before-rewind', 'stopped'], - ['after', null] - ]) - }) - - it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { - const after = card('after', 5) - expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ - 'stopped', - 'restarted' - ]) - expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) - expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() - expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) - }) - - it("a card names the first pause holding it, and the header names the first held card's", () => { - const cards = [card('before', 3), card('after', 5)] - expect(holding(cards, 5, 6)).toEqual([ - ['before', 'stopped'], - ['after', 'restarted'] - ]) - expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') - }) - - it('a card from before the open waits in order, and so do the cards behind it', () => { - const cards = [card('kept', 1), card('behind', 2)] - expect(holding(cards, 0, 4)).toEqual([ - ['kept', 'restarted'], - ['behind', 'restarted'] - ]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() - }) - - it('a card held on its own from before the open starts no reopen pause', () => { - const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] - expect(pausesOver(cards, 0, 4)).toEqual([]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') - }) - - it("a /clear's pause that holds nothing never hides a reopen's", () => { - const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] - const pauses = pausesOver(cards, 0, 4, ['cleared']) - expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) - expect( - cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - ).toEqual([ - ['cleared', null], - ['typed', 'restarted'] - ]) - expect(nextSendableQueuedCard(pauses, cards)).toBeNull() - }) - }) + const fixture = createFixture() + registerQueuedMessageStopPauseTests(fixture) + registerQueuedMessageReopenPauseTests(fixture) + registerQueuedMessagePauseHeldCardsTests() } diff --git a/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts new file mode 100644 index 000000000000..d9cca6b2e250 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts @@ -0,0 +1,243 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it, vi } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import type { AgentSessionJournal } from './journal-store' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' + +export function registerQueuedMessageReopenPauseTests( + fixture: ReturnType +): void { + describe('which cards a pause holds', () => { + it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + await journal.close() + journal = await fixture.open() + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + }) + + it('a steer the Stop withdrew comes back in its own place, and is held', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'steered') + await journal.appendSubmission( + { + clientMessageId: 'send-now-1', + payloadFingerprint: fixture.fingerprintOf('steered'), + body: fixture.message('steered'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'steered', expect: 'waiting' } + ) + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + await journal.resolveDispatch({ + clientMessageId: 'send-now-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([ + ['steered', true], + ['after', false] + ]) + }) + + it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'newer') + await expect( + journal.appendSubmission( + { + clientMessageId: 'drain-newer', + payloadFingerprint: fixture.fingerprintOf('newer'), + body: fixture.message('newer'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'newer', + expect: 'waiting', + yieldsToPause: true + } + ) + ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') + }) + + it("'cleared' holds the cards already queued, not one typed after it", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried-1') + await fixture.queueDraft(journal, 'carried-2') + await fixture.clearContext(journal) + await fixture.queueDraft(journal, 'typed-here') + expect(fixture.held(journal)).toEqual([ + ['carried-1', true], + ['carried-2', true], + ['typed-here', false] + ]) + }) + }) + + describe("a reopen's pause", () => { + /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ + async function reopen( + journal: AgentSessionJournal, + failMark = false + ): Promise { + await journal.close() + const reopened = await fixture.open() + if (failMark) { + vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) + await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') + } else { + await reopened.markQueueReopen(0) + } + return reopened + } + + it('holds the cards queued before the reopen, never one queued after its mark', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'carry-on')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('%s after the reopen lifts it', async (_name, lift) => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a turn the agent has not accepted yet lifts nothing', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await fixture.turn(journal, 'carry-on', false) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'in-flight') + await journal.appendSubmission( + { + clientMessageId: 'drain-1', + payloadFingerprint: fixture.fingerprintOf('in-flight'), + body: fixture.message('in-flight'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'in-flight', expect: 'waiting' } + ) + journal = await reopen(journal) + await journal.resolveDispatch({ + clientMessageId: 'drain-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { + surface: 'rejection' + }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([['in-flight', true]]) + }) + + it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'kept') + const stopped = journal.cursor().sequence + 1 + await fixture.turn(journal, 'later') + await journal.markQueueReopen(0, stopped) + expect(fixture.reason(journal)).toBeNull() + + const reopened = await reopen(journal) + expect(fixture.reason(reopened)).toBe('restarted') + await reopened.markQueueReopen(0, stopped) + expect(fixture.reason(reopened)).toBe('restarted') + }) + + it('a reopen with no waiting card writes nothing', async () => { + let journal = await fixture.open() + await fixture.turn(journal, 'earlier') + const before = journal.cursor() + journal = await reopen(journal) + expect(journal.cursor()).toEqual(before) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([['after', false]]) + }) + + it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('without a mark the open itself is where the pause begins', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal, true) + expect(fixture.held(journal)).toEqual([['before', true]]) + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + }) + + it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { + let journal = await fixture.open() + const db = new Database(journalDatabasePath(fixture.root)) + for (const [position, id, stored] of [ + [1, 'was-kept', 'kept'], + [2, 'was-stopped', 'stopped'], + [3, 'failed', 'send_failed'] + ] as const) { + db.prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason) + VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` + ).run(fixture.IDENTITY.sessionId, id, position, JSON.stringify(fixture.message(id)), stored) + } + db.close() + journal = await reopen(journal) + expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ + ['was-kept', null], + ['was-stopped', null], + ['failed', 'send_failed'] + ]) + expect(fixture.held(journal)).toEqual([ + ['was-kept', true], + ['was-stopped', true], + ['failed', false] + ]) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts new file mode 100644 index 000000000000..82a13e35ff29 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts @@ -0,0 +1,246 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { liveTestJournalRows } from './journal-host-database-test-support' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import { applyJournalRow, createJournalReducerState } from './journal-reducer' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function registerQueuedMessageStopPauseTests( + fixture: ReturnType +): void { + describe("the queue's pause, derived from the journal", () => { + it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { + let journal = await fixture.open() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.queueDraft(journal, 'draft-1') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'before-stop', false) + await fixture.userStop(journal) + // Late acceptance of a pre-Stop send cannot lift the pause. + await fixture.acceptTurn(journal, 'before-stop') + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'mail', false) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.acceptTurn(journal, 'mail') + expect(fixture.reason(journal)).toBeNull() + }) + + it('a later Stop is the latest, and a Resume row lifts it', async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await fixture.turn(journal, 'typed') + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it('a card kept by /clear stays paused until Resume in the same journal', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + expect(fixture.reason(journal)).toBe('cleared') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('cleared') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.pauseTables()).toBe(0) + }) + + it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'launch', false) + expect(fixture.reason(journal)).toBe('cleared') + await fixture.acceptTurn(journal, 'launch') + expect(fixture.reason(journal)).toBeNull() + }) + + it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'typed') + await journal.appendStopEvent( + { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, + 0 + ) + const db = new Database(journalDatabasePath(fixture.root), { readonly: true }) + const stored = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + db.close() + const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') + expect(parsed).toMatchObject({ + ok: true, + row: { + kind: 'tombstone', + stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } + } + }) + if (!parsed.ok || parsed.row.kind !== 'tombstone') { + throw new Error('expected a tombstone row') + } + expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) + // Older readers ignore the annotation and remove a nonexistent item. + const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row + const state = createJournalReducerState(fixture.IDENTITY.sessionId, parsed.row.epoch) + for (const row of stored.slice(0, -1)) { + const earlier = parseJournalRow(row.rowJson) + if (earlier.ok) { + applyJournalRow(state, earlier.row) + } + } + const items = [...state.items.keys()] + const submissions = [...state.submissions.keys()] + applyJournalRow(state, asOlderBuildReadsIt) + expect([...state.items.keys()]).toEqual(items) + expect([...state.submissions.keys()]).toEqual(submissions) + }) + + it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + const corrupted = async ( + append: Promise<{ sequence: number }>, + key: string, + value: unknown + ) => { + const { sequence } = await append + await journal.close() + fixture.rewriteRows({ [sequence]: [key, value] }) + journal = await fixture.open() + } + const malformed = [null, 'stopped', { at: 1 }] + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBeNull() + } + await fixture.userStop(journal) + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBe('stopped') + } + await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + await fixture.userStop(journal) + const consume = (id: string, automatic: boolean) => + journal.appendSubmission( + { + clientMessageId: id, + payloadFingerprint: fixture.fingerprintOf('draft-1'), + body: fixture.message('draft-1'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'draft-1', + expect: 'waiting', + ...(automatic ? { yieldsToPause: true as const } : {}) + } + ) + await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.submission('drain-1')).toBeUndefined() + expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') + await consume('send-now-1', false) + expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') + }) + + it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'typed') + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const reason of ['user-close', 'host-stop', 'evict'] as const) { + await journal.appendStopEvent({ reason }, 0) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. + await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) + expect(fixture.reason(journal)).toBeNull() + }) + + it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const later of ['host-stop', 'evict', 'user-close'] as const) { + await fixture.userStop(journal) + expect(fixture.held(journal)).toEqual([['draft-1', true]]) + await journal.appendStopEvent({ reason: later }, 0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.held(journal)).toEqual([['draft-1', false]]) + } + }) + + it("a person's Stop with no later Stop event is not lifted", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + // Eviction rows must describe ended work or they would incorrectly lift this pause. + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it('the restated Stop is the same event: its reason, turn, caller and time', async () => { + const journal = await fixture.open() + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) + const stopped = fixture.stopEvents() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.stopEvents()).toEqual(stopped) + expect(stopped).toEqual([ + { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } + ]) + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'typed')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'typed') + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts index fc3b8ba378cf..cefa7f7c1c08 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts @@ -6,6 +6,10 @@ import { readAgentJournalMessageBody } from '../../../shared/agent-session-journ import { readStoredRejectionFact } from './journal-dispatch-reducer' import type { QueuedMessageRow } from './queued-message-table' import { readAgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' +import { storedMessageBody } from './journal-storage-schema' +import { storageVerdict, strictStorage } from './journal-storage-strict' + +const strictBody = strictStorage(storedMessageBody) export const LEGACY_QUEUED_MESSAGE_COLUMNS = 'message_id, position, body_json, fingerprint, state, hold_reason, returned_reason, returned_rejection, consumed_as, queued_epoch, queued_sequence, options_json' @@ -34,8 +38,10 @@ export function readStoredQueuedMessageRow(row: unknown): QueuedMessageRow | nul return null } const state = record.state + // A body key this build does not declare stays on disk with the card, never adopted without it. if ( readAgentJournalMessageBody(body) !== 'readable' || + storageVerdict(strictBody, body) === 'newer' || (state !== 'waiting' && state !== 'dispatched' && state !== 'returned' && state !== 'withdrawn') ) { return null diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts new file mode 100644 index 000000000000..e1e740bdb44f --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts @@ -0,0 +1,210 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener +} from '../agent-session-journal/journal-host-database-test-support' +import { projectJournalBatch } from './agent-session-journal-batch' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + IDENTITY, + appendItems, + body, + item, + tick +} from './agent-session-history-contract-test-fixture' + +const outcomeJournals = createTrackedJournalOpener() + +describe('projectJournalBatch', () => { + it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await fixture.journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const cursor = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ + settlementId: 'settlement-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: item(1), + body: body('one'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: item(2), + body: body('two'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 1 + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + expect(page.page.removedItemIds).toHaveLength(1) + expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) + + const tail = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 1 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + }) + + it('accepts sparse outcome sequence groups', async () => { + // The shared fixture pins the input format; sparse groups exist only in an outcome epoch. + const root = await mkdtemp(join(tmpdir(), 'orca-history-outcomes-')) + const journal = await outcomeJournals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick + }) + try { + for (let ordinal = 1; ordinal <= 3; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + expect(since.rows.every((row) => row.kind === 'outcome')).toBe(true) + const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) + expect( + projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) + ).toMatchObject({ ok: true }) + } finally { + await journal.close() + await closeTestJournalHostDatabase(root) + await rm(root, { recursive: true, force: true }) + } + }) + + it('publishes touched items at their current reduced state, not as a delta', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendItem(item(1), body('revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.items).toHaveLength(1) + expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) + expect(projected.batch.cursor).toEqual(fixture.journal.cursor()) + }) + + it('lists a tombstoned item as removed', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.removedItemIds).toHaveLength(1) + expect(projected.batch.items).toHaveLength(0) + }) + + it('publishes a mismatched provider echo under its submission slot', async () => { + const message: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'queued follow-up' }] + } + await fixture.journal.appendSubmission({ + clientMessageId: 'client-follow-up', + payloadFingerprint: structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body: message } + }), + body: message, + fence: 1 + }) + const cursor = fixture.journal.cursor() + await fixture.journal.resolveDispatch({ + clientMessageId: 'client-follow-up', + state: 'accepted', + providerIdentity: { + provider: 'codex', + threadId: 'thread-1', + turnId: 'predicted', + ordinal: 0 + }, + fence: 1 + }) + await fixture.journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, + message, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: IDENTITY.sessionId, + direction: 'after', + cursor + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items).toMatchObject([ + { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } + ]) + expect(page.page.removedItemIds).toEqual([]) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts new file mode 100644 index 000000000000..b14576916eac --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { fixture, body, item } from './agent-session-history-contract-test-fixture' + +describe('history page byte ceiling', () => { + // Several legal messages exceed the 4 MiB outbound cap. + const LARGE_TEXT = 'x'.repeat(250 * 1024) + + async function appendLargeItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await fixture.journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + } + + function pageOf(result: ReturnType) { + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + serializeRemoteRuntimePayload(result.page) + return result.page + } + + it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { + await appendLargeItems(20) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items.length).toBeGreaterThan(0) + expect(tail.hasOlder).toBe(true) + + const seen = tail.items.map((entry) => entry.itemId) + let cursor = tail.window.nextCursor + let hasOlder = tail.hasOlder + let guard = 0 + while (hasOlder) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'before', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasOlder = page.hasOlder + } + expect(new Set(seen).size).toBe(20) + }) + + it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { + const start = { epoch: fixture.journal.epoch, sequence: 0 } + await appendLargeItems(20) + + const first = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + ) + expect(first.items.length).toBeGreaterThan(0) + expect(first.hasNewer).toBe(true) + + const seen = first.items.map((entry) => entry.itemId) + let cursor = first.window.nextCursor + let hasNewer = first.hasNewer + let guard = 0 + while (hasNewer) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasNewer = page.hasNewer + } + expect(new Set(seen).size).toBe(20) + }) + + it('sends a single over-budget item shortened and marked, never replaced', async () => { + await fixture.journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items).toHaveLength(1) + const sent = tail.items[0] + const text = + sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' + ? sent.body.blocks[0].text + : '' + expect(sent?.shortened).toBe(true) + expect(text.startsWith('1:yyy')).toBe(true) + expect(text.length).toBeLessThan(3 * 1024 * 1024) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts new file mode 100644 index 000000000000..7f36479ed85c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts @@ -0,0 +1,148 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION +} from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import type { + JournalItemRow, + JournalRow, + JournalTombstoneRow +} from '../agent-session-journal/journal-row-schema' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +let clock = 1_000 + +let epochs = 0 + +let journal: AgentSessionJournal + +export function tick(): number { + clock += 1 + return clock +} + +export function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +export function body(text: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } +} + +export async function appendItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) + clock = 1_000 + epochs = 0 + journal = await journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => { + epochs += 1 + return `epoch-${epochs}` + } + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export function serializedPageBytes(value: unknown): number { + return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') +} + +export type RawSeedRow = + | Omit + | Omit + +/** Seed raw legacy rows, then reopen to exercise current read bounds. */ + +export async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { + const full = rows.map( + (row) => + ({ + ...row, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: journal.epoch, + fence: 1, + ts: tick() + }) as JournalRow + ) + await journal.close() + const opened = openTestJournalHostDatabase(root) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of full) { + insertTestJournalRow(opened.db, IDENTITY.sessionId, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) +} + +export const fixture = { + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts new file mode 100644 index 000000000000..80a239e8cdde --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from 'vitest' +import { boundJournalKeyComponent } from '../../../shared/agent-session-journal-item-key' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + body, + reopenWithRawRows, + serializedPageBytes +} from './agent-session-history-contract-test-fixture' + +describe('pre-existing oversized identities', () => { + // Legacy oversized tombstone IDs cannot fit any outbound page. + const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + + it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, + { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } + ]) + + for (const sequence of [seq, seq + 1]) { + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence }, + limit: 40 + }) + expect(result.ok).toBe(false) + if (result.ok) { + throw new Error('expected a reset') + } + expect(result.reset).toBe('cursor_compacted') + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + // Reset replaces client state without sending an unsendable removal ID. + expect(result.page.items).toEqual([]) + const liveCursor = result.page.liveCursor + if (!liveCursor) { + throw new Error('expected a live cursor on the reset page') + } + expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) + + const resumed = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: liveCursor, + limit: 40 + }) + expect(resumed.ok).toBe(true) + } + }) + + it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { + const seq = fixture.journal.cursor().sequence + const removalIds = Array.from( + { length: 30 }, + (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` + ) + const reopened = await reopenWithRawRows( + removalIds.map((itemId, index) => ({ + kind: 'tombstone' as const, + itemId, + revision: 1, + seq: seq + 1 + index + })) + ) + + const seen = new Set() + let cursor = { epoch: reopened.epoch, sequence: seq } + let guard = 0 + while (true) { + guard += 1 + expect(guard).toBeLessThan(30) + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + for (const removed of result.page.removedItemIds) { + seen.add(removed) + } + cursor = result.page.window.nextCursor + if (!result.page.hasNewer) { + break + } + } + expect(seen).toEqual(new Set(removalIds)) + }) + + it('bounds the truncation marker id for a live oversized-id item', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } + ]) + + const tail = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(tail.page.items).toHaveLength(1) + const marker = tail.page.items[0] + expect(marker?.body.kind).toBe('status') + expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + expect(marker?.itemId.length).toBeLessThan(2048) + + const forward = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence: seq }, + limit: 40 + }) + if (!forward.ok) { + throw new Error(`expected a page, got reset ${forward.reset}`) + } + expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + }) +}) + +describe('identity bounding at admission', () => { + it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { + const oversized: AgentJournalItemIdentity = { + provider: 'codex', + threadId: 'thread-1', + turnId: 'T'.repeat(5 * 1024 * 1024), + ordinal: 1 + } + const start = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence } + const appended = await fixture.journal.appendItem(oversized, body('bounded'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(appended.itemId.length).toBeLessThan(2048) + expect(appended.itemId).toContain('~orca-oversized~') + + const beforeTombstone = fixture.journal.cursor() + await fixture.journal.appendTombstone(oversized, { fence: 1 }) + + const created = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + if (!created.ok) { + throw new Error(`expected a page, got reset ${created.reset}`) + } + expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(created.page.removedItemIds).toEqual([appended.itemId]) + + const removal = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: beforeTombstone, + limit: 40 + }) + if (!removal.ok) { + throw new Error(`expected a page, got reset ${removal.reset}`) + } + expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(removal.page.removedItemIds).toEqual([appended.itemId]) + }) + + it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { + const oversized = 'x'.repeat(2 * 1024 * 1024) + const bounded = boundJournalKeyComponent(oversized) + expect(bounded).toBe(boundJournalKeyComponent(oversized)) + expect(boundJournalKeyComponent(bounded)).toBe(bounded) + expect(bounded.length).toBeLessThan(2048) + expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) + expect(boundJournalKeyComponent('short')).toBe('short') + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts index 42bf2fefec6d..8904d93b663e 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts @@ -1,39 +1,8 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - agentJournalSubmissionKey, - boundJournalKeyComponent -} from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import type { - JournalItemRow, - JournalRow, - JournalTombstoneRow -} from '../agent-session-journal/journal-row-schema' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { projectJournalBatch } from './agent-session-journal-batch' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { hostTestMessage } from './structured-agent-session-host-test-data' import { createAgentSessionCatchUpReader, @@ -44,63 +13,14 @@ import { readAgentSessionConversationOutline } from './agent-session-conversatio import { shortenedAgentJournalItem } from './agent-session-item-wire-form' import { firstStructuredChatNamingPrompt } from '../../../shared/structured-chat-naming-eligibility' import { structuredSessionGateFacts } from '../../runtime/orchestration/structured-session-pointer-delivery' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' - -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') -} - -const journals = createTrackedJournalOpener() -let root: string -let clock = 1_000 -let epochs = 0 -let journal: AgentSessionJournal -function tick(): number { - clock += 1 - return clock -} - -function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } -} - -function body(text: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } -} - -async function appendItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) - clock = 1_000 - epochs = 0 - journal = await journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => { - epochs += 1 - return `epoch-${epochs}` - } - }) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + IDENTITY, + appendItems, + body, + item +} from './agent-session-history-contract-test-fixture' describe('resolveHistoryLimit', () => { it('clamps rather than rejecting so a mid-scroll client keeps paging', () => { @@ -115,11 +35,15 @@ describe('resolveHistoryLimit', () => { describe('readAgentSessionHistory', () => { it('refreshes a retained catch-up reader after a same-cursor disk reload', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options) - const view = journal.publicRead() + await fixture.journal.appendItem( + item(0), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + options + ) + const view = fixture.journal.publicRead() expect(view.snapshot.items).toHaveLength(1) - const cursor = journal.cursor() - const read = createAgentSessionCatchUpReader(journal, undefined, view) + const cursor = fixture.journal.cursor() + const read = createAgentSessionCatchUpReader(fixture.journal, undefined, view) const request = { sessionId: IDENTITY.sessionId, direction: 'after' as const, @@ -129,13 +53,12 @@ describe('readAgentSessionHistory', () => { ok: true, page: { items: [{ body: { state: 'running' } }], latestTurn: { turn: { state: 'running' } } } }) - openTestJournalHostDatabase(root) - .db.prepare( - "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" - ) - .run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) - await journal.open() - expect(journal.cursor()).toEqual(cursor) + const { db } = openTestJournalHostDatabase(fixture.root) + db.prepare( + "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" + ).run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) + await fixture.journal.open() + expect(fixture.journal.cursor()).toEqual(cursor) expect(read(request)).toMatchObject({ ok: true, page: { @@ -147,35 +70,35 @@ describe('readAgentSessionHistory', () => { it('serves current detail, outline, naming and mail facts without changing later history', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'u', payloadFingerprint: 'u', body: hostTestMessage('Name this'), fence: 1 }) - const turn = await journal.appendItem( + const turn = await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options ) const replies = { ...options, turnScope: { kind: 'turn' as const, turnItemId: turn.itemId } } - await journal.appendItem(item(1), body('obsolete reply'), replies) - await journal.appendItem(item(2), body('initial reply'), replies) - const warm = journal.snapshot() - await journal.resolveDispatch({ + await fixture.journal.appendItem(item(1), body('obsolete reply'), replies) + await fixture.journal.appendItem(item(2), body('initial reply'), replies) + const warm = fixture.journal.snapshot() + await fixture.journal.resolveDispatch({ clientMessageId: 'u', state: 'accepted', providerIdentity: null, fence: 1 }) - await journal.appendItem(item(2), body('Revised reply'), replies) - await journal.appendTombstone(item(1), { fence: 1 }) - await journal.appendItem( + await fixture.journal.appendItem(item(2), body('Revised reply'), replies) + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'completed' }, options ) - const current = journal.snapshot() + const current = fixture.journal.snapshot() const expected = structuredClone(current) expect(current).not.toBe(warm) const detail = current.items.at(-1)! @@ -189,17 +112,17 @@ describe('readAgentSessionHistory', () => { expect(structuredSessionGateFacts(current.items).turnRunning).toBe(false) expect(current.submissions).toMatchObject([{ clientMessageId: 'u', dispatchState: 'accepted' }]) expect( - readAgentSessionHistory(journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) + readAgentSessionHistory(fixture.journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) ).toMatchObject({ ok: true, page: { items: expected.items, submissions: expected.submissions } }) - expect(journal.snapshot()).toEqual(expected) + expect(fixture.journal.snapshot()).toEqual(expected) }) it('serves the newest page on tail and pages backward from it', async () => { await appendItems(5) - const tail = readAgentSessionHistory(journal, { + const tail = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 2 @@ -210,9 +133,9 @@ describe('readAgentSessionHistory', () => { expect(tail.page.items.map((entry) => entry.body)).toEqual([body('item-4'), body('item-5')]) expect(tail.page.hasOlder).toBe(true) expect(tail.page.hasNewer).toBe(false) - expect(tail.page.liveCursor).toEqual(journal.cursor()) + expect(tail.page.liveCursor).toEqual(fixture.journal.cursor()) - const older = readAgentSessionHistory(journal, { + const older = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: tail.page.window.nextCursor, @@ -227,9 +150,9 @@ describe('readAgentSessionHistory', () => { it('catches a live reader up from its cursor and stops at the limit', async () => { await appendItems(2) - const cursor = journal.cursor() + const cursor = fixture.journal.cursor() await appendItems(5) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor, @@ -245,10 +168,10 @@ describe('readAgentSessionHistory', () => { it('carries tombstones in a forward catch-up page', async () => { await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor @@ -263,26 +186,30 @@ describe('readAgentSessionHistory', () => { it('reports a forward read with no cursor as cursor_ahead rather than serving the tail', async () => { await appendItems(1) expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'after' }) + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after' }) ).toMatchObject({ ok: false, reset: 'cursor_ahead' }) }) it('resets a cursor from a previous epoch', async () => { await appendItems(1) - const stale = journal.cursor() - await journal.rollEpoch('legacy_import', 2) + const stale = fixture.journal.cursor() + await fixture.journal.rollEpoch('legacy_import', 2) for (const direction of ['before', 'after'] as const) { expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction, cursor: stale }) + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction, + cursor: stale + }) ).toMatchObject({ ok: false, reset: 'epoch_changed' }) } }) it('resets a cursor ahead of the journal', async () => { await appendItems(1) - const ahead = { epoch: journal.epoch, sequence: journal.cursor().sequence + 10 } + const ahead = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence + 10 } expect( - readAgentSessionHistory(journal, { + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: ahead @@ -291,13 +218,16 @@ describe('readAgentSessionHistory', () => { }) it('carries the submission for a message on the page', async () => { - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'msg-1', payloadFingerprint: 'a'.repeat(64), body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hi' }] }, fence: 1 }) - const page = readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail' }) + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail' + }) if (!page.ok) { throw new Error(`expected a page, got reset ${page.reset}`) } @@ -309,498 +239,3 @@ describe('readAgentSessionHistory', () => { }) }) }) - -describe('history page byte ceiling', () => { - // Several legal messages exceed the 4 MiB outbound cap. - const LARGE_TEXT = 'x'.repeat(250 * 1024) - - async function appendLargeItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - } - - function pageOf(result: ReturnType) { - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - serializeRemoteRuntimePayload(result.page) - return result.page - } - - it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { - await appendLargeItems(20) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items.length).toBeGreaterThan(0) - expect(tail.hasOlder).toBe(true) - - const seen = tail.items.map((entry) => entry.itemId) - let cursor = tail.window.nextCursor - let hasOlder = tail.hasOlder - let guard = 0 - while (hasOlder) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'before', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasOlder = page.hasOlder - } - expect(new Set(seen).size).toBe(20) - }) - - it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { - const start = { epoch: journal.epoch, sequence: 0 } - await appendLargeItems(20) - - const first = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - ) - expect(first.items.length).toBeGreaterThan(0) - expect(first.hasNewer).toBe(true) - - const seen = first.items.map((entry) => entry.itemId) - let cursor = first.window.nextCursor - let hasNewer = first.hasNewer - let guard = 0 - while (hasNewer) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasNewer = page.hasNewer - } - expect(new Set(seen).size).toBe(20) - }) - - it('sends a single over-budget item shortened and marked, never replaced', async () => { - await journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items).toHaveLength(1) - const sent = tail.items[0] - const text = - sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' - ? sent.body.blocks[0].text - : '' - expect(sent?.shortened).toBe(true) - expect(text.startsWith('1:yyy')).toBe(true) - expect(text.length).toBeLessThan(3 * 1024 * 1024) - }) -}) - -describe('projectJournalBatch', () => { - it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const cursor = journal.cursor() - await journal.appendLifecycleBatch({ - settlementId: 'settlement-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('one'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: item(2), - body: body('two'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - - const page = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 1 - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - expect(page.page.removedItemIds).toHaveLength(1) - expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) - - const tail = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'tail', - limit: 1 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - }) - - it('reports a hole in the row sequence as journal_gap', async () => { - await appendItems(3) - const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) - expect( - projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) - ).toEqual({ ok: false, reset: 'journal_gap' }) - }) - - it('publishes touched items at their current reduced state, not as a delta', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.items).toHaveLength(1) - expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) - expect(projected.batch.cursor).toEqual(journal.cursor()) - }) - - it('lists a tombstoned item as removed', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.removedItemIds).toHaveLength(1) - expect(projected.batch.items).toHaveLength(0) - }) - - it('publishes a mismatched provider echo under its submission slot', async () => { - const message: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'queued follow-up' }] - } - await journal.appendSubmission({ - clientMessageId: 'client-follow-up', - payloadFingerprint: structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body: message } - }), - body: message, - fence: 1 - }) - const cursor = journal.cursor() - await journal.resolveDispatch({ - clientMessageId: 'client-follow-up', - state: 'accepted', - providerIdentity: { - provider: 'codex', - threadId: 'thread-1', - turnId: 'predicted', - ordinal: 0 - }, - fence: 1 - }) - await journal.appendItem( - { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, - message, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const page = readAgentSessionHistory(journal, { - sessionId: IDENTITY.sessionId, - direction: 'after', - cursor - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items).toMatchObject([ - { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } - ]) - expect(page.page.removedItemIds).toEqual([]) - }) -}) - -function serializedPageBytes(value: unknown): number { - return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') -} - -type RawSeedRow = - | Omit - | Omit - -/** Seed raw legacy rows, then reopen to exercise current read bounds. */ -async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { - const full = rows.map( - (row) => - ({ - ...row, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: journal.epoch, - fence: 1, - ts: tick() - }) as JournalRow - ) - await journal.close() - const opened = openTestJournalHostDatabase(root) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of full) { - insertTestJournalRow(opened.db, IDENTITY.sessionId, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) -} - -describe('pre-existing oversized identities', () => { - // Legacy oversized tombstone IDs cannot fit any outbound page. - const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - - it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, - { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } - ]) - - for (const sequence of [seq, seq + 1]) { - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence }, - limit: 40 - }) - expect(result.ok).toBe(false) - if (result.ok) { - throw new Error('expected a reset') - } - expect(result.reset).toBe('cursor_compacted') - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - // Reset replaces client state without sending an unsendable removal ID. - expect(result.page.items).toEqual([]) - const liveCursor = result.page.liveCursor - if (!liveCursor) { - throw new Error('expected a live cursor on the reset page') - } - expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) - - const resumed = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: liveCursor, - limit: 40 - }) - expect(resumed.ok).toBe(true) - } - }) - - it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { - const seq = journal.cursor().sequence - const removalIds = Array.from( - { length: 30 }, - (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` - ) - const reopened = await reopenWithRawRows( - removalIds.map((itemId, index) => ({ - kind: 'tombstone' as const, - itemId, - revision: 1, - seq: seq + 1 + index - })) - ) - - const seen = new Set() - let cursor = { epoch: reopened.epoch, sequence: seq } - let guard = 0 - while (true) { - guard += 1 - expect(guard).toBeLessThan(30) - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - for (const removed of result.page.removedItemIds) { - seen.add(removed) - } - cursor = result.page.window.nextCursor - if (!result.page.hasNewer) { - break - } - } - expect(seen).toEqual(new Set(removalIds)) - }) - - it('bounds the truncation marker id for a live oversized-id item', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } - ]) - - const tail = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'tail', - limit: 40 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(tail.page.items).toHaveLength(1) - const marker = tail.page.items[0] - expect(marker?.body.kind).toBe('status') - expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - expect(marker?.itemId.length).toBeLessThan(2048) - - const forward = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence: seq }, - limit: 40 - }) - if (!forward.ok) { - throw new Error(`expected a page, got reset ${forward.reset}`) - } - expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - }) -}) - -describe('identity bounding at admission', () => { - it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { - const oversized: AgentJournalItemIdentity = { - provider: 'codex', - threadId: 'thread-1', - turnId: 'T'.repeat(5 * 1024 * 1024), - ordinal: 1 - } - const start = { epoch: journal.epoch, sequence: journal.cursor().sequence } - const appended = await journal.appendItem(oversized, body('bounded'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(appended.itemId.length).toBeLessThan(2048) - expect(appended.itemId).toContain('~orca-oversized~') - - const beforeTombstone = journal.cursor() - await journal.appendTombstone(oversized, { fence: 1 }) - - const created = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - if (!created.ok) { - throw new Error(`expected a page, got reset ${created.reset}`) - } - expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(created.page.removedItemIds).toEqual([appended.itemId]) - - const removal = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: beforeTombstone, - limit: 40 - }) - if (!removal.ok) { - throw new Error(`expected a page, got reset ${removal.reset}`) - } - expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(removal.page.removedItemIds).toEqual([appended.itemId]) - }) - - it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { - const oversized = 'x'.repeat(2 * 1024 * 1024) - const bounded = boundJournalKeyComponent(oversized) - expect(bounded).toBe(boundJournalKeyComponent(oversized)) - expect(boundJournalKeyComponent(bounded)).toBe(bounded) - expect(bounded.length).toBeLessThan(2048) - expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) - expect(boundJournalKeyComponent('short')).toBe('short') - }) -}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts index b0e169ce6b7a..cf385869ec38 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts @@ -10,10 +10,8 @@ import type { import type { AgentSessionJournalBatch } from '../../../shared/agent-session-wire' import { isStructuredAgentSessionStopNote } from './structured-agent-session-command-turn' import { findSequenceGap } from '../agent-session-journal/journal-cursor' -import { - isJournalStopOrResumeRow, - type JournalRow -} from '../agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../agent-session-journal/journal-read-row' +import { isJournalStopOrResumeRow } from '../agent-session-journal/journal-row-schema' export type JournalBatchProjection = | { ok: true; batch: AgentSessionJournalBatch } @@ -21,22 +19,34 @@ export type JournalBatchProjection = | { ok: false; reset: 'journal_gap' } export function projectJournalBatch(input: { - rows: readonly JournalRow[] + rows: readonly JournalReadRow[] snapshot: AgentJournalSnapshot afterSequence: number canonicalItemId?: (itemId: string) => string }): JournalBatchProjection { - const gap = findSequenceGap( - input.rows.map((row) => row.seq), - input.afterSequence + 1 - ) - if (gap) { + if ( + input.rows.every((row) => row.kind !== 'outcome') && + findSequenceGap( + input.rows.map((row) => row.seq), + input.afterSequence + 1 + ) + ) { return { ok: false, reset: 'journal_gap' } } const aliases = submissionAliases(input.snapshot.submissions) const touchedItemIds = new Set() const touchedClientMessageIds = new Set() for (const row of input.rows) { + if (row.kind === 'outcome') { + for (const itemId of row.itemIds) { + touchedItemIds.add(input.canonicalItemId?.(itemId) ?? aliases.get(itemId) ?? itemId) + } + for (const clientMessageId of row.submissionIds) { + touchedClientMessageIds.add(clientMessageId) + touchedItemIds.add(agentJournalSubmissionKey(clientMessageId)) + } + continue + } if (row.kind === 'lifecycle-batch') { for (const mutation of row.mutations) { touchedItemIds.add( diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts new file mode 100644 index 000000000000..548fb9143d19 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts @@ -0,0 +1,102 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalTurnLifecycle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' + +export const journals = createTrackedJournalOpener() + +export const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const + +export const turnItemId = agentJournalItemKey(turnIdentity) + +export const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') + +export const noteId = agentJournalItemKey(noteIdentity) + +export const scope = { kind: 'turn', turnItemId } as const + +export const unconfirmed: AgentJournalItemBody = { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), + tone: 'error', + presentation: 'error' +} + +export const ordinary = { kind: 'status', text: 'Cancellation requested.' } + +let root: string + +let journal: AgentSessionJournal + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) + journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: root + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { + const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } + await journal.appendItem( + turnIdentity, + legacy + ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } + : { kind: 'turn', ...lifecycle }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) +} + +export async function note(body: AgentJournalItemBody = unconfirmed) { + await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) +} + +export function readNote() { + return journal.snapshot().items.find((item) => item.itemId === noteId)! +} + +export function rows() { + const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!result.ok) { + throw new Error(result.reset) + } + return result.rows +} + +export const fixture = { + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts new file mode 100644 index 000000000000..e70fb89fa7b2 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts @@ -0,0 +1,138 @@ +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { readAgentSessionHistory } from './agent-session-history-page' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' +import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' + +import { + fixture, + note, + noteId, + ordinary, + rows, + scope, + turn, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' + +it('shrinks the triggering row window without dropping the dependent note', async () => { + await turn('running') + await note() + const held = fixture.journal.cursor() + const large = { + kind: 'message', + role: 'assistant', + blocks: [ + { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } + ] + } as const + for (const clientMessageId of ['large-1', 'large-2']) { + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId }, + { ...large, blocks: [...large.blocks] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await turn('interrupted') + const first = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: held, + limit: 3 + }) + if (!first.ok) { + throw new Error(first.reset) + } + expect(first.page.hasNewer).toBe(true) + const next = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 3 + }) + expect(next).toMatchObject({ + ok: true, + page: { + items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), + window: { nextCursor: fixture.journal.cursor() } + } + }) +}) + +it('refreshes at the exact tip using bounded frames and no durable writes', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const stored = rows() + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'reconnect', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event) + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + expect( + batches.every( + (batch) => + batch.items.length <= 200 && + Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && + batch.cursor.sequence === fixture.journal.cursor().sequence + ) + ).toBe(true) + expect( + batches + .flatMap((batch) => batch.items) + .every( + (item) => + item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure + ) + ).toBe(true) + expect(rows()).toEqual(stored) +}) + +it('refreshes a phone within its frames, in bounded pages', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'phone', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event), + boundedFrames: true + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + for (const event of events) { + expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( + MOBILE_BRIDGE_MAX_FRAME_BYTES + ) + } +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts index 844b1a625b29..35393c9aae3a 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts @@ -1,88 +1,32 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody, - type AgentJournalTurnLifecycle + type AgentJournalItemBody } from '../../../shared/agent-session-journal-types' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - applyJournalRow, - createJournalReducerState, - renderJournalState -} from '../agent-session-journal/journal-reducer' +import { restoreJournal } from '../agent-session-journal/journal-open' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { renderJournalState } from '../agent-session-journal/journal-reducer' import { projectJournalBatch } from './agent-session-journal-batch' import { readAgentSessionHistory } from './agent-session-history-page' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' -import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' -import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' - -const journals = createTrackedJournalOpener() -const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const -const turnItemId = agentJournalItemKey(turnIdentity) -const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') -const noteId = agentJournalItemKey(noteIdentity) -const scope = { kind: 'turn', turnItemId } as const -const unconfirmed: AgentJournalItemBody = { - kind: 'status', - ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), - tone: 'error', - presentation: 'error' -} -const ordinary = { kind: 'status', text: 'Cancellation requested.' } -let root: string -let journal: AgentSessionJournal -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) - journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: root - }) -}) -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { - const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } - await journal.appendItem( - turnIdentity, - legacy - ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } - : { kind: 'turn', ...lifecycle }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) -} -async function note(body: AgentJournalItemBody = unconfirmed) { - await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) -} -function readNote() { - return journal.snapshot().items.find((item) => item.itemId === noteId)! -} -function rows() { - const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!result.ok) { - throw new Error(result.reset) - } - return result.rows -} +import { + fixture, + note, + noteId, + noteIdentity, + ordinary, + readNote, + rows, + scope, + turn, + turnIdentity, + turnItemId, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' it.each([false, true])( 'derives an interrupted turn note without changing any stored row (legacy=%s)', @@ -90,8 +34,8 @@ it.each([false, true])( await turn('running', legacy) await note() const prior = readNote() - const raw = journal.itemBody(noteId) - const held = journal.cursor() + const raw = fixture.journal.itemBody(noteId) + const held = fixture.journal.cursor() await turn('interrupted', legacy) const stored = rows() const projected = readNote() @@ -99,18 +43,19 @@ it.each([false, true])( expect(projected).toEqual({ ...prior, body: ordinary }) expect(projected).not.toBe(prior) expect(readNote()).toBe(projected) - expect(journal.itemBody(noteId)).toBe(raw) + expect(fixture.journal.itemBody(noteId)).toBe(raw) expect(rows()).toEqual(stored) - expect(stored.filter((row) => row.kind === 'item' && row.itemId === noteId)).toHaveLength(1) - const replay = createJournalReducerState('session-1', journal.epoch) - stored.forEach((row) => applyJournalRow(replay, row)) + expect( + stored.filter((row) => row.kind === 'outcome' && row.itemIds.includes(noteId)) + ).toHaveLength(1) + const replay = restoreJournal(openTestJournalHostDatabase(fixture.root).db, 'session-1')!.state expect(replay.items.get(noteId)?.body).toEqual(unconfirmed) expect(renderJournalState(replay).items.find((item) => item.itemId === noteId)?.body).toEqual( ordinary ) const batch = projectJournalBatch({ rows: stored.filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -133,7 +78,7 @@ it.each(['running', 'completed', 'unverifiable', 'missing'] as const)( await turn(state) } await note() - expect(readNote().body).toBe(journal.itemBody(noteId)) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) expect(readNote().body).toEqual(unconfirmed) } ) @@ -145,20 +90,23 @@ it('leaves unrelated failures and non-Stop notes unchanged', async () => { ...agentSessionFailureWords(agentSessionFailureFact('providerExited'), { surface: 'row' }) } await note(failed) - await journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { + await fixture.journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { fence: 1, turnScope: scope }) - expect(readNote().body).toBe(journal.itemBody(noteId)) - expect(journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) + expect(fixture.journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) }) it('derives the op-keyed note after the retained association write re-keys it onto the turn', async () => { const op = structuredAgentSessionStopNoteIdentity('operation-1') - await journal.appendItem(op, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await fixture.journal.appendItem(op, unconfirmed, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) await turn('running') - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'stop-note-on-turn', fence: 1, mutations: [ @@ -168,17 +116,17 @@ it('derives the op-keyed note after the retained association write re-keys it on }) await turn('interrupted') expect(readNote().body).toEqual(ordinary) - expect(journal.itemBody(noteId)).toEqual(unconfirmed) + expect(fixture.journal.itemBody(noteId)).toEqual(unconfirmed) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ ok: true, batch: { removedItemIds: [agentJournalItemKey(op)] } }) }) it('keeps an operation note unconfirmed when no turn opened before the kill failed', async () => { - await journal.appendItem(noteIdentity, unconfirmed, { + await fixture.journal.appendItem(noteIdentity, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) @@ -189,8 +137,8 @@ it('keeps an operation note unconfirmed when no turn opened before the kill fail it('re-emits the note for lifecycle turn mutations and restores the raw wording for a turn tombstone', async () => { await turn('running') await note() - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'ended', fence: 1, mutations: [ @@ -204,7 +152,7 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording }) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -216,15 +164,15 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording ] } }) - const ended = journal.cursor() - await journal.appendLifecycleBatch({ + const ended = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'removed', fence: 1, mutations: [{ kind: 'tombstone', identity: turnIdentity }] }) const removed = projectJournalBatch({ rows: rows().filter((row) => row.seq > ended.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: ended.sequence }) expect(removed).toMatchObject({ @@ -239,9 +187,9 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording it('pages the end with its earlier note and advances by the consumed end row', async () => { await turn('running') await note() - const held = journal.cursor() + const held = fixture.journal.cursor() await turn('interrupted') - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -254,11 +202,11 @@ it('pages the end with its earlier note and advances by the consumed end row', a expect.objectContaining({ itemId: turnItemId }), expect.objectContaining({ itemId: noteId, body: ordinary }) ], - window: { nextCursor: journal.cursor() }, + window: { nextCursor: fixture.journal.cursor() }, hasNewer: false } }) - const notePage = readAgentSessionHistory(journal, { + const notePage = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 1 @@ -271,9 +219,9 @@ it('pages the end with its earlier note and advances by the consumed end row', a it('derives a note page with its ended turn on an earlier page, in either paging direction', async () => { await turn('interrupted') - const held = journal.cursor() + const held = fixture.journal.cursor() await note() - const forward = readAgentSessionHistory(journal, { + const forward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -283,18 +231,18 @@ it('derives a note page with its ended turn on an earlier page, in either paging ok: true, page: { items: [expect.objectContaining({ itemId: noteId, body: ordinary })], - window: { nextCursor: journal.cursor() } + window: { nextCursor: fixture.journal.cursor() } } }) - await journal.appendItem( + await fixture.journal.appendItem( { provider: 'orca', clientMessageId: 'later' }, { kind: 'status', text: 'Later' }, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - const backward = readAgentSessionHistory(journal, { + const backward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', - cursor: journal.cursor(), + cursor: fixture.journal.cursor(), limit: 1 }) expect(backward).toMatchObject({ @@ -305,114 +253,3 @@ it('derives a note page with its ended turn on an earlier page, in either paging } }) }) - -it('shrinks the triggering row window without dropping the dependent note', async () => { - await turn('running') - await note() - const held = journal.cursor() - const large = { - kind: 'message', - role: 'assistant', - blocks: [ - { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } - ] - } as const - for (const clientMessageId of ['large-1', 'large-2']) { - await journal.appendItem( - { provider: 'orca', clientMessageId }, - { ...large, blocks: [...large.blocks] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await turn('interrupted') - const first = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: held, - limit: 3 - }) - if (!first.ok) { - throw new Error(first.reset) - } - expect(first.page.hasNewer).toBe(true) - const next = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: first.page.window.nextCursor, - limit: 3 - }) - expect(next).toMatchObject({ - ok: true, - page: { - items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), - window: { nextCursor: journal.cursor() } - } - }) -}) - -it('refreshes at the exact tip using bounded frames and no durable writes', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const stored = rows() - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'reconnect', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - expect( - batches.every( - (batch) => - batch.items.length <= 200 && - Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && - batch.cursor.sequence === journal.cursor().sequence - ) - ).toBe(true) - expect( - batches - .flatMap((batch) => batch.items) - .every( - (item) => - item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure - ) - ).toBe(true) - expect(rows()).toEqual(stored) -}) - -it('refreshes a phone within its frames, in bounded pages', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'phone', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event), - boundedFrames: true - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - for (const event of events) { - expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( - MOBILE_BRIDGE_MAX_FRAME_BYTES - ) - } -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts index 44ffbe9b9268..5117fe2f054b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts @@ -15,7 +15,7 @@ export type PromptProjection = { } export function reusePromptProjection( - journal: Partial>, + journal: Partial>, prior: PromptProjection | undefined, cursor: Pick, liveFence: number | null @@ -35,16 +35,24 @@ export function reusePromptProjection( prior.dependencies.has(change.itemId) || (change.kind === 'item' && (change.body.kind === 'approval' || change.body.kind === 'question')) + const outcomeTouches = (itemId: string): boolean => { + if (!journal.item || prior.dependencies.has(itemId)) { + return true + } + const body = journal.item(itemId)?.body + return body?.kind === 'approval' || body?.kind === 'question' + } if ( delta.ok && delta.cursor.sequence === cursor.sequence && delta.rows.at(-1)?.seq === cursor.sequence && - delta.rows.every( - (row, index) => - row.seq === prior.sequence + index + 1 && - (row.kind === 'lifecycle-batch' - ? !row.mutations.some(touches) - : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) + delta.rows.every((row, index) => + row.kind === 'outcome' + ? row.submissionIds.length === 0 && !row.itemIds.some(outcomeTouches) + : row.seq === prior.sequence + index + 1 && + (row.kind === 'lifecycle-batch' + ? !row.mutations.some(touches) + : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) ) ) { prior.sequence = cursor.sequence diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts index 1b6082b1efb0..fdec1d981d3f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts @@ -256,7 +256,9 @@ describe('an open chat receives each row once', () => { epoch: row.epoch, sequence: row.seq, kind: row.kind, - itemId: 'itemId' in row ? row.itemId : null + // A new chat saves outcomes, whose change index names the items each sequence wrote. + itemId: + row.kind === 'outcome' ? row.itemIds.join() : 'itemId' in row ? row.itemId : null })) : [] }) @@ -285,7 +287,7 @@ describe('an open chat receives each row once', () => { { epoch: committedCursor.epoch, sequence: committedCursor.sequence, - kind: 'item', + kind: 'outcome', itemId: 'orca:streamed' } ] diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts new file mode 100644 index 000000000000..6e8495326656 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts @@ -0,0 +1,214 @@ +import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' +import { expect, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' +import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' +import { + claudeFrame as frame, + claudeWasSent as wrote, + type FakeConnection +} from '../../claude/claude-structured-session-test-support' +import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + CAPABILITIES, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +export function eventually(assertion: () => T | Promise): Promise { + return vi.waitFor(assertion, { timeout: 10_000 }) +} + +export function envelope( + method: 'agentSession.send' | 'agentSession.cancel', + fields: Record, + fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence +) { + return { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method, + sessionId: SESSION, + fields + }) + } +} + +export async function send(text: string, fence?: number): Promise { + const body = hostTestMessage(text) + const sent = await fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body }, fence), + body + }) + if (!sent.ok) { + throw new Error('send refused') + } + return sent.value.clientMessageId +} + +export async function dispatch(clientMessageId: string) { + const submission = (await fixture.host.journalSnapshot(SESSION)).submissions.find( + (entry) => entry.clientMessageId === clientMessageId + ) + return { state: submission?.dispatchState, reason: submission?.reason } +} + +export async function openTurn( + connection: FakeConnection, + text = 'Write a long reply.' +): Promise { + const clientMessageId = await send(text) + await eventually(() => + expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) + ) + frame(connection, { + type: 'system', + subtype: 'init', + uuid: `init-${text}`, + model: 'claude-sonnet-5', + capabilities: CAPABILITIES + }) + const written = connection.sent.at(-1)! + frame(connection, { ...written, uuid: written.uuid }) + frame(connection, { + type: 'assistant', + uuid: 'stopped-turn-leaf', + parent_tool_use_id: null, + message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } + }) + await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) + const turnId = activeStructuredAgentSessionTurnId( + (await fixture.host.journalSnapshot(SESSION)).items + ) + expect(turnId).not.toBeNull() + return turnId! +} + +export function stop(turnId?: string) { + const fields = turnId === undefined ? {} : { turnId } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +/** Drain through Stop’s queued second step. */ + +export function stopEventsAtClose(connection: FakeConnection): () => number | undefined { + let atClose: number | undefined + const close = connection.close + connection.close = async () => { + const journal = fixture.host.collaboratorsForTests().sessions.get(SESSION)?.journal + atClose ??= journal?.stopMarks.latest()?.event.reason === 'user-stop' ? 1 : 0 + return close() + } + return () => atClose +} + +export async function interruptSent(connection: FakeConnection): Promise { + await eventually(() => + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + ) +} + +export async function turnOutcome(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const snapshot = await fixture.host.journalSnapshot(SESSION) + return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) + ?.outcome +} + +export async function statusTexts(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + return (await fixture.host.journalSnapshot(SESSION)).items.flatMap((item) => + item.body.kind === 'status' ? [String(item.body.text)] : [] + ) +} + +export async function sendUnechoed(connection: FakeConnection): Promise { + const clientMessageId = await send('Write a long reply.') + await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) + return clientMessageId +} + +export function childRecords() { + return fixture.statusSubject + ? fixture.server.getStructuredChildWorkViews(fixture.statusSubject) + : [] +} + +export async function agentStatus() { + await fixture.host.flushStreamedEvents(SESSION) + const { items, submissions } = await fixture.host.journalSnapshot(SESSION) + const { summary } = projectStructuredAgentSessionStatusState( + items, + submissions, + fixture.store.getRecord(SESSION)!.lease.runtimeFence + ) + return summary.status + ? structuredAgentSessionAgentStatus({ + status: summary.status, + turnOutcome: summary.turnOutcome, + childWork: childRecords() + }) + : null +} + +export async function ask( + connection: FakeConnection, + toolName: string, + input: Record, + signal?: AbortSignal +): Promise<{ + answered: ReturnType + card: { itemId: string; expectedRevision: number } +}> { + const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { + input, + ...(signal ? { signal } : {}) + }) + const card = await eventually(async () => { + await fixture.host.flushStreamedEvents(SESSION) + const item = (await fixture.host.journalSnapshot(SESSION)).items.find( + (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' + ) + expect(item).toBeDefined() + return { itemId: item!.itemId, expectedRevision: item!.revision } + }) + return { answered, card } +} + +export function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { + const fields = { turnId, prompt } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +export async function cardResolution(itemId: string): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const body = (await fixture.host.journalSnapshot(SESSION)).items.find( + (item) => item.itemId === itemId + )?.body + return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined +} + +export const stopAcrossGrace = createStoppedClaudeDeadline({ + host: () => fixture.host, + adapter: () => fixture.adapter, + claude: () => fixture.claude, + sessionId: SESSION, + stop, + laneDrained +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts new file mode 100644 index 000000000000..6bc9368546a5 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -0,0 +1,235 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' +import { AgentHookServer } from '../../agent-hooks/server' +import { runClaudeControl } from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' +import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' +import { + fakeClaude, + PROVIDER_SESSION_ID +} from '../../claude/claude-structured-session-test-support' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + hostTestAttachParams, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' + +export const CALLER = { callerKey: 'client-1' } +// Claude Code 2.1.280 system/init capabilities. + +export const CAPABILITIES = [ + 'interrupt_receipt_v1', + 'interrupt_cancel_queued_v1', + 'msg_lifecycle_v1' +] + +let root: string + +let host: StructuredAgentSessionHost + +let adapter: ClaudeStructuredSessionAdapter + +let store: AgentSessionRecordStore + +let queued: string[] + +let claude: ReturnType + +let events: ClaudeStructuredSessionEvent[] + +let logs: ReturnType + +let server: AgentHookServer + +let statusSubject: AgentStatusStructuredSessionSubject | undefined + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) + resetHostTestOperationIds() + queued = [] + events = [] + logs = recordingStructuredAgentSessionLogger() + server = new AgentHookServer() + statusSubject = undefined + claude = fakeClaude({ + replayUuid: null, + routes: { + interrupt: (params) => + params?.cancelQueued + ? { still_queued: [], cancelled: queued.splice(0) } + : { still_queued: [...queued] } + } + }) + const lifecycle: Promise[] = [] + adapter = new ClaudeStructuredSessionAdapter({ + resolveLaunch: async () => ({ + pathToClaudeCodeExecutable: 'claude', + options: {}, + cwd: root, + claudeConfigDir: join(root, 'claude-home'), + providerSessionId: PROVIDER_SESSION_ID, + resumeLeafUuid: null, + resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, + cliFlag: async () => 'supported' as const, + continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 + }), + onEvent: (event) => { + events.push(event) + const mapped = structuredClaudeLifecycleEvent(event) + if (mapped) { + lifecycle.push(host.handleAdapterEvent(mapped)) + } + }, + onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), + onChildWorkEvidence: (sessionId, evidence) => + host.publishChildWorkEvidence(sessionId, evidence), + openConnection: claude.openConnection, + readProcessStartTime: async () => 1_700_000_000_000, + now: () => NOW + }) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + store, + adapter: Object.assign(adapter, { supportsCreate: () => true }), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + logger: logs.logger, + statusSink: { + publish: (summary, subject) => { + statusSubject = subject + server.ingestStructuredStatus(summary, subject) + }, + forget: (subject) => server.dropStructuredStatus(subject), + publishChildWork: (subject, evidence, provider) => + server.ingestStructuredChildWork(subject, evidence, provider), + readChildWork: (subject) => server.getStructuredChildWorkViews(subject) + }, + now: () => NOW + }) + const params = hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, + providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } + }) + expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) + await Promise.all(lifecycle) +}) + +afterEach(async () => { + vi.restoreAllMocks() + vi.useRealTimers() + await adapter.closeAll() + await host.flushAllStreamedEvents() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) + +export const INTERRUPTED_RESULT = { + type: 'result', + subtype: 'error_during_execution', + is_error: true, + terminal_reason: 'aborted_streaming', + uuid: 'interrupted-result' +} + +// Exercise the real control deadline with a request that never answers. + +export const NEVER_ANSWERS = (options?: Record) => + runClaudeControl( + 'interrupt', + () => new Promise(() => {}), + typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined + ) + +export const BRANCH_QUESTION = { + questions: [ + { + question: 'Which branch?', + header: 'Branch', + multiSelect: false, + options: [{ label: 'main' }, { label: 'dev' }] + } + ] +} +export const fixture = { + get adapter() { + return adapter + }, + set adapter(value: typeof adapter) { + adapter = value + }, + get claude() { + return claude + }, + set claude(value: typeof claude) { + claude = value + }, + get events() { + return events + }, + set events(value: typeof events) { + events = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get logs() { + return logs + }, + set logs(value: typeof logs) { + logs = value + }, + get queued() { + return queued + }, + set queued(value: typeof queued) { + queued = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get server() { + return server + }, + set server(value: typeof server) { + server = value + }, + get statusSubject() { + return statusSubject + }, + set statusSubject(value: typeof statusSubject) { + statusSubject = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts index 4f2e44787801..84bcd596134a 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts @@ -1,289 +1,38 @@ -// Claude Stop answers the interrupt before serialized child shutdown; next send resumes the resting conversation. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { expect, it } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' -import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' -import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' -import { AgentHookServer } from '../../agent-hooks/server' -import { - ClaudeControlRequestError, - runClaudeControl -} from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeControlRequestError } from '../../claude/claude-agent-sdk-control-requests' import { CLAUDE_STOP_GRACE_MS } from '../../claude/claude-request-end-wait' -import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' import { claudeFrame as frame, claudeWasSent as wrote, - fakeClaude, - PROVIDER_SESSION_ID, - type FakeConnection + PROVIDER_SESSION_ID } from '../../claude/claude-structured-session-test-support' -import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { StructuredAgentSessionHost } from './structured-agent-session-host' -import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' -import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' + fixture, + INTERRUPTED_RESULT, + NEVER_ANSWERS, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' import { - HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' - -const CALLER = { callerKey: 'client-1' } -// Claude Code 2.1.280 system/init capabilities. -const CAPABILITIES = ['interrupt_receipt_v1', 'interrupt_cancel_queued_v1', 'msg_lifecycle_v1'] - -let root: string -let host: StructuredAgentSessionHost -let adapter: ClaudeStructuredSessionAdapter -let store: AgentSessionRecordStore -let queued: string[] -let claude: ReturnType -let events: ClaudeStructuredSessionEvent[] -let logs: ReturnType -let server: AgentHookServer -let statusSubject: AgentStatusStructuredSessionSubject | undefined - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) - resetHostTestOperationIds() - queued = [] - events = [] - logs = recordingStructuredAgentSessionLogger() - server = new AgentHookServer() - statusSubject = undefined - claude = fakeClaude({ - replayUuid: null, - routes: { - interrupt: (params) => - params?.cancelQueued - ? { still_queued: [], cancelled: queued.splice(0) } - : { still_queued: [...queued] } - } - }) - const lifecycle: Promise[] = [] - adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: root, - claudeConfigDir: join(root, 'claude-home'), - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, - cliFlag: async () => 'supported' as const, - continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 - }), - onEvent: (event) => { - events.push(event) - const mapped = structuredClaudeLifecycleEvent(event) - if (mapped) { - lifecycle.push(host.handleAdapterEvent(mapped)) - } - }, - onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), - onChildWorkEvidence: (sessionId, evidence) => - host.publishChildWorkEvidence(sessionId, evidence), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now: () => NOW - }) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - store, - adapter: Object.assign(adapter, { supportsCreate: () => true }), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - logger: logs.logger, - statusSink: { - publish: (summary, subject) => { - statusSubject = subject - server.ingestStructuredStatus(summary, subject) - }, - forget: (subject) => server.dropStructuredStatus(subject), - publishChildWork: (subject, evidence, provider) => - server.ingestStructuredChildWork(subject, evidence, provider), - readChildWork: (subject) => server.getStructuredChildWorkViews(subject) - }, - now: () => NOW - }) - const params = hostTestAttachParams(null, { - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, - providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) - await Promise.all(lifecycle) -}) - -afterEach(async () => { - vi.restoreAllMocks() - vi.useRealTimers() - await adapter.closeAll() - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -function eventually(assertion: () => T | Promise): Promise { - return vi.waitFor(assertion, { timeout: 10_000 }) -} - -function envelope( - method: 'agentSession.send' | 'agentSession.cancel', - fields: Record, - fence = store.getRecord(SESSION)!.lease.runtimeFence -) { - return { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method, - sessionId: SESSION, - fields - }) - } -} - -async function send(text: string, fence?: number): Promise { - const body = hostTestMessage(text) - const sent = await host.send(CALLER, { - envelope: envelope('agentSession.send', { body }, fence), - body - }) - if (!sent.ok) { - throw new Error('send refused') - } - return sent.value.clientMessageId -} - -async function dispatch(clientMessageId: string) { - const submission = (await host.journalSnapshot(SESSION)).submissions.find( - (entry) => entry.clientMessageId === clientMessageId - ) - return { state: submission?.dispatchState, reason: submission?.reason } -} - -async function openTurn(connection: FakeConnection, text = 'Write a long reply.'): Promise { - const clientMessageId = await send(text) - await eventually(() => - expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) - ) - frame(connection, { - type: 'system', - subtype: 'init', - uuid: `init-${text}`, - model: 'claude-sonnet-5', - capabilities: CAPABILITIES - }) - const written = connection.sent.at(-1)! - frame(connection, { ...written, uuid: written.uuid }) - frame(connection, { - type: 'assistant', - uuid: 'stopped-turn-leaf', - parent_tool_use_id: null, - message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } - }) - await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) - const turnId = activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - expect(turnId).not.toBeNull() - return turnId! -} - -function stop(turnId?: string) { - const fields = turnId === undefined ? {} : { turnId } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -/** Drain through Stop’s queued second step. */ -const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) - -const stopAcrossGrace = createStoppedClaudeDeadline({ - host: () => host, - adapter: () => adapter, - claude: () => claude, - sessionId: SESSION, + agentStatus, + childRecords, + dispatch, + eventually, + interruptSent, + openTurn, + send, + sendUnechoed, + statusTexts, stop, - laneDrained -}) - -function stopEventsAtClose(connection: FakeConnection): () => number | undefined { - let atClose: number | undefined - const close = connection.close - connection.close = async () => { - const journal = host.collaboratorsForTests().sessions.get(SESSION)?.journal - const since = journal?.readSince({ epoch: journal.epoch, sequence: 0 }) - atClose ??= since?.ok - ? since.rows.filter( - (row) => row.kind === 'tombstone' && row.stopEvent?.reason === 'user-stop' - ).length - : -1 - return close() - } - return () => atClose -} - -const INTERRUPTED_RESULT = { - type: 'result', - subtype: 'error_during_execution', - is_error: true, - terminal_reason: 'aborted_streaming', - uuid: 'interrupted-result' -} - -// Exercise the real control deadline with a request that never answers. -const NEVER_ANSWERS = (options?: Record) => - runClaudeControl( - 'interrupt', - () => new Promise(() => {}), - typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined - ) - -async function interruptSent(connection: FakeConnection): Promise { - await eventually(() => - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - ) -} - -async function turnOutcome(): Promise { - await host.flushStreamedEvents(SESSION) - const snapshot = await host.journalSnapshot(SESSION) - return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) - ?.outcome -} - -async function statusTexts(): Promise { - await host.flushStreamedEvents(SESSION) - return (await host.journalSnapshot(SESSION)).items.flatMap((item) => - item.body.kind === 'status' ? [String(item.body.text)] : [] - ) -} + stopEventsAtClose, + turnOutcome, + stopAcrossGrace +} from './structured-agent-session-claude-stop-contract-test-actions' it('answers on the interrupt, ends the child once the stopped turn ends, and rests at that turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -297,47 +46,20 @@ it('answers on the interrupt, ends the child once the stopped turn ends, and res expect(connection.closed).toBe(true) expect(eventsAtClose()).toBe(1) - expect(store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + expect(fixture.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') expect(await turnOutcome()).toBe('cancellation') // Resume must use the stopped turn’s own leaf. - expect(events.findLast((event) => event.type === 'handle')).toMatchObject({ + expect(fixture.events.findLast((event) => event.type === 'handle')).toMatchObject({ type: 'handle', providerSessionId: PROVIDER_SESSION_ID, leafUuid: 'stopped-turn-leaf' }) }) -async function sendUnechoed(connection: FakeConnection): Promise { - const clientMessageId = await send('Write a long reply.') - await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) - return clientMessageId -} - -function childRecords() { - return statusSubject ? server.getStructuredChildWorkViews(statusSubject) : [] -} - -async function agentStatus() { - await host.flushStreamedEvents(SESSION) - const { items, submissions } = await host.journalSnapshot(SESSION) - const { summary } = projectStructuredAgentSessionStatusState( - items, - submissions, - store.getRecord(SESSION)!.lease.runtimeFence - ) - return summary.status - ? structuredAgentSessionAgentStatus({ - status: summary.status, - turnOutcome: summary.turnOutcome, - childWork: childRecords() - }) - : null -} - it('reads a Stop pressed before Claude echoed the send as interrupted, not as a finished turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! // Match CLI wind-down ordering after an interrupt before echo. - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { setTimeout(() => { const written = connection.sent.find((message) => message.type === 'user')! frame(connection, { ...written, uuid: written.uuid }) @@ -367,9 +89,9 @@ it('reads a Stop pressed before Claude echoed the send as interrupted, not as a }) it('ends the child once the grace runs out when Claude says nothing after a Stop before the echo', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) - claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) + fixture.claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) const clientMessageId = await sendUnechoed(connection) await expect(stopAcrossGrace(connection, 'request-end')).resolves.toMatchObject({ @@ -384,11 +106,11 @@ it('ends the child once the grace runs out when Claude says nothing after a Stop }, 15_000) it('withdraws a follow-up Claude queued behind the turn before the child ends, never doubt', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) const followUp = await send('And then this.') await eventually(() => expect(connection.sent.at(-1)?.message).toBeDefined()) - queued.push(String(connection.sent.at(-1)!.uuid)) + fixture.queued.push(String(connection.sent.at(-1)!.uuid)) await eventually(async () => expect((await dispatch(followUp)).state).toBe('pending')) await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) @@ -404,10 +126,10 @@ it('withdraws a follow-up Claude queued behind the turn before the child ends, n }) it('ends the child at once when Claude refuses the interrupt, and says only that the stop was asked', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new ClaudeControlRequestError('interrupt', 'Claude did not answer the interrupt.') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -426,10 +148,10 @@ it('ends the child at once when Claude refuses the interrupt, and says only that }) it('ends the child when the interrupt fails, with no unconfirmed row', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new Error('control request lost') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -443,8 +165,8 @@ it('ends the child when the interrupt fails, with no unconfirmed row', async () }) it('ends the child within the grace when Claude never answers the interrupt', async () => { - claude.routes.interrupt = NEVER_ANSWERS - const connection = claude.connections[0]! + fixture.claude.routes.interrupt = NEVER_ANSWERS + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -461,7 +183,7 @@ it('ends the child within the grace when Claude never answers the interrupt', as }, 15_000) it('ends background work Claude runs when the Stop ends the child', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) frame(connection, { type: 'system', @@ -496,7 +218,7 @@ it('ends background work Claude runs when the Stop ends the child', async () => }) it('starts a new child for the next send after a Stop, on the same Claude conversation', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) await stop() frame(connection, INTERRUPTED_RESULT) @@ -504,12 +226,12 @@ it('starts a new child for the next send after a Stop, on the same Claude conver const next = await send('Carry on.') const resumed = await eventually(() => { - const started = claude.connections.at(-1) + const started = fixture.claude.connections.at(-1) expect(started).not.toBe(connection) expect(started && wrote(started, 'Carry on.')).toBe(true) return started! }) - expect(store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ + expect(fixture.store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ nativeId: PROVIDER_SESSION_ID }) expect(resumed.closed).toBe(false) @@ -517,19 +239,19 @@ it('starts a new child for the next send after a Stop, on the same Claude conver }) it('delivers a send issued with the pre-Stop fence during the Stop to the resumed child only', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence let childrenWhenClosed: number | undefined const close = connection.close connection.close = async () => { const proven = await close() - childrenWhenClosed = claude.connections.length + childrenWhenClosed = fixture.claude.connections.length return proven } let answer!: () => void - claude.routes.interrupt = () => + fixture.claude.routes.interrupt = () => new Promise((resolve) => { answer = () => resolve({ still_queued: [], cancelled: [] }) }) @@ -544,7 +266,7 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume await expect(sent).resolves.toEqual(expect.any(String)) const resumed = await eventually(() => { - const started = claude.connections.at(-1)! + const started = fixture.claude.connections.at(-1)! expect(started).not.toBe(connection) expect(wrote(started, 'Typed during the Stop.')).toBe(true) return started @@ -552,321 +274,6 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume expect(childrenWhenClosed).toBe(1) expect(resumed.closed).toBe(false) expect(wrote(connection, 'Typed during the Stop.')).toBe(false) - expect(store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) + expect(fixture.store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) expect((await statusTexts()).filter((text) => text !== 'Cancellation requested.')).toEqual([]) }) - -it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence - let childrenWhenClosed: number | undefined - const close = connection.close - connection.close = async () => { - const proven = await close() - childrenWhenClosed = claude.connections.length - return proven - } - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - // Issue under the old fence while Stop’s second step awaits turn end. - const body = hostTestMessage('Queued during the Stop.') - const sent = host.send(CALLER, { - envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), - body, - delivery: 'queue-if-active' - }) - frame(connection, INTERRUPTED_RESULT) - - expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Queued during the Stop.')).toBe(true) - }) - expect(childrenWhenClosed).toBe(1) - expect(wrote(connection, 'Queued during the Stop.')).toBe(false) -}) - -it("runs nothing queued during the Stop's first step before the child's end", async () => { - const connection = claude.connections[0]! - await openTurn(connection) - let answer!: () => void - claude.routes.interrupt = () => - new Promise((resolve) => { - answer = () => resolve({ still_queued: [], cancelled: [] }) - }) - - const stopped = stop() - await interruptSent(connection) - let childLiveForNextOperation: boolean | undefined - const next = host['tasks'].serialize(SESSION, async () => { - childLiveForNextOperation = !connection.closed - }) - answer() - await stopped - frame(connection, INTERRUPTED_RESULT) - await next - - expect(childLiveForNextOperation).toBe(false) -}) - -it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const close = connection.close - connection.close = async () => false - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([ - expect.objectContaining({ - fields: expect.objectContaining({ - scope: 'chat-stop', - error: expect.objectContaining({ - name: 'StructuredAgentSessionEvictionError', - step: 'stop-provider-child' - }) - }) - }) - ]) - connection.close = close -}) - -it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - await send('Follow-up.') - await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) - - await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - await laneDrained() - - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}, 15_000) - -it('keeps a second Stop pressed while the first ends the child quiet', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - const second = stop() - frame(connection, INTERRUPTED_RESULT) - - await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - expect(connection.closed).toBe(true) - expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([]) -}) - -const BRANCH_QUESTION = { - questions: [ - { - question: 'Which branch?', - header: 'Branch', - multiSelect: false, - options: [{ label: 'main' }, { label: 'dev' }] - } - ] -} - -async function ask( - connection: FakeConnection, - toolName: string, - input: Record, - signal?: AbortSignal -): Promise<{ - answered: ReturnType - card: { itemId: string; expectedRevision: number } -}> { - const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { - input, - ...(signal ? { signal } : {}) - }) - const card = await eventually(async () => { - await host.flushStreamedEvents(SESSION) - const item = (await host.journalSnapshot(SESSION)).items.find( - (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' - ) - expect(item).toBeDefined() - return { itemId: item!.itemId, expectedRevision: item!.revision } - }) - return { answered, card } -} - -function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { - const fields = { turnId, prompt } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -async function cardResolution(itemId: string): Promise { - await host.flushStreamedEvents(SESSION) - const body = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.itemId === itemId - )?.body - return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined -} - -it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) - expect(reply).not.toHaveProperty('interrupt') - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - turnId - ) - expect(await statusTexts()).toEqual([]) -}) - -it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { - const connection = claude.connections[0]! - const eventsAtClose = stopEventsAtClose(connection) - const turnId = await openTurn(connection) - const request = new AbortController() - const { answered, card } = await ask( - connection, - 'AskUserQuestion', - BRANCH_QUESTION, - request.signal - ) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - request.abort() - await host.flushStreamedEvents(SESSION) - // Prompt cancellation must land before child exit so answers are already disabled. - expect(connection.closed).toBe(false) - const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(connection.closed).toBe(true) - expect(eventsAtClose()).toBe(1) - expect(await turnOutcome()).toBe('cancellation') - expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - await send('Carry on.') - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Carry on.')).toBe(true) - }) -}) - -it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - - await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ - behavior: 'deny', - message: expect.stringMatching(/dismissed/) - }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}) - -it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { - const connection = claude.connections[0]! - const earlier = await openTurn(connection) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const running = await openTurn(connection, 'Now something else.') - expect(running).not.toBe(earlier) - - await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ behavior: 'deny' }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - running - ) -}) - -it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'ExitPlanMode', { - plan: '# Release\n\n- Tag it' - }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny' }) - expect(reply).not.toHaveProperty('interrupt') - expect(JSON.stringify(reply)).toMatch(/wait for them/) - expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - const cards = (await host.journalSnapshot(SESSION)).items.filter( - (item) => item.body.kind === 'approval' - ) - expect(cards).toHaveLength(1) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(await statusTexts()).toEqual([]) -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts new file mode 100644 index 000000000000..7f69b287d787 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts @@ -0,0 +1,46 @@ +import { expect, it } from 'vitest' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + openTurn, + statusTexts +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'ExitPlanMode', { + plan: '# Release\n\n- Tag it' + }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny' }) + expect(reply).not.toHaveProperty('interrupt') + expect(JSON.stringify(reply)).toMatch(/wait for them/) + expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + const cards = (await fixture.host.journalSnapshot(SESSION)).items.filter( + (item) => item.body.kind === 'approval' + ) + expect(cards).toHaveLength(1) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(await statusTexts()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts new file mode 100644 index 000000000000..d44134cb7005 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts @@ -0,0 +1,268 @@ +import { expect, it } from 'vitest' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { + claudeFrame as frame, + claudeWasSent as wrote +} from '../../claude/claude-structured-session-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage +} from './structured-agent-session-host-test-data' + +import { + fixture, + BRANCH_QUESTION, + CALLER, + INTERRUPTED_RESULT, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + envelope, + eventually, + interruptSent, + openTurn, + send, + statusTexts, + stop, + stopEventsAtClose, + turnOutcome +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence + let childrenWhenClosed: number | undefined + const close = connection.close + connection.close = async () => { + const proven = await close() + childrenWhenClosed = fixture.claude.connections.length + return proven + } + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + // Issue under the old fence while Stop’s second step awaits turn end. + const body = hostTestMessage('Queued during the Stop.') + const sent = fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), + body, + delivery: 'queue-if-active' + }) + frame(connection, INTERRUPTED_RESULT) + + expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Queued during the Stop.')).toBe(true) + }) + expect(childrenWhenClosed).toBe(1) + expect(wrote(connection, 'Queued during the Stop.')).toBe(false) +}) + +it("runs nothing queued during the Stop's first step before the child's end", async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + let answer!: () => void + fixture.claude.routes.interrupt = () => + new Promise((resolve) => { + answer = () => resolve({ still_queued: [], cancelled: [] }) + }) + + const stopped = stop() + await interruptSent(connection) + let childLiveForNextOperation: boolean | undefined + const next = fixture.host['tasks'].serialize(SESSION, async () => { + childLiveForNextOperation = !connection.closed + }) + answer() + await stopped + frame(connection, INTERRUPTED_RESULT) + await next + + expect(childLiveForNextOperation).toBe(false) +}) + +it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const close = connection.close + connection.close = async () => false + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([ + expect.objectContaining({ + fields: expect.objectContaining({ + scope: 'chat-stop', + error: expect.objectContaining({ + name: 'StructuredAgentSessionEvictionError', + step: 'stop-provider-child' + }) + }) + }) + ]) + connection.close = close +}) + +it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + await send('Follow-up.') + await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) + + await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + await laneDrained() + + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('keeps a second Stop pressed while the first ends the child quiet', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + const second = stop() + frame(connection, INTERRUPTED_RESULT) + + await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + expect(connection.closed).toBe(true) + expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([]) +}) + +it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) + expect(reply).not.toHaveProperty('interrupt') + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(turnId) + expect(await statusTexts()).toEqual([]) +}) + +it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { + const connection = fixture.claude.connections[0]! + const eventsAtClose = stopEventsAtClose(connection) + const turnId = await openTurn(connection) + const request = new AbortController() + const { answered, card } = await ask( + connection, + 'AskUserQuestion', + BRANCH_QUESTION, + request.signal + ) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + request.abort() + await fixture.host.flushStreamedEvents(SESSION) + // Prompt cancellation must land before child exit so answers are already disabled. + expect(connection.closed).toBe(false) + const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(connection.closed).toBe(true) + expect(eventsAtClose()).toBe(1) + expect(await turnOutcome()).toBe('cancellation') + expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + await send('Carry on.') + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Carry on.')).toBe(true) + }) +}) + +it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + + await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ + behavior: 'deny', + message: expect.stringMatching(/dismissed/) + }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { + const connection = fixture.claude.connections[0]! + const earlier = await openTurn(connection) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const running = await openTurn(connection, 'Now something else.') + expect(running).not.toBe(earlier) + + await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ behavior: 'deny' }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(running) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts index 94139e11a98d..e31ae2e5ea9b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts @@ -29,10 +29,10 @@ afterEach(() => rig.dispose()) const journal = () => rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const db = () => openTestJournalHostDatabase(rig.root).db -const rawPrefix = (sequence: number) => +const canonicalPrefix = (sequence: number) => db() .prepare( - 'SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq <= ? ORDER BY seq' + 'SELECT seq, field, entry_key, ordinal, value_json, deleted FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ? AND epoch = ?) AND seq <= ? ORDER BY seq, field, entry_key' ) .all(SESSION, journal().cursor().epoch, sequence) @@ -62,7 +62,7 @@ async function seed() { const prefix = journal() .snapshot() .items.filter((item) => item.sequence <= floor.sequence) - const raw = rawPrefix(floor.sequence) + const raw = canonicalPrefix(floor.sequence) const kept = await send('kept after clear', 'kept') const target = await send('rewound after clear', 'target') const fields = { itemId: target, expectedEpoch: journal().cursor().epoch } @@ -215,7 +215,7 @@ describe('rewind behind a clear boundary', () => { .snapshot() .items.filter((item) => item.sequence <= floor.sequence) ).toEqual(prefix) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect( journal() .snapshot() @@ -257,7 +257,7 @@ describe('rewind behind a clear boundary', () => { rig.store.getRecord(SESSION)!.lease.runtimeFence ) expect(journal().snapshot()).toEqual(recovered) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect(rewind).toHaveBeenCalledOnce() expect(await rig.host.rewind(CALLER, params)).toMatchObject({ ok: true, replayed: true }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts index 7238f2bf166a..493d4f4b9975 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts @@ -50,6 +50,9 @@ export class StructuredAgentSessionConversations extends Map< super() } + loadedSessionIds = (): string[] => + [...this].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + override set(sessionId: string, session: StructuredAgentSessionHostSession): this { const { journal } = session if (this.get(sessionId)?.journal === journal) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts new file mode 100644 index 000000000000..d4cc9d842658 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts @@ -0,0 +1,240 @@ +import { mkdir, realpath, writeFile, rm, symlink, readFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { createRestTestRig } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' +import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' +import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' +import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' +import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' +import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' + +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' + +it.each([100, 1000])( + 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', + async (size) => { + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. + const captured = ( + await readFile( + join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), + 'utf8' + ) + ) + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)) + .find((row) => row.type === 'user' && !row.isMeta) + expect(captured.cwd).toBe('/tmp/project') + await writeFile( + transcriptPath, + `${Array.from({ length: size }, (_, index) => + JSON.stringify({ + ...captured, + uuid: `original-${index}`, + sessionId: THREAD, + cwd: physical, + message: { role: 'user', content: 'original physical-keyed context' } + }) + ).join('\n')}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + const publishTab = vi.fn(async () => { + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + }) + const result = await fixture.rig.host.create(CALLER, params, { publishTab }) + expect(result).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ + blocks: [{ type: 'text', text: 'original physical-keyed context' }] + }) + }) + ]) + } + } + }) + expect(publishTab).toHaveBeenCalledOnce() + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) + expect(params.adopt?.source?.workspaceCwd).toBe(registered) + const record = fixture.rig.store.getRecord(SESSION)! + expect( + await resolveAgentSessionLaunchDirectory( + { store: fixture.rig.store, resolveWorkspacePath: async () => registered }, + record + ) + ).toBe(registered) + expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) + const hasTranscript = vi.fn( + async ({ + providerSessionId, + claudeConfigDir + }: { + providerSessionId: string + claudeConfigDir: string + }) => + providerSessionId === THREAD && + claudeConfigDir === fixture.rig.root && + (await readFile(transcriptPath, 'utf8')).includes(THREAD) + ) + const launch = await createClaudeStructuredLaunchResolver({ + store: fixture.rig.store, + resolveWorkspacePath: async () => registered, + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + resolveInheritedEnv: async () => ({}), + resolveAuthPolicy: () => ({ account: 'system' }), + resolveLaunchArgs: () => [], + hasTranscript + })({ + identity: { + sessionId: SESSION, + workspaceId: record.location.workspaceId, + hostId: 'local', + agent: 'claude', + providerHandle: record.providerHandleChain[0].handle + } + }) + expect(launch).toMatchObject({ + cwd: registered, + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root, + options: { resume: THREAD } + }) + expect(hasTranscript).toHaveBeenCalledWith({ + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(probe).toHaveBeenCalledOnce() + await fixture.rig.host.flushAllStreamedEvents() + await fixture.rig.restart() + await rm(transcriptPath) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + replayed: true + }) + expect(probe).toHaveBeenCalledOnce() + } +) + +it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { + const physical = join(await realpath(fixture.rig.root), 'physical') + const moved = join(await realpath(fixture.rig.root), 'moved') + const registered = join(fixture.rig.root, 'registered') + await mkdir(physical) + await mkdir(moved) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') + const sourceCwd = join(physical, 'pkg') + const workspaceCwd = join(registered, 'pkg') + expect(await realpath(workspaceCwd)).toBe(moved) + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + const save = async (sessionId: string, cwd: string) => + writeFile( + transcriptPath, + `${JSON.stringify({ + type: 'user', + uuid: 'original', + sessionId, + cwd, + message: { role: 'user', content: 'ancestor context' } + })}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + await save('wrong-provider', sourceCwd) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(probe).not.toHaveBeenCalled() + await save(THREAD, join(fixture.rig.root, 'foreign')) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await save(THREAD, sourceCwd) + await rm(registered) + await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await rm(registered) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) +}) + +it.each(['opencode', 'opencode2'] as const)( + 'commits %s actual database history using the same linked-cwd admission', + async (agent) => { + const definition = structuredAgentRuntimeRegistration(agent)!.definition + await fixture.rig.dispose() + fixture.rig = await createRestTestRig({ + agents: structuredAgentsDeclaringNothing([definition]) + }) + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, 'opencode.db') + writeOpenCodeSqliteDatabase(transcriptPath, [ + { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } + ]) + const params = createTestParams(undefined, { + agent, + provider: agent, + accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, + adopt: { + providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts new file mode 100644 index 000000000000..d6c51fbe8582 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts @@ -0,0 +1,73 @@ +import { writeFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { createRestTestRig, type RestTestRig } from './structured-agent-session-rest-test-rig' +import { createTestParams } from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +let rig: RestTestRig + +beforeEach(async () => { + rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) +}) + +afterEach(async () => { + await rig.dispose() + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +export async function adoptedParams(history = 'adopted history', threadId = THREAD) { + const transcriptPath = join(rig.root, 'rollout.jsonl') + await writeFile( + transcriptPath, + [ + JSON.stringify({ + type: 'session_meta', + payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } + }), + JSON.stringify({ + type: 'response_item', + timestamp: '2026-09-06T18:00:01.000Z', + payload: { type: 'message', role: 'user', content: history } + }) + ].join('\n') + ) + return createTestParams(undefined, { + adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } + }) +} + +export function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { + return createTestParams(undefined, { + ...params, + envelope: { + ...params.envelope, + sessionId: 'session-second', + clientOperationId: hostTestOperationId() + } + }) +} + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts new file mode 100644 index 000000000000..13cb15d897c3 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts @@ -0,0 +1,236 @@ +import { writeFile, rm } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { restTestSend } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + stopCreatedChat, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId, + hostTestMessage +} from './structured-agent-session-host-test-data' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + adoptedParams, + anotherSession +} from './structured-agent-session-create-adoption-contract-test-fixture' + +it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { + const params = await adoptedParams() + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) + }) + ]) + } + } + }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } + ]) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + await rm(join(fixture.rig.root, 'rollout.jsonl')) + expect( + await fixture.rig.host.create(CALLER, { + ...params, + accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, + adopt: { providerHandle: codexProviderHandle(THREAD) } + }) + ).toMatchObject({ ok: true, replayed: true }) + expect(await fixture.rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledWith( + expect.objectContaining({ + identity: expect.objectContaining({ + providerHandle: expect.objectContaining({ nativeId: THREAD }) + }) + }) + ) + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) +}) + +it('refuses concurrent adoption of a provider conversation by another session', async () => { + const params = await adoptedParams() + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { + refusal: { + code: 'agent_session_conflict', + details: { + reason: 'conversationHeldElsewhere', + owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } + }, + createAttemptRefusedBeforeCommit: true + } + } + ]) + expect(fixture.rig.store.listRecords()).toHaveLength(1) + expect(fixture.rig.store.listOperationRows()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it('refuses concurrent founding under a tab another chat already owns', async () => { + const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } + ]) + expect(fixture.rig.store.listVisibleSessionIds()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['missing', 'empty', 'malformed'] as const)( + 'refuses %s history before founding anything', + async (source) => { + const params = await adoptedParams() + await (source === 'missing' + ? rm(join(fixture.rig.root, 'rollout.jsonl')) + : writeFile( + join(fixture.rig.root, 'rollout.jsonl'), + source === 'empty' ? '' : '{broken json}\n' + )) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + } +) + +it('does not found a record whose account namespace its agent cannot drive', async () => { + const params = createTestParams(undefined, { + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) +}) + +it.each([ + { executionHostId: 'local', wslDistro: null }, + { executionHostId: 'ssh:host-1', wslDistro: null }, + { executionHostId: 'local', wslDistro: 'Ubuntu' }, + { executionHostId: 'runtime:paired-host', wslDistro: null } +] as const)( + 'preserves folder execution identity at rest: $executionHostId $wslDistro', + async (location) => { + const params = createTestParams(undefined, { + location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.location).toEqual(params.location) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) + +it('pins the host-resolved directory of a floating chat before any acquire', async () => { + const params = createTestParams(undefined, { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: FLOATING_TERMINAL_WORKTREE_ID, + workspaceKind: 'folder' + } + }) + expect( + await fixture.rig.host.create(CALLER, params, { hostLaunchDirectory: fixture.rig.root }) + ).toMatchObject({ + ok: true + }) + expect(fixture.rig.store.getRecord(SESSION)?.launchDirectory).toBe(fixture.rig.root) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['adopted', 'blank'] as const)( + 'retries a rolled-back create with only the new %s history', + async (nextSource) => { + const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } + const adopted = await adoptedParams('old imported history') + const db = openTestJournalHostDatabase(fixture.rig.root).db + db.exec( + `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_outcomes WHEN NEW.field = 'submissions' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` + ) + expect( + await fixture.rig.host.create(CALLER, createTestParams(first, adopted), { + firstMessage: first + }) + ).toMatchObject({ ok: false }) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.listOperationRows()).toEqual([]) + db.exec('DROP TRIGGER refuse_first') + const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } + const nextParams = + nextSource === 'adopted' + ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') + : createTestParams() + let stopping: ReturnType | undefined + const result = await fixture.rig.host.create( + CALLER, + createTestParams(next, { + ...nextParams, + envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } + }), + { + firstMessage: next, + publishTab: async () => { + stopping = stopCreatedChat(fixture.rig.host) + } + } + ) + expect(result).toMatchObject({ ok: true }) + if (!result.ok) { + throw new Error('retry create failed') + } + const history = (text: string) => + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) + }) + expect(result.value.page.items).not.toEqual( + expect.arrayContaining([history('old imported history')]) + ) + if (nextSource === 'adopted') { + expect(result.value.page.items).toEqual( + expect.arrayContaining([history('new imported history')]) + ) + } + expect(await stopping).toMatchObject({ ok: true }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index bc074176eac7..e3b6bb3ca948 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -1,36 +1,4 @@ -import { mkdir, realpath, rename, writeFile, rm, symlink, readFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - createRestTestRig, - restTestSend, - type RestTestRig -} from './structured-agent-session-rest-test-rig' -import { - createTestParams, - stopCreatedChat, - CREATE_TEST_CALLER as CALLER -} from './structured-agent-session-create-test-fixture' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestOperationId, - hostTestMessage -} from './structured-agent-session-host-test-data' -import type { AgentSessionAttachParams } from './structured-agent-session-attach' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' -import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' -import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' -import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' -import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' -import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' -import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' - +import { mkdir, realpath, rename, writeFile } from 'node:fs/promises' vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { const query = await import('../transcript-opencode-sqlite-query') return { @@ -40,7 +8,16 @@ vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (or query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) } }) - +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' import { codexLegacyMirrorRecords, writeCodexHistoryFixture @@ -52,47 +29,7 @@ import { } from '../../runtime/structured-agent-session-create-adoption' import { prepareCodexAiVaultSessionResume } from '../../codex/codex-ai-vault-session-resume' -let rig: RestTestRig -beforeEach(async () => { - rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) -}) -afterEach(async () => { - await rig.dispose() - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -async function adoptedParams(history = 'adopted history', threadId = THREAD) { - const transcriptPath = join(rig.root, 'rollout.jsonl') - await writeFile( - transcriptPath, - [ - JSON.stringify({ - type: 'session_meta', - payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } - }), - JSON.stringify({ - type: 'response_item', - timestamp: '2026-09-06T18:00:01.000Z', - payload: { type: 'message', role: 'user', content: history } - }) - ].join('\n') - ) - return createTestParams(undefined, { - adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } - }) -} - -function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { - return createTestParams(undefined, { - ...params, - envelope: { - ...params.envelope, - sessionId: 'session-second', - clientOperationId: hostTestOperationId() - } - }) -} +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' it.each([ ['matching', THREAD], @@ -101,8 +38,8 @@ it.each([ ] as const)( 'resolves a selected-account rollout with %s metadata before at-rest publication', async (_kind, metadataId) => { - vi.stubEnv('ORCA_USER_DATA_PATH', join(rig.root, 'host-data')) - const accountHome = { variable: 'CODEX_HOME', path: join(rig.root, 'selected-account') } + vi.stubEnv('ORCA_USER_DATA_PATH', join(fixture.rig.root, 'host-data')) + const accountHome = { variable: 'CODEX_HOME', path: join(fixture.rig.root, 'selected-account') } const sessions = join(accountHome.path, 'sessions') await mkdir(sessions, { recursive: true }) const rollout = await writeCodexHistoryFixture( @@ -116,7 +53,7 @@ it.each([ await writeFile( rollout.filePath, [ - { type: 'session_meta', payload: { id: THREAD, cwd: rig.root } }, + { type: 'session_meta', payload: { id: THREAD, cwd: fixture.rig.root } }, ...codexLegacyMirrorRecords() ] .map((record) => JSON.stringify(record)) @@ -138,11 +75,11 @@ it.each([ providerSessionId: THREAD, selectedAccountHome: accountHome, launchEnv: {}, - workspaceCwd: rig.root, + workspaceCwd: fixture.rig.root, prepareCodexResume: (args) => prepareCodexAiVaultSessionResume(args, { runtimeHome: null, - systemCodexHomePath: join(rig.root, 'system-account'), + systemCodexHomePath: join(fixture.rig.root, 'system-account'), preparePinnedLaunchHome: async () => { throw new Error('At-rest adoption must not ready a fork launch') } @@ -152,7 +89,7 @@ it.each([ expect(adoption.transcriptPath).toBe( await realpath(join(sessions, `rollout-2026-10-27T00-00-00-${THREAD}.jsonl`)) ) - const result = await rig.host.create( + const result = await fixture.rig.host.create( CALLER, createTestParams(undefined, { accountHome: adoption.accountHome, @@ -166,12 +103,12 @@ it.each([ }) ?? undefined, transcriptPath: adoption.transcriptPath, providerSessionId: THREAD, - workspaceCwd: rig.root + workspaceCwd: fixture.rig.root }) }) ) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() if (metadataId !== THREAD) { expect(result).toMatchObject({ ok: false, @@ -181,16 +118,16 @@ it.each([ createAttemptRefusedBeforeCommit: true } }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - expect(rig.store.listVisibleSessionIds()).toEqual([]) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([]) return } expect(result.ok).toBe(true) if (!result.ok) { throw new Error('Real selected-account adoption failed') } - const snapshot = await rig.host.journalSnapshot(SESSION) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) expect(snapshot.items.map(({ body }) => body)).toEqual( _kind === 'legacy' ? [ @@ -212,407 +149,10 @@ it.each([ ] ) expect(result.value.page.items).toEqual(snapshot.items) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } ]) - expect(rig.store.listVisibleSessionIds()).toEqual([SESSION]) - } -) - -it.each([100, 1000])( - 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', - async (size) => { - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. - const captured = ( - await readFile( - join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), - 'utf8' - ) - ) - .split('\n') - .filter(Boolean) - .map((line) => JSON.parse(line)) - .find((row) => row.type === 'user' && !row.isMeta) - expect(captured.cwd).toBe('/tmp/project') - await writeFile( - transcriptPath, - `${Array.from({ length: size }, (_, index) => - JSON.stringify({ - ...captured, - uuid: `original-${index}`, - sessionId: THREAD, - cwd: physical, - message: { role: 'user', content: 'original physical-keyed context' } - }) - ).join('\n')}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - const publishTab = vi.fn(async () => { - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - }) - const result = await rig.host.create(CALLER, params, { publishTab }) - expect(result).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - blocks: [{ type: 'text', text: 'original physical-keyed context' }] - }) - }) - ]) - } - } - }) - expect(publishTab).toHaveBeenCalledOnce() - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) - expect(params.adopt?.source?.workspaceCwd).toBe(registered) - const record = rig.store.getRecord(SESSION)! - expect( - await resolveAgentSessionLaunchDirectory( - { store: rig.store, resolveWorkspacePath: async () => registered }, - record - ) - ).toBe(registered) - expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) - const hasTranscript = vi.fn( - async ({ - providerSessionId, - claudeConfigDir - }: { - providerSessionId: string - claudeConfigDir: string - }) => - providerSessionId === THREAD && - claudeConfigDir === rig.root && - (await readFile(transcriptPath, 'utf8')).includes(THREAD) - ) - const launch = await createClaudeStructuredLaunchResolver({ - store: rig.store, - resolveWorkspacePath: async () => registered, - resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), - resolveInheritedEnv: async () => ({}), - resolveAuthPolicy: () => ({ account: 'system' }), - resolveLaunchArgs: () => [], - hasTranscript - })({ - identity: { - sessionId: SESSION, - workspaceId: record.location.workspaceId, - hostId: 'local', - agent: 'claude', - providerHandle: record.providerHandleChain[0].handle - } - }) - expect(launch).toMatchObject({ - cwd: registered, - providerSessionId: THREAD, - claudeConfigDir: rig.root, - options: { resume: THREAD } - }) - expect(hasTranscript).toHaveBeenCalledWith({ - providerSessionId: THREAD, - claudeConfigDir: rig.root - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(probe).toHaveBeenCalledOnce() - await rig.host.flushAllStreamedEvents() - await rig.restart() - await rm(transcriptPath) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) - expect(probe).toHaveBeenCalledOnce() - } -) - -it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { - const physical = join(await realpath(rig.root), 'physical') - const moved = join(await realpath(rig.root), 'moved') - const registered = join(rig.root, 'registered') - await mkdir(physical) - await mkdir(moved) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') - const sourceCwd = join(physical, 'pkg') - const workspaceCwd = join(registered, 'pkg') - expect(await realpath(workspaceCwd)).toBe(moved) - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - const save = async (sessionId: string, cwd: string) => - writeFile( - transcriptPath, - `${JSON.stringify({ - type: 'user', - uuid: 'original', - sessionId, - cwd, - message: { role: 'user', content: 'ancestor context' } - })}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - await save('wrong-provider', sourceCwd) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(probe).not.toHaveBeenCalled() - await save(THREAD, join(rig.root, 'foreign')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await save(THREAD, sourceCwd) - await rm(registered) - await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await rm(registered) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) -}) - -it.each(['opencode', 'opencode2'] as const)( - 'commits %s actual database history using the same linked-cwd admission', - async (agent) => { - const definition = structuredAgentRuntimeRegistration(agent)!.definition - await rig.dispose() - rig = await createRestTestRig({ agents: structuredAgentsDeclaringNothing([definition]) }) - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, 'opencode.db') - writeOpenCodeSqliteDatabase(transcriptPath, [ - { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } - ]) - const params = createTestParams(undefined, { - agent, - provider: agent, - accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, - adopt: { - providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { - const params = await adoptedParams() - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) - }) - ]) - } - } - }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ - { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } - ]) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - await rm(join(rig.root, 'rollout.jsonl')) - expect( - await rig.host.create(CALLER, { - ...params, - accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, - adopt: { providerHandle: codexProviderHandle(THREAD) } - }) - ).toMatchObject({ ok: true, replayed: true }) - expect(await rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire).toHaveBeenCalledWith( - expect.objectContaining({ - identity: expect.objectContaining({ - providerHandle: expect.objectContaining({ nativeId: THREAD }) - }) - }) - ) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) -}) - -it('refuses concurrent adoption of a provider conversation by another session', async () => { - const params = await adoptedParams() - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { - refusal: { - code: 'agent_session_conflict', - details: { - reason: 'conversationHeldElsewhere', - owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } - }, - createAttemptRefusedBeforeCommit: true - } - } - ]) - expect(rig.store.listRecords()).toHaveLength(1) - expect(rig.store.listOperationRows()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it('refuses concurrent founding under a tab another chat already owns', async () => { - const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } - ]) - expect(rig.store.listVisibleSessionIds()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['missing', 'empty', 'malformed'] as const)( - 'refuses %s history before founding anything', - async (source) => { - const params = await adoptedParams() - await (source === 'missing' - ? rm(join(rig.root, 'rollout.jsonl')) - : writeFile(join(rig.root, 'rollout.jsonl'), source === 'empty' ? '' : '{broken json}\n')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_identity_required', - details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - } -) - -it('does not found a record whose account namespace its agent cannot drive', async () => { - const params = createTestParams(undefined, { - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { code: 'structured_agent_session_unsupported' } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) -}) - -it.each([ - { executionHostId: 'local', wslDistro: null }, - { executionHostId: 'ssh:host-1', wslDistro: null }, - { executionHostId: 'local', wslDistro: 'Ubuntu' }, - { executionHostId: 'runtime:paired-host', wslDistro: null } -] as const)( - 'preserves folder execution identity at rest: $executionHostId $wslDistro', - async (location) => { - const params = createTestParams(undefined, { - location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.location).toEqual(params.location) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('pins the host-resolved directory of a floating chat before any acquire', async () => { - const params = createTestParams(undefined, { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: FLOATING_TERMINAL_WORKTREE_ID, - workspaceKind: 'folder' - } - }) - expect(await rig.host.create(CALLER, params, { hostLaunchDirectory: rig.root })).toMatchObject({ - ok: true - }) - expect(rig.store.getRecord(SESSION)?.launchDirectory).toBe(rig.root) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['adopted', 'blank'] as const)( - 'retries a rolled-back create with only the new %s history', - async (nextSource) => { - const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } - const adopted = await adoptedParams('old imported history') - const db = openTestJournalHostDatabase(rig.root).db - db.exec( - `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_rows WHEN NEW.row_json LIKE '%"kind":"submission"%' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` - ) - expect( - await rig.host.create(CALLER, createTestParams(first, adopted), { firstMessage: first }) - ).toMatchObject({ ok: false }) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.listOperationRows()).toEqual([]) - db.exec('DROP TRIGGER refuse_first') - const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } - const nextParams = - nextSource === 'adopted' - ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') - : createTestParams() - let stopping: ReturnType | undefined - const result = await rig.host.create( - CALLER, - createTestParams(next, { - ...nextParams, - envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } - }), - { - firstMessage: next, - publishTab: async () => { - stopping = stopCreatedChat(rig.host) - } - } - ) - expect(result).toMatchObject({ ok: true }) - if (!result.ok) { - throw new Error('retry create failed') - } - const history = (text: string) => - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) - }) - expect(result.value.page.items).not.toEqual( - expect.arrayContaining([history('old imported history')]) - ) - if (nextSource === 'adopted') { - expect(result.value.page.items).toEqual( - expect.arrayContaining([history('new imported history')]) - ) - } - expect(await stopping).toMatchObject({ ok: true }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([SESSION]) } ) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts index 607776d1a619..bf0d0a058346 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts @@ -19,7 +19,7 @@ import { type StructuredAgentSessionState } from '../../../shared/structured-agent-session-reducer' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -244,9 +244,10 @@ describe('a waiting card when the generation ahead of it ends', () => { expect(journal.queuedMessages.get(card?.messageId ?? '')?.state).toBe('dispatched') ) // Generation-end publication alone must wake delivery without an intervening journal write. - const first = liveTestJournalRows(database.db, SESSION).find((row) => row.seq > before) - expect(JSON.parse(first?.rowJson ?? '{}')).toMatchObject({ - kind: 'submission', + const first = readTestJournalOutcomes(database.db, SESSION).find( + (row) => row.seq > before && row.field === 'submissions' + ) + expect(JSON.parse(first?.json ?? '[null, {}]')[1]).toMatchObject({ queuedMessageId: card?.messageId }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index 0d4fb78ee9ff..0a64e9dd7b1e 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts @@ -145,8 +145,7 @@ export class StructuredAgentSessionHost { private now = (): number => this.deps.now?.() ?? Date.now() hasSession = (sessionId: string): boolean => this.sessions.has(sessionId) - loadedSessionIds = (): string[] => - [...this.sessions].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + loadedSessionIds = this.sessions.loadedSessionIds hasLoadedProviders = (): boolean => this.loadedSessionIds().length > 0 sessionAgent = (sessionId: string) => this.deps.store.getConversation(sessionId)?.provider ?? null diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts new file mode 100644 index 000000000000..e1f897b27aaf --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts @@ -0,0 +1,136 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' + +describe('settling a send the provider proves it received after the ack window', () => { + it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { + fixture.dispatch.mockImplementationOnce( + (input) => + new Promise((_resolve, reject) => { + input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { + once: true + }) + }) + ) + const params = sendParams('stopped before its write') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + expect(fixture.dispatch.mock.calls[0]?.[0].signal).toBeDefined() + + const stopped = await fixture.host.cancel(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: SESSION, + fields: {} + }) + } + }) + expect(stopped).toMatchObject({ ok: true }) + await vi.waitFor(async () => + expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) + ) + const before = journal().cursor() + await fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + }) + + const after = journal().readSince(before) + expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'rejected', + rejection: { kind: 'cancelled' } + } + ]) + }) + + it('accepts from the durable echo row when the direct settlement write fails', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('settle from provider echo') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( + new Error('direct settlement write failed') + ) + + await expect( + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } + }) + ).rejects.toThrow('direct settlement write failed') + await journal().appendItem( + { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, + params.body, + { + fence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + } + ]) + }) + + it('leaves an already accepted send alone, adding no row', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('ordinary send') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + const before = journal().cursor() + const receipt = (uuid: string) => + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } + }) + + await Promise.all([receipt('echo-row'), receipt('echo-row')]) + await receipt('a-different-uuid') + + const after = journal().readSince(before) + expect(after.ok && after.rows).toHaveLength(1) + expect(journal().submission(params.envelope.clientOperationId)).toMatchObject({ + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + }) + }) + + it('ignores a session this host is not holding', async () => { + await expect( + fixture.host.settleLateDispatch({ + sessionId: 'session-that-is-not-attached', + clientMessageId: 'whatever', + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } + }) + ).resolves.toBeUndefined() + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts new file mode 100644 index 000000000000..e52ab14e281f --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts @@ -0,0 +1,180 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi, type Mock } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import type { AgentSessionMutationEnvelope } from '../../../shared/agent-session-wire' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { + AgentSessionDispatchOutcome, + StructuredAgentSessionAdapter +} from './structured-agent-session-adapter' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' +import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' + +export const CALLER = { callerKey: 'client-1' } + +let root: string + +let store: AgentSessionRecordStore + +let host: StructuredAgentSessionHost + +let dispatch: Mock + +let closeSession: Mock> + +export function accepted(): AgentSessionDispatchOutcome { + return { + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + } +} + +export function sendParams(text: string): { + envelope: AgentSessionMutationEnvelope + body: ReturnType +} { + const body = hostTestMessage(text) + return { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + } +} + +export async function submissions(): Promise { + const state = await host.history({ sessionId: SESSION, direction: 'tail' }) + return state.ok ? state.page.submissions : null +} + +export function journal(): AgentSessionJournal { + return ( + host as unknown as { sessions: Map } + ).sessions.get(SESSION)!.journal +} + +export async function handedOver(clientMessageId: string): Promise { + await vi.waitFor(async () => { + expect( + journal() + .submissions() + .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt + ).toBeDefined() + expect(dispatch).toHaveBeenCalled() + }) +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) + resetHostTestOperationIds() + dispatch = vi.fn(async () => accepted()) + closeSession = vi.fn(async () => true) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + logger: createStructuredAgentSessionLogger(), + store, + adapter: startsWhenPublished( + { + open: async () => ({ + reportedOptions: { model: '' } + }), + acquire: vi.fn(async ({ fence }) => ({ + acquisitionGeneration: globalThis.crypto.randomUUID(), + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 1_700_000_000_000, + spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' + }, + link: { + linkId: `link-${fence}`, + handle: codexProviderHandle(THREAD), + origin: 'created' as const, + mintedAtFence: fence, + observedAt: NOW + } + })), + releaseAcquisition: vi.fn(async () => true), + dispatch, + closeSession, + cancelTurn: vi.fn(async () => ({ cancelled: true })), + answerPrompt: vi.fn(async () => undefined), + setOption: vi.fn(async () => undefined) + }, + () => host + ), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + now: () => NOW + }) + expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) +}) + +afterEach(async () => { + await host.flushAllStreamedEvents() + await host.close(SESSION, 'evict') + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get closeSession() { + return closeSession + }, + set closeSession(value: typeof closeSession) { + closeSession = value + }, + get dispatch() { + return dispatch + }, + set dispatch(value: typeof dispatch) { + dispatch = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts index a585a428aaf7..0e7ec86e66d8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts @@ -1,180 +1,48 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { describe, expect, it, vi } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import type { - AgentSessionMutationEnvelope, - AgentSessionSubscribeEvent -} from '../../../shared/agent-session-wire' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import type { - AgentSessionDispatchOutcome, - StructuredAgentSessionAdapter -} from './structured-agent-session-adapter' -import { StructuredAgentSessionHost } from './structured-agent-session-host' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import type { AgentSessionDispatchOutcome } from './structured-agent-session-adapter' import { - HOST_TEST_NOW as NOW, HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds + HOST_TEST_THREAD as THREAD } from './structured-agent-session-host-test-data' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' -import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' - import { closeStructuredAgentSessionHandovers, finalizingStructuredAgentSessionInput, structuredAgentSessionHandingOver } from './structured-agent-session-handing-over' -const CALLER = { callerKey: 'client-1' } - -let root: string -let store: AgentSessionRecordStore -let host: StructuredAgentSessionHost -let dispatch: Mock -let closeSession: Mock> - -function accepted(): AgentSessionDispatchOutcome { - return { - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - } -} - -function sendParams(text: string): { - envelope: AgentSessionMutationEnvelope - body: ReturnType -} { - const body = hostTestMessage(text) - return { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - } -} - -async function submissions(): Promise { - const state = await host.history({ sessionId: SESSION, direction: 'tail' }) - return state.ok ? state.page.submissions : null -} - -function journal(): AgentSessionJournal { - return ( - host as unknown as { sessions: Map } - ).sessions.get(SESSION)!.journal -} - -async function handedOver(clientMessageId: string): Promise { - await vi.waitFor(async () => { - expect( - journal() - .submissions() - .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt - ).toBeDefined() - expect(dispatch).toHaveBeenCalled() - }) -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) - resetHostTestOperationIds() - dispatch = vi.fn(async () => accepted()) - closeSession = vi.fn(async () => true) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - logger: createStructuredAgentSessionLogger(), - store, - adapter: startsWhenPublished( - { - open: async () => ({ - reportedOptions: { model: '' } - }), - acquire: vi.fn(async ({ fence }) => ({ - acquisitionGeneration: globalThis.crypto.randomUUID(), - process: { - hostId: 'local', - pid: 4242, - processStartTimeMs: 1_700_000_000_000, - spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' - }, - link: { - linkId: `link-${fence}`, - handle: codexProviderHandle(THREAD), - origin: 'created' as const, - mintedAtFence: fence, - observedAt: NOW - } - })), - releaseAcquisition: vi.fn(async () => true), - dispatch, - closeSession, - cancelTurn: vi.fn(async () => ({ cancelled: true })), - answerPrompt: vi.fn(async () => undefined), - setOption: vi.fn(async () => undefined) - }, - () => host - ), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - now: () => NOW - }) - expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) -}) - -afterEach(async () => { - await host.flushAllStreamedEvents() - await host.close(SESSION, 'evict') - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' describe('settling a send the provider proves it received after the ack window', () => { it('publishes acceptance during a pending send and never reopens it for retry', async () => { let finishDispatch!: (outcome: AgentSessionDispatchOutcome) => void - dispatch.mockImplementationOnce( + fixture.dispatch.mockImplementationOnce( () => new Promise((resolve) => { finishDispatch = resolve }) ) const events: AgentSessionSubscribeEvent[] = [] - const unsubscribe = await host.subscribe({ + const unsubscribe = await fixture.host.subscribe({ id: 'late-receipt', sessionId: SESSION, emit: (event) => events.push(event) }) const params = sendParams('echo before send completes') - const pending = host.send(CALLER, params) - await vi.waitFor(async () => expect(dispatch).toHaveBeenCalledTimes(1)) + const pending = fixture.host.send(CALLER, params) + await vi.waitFor(async () => expect(fixture.dispatch).toHaveBeenCalledTimes(1)) try { - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'early-echo' } @@ -205,11 +73,13 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) ) - await expect(host.send(CALLER, { ...params, retryUnknown: true })).resolves.toMatchObject({ + await expect( + fixture.host.send(CALLER, { ...params, retryUnknown: true }) + ).resolves.toMatchObject({ ok: true, value: { submission: { dispatchState: 'accepted' } } }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it.each(['N-first', 'O-first'] as const)( @@ -218,7 +88,7 @@ describe('settling a send the provider proves it received after the ack window', const original = Promise.withResolvers() const nested = Promise.withResolvers() const entered = Promise.withResolvers() - dispatch.mockImplementationOnce(() => original.promise) + fixture.dispatch.mockImplementationOnce(() => original.promise) const held = journal() const acceptLate = held.acceptLate.bind(held) const acceptance = vi.spyOn(held, 'acceptLate').mockImplementation(async (input) => { @@ -228,13 +98,13 @@ describe('settling a send the provider proves it received after the ack window', }) const params = sendParams('overlapping result and receipt') const id = params.envelope.clientOperationId - const sending = host.send(CALLER, params) + const sending = fixture.host.send(CALLER, params) let settlement: Promise | undefined let observed: Promise | undefined let completed = 0 try { await handedOver(id) - settlement = host.settleLateDispatch({ + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: id, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'overlap-echo' } @@ -279,7 +149,7 @@ describe('settling a send the provider proves it received after the ack window', dispatchState: 'accepted', providerItemId: `claude:${THREAD}:overlap-echo` }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) expect(acceptance).toHaveBeenCalledTimes(1) } finally { original.resolve({ state: 'unknown', reason: 'cleanup' }) @@ -291,16 +161,16 @@ describe('settling a send the provider proves it received after the ack window', ) it('persists an echo received while the provider is closing', async () => { - dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) const params = sendParams('received just before shutdown') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) let settlement: Promise | undefined - closeSession.mockImplementationOnce(async () => { - settlement = host.settleLateDispatch({ + fixture.closeSession.mockImplementationOnce(async () => { + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'closing-echo' } @@ -309,23 +179,23 @@ describe('settling a send the provider proves it received after the ack window', return true }) - await host.close(SESSION, 'evict') + await fixture.host.close(SESSION, 'evict') await expect(settlement).resolves.toBeUndefined() - await host.revealSession(SESSION) + await fixture.host.revealSession(SESSION) expect(await submissions()).toMatchObject([{ dispatchState: 'accepted' }]) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('moves a durable unknown to accepted so nothing offers to send it again', async () => { - dispatch.mockRejectedValueOnce(new Error('socket closed')) + fixture.dispatch.mockRejectedValueOnce(new Error('socket closed')) const params = sendParams('sent while a turn was running') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-uuid' } @@ -335,22 +205,22 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) // Retry previously redelivered; the settled send must remain single-dispatch. - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('settles a provider-cancelled queued send as rejected', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) const params = sendParams('queued behind the active turn') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, state: 'rejected', ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }) }) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-echo' } @@ -365,119 +235,4 @@ describe('settling a send the provider proves it received after the ack window', } ]) }) - - it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { - dispatch.mockImplementationOnce( - (input) => - new Promise((_resolve, reject) => { - input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { - once: true - }) - }) - ) - const params = sendParams('stopped before its write') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - expect(dispatch.mock.calls[0]?.[0].signal).toBeDefined() - - const stopped = await host.cancel(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.cancel', - sessionId: SESSION, - fields: {} - }) - } - }) - expect(stopped).toMatchObject({ ok: true }) - await vi.waitFor(async () => - expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) - ) - const before = journal().cursor() - await host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - }) - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'rejected', - rejection: { kind: 'cancelled' } - } - ]) - }) - - it('accepts from the durable echo row when the direct settlement write fails', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('settle from provider echo') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( - new Error('direct settlement write failed') - ) - - await expect( - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } - }) - ).rejects.toThrow('direct settlement write failed') - await journal().appendItem( - { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, - params.body, - { - fence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'accepted', - providerItemId: `claude:${THREAD}:echo-row` - } - ]) - }) - - it('leaves an already accepted send alone, adding no row', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('ordinary send') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - const before = journal().cursor() - const receipt = (uuid: string) => - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } - }) - - await Promise.all([receipt('echo-row'), receipt('echo-row')]) - await receipt('a-different-uuid') - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toMatchObject([ - { state: 'accepted', providerItemId: `claude:${THREAD}:echo-row` } - ]) - }) - - it('ignores a session this host is not holding', async () => { - await expect( - host.settleLateDispatch({ - sessionId: 'session-that-is-not-attached', - clientMessageId: 'whatever', - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } - }) - ).resolves.toBeUndefined() - }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts index 4a88e0b19731..0c4efcd8055c 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts @@ -6,7 +6,7 @@ import { import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' @@ -31,10 +31,11 @@ export const TURN: AgentJournalItemIdentity = { export const TURN_KEY = agentJournalItemKey(TURN) const IN_TURN = { kind: 'turn' as const, turnItemId: TURN_KEY } export const APPROVAL: AgentJournalItemIdentity = { ...TURN, ordinal: 2 } -/** All settlement rows carry recovered=true. */ +/** Recovered outcome values carry recovered=true. */ export const REJECT_RECOVERED_ROWS = ` - CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_rows - WHEN json_extract(NEW.row_json, '$.recovered') = 1 + CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_outcomes + WHEN (NEW.field = 'items' AND json_extract(NEW.value_json, '$.recovered') = 1) + OR (NEW.field = 'submissions' AND json_extract(NEW.value_json, '$[1].recovered') = 1) BEGIN SELECT RAISE(ABORT, 'temporary storage failure'); END; ` @@ -73,7 +74,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { throw new Error('expected the original child') } const database = openTestJournalHostDatabase(current.root) - const before = liveTestJournalRows(database.db, SESSION) + const before = readTestJournalOutcomes(database.db, SESSION) vi.spyOn(console, 'warn').mockImplementation(() => undefined) database.db.exec(REJECT_RECOVERED_ROWS) await current.host.handleAdapterEvent({ @@ -91,7 +92,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { runtimeFence: child.fence + 1, deathEvidence: { kind: 'exit-observed', ownerFence: child.fence } }) - expect(liveTestJournalRows(database.db, SESSION)).toEqual(before) + expect(readTestJournalOutcomes(database.db, SESSION)).toEqual(before) return { session, database, deadFence: child.fence } } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts index ff51888df851..7feeff48e190 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import * as reducer from '../agent-session-journal/journal-reducer' -import { DISPATCH_DOUBT_SUBMISSION_MISSING } from '../agent-session-journal/journal-dispatch-doubt-reasons' import { sendStructuredAgentSessionTurn } from './structured-agent-session-host-mutations' import { mutateStructuredAgentSession } from './structured-agent-session-mutation-context' import { sendPlan } from './structured-agent-session-mutation-plans' @@ -121,7 +120,8 @@ it('replays a queued draft after publication fails without waking delivery', asy expect(ctx.wakeDelivery).not.toHaveBeenCalled() }) -it('answers the same doubt on the first reply and resend when the committed row cannot fold', async () => { +// The row commits with its fold or not at all; nothing is recorded, so a resend runs again. +it('refuses the first reply and resend when the submission cannot fold', async () => { const ctx = context() const request = params() const fold = reducer.applyJournalRow @@ -133,26 +133,12 @@ it('answers the same doubt on the first reply and resend when the committed row }) const journal = rig.host['sessions'].get(SESSION)!.journal const append = vi.spyOn(journal, 'appendSubmission') - const accepted = await sendStructuredAgentSessionTurn(ctx, CALLER, request) + const refused = await sendStructuredAgentSessionTurn(ctx, CALLER, request) const replay = await sendStructuredAgentSessionTurn(ctx, CALLER, request) - expect(accepted).toMatchObject({ - ok: true, - replayed: true, - value: { - submission: { - dispatchState: 'unknown', - reason: DISPATCH_DOUBT_SUBMISSION_MISSING, - recovered: true - } - } - }) - expect(replay).toEqual(accepted) + expect(refused).toMatchObject({ ok: false }) + expect(replay).toMatchObject({ ok: false }) expect(journal.submissions()).toHaveLength(0) - expect( - rig.store.readCommandReceipt({ kind: 'global' }, request.envelope.clientOperationId) - ).toMatchObject({ verdict: 'readable', receipt: { status: 'accepted' } }) - expect(append).toHaveBeenCalledOnce() - expect(ctx.wakeDelivery).toHaveBeenCalledOnce() + expect(append).toHaveBeenCalledTimes(2) }) it('logs a throw after commit and wakes once before answering from receipt replay', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts index 5642a0fc26e1..d6b260f364bc 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts @@ -95,85 +95,6 @@ async function relaunch(): Promise { return host } -const NEWER_APPROVAL: AgentJournalItemBody = JSON.parse( - JSON.stringify({ - kind: 'approval', - title: 'Review proposed change', - detail: null, - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - options: [{ id: 'allow', label: 'Approve' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - }) -) - -it("settles a newer Orca's pending approval as it was, and the chat takes its next message", async () => { - await attach() - emit(7, NEWER_APPROVAL) - const host = await relaunch() - - expect(await send(host, 'after the newer approval')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalled()) - - const approval = (await historyBodies(host)).find((body) => body.kind === 'approval') - expect(approval).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - -// A newer background approval can block queues forever; a direct send starts the turn that cancels it. -it("takes a send past a newer Orca's live approval, and the next turn's card cancel settles it", async () => { - // Model providers whose card Cancel requires the live turn’s Stop path. - const dismissPrompt = vi.fn(async ({ commit }: { commit: () => Promise }) => commit()) - Object.assign(hostTestState().host.deps.adapter, { - routePromptCancel: () => ({ kind: 'stop' }), - dismissPrompt - }) - await attach() - emit(7, NEWER_APPROVAL) - const { host } = hostTestState() - await host.flushStreamedEvents(SESSION) - - const body = hostTestMessage('queued behind it') - const queuedFields = { body, delivery: 'queue-if-active' as const } - expect( - await host.send(CALLER, { - envelope: envelope('agentSession.send', queuedFields), - ...queuedFields - }) - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - expect(hostTestState().dispatch).not.toHaveBeenCalled() - - const sent = await send(host, 'carry on') - expect(sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalledOnce()) - providerEvents().appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'turn-2', ordinal: 8 }, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: NOW }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(SESSION) - - const card = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.body.kind === 'approval' - )! - const fields = { - turnId: 'turn-2', - prompt: { itemId: card.itemId, expectedRevision: card.revision } - } - expect( - await host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) - ).toMatchObject({ ok: true }) - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(hostTestState().cancelTurn).not.toHaveBeenCalled() - expect((await historyBodies(host)).find((entry) => entry.kind === 'approval')).toMatchObject({ - subject: { kind: 'diff' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - it('ends a turn whose provider output would not read back as failed, and the next send works', async () => { const closeSession = vi.fn(async () => true) Object.assign(hostTestState().host.deps.adapter, { closeSession }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts index 4e4587b2c189..aaa088eb3520 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts @@ -328,35 +328,6 @@ describe("a card's own Cancel, as its provider answers it", () => { return { result, routes, answerPrompt, dismissPrompt, card } } - describe('on an approval whose subject a newer Orca wrote, which only its Cancel answers', () => { - const NEWER_SUBJECT: AgentJournalApprovalSubject = JSON.parse('{"kind":"diff","path":"a.ts"}') - - it('has Claude decline the request, the turn going on, and keeps the subject as it was', async () => { - const { routes, dismissPrompt, card } = await cancelCard( - { kind: 'dismiss' }, - 1, - true, - true, - NEWER_SUBJECT - ) - - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(routes.interrupt).not.toHaveBeenCalled() - expect(routes.stop).not.toHaveBeenCalled() - expect(card).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts' }, - resolution: { state: 'cancelled' } - }) - }) - - it('has Codex end the turn holding it', async () => { - const { routes, dismissPrompt } = await cancelCard(undefined, 1, true, true, NEWER_SUBJECT) - - expect(routes.interrupt).toHaveBeenCalledOnce() - expect(dismissPrompt).not.toHaveBeenCalled() - }) - }) - it('interrupts the turn holding the card for a provider that gives no answer', async () => { const { routes, answerPrompt } = await cancelCard(undefined) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts new file mode 100644 index 000000000000..f80288b9d120 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect } from 'vitest' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalAnsweredTurnIdentity, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' +import { + createQueuedMessageTestRig, + type QueuedMessageTestRig +} from './structured-agent-session-queued-message-rig.test-fixture' + +let rig: QueuedMessageTestRig + +beforeEach(async () => { + rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) +}) + +afterEach(() => rig.dispose()) + +export const db = () => openTestJournalHostDatabase(rig.root).db + +export const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }], + ...(text === '/compact' ? { command: { name: 'compact' } } : {}) +}) + +export const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +export const words = (fact: 'providerRejected' | 'cancelled') => + agentSessionFailureWords( + fact === 'providerRejected' + ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) + : agentSessionFailureFact(fact), + { surface: 'rejection' } + ) + +export function journalFor(sessionId: string): AgentSessionJournal { + return new AgentSessionJournal({ + database: openTestJournalHostDatabase(rig.root), + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle + } + }) +} + +export async function handOff( + journal: AgentSessionJournal, + attempt: string, + card: string, + text: string, + as: 'providerRejected' | 'cancelled' | 'accepted', + fence = 0, + beforeAnswer?: () => Promise, + answeredInTurn?: AgentJournalAnsweredTurnIdentity +): Promise { + const body = message(text) + const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) + await journal.appendSubmission({ + clientMessageId: attempt, + payloadFingerprint, + body, + fence, + handoverRecorded: true, + queuedMessageId: card + }) + await journal.resolveDispatch({ + clientMessageId: attempt, + state: 'pending', + fence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await beforeAnswer?.() + await journal.resolveDispatch( + as === 'accepted' + ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } + : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } + ) +} + +export type Legacy = [ + id: string, + state: string, + text: string | null, + consumedAs?: string, + hold?: string +] + +export function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { + const insert = db().prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` + ) + rows.forEach(([id, state, text, consumedAs, hold], index) => { + const body = text === null ? '{' : JSON.stringify(message(text)) + const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) + const reason = state === 'returned' ? 'refused before' : null + insert.run( + sessionId, + id, + index + 1, + body, + print, + state, + hold ?? null, + reason, + consumedAs ?? null + ) + }) +} + +export const legacyIds = (sessionId = SESSION) => + db() + .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') + .all(sessionId) + .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) + +export function queueRows(sessionId = SESSION): string[] { + return readTestQueueChanges(db(), sessionId).map( + ({ messageId, op, returned }) => `${messageId}:${op}${returned ? '+refusal' : ''}` + ) +} + +export async function nothingSentTo(...cards: string[]): Promise { + await new Promise((resolve) => setTimeout(resolve, 100)) + for (const card of cards) { + expect(await rig.handoff(card)).toBeUndefined() + } +} + +export const retainedHistoryCases = [ + { adopt: false, proof: 'none' }, + { adopt: true, proof: 'none' }, + { adopt: false, proof: 'dispatch' }, + { adopt: true, proof: 'item' } +] + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts new file mode 100644 index 000000000000..e7205de6c27c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts @@ -0,0 +1,206 @@ +import { expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + reduceStructuredAgentSession +} from '../../../shared/structured-agent-session-reducer' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { readAgentSessionHistory } from './agent-session-history-page' +import { subscriberHistoryReader } from './agent-session-bounded-frames' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + db, + handOff, + journalFor, + message, + retainedHistoryCases, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { + const earlier = journalFor(SESSION) + await earlier.open() + const append = async (journal: AgentSessionJournal, ordinal: number) => { + await journal.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('x'.repeat(4_000)), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await append(earlier, 0) + await handOff( + earlier, + 'u', + 'q', + 'stopped words', + 'cancelled', + 0, + async () => { + for (let index = 1; index <= 205; index++) { + await append(earlier, index) + } + }, + proof === 'none' + ? undefined + : { + turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, + via: 'steer' + } + ) + const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) + expect(stale.ok).toBe(true) + await earlier.close() + seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + if (!adopt) { + db().exec('DROP TRIGGER b2_fail_import') + } + const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } + const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) + const base = { sessionId: SESSION, journal, fence: 0 } + const oldEvents: AgentSessionSubscribeEvent[] = [] + feed.open({ + ...base, + id: 'old', + cursor: journal.cursor(), + snapshotCatchUp: false, + readsCurrentRequests: false, + emit: (event) => oldEvents.push(event) + }) + expect(oldEvents).toEqual([ + { + type: 'batch', + sessionId: SESSION, + fence: 0, + hostNow: expect.any(Number), + activity: null, + ...queue, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } + } + ]) + const corrected: AgentSessionSubscribeEvent[][] = [] + const clients: (() => ReturnType)[] = [] + for (const boundedFrames of [false, true]) { + let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { + type: 'history-page', + page: structuredClone(stale.page) + }) + const events: AgentSessionSubscribeEvent[] = [] + corrected.push(events) + clients.push(() => state) + const reader = subscriberHistoryReader({ boundedFrames }) + feed.open({ + ...base, + id: `new-${boundedFrames}`, + cursor: journal.cursor(), + boundedFrames, + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => { + events.push(event) + state = reduceStructuredAgentSession(state, { + type: 'event', + event: structuredClone(event) + }) + } + }) + expect(events[0]?.type).toBe('snapshot') + while (state.hasOlder) { + const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } + const older = readAgentSessionHistory( + journal, + { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, + { reader } + ) + expect(older.ok).toBe(true) + state = reduceStructuredAgentSession(state, { + type: 'older-page', + requestedCursor, + page: structuredClone(older.page) + }) + } + const canonical = journal.snapshot() + expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) + feed.publish(SESSION, journal) + await append(journal, 205) + feed.publish(SESSION, journal) + } + const cursor = journal.cursor() + const after = readAgentSessionHistory(journal, { + sessionId: SESSION, + direction: 'after', + cursor + }) + expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) + if (!adopt) { + await journal.queuedMessages.importAtOpen() + feed.publish(SESSION, journal) + } + if (proof !== 'none') { + const placed = journal + .snapshot() + .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) + const loaded = clients.map((client) => client().items.length) + const normalizationKey = journal.publicRead().normalizationKey + const identity = { + provider: 'codex' as const, + threadId: 'history', + turnId: 't', + ordinal: 206 + } + if (proof === 'dispatch') { + await journal.acceptLate({ + clientMessageId: 'u', + state: 'accepted', + fence: 0, + providerIdentity: identity + }) + } + await journal.appendItem(identity, message('stopped words'), threadWrite) + feed.publish(SESSION, journal) + expect(journal.submission('u')?.dispatchState).toBe('accepted') + expect(journal.receiptFor('u')).not.toBeNull() + expect(journal.publicRead().normalizationKey).toBe(normalizationKey) + expect(clients.map((client) => client().items.length)).toEqual(loaded) + for (const client of clients) { + expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ + sequence: placed?.sequence, + observedAt: placed?.observedAt, + turnScope: placed?.turnScope, + revision: 1 + }) + expect( + client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState + ).toBe('accepted') + } + } + expect( + corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) + ).toEqual([1, 1]) + expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) + await journal.close() + const reopened = journalFor(SESSION) + await reopened.open() + const resumed: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + ...base, + journal: reopened, + id: 'reopen', + cursor: reopened.cursor(), + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => resumed.push(event) + }) + expect(resumed[0]?.type).toBe('snapshot') + await reopened.close() +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts new file mode 100644 index 000000000000..62463e7ce2bd --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts @@ -0,0 +1,207 @@ +import { expect, it, vi } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createAgentSessionCatchUpReader } from './agent-session-history-page' +import { + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { + eventually, + QUEUED_RIG_CALLER as CALLER +} from './structured-agent-session-queued-message-rig.test-fixture' + +import { + fixture, + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + nothingSentTo, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { + const journal = journalFor(SESSION) + const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) + seedLegacy(SESSION, rows) + db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + await journal.open() + expect(legacyIds()).toHaveLength(size) + const feed = new AgentSessionSubscribers() + const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } + const received: AgentSessionSubscribeEvent[][] = [[], [], []] + received.forEach((events, index) => + feed.open({ + ...base, + id: String(index), + boundedFrames: index === 1, + snapshotCatchUp: index !== 2, + readsCurrentRequests: index !== 2, + emit: (event) => events.push(event) + }) + ) + let visits = 0 + const flatMap = Array.prototype.flatMap + const scans = vi.spyOn(Array.prototype, 'flatMap') + scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { + const legacy = this.length === size && this[0]?.messageId === 'waiting-0' + return flatMap.call(this, (...args) => { + visits += legacy ? 1 : 0 + return callback.apply(thisArg, args) + }) + }) + try { + const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } + await journal.appendItem(turn, message('progress'), threadWrite) + feed.publish(SESSION, journal) + expect(visits).toBe(2 * size) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) + for (const events of received) { + const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) + expect(items.map((i) => i.body)).toContainEqual(message('progress')) + expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) + } + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } + await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) + feed.publish(SESSION, journal) + const view = journal.publicRead() + expect(view.normalizationKey).not.toBe('') + expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ + dispatchState: 'unknown', + queuedMessageId: 'waiting-0' + }) + const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) + expect(item?.body).toEqual(message('words')) + expect(item?.sequence).toBeLessThan(journal.cursor().sequence) + expect(journal.submission('u')?.dispatchState).toBe('rejected') + expect(visits).toBeGreaterThanOrEqual(2 * size) + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) + } finally { + scans.mockRestore() + db().exec('DROP TRIGGER b2_raw_fail_import') + await journal.close() + } +}) + +it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { + const earlier = journalFor(SESSION) + await earlier.open() + await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) + await handOff(earlier, 'u', 'q', 'words', 'cancelled') + await earlier.close() + seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) + db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const journal = journalFor(SESSION) + await journal.open() + const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) + const key = journal.publicRead().normalizationKey + const snapshot = journal.snapshot() + expect(journal.snapshot()).toBe(snapshot) + expect(key).not.toBe('') + const cursor = journal.cursor() + const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) + const request = { sessionId: SESSION, direction: 'tail' as const } + const beforeImport = catchUp(request) + expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) + db().exec('DROP TRIGGER b2_source_fail_import') + await journal.queuedMessages.importAtOpen() + expect(journal.cursor()).toEqual(cursor) + expect(legacyIds()).toEqual([]) + expect(journal.snapshot()).not.toBe(snapshot) + expect(catchUp(request)).toEqual(beforeImport) + expect(ids).toHaveBeenCalledTimes(1) + expect(journal.publicRead().normalizationKey).toBe(key) + expect(ids).toHaveBeenCalledTimes(2) + ids.mockRestore() + const identity = { provider: 'orca' as const, clientMessageId: 'u' } + await journal.appendTombstone(identity, { fence: 0 }) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.appendItem(identity, message('recreated'), threadWrite) + expect([key, '']).not.toContain(journal.publicRead().normalizationKey) + expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) + await journal.rollEpoch('handle_forked', 0) + expect(journal.epoch).not.toBe(cursor.epoch) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.close() +}) + +it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { + const earlier = journalFor(SESSION) + const clear = { command: 'clear' as const } + expect( + await fixture.rig.host.conversationCommand(CALLER, { + ...clear, + envelope: fixture.rig.envelope( + clear, + 'agentSession.conversationCommand', + hostTestOperationId() + ) + }) + ).toMatchObject({ ok: true }) + const target = fixture.rig.send('rewound away') + expect(await target.result).toMatchObject({ ok: true }) + await eventually(async () => + expect((await fixture.rig.submission(target.id))?.handedOverAt).toBeDefined() + ) + await fixture.rig.settleAccepted(target.id, 'target') + await fixture.rig.host.close(SESSION, 'evict') + await earlier.open() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await handOff( + earlier, + 'att-refused', + 'disp-refused', + 'refused, never settled', + 'providerRejected', + fence + ) + await earlier.close() + seedLegacy(SESSION, [ + ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], + ['edited', 'waiting', 'waiting, edited'] + ]) + db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const held = [ + { messageId: 'disp-refused', state: 'returned' }, + { messageId: 'edited', state: 'waiting' } + ] + expect(await fixture.rig.drafts()).toEqual(held) + db().exec('DROP TRIGGER fail_import') + warned.mockRestore() + + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } + expect( + await fixture.rig.host.rewind(CALLER, { + ...rewound, + envelope: fixture.rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) + }) + ).toMatchObject({ ok: true }) + expect(live.epoch).toBe(rewound.expectedEpoch) + expect(live.submission('att-refused')).toBeUndefined() + expect(await fixture.rig.drafts()).toEqual(held) + await nothingSentTo('edited') + expect(legacyIds()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts new file mode 100644 index 000000000000..e0b17e43649e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts @@ -0,0 +1,167 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( + 'publication reuse: $size historical items, adopted=$adopt', + async ({ size, adopt }) => { + const corrections = size / 10 + const earlier = journalFor(SESSION) + await earlier.open() + await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { + for (let ordinal = 0; ordinal < size; ordinal++) { + await earlier.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('old answer'), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + }) + for (let index = 1; index < corrections; index++) { + await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') + } + await earlier.close() + seedLegacy( + SESSION, + Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) + ) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) + const display = journal.queuedMessages.displayState() + const feed = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + let visits = 0 + let keyVisits = 0 + function counted(iterator: MapIterator, correction = false): MapIterator { + const next = iterator.next.bind(iterator) + iterator.next = (...args) => { + const result = next(...args) + if (!result.done) { + if (correction) { + keyVisits++ + } else { + visits++ + } + } + return result + } + return iterator + } + const values = Map.prototype.values + const entries = Map.prototype[Symbol.iterator] + const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( + this: Map + ) { + return counted(values.call(this)) + }) + const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( + this: Map + ) { + return counted(entries.call(this)) + }) + const setIterator = Set.prototype[Symbol.iterator] + const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( + this: Set + ) { + return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) + }) + const gets = vi.spyOn(Map.prototype, 'get') + const sourceGets = () => + gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) + const sorts = vi.spyOn(Array.prototype, 'sort') + const json = vi.spyOn(JSON, 'stringify') + const work = () => [ + keyVisits, + sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, + json.mock.calls.filter( + ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' + ).length + ] + const reset = () => { + keyVisits = 0 + gets.mockClear() + sorts.mockClear() + json.mockClear() + } + try { + for (const id of ['perf-a', 'perf-b', 'old']) { + feed.open({ + sessionId: SESSION, + journal, + fence: 0, + id, + boundedFrames: id === 'perf-b', + cursor: journal.cursor(), + snapshotCatchUp: id !== 'old', + readsCurrentRequests: id !== 'old', + emit: (event) => events.push(event) + }) + } + expect(work()).toEqual([corrections, 1, 1]) + expect(sourceGets()).toHaveLength(2 * corrections) + expect(visits).toBeGreaterThanOrEqual(size) + const key = journal.publicRead().normalizationKey + reset() + visits = 0 + for (let publication = 0; publication < 5; publication++) { + feed.publish(SESSION, journal) + } + // Only subscriber visits; history copies/materialization would add N visits. + expect(visits).toBe(15) + expect(work()).toEqual([0, 0, 0]) + expect(sourceGets()).toHaveLength(0) + const cursor = journal.cursor() + const snapshot = journal.snapshot() + await journal.open() + expect(journal.cursor()).toEqual(cursor) + expect(journal.queuedMessages.displayState() === display).toBe(false) + expect(journal.snapshot()).not.toBe(snapshot) + feed.publish(SESSION, journal) + // A reopen that retries the failed import writes one card; its outcome write lists that card + // once in the card map and once in the order set: a constant 2, whatever the history size. + expect(work()).toEqual([corrections + (adopt ? 0 : 2), 1, 1]) + reset() + await journal.appendItem( + { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, + message('progress'), + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) + expect(work()).toEqual([0, 0, 0]) + reset() + feed.publish(SESSION, journal) + const latest = events.at(-1) + expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( + message('progress') + ) + expect(work()).toEqual([corrections, 1, 1]) + expect(journal.publicRead().normalizationKey).toBe(key) + } finally { + for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { + spy.mockRestore() + } + if (!adopt) { + db().exec('DROP TRIGGER b2_perf_fail_import') + } + } + expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) + await journal.close() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts index d23c33a6ba17..b64235a408e1 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts @@ -1,173 +1,29 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalAnsweredTurnIdentity, - type AgentJournalMessageItem -} from '../../../shared/agent-session-journal-types' -import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { projectStructuredAgentSessionMessages } from '../../../shared/structured-agent-session-message-projection' import { structuredAgentSessionCommandTurnIdentity } from '../../../shared/structured-agent-session-command-turn-identity' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - EMPTY_STRUCTURED_AGENT_SESSION, - reduceStructuredAgentSession -} from '../../../shared/structured-agent-session-reducer' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { - createAgentSessionCatchUpReader, - readAgentSessionHistory -} from './agent-session-history-page' -import { subscriberHistoryReader } from './agent-session-bounded-frames' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { HOST_TEST_SESSION as SESSION, hostTestOperationId } from './structured-agent-session-host-test-data' -import { - createQueuedMessageTestRig, - eventually, - QUEUED_RIG_CALLER as CALLER, - type QueuedMessageTestRig -} from './structured-agent-session-queued-message-rig.test-fixture' - -let rig: QueuedMessageTestRig - -beforeEach(async () => { - rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) -}) - -afterEach(() => rig.dispose()) - -const db = () => openTestJournalHostDatabase(rig.root).db -const message = (text: string): AgentJournalMessageItem => ({ - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }], - ...(text === '/compact' ? { command: { name: 'compact' } } : {}) -}) -const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } -const words = (fact: 'providerRejected' | 'cancelled') => - agentSessionFailureWords( - fact === 'providerRejected' - ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) - : agentSessionFailureFact(fact), - { surface: 'rejection' } - ) - -function journalFor(sessionId: string): AgentSessionJournal { - return new AgentSessionJournal({ - database: openTestJournalHostDatabase(rig.root), - identity: { - sessionId, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle - } - }) -} +import { eventually } from './structured-agent-session-queued-message-rig.test-fixture' -async function handOff( - journal: AgentSessionJournal, - attempt: string, - card: string, - text: string, - as: 'providerRejected' | 'cancelled' | 'accepted', - fence = 0, - beforeAnswer?: () => Promise, - answeredInTurn?: AgentJournalAnsweredTurnIdentity -): Promise { - const body = message(text) - const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) - await journal.appendSubmission({ - clientMessageId: attempt, - payloadFingerprint, - body, - fence, - handoverRecorded: true, - queuedMessageId: card - }) - await journal.resolveDispatch({ - clientMessageId: attempt, - state: 'pending', - fence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await beforeAnswer?.() - await journal.resolveDispatch( - as === 'accepted' - ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } - : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } - ) -} - -type Legacy = [id: string, state: string, text: string | null, consumedAs?: string, hold?: string] - -function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { - const insert = db().prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` - ) - rows.forEach(([id, state, text, consumedAs, hold], index) => { - const body = text === null ? '{' : JSON.stringify(message(text)) - const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) - const reason = state === 'returned' ? 'refused before' : null - insert.run( - sessionId, - id, - index + 1, - body, - print, - state, - hold ?? null, - reason, - consumedAs ?? null - ) - }) -} - -const legacyIds = (sessionId = SESSION) => - db() - .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') - .all(sessionId) - .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) - -function queueRows(sessionId = SESSION): string[] { - return db() - .prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(sessionId) - .flatMap((row) => { - const json = typeof row === 'object' && row !== null && 'row_json' in row ? row.row_json : '' - const parsed: unknown = JSON.parse(String(json)) - if (typeof parsed !== 'object' || parsed === null || !('kind' in parsed)) { - return [] - } - if (parsed.kind !== 'queue' || !('messageId' in parsed) || !('change' in parsed)) { - return [] - } - const change = JSON.stringify(parsed.change) - const op = /"op":"(\w+)"/.exec(change)?.[1] - return [`${String(parsed.messageId)}:${op}${change.includes('"returned"') ? '+refusal' : ''}`] - }) -} - -async function nothingSentTo(...cards: string[]): Promise { - await new Promise((resolve) => setTimeout(resolve, 100)) - for (const card of cards) { - expect(await rig.handoff(card)).toBeUndefined() - } -} +import { + fixture, + db, + handOff, + journalFor, + legacyIds, + nothingSentTo, + queueRows, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' it("moves an earlier build's cards into the journal, each action its own card, the rest once per open", async () => { // Legacy handoffs were journaled while cards lived in a separate table. - await rig.drafts() - await rig.host.close(SESSION, 'evict') + await fixture.rig.drafts() + await fixture.rig.host.close(SESSION, 'evict') const earlier = journalFor(SESSION) await earlier.open() await handOff(earlier, 'att-present', 'ret-present', 'returned here', 'providerRejected') @@ -210,14 +66,14 @@ it("moves an earlier build's cards into the journal, each action its own card, t { messageId: 'edited', state: 'waiting' }, { messageId: 'held', state: 'waiting', paused: true } ] - expect(await rig.drafts()).toEqual(published) + expect(await fixture.rig.drafts()).toEqual(published) const stopped = async () => { - const { items, submissions } = await rig.host.journalSnapshot(SESSION) + const { items, submissions } = await fixture.rig.host.journalSnapshot(SESSION) return projectStructuredAgentSessionMessages(items, [], submissions).find( (entry) => entry.id === agentJournalSubmissionKey('att-stopped') ) } - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const rawStopped = structuredClone(live.submission('att-stopped')) const displayedStopped = await stopped() expect(displayedStopped).toMatchObject({ @@ -236,26 +92,28 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(queueRows()).toEqual([]) const deletion = hostTestOperationId() - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ value: { deleted: true } }) - const sent = await rig.sendNow('ret-gone') + const sent = await fixture.rig.sendNow('ret-gone') expect(sent).toMatchObject({ ok: true, value: { submission: { queuedMessageId: 'ret-gone' } } }) + // Saved cards are whole values: an import stores each card as it reads, refused or not. expect(queueRows()).toEqual([ - 'ret-present:queued', + 'ret-present:queued+refusal', 'ret-present:withdrawn', - 'ret-gone:queued+refusal' + 'ret-gone:queued+refusal', + 'ret-gone:dispatched' ]) expect(legacyIds()).toEqual(all.filter((id) => id !== 'ret-present' && id !== 'ret-gone')) await nothingSentTo('edited', 'held') // Reopen imports atomically; write refusals only for handoffs absent from this epoch. - await rig.restartHostProcess() - expect(await rig.drafts()).toEqual(published.slice(2)) + await fixture.rig.restartHostProcess() + expect(await fixture.rig.drafts()).toEqual(published.slice(2)) expect(legacyIds()).toEqual(['broken']) - expect(queueRows().slice(3)).toEqual([ + expect(queueRows().slice(4)).toEqual([ 'cmd-gone:queued+refusal', - 'disp-refused:queued', + 'disp-refused:queued+refusal', 'stopped-same:queued', 'stopped-edited:queued', 'orphan:queued', @@ -266,33 +124,33 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(await stopped()).toEqual(displayedStopped) // Refused commands become spent once their own turn reports failure. - const adopted = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const adopted = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal await adopted.appendItem( structuredAgentSessionCommandTurnIdentity('att-cmd'), { kind: 'status', text: 'Compact failed' }, { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - expect(await rig.drafts()).toEqual(published.slice(3)) - expect(await rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) - await rig.resume() - await eventually(async () => expect(await rig.handoff('edited')).toBeDefined()) + expect(await fixture.rig.drafts()).toEqual(published.slice(3)) + expect(await fixture.rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) + await fixture.rig.resume() + await eventually(async () => expect(await fixture.rig.handoff('edited')).toBeDefined()) await nothingSentTo('held') - expect((await rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') - expect(await rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) - const resent = await rig.handoffId('stopped-edited') + expect((await fixture.rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') + expect(await fixture.rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) + const resent = await fixture.rig.handoffId('stopped-edited') expect(resent).not.toBe('att-edited') - await rig.settleAccepted(resent, 'resent') + await fixture.rig.settleAccepted(resent, 'resent') const rows = queueRows() - await rig.restartHostProcess() - await rig.drafts() + await fixture.rig.restartHostProcess() + await fixture.rig.drafts() expect(queueRows()).toEqual(rows) expect(await stopped()).toEqual(displayedStopped) expect(legacyIds()).toEqual(['broken']) - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ replayed: true, value: { deleted: true } }) @@ -313,519 +171,3 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(reopened.queuedMessages.list()).toEqual([]) await reopened.close() }) - -it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( - 'publication reuse: $size historical items, adopted=$adopt', - async ({ size, adopt }) => { - const corrections = size / 10 - const earlier = journalFor(SESSION) - await earlier.open() - await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { - for (let ordinal = 0; ordinal < size; ordinal++) { - await earlier.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('old answer'), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - }) - for (let index = 1; index < corrections; index++) { - await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') - } - await earlier.close() - seedLegacy( - SESSION, - Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) - ) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) - const display = journal.queuedMessages.displayState() - const feed = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - let visits = 0 - let keyVisits = 0 - function counted(iterator: MapIterator, correction = false): MapIterator { - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - if (correction) { - keyVisits++ - } else { - visits++ - } - } - return result - } - return iterator - } - const values = Map.prototype.values - const entries = Map.prototype[Symbol.iterator] - const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( - this: Map - ) { - return counted(values.call(this)) - }) - const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( - this: Map - ) { - return counted(entries.call(this)) - }) - const setIterator = Set.prototype[Symbol.iterator] - const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( - this: Set - ) { - return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) - }) - const gets = vi.spyOn(Map.prototype, 'get') - const sourceGets = () => - gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) - const sorts = vi.spyOn(Array.prototype, 'sort') - const json = vi.spyOn(JSON, 'stringify') - const work = () => [ - keyVisits, - sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, - json.mock.calls.filter( - ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' - ).length - ] - const reset = () => { - keyVisits = 0 - gets.mockClear() - sorts.mockClear() - json.mockClear() - } - try { - for (const id of ['perf-a', 'perf-b', 'old']) { - feed.open({ - sessionId: SESSION, - journal, - fence: 0, - id, - boundedFrames: id === 'perf-b', - cursor: journal.cursor(), - snapshotCatchUp: id !== 'old', - readsCurrentRequests: id !== 'old', - emit: (event) => events.push(event) - }) - } - expect(work()).toEqual([corrections, 1, 1]) - expect(sourceGets()).toHaveLength(2 * corrections) - expect(visits).toBeGreaterThanOrEqual(size) - const key = journal.publicRead().normalizationKey - reset() - visits = 0 - for (let publication = 0; publication < 5; publication++) { - feed.publish(SESSION, journal) - } - // Only subscriber visits; history copies/materialization would add N visits. - expect(visits).toBe(15) - expect(work()).toEqual([0, 0, 0]) - expect(sourceGets()).toHaveLength(0) - const cursor = journal.cursor() - const snapshot = journal.snapshot() - await journal.open() - expect(journal.cursor()).toEqual(cursor) - expect(journal.queuedMessages.displayState() === display).toBe(false) - expect(journal.snapshot()).not.toBe(snapshot) - feed.publish(SESSION, journal) - expect(work()).toEqual([corrections, 1, 1]) - reset() - await journal.appendItem( - { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, - message('progress'), - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) - expect(work()).toEqual([0, 0, 0]) - reset() - feed.publish(SESSION, journal) - const latest = events.at(-1) - expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( - message('progress') - ) - expect(work()).toEqual([corrections, 1, 1]) - expect(journal.publicRead().normalizationKey).toBe(key) - } finally { - for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { - spy.mockRestore() - } - if (!adopt) { - db().exec('DROP TRIGGER b2_perf_fail_import') - } - } - expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) - await journal.close() - } -) - -it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { - const journal = journalFor(SESSION) - const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) - seedLegacy(SESSION, rows) - db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - await journal.open() - expect(legacyIds()).toHaveLength(size) - const feed = new AgentSessionSubscribers() - const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } - const received: AgentSessionSubscribeEvent[][] = [[], [], []] - received.forEach((events, index) => - feed.open({ - ...base, - id: String(index), - boundedFrames: index === 1, - snapshotCatchUp: index !== 2, - readsCurrentRequests: index !== 2, - emit: (event) => events.push(event) - }) - ) - let visits = 0 - const flatMap = Array.prototype.flatMap - const scans = vi.spyOn(Array.prototype, 'flatMap') - scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { - const legacy = this.length === size && this[0]?.messageId === 'waiting-0' - return flatMap.call(this, (...args) => { - visits += legacy ? 1 : 0 - return callback.apply(thisArg, args) - }) - }) - try { - const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } - await journal.appendItem(turn, message('progress'), threadWrite) - feed.publish(SESSION, journal) - expect(visits).toBe(2 * size) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) - for (const events of received) { - const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) - expect(items.map((i) => i.body)).toContainEqual(message('progress')) - expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) - } - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } - await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) - feed.publish(SESSION, journal) - const view = journal.publicRead() - expect(view.normalizationKey).not.toBe('') - expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ - dispatchState: 'unknown', - queuedMessageId: 'waiting-0' - }) - const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) - expect(item?.body).toEqual(message('words')) - expect(item?.sequence).toBeLessThan(journal.cursor().sequence) - expect(journal.submission('u')?.dispatchState).toBe('rejected') - expect(visits).toBeGreaterThanOrEqual(2 * size) - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) - } finally { - scans.mockRestore() - db().exec('DROP TRIGGER b2_raw_fail_import') - await journal.close() - } -}) - -it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { - const earlier = journalFor(SESSION) - await earlier.open() - await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) - await handOff(earlier, 'u', 'q', 'words', 'cancelled') - await earlier.close() - seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) - db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const journal = journalFor(SESSION) - await journal.open() - const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) - const key = journal.publicRead().normalizationKey - const snapshot = journal.snapshot() - expect(journal.snapshot()).toBe(snapshot) - expect(key).not.toBe('') - const cursor = journal.cursor() - const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) - const request = { sessionId: SESSION, direction: 'tail' as const } - const beforeImport = catchUp(request) - expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) - db().exec('DROP TRIGGER b2_source_fail_import') - await journal.queuedMessages.importAtOpen() - expect(journal.cursor()).toEqual(cursor) - expect(legacyIds()).toEqual([]) - expect(journal.snapshot()).not.toBe(snapshot) - expect(catchUp(request)).toEqual(beforeImport) - expect(ids).toHaveBeenCalledTimes(1) - expect(journal.publicRead().normalizationKey).toBe(key) - expect(ids).toHaveBeenCalledTimes(2) - ids.mockRestore() - const identity = { provider: 'orca' as const, clientMessageId: 'u' } - await journal.appendTombstone(identity, { fence: 0 }) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.appendItem(identity, message('recreated'), threadWrite) - expect([key, '']).not.toContain(journal.publicRead().normalizationKey) - expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) - await journal.rollEpoch('handle_forked', 0) - expect(journal.epoch).not.toBe(cursor.epoch) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.close() -}) - -it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { - const earlier = journalFor(SESSION) - const clear = { command: 'clear' as const } - expect( - await rig.host.conversationCommand(CALLER, { - ...clear, - envelope: rig.envelope(clear, 'agentSession.conversationCommand', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - const target = rig.send('rewound away') - expect(await target.result).toMatchObject({ ok: true }) - await eventually(async () => - expect((await rig.submission(target.id))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(target.id, 'target') - await rig.host.close(SESSION, 'evict') - await earlier.open() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await handOff( - earlier, - 'att-refused', - 'disp-refused', - 'refused, never settled', - 'providerRejected', - fence - ) - await earlier.close() - seedLegacy(SESSION, [ - ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], - ['edited', 'waiting', 'waiting, edited'] - ]) - db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const held = [ - { messageId: 'disp-refused', state: 'returned' }, - { messageId: 'edited', state: 'waiting' } - ] - expect(await rig.drafts()).toEqual(held) - db().exec('DROP TRIGGER fail_import') - warned.mockRestore() - - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } - expect( - await rig.host.rewind(CALLER, { - ...rewound, - envelope: rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - expect(live.epoch).toBe(rewound.expectedEpoch) - expect(live.submission('att-refused')).toBeUndefined() - expect(await rig.drafts()).toEqual(held) - await nothingSentTo('edited') - expect(legacyIds()).toEqual([]) -}) - -const retainedHistoryCases = [ - { adopt: false, proof: 'none' }, - { adopt: true, proof: 'none' }, - { adopt: false, proof: 'dispatch' }, - { adopt: true, proof: 'item' } -] -it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { - const earlier = journalFor(SESSION) - await earlier.open() - const append = async (journal: AgentSessionJournal, ordinal: number) => { - await journal.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('x'.repeat(4_000)), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await append(earlier, 0) - await handOff( - earlier, - 'u', - 'q', - 'stopped words', - 'cancelled', - 0, - async () => { - for (let index = 1; index <= 205; index++) { - await append(earlier, index) - } - }, - proof === 'none' - ? undefined - : { - turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, - via: 'steer' - } - ) - const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) - expect(stale.ok).toBe(true) - await earlier.close() - seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - if (!adopt) { - db().exec('DROP TRIGGER b2_fail_import') - } - const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } - const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) - const base = { sessionId: SESSION, journal, fence: 0 } - const oldEvents: AgentSessionSubscribeEvent[] = [] - feed.open({ - ...base, - id: 'old', - cursor: journal.cursor(), - snapshotCatchUp: false, - readsCurrentRequests: false, - emit: (event) => oldEvents.push(event) - }) - expect(oldEvents).toEqual([ - { - type: 'batch', - sessionId: SESSION, - fence: 0, - hostNow: expect.any(Number), - activity: null, - ...queue, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - } - ]) - const corrected: AgentSessionSubscribeEvent[][] = [] - const clients: (() => ReturnType)[] = [] - for (const boundedFrames of [false, true]) { - let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { - type: 'history-page', - page: structuredClone(stale.page) - }) - const events: AgentSessionSubscribeEvent[] = [] - corrected.push(events) - clients.push(() => state) - const reader = subscriberHistoryReader({ boundedFrames }) - feed.open({ - ...base, - id: `new-${boundedFrames}`, - cursor: journal.cursor(), - boundedFrames, - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => { - events.push(event) - state = reduceStructuredAgentSession(state, { - type: 'event', - event: structuredClone(event) - }) - } - }) - expect(events[0]?.type).toBe('snapshot') - while (state.hasOlder) { - const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } - const older = readAgentSessionHistory( - journal, - { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, - { reader } - ) - expect(older.ok).toBe(true) - state = reduceStructuredAgentSession(state, { - type: 'older-page', - requestedCursor, - page: structuredClone(older.page) - }) - } - const canonical = journal.snapshot() - expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) - feed.publish(SESSION, journal) - await append(journal, 205) - feed.publish(SESSION, journal) - } - const cursor = journal.cursor() - const after = readAgentSessionHistory(journal, { - sessionId: SESSION, - direction: 'after', - cursor - }) - expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) - if (!adopt) { - await journal.queuedMessages.importAtOpen() - feed.publish(SESSION, journal) - } - if (proof !== 'none') { - const placed = journal - .snapshot() - .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) - const loaded = clients.map((client) => client().items.length) - const normalizationKey = journal.publicRead().normalizationKey - const identity = { - provider: 'codex' as const, - threadId: 'history', - turnId: 't', - ordinal: 206 - } - if (proof === 'dispatch') { - await journal.acceptLate({ - clientMessageId: 'u', - state: 'accepted', - fence: 0, - providerIdentity: identity - }) - } - await journal.appendItem(identity, message('stopped words'), threadWrite) - feed.publish(SESSION, journal) - expect(journal.submission('u')?.dispatchState).toBe('accepted') - expect(journal.receiptFor('u')).not.toBeNull() - expect(journal.publicRead().normalizationKey).toBe(normalizationKey) - expect(clients.map((client) => client().items.length)).toEqual(loaded) - for (const client of clients) { - expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ - sequence: placed?.sequence, - observedAt: placed?.observedAt, - turnScope: placed?.turnScope, - revision: 1 - }) - expect( - client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState - ).toBe('accepted') - } - } - expect( - corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) - ).toEqual([1, 1]) - expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) - await journal.close() - const reopened = journalFor(SESSION) - await reopened.open() - const resumed: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - ...base, - journal: reopened, - id: 'reopen', - cursor: reopened.cursor(), - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => resumed.push(event) - }) - expect(resumed[0]?.type).toBe('snapshot') - await reopened.close() -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts new file mode 100644 index 000000000000..b2b106efb964 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts @@ -0,0 +1,34 @@ +import { + seedLegacyTestJournal, + openTestJournalHostDatabase, + pinTestJournalInputMode +} from '../agent-session-journal/journal-host-database-test-support' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { HOST_TEST_NOW, HOST_TEST_THREAD } from './structured-agent-session-host-test-data' +import type { StructuredAgentSessionHost } from './structured-agent-session-host' + +export function seedQueuedRigLegacyJournal( + root: string, + sessionId: string, + agent?: 'claude' +): (host: StructuredAgentSessionHost) => void { + seedLegacyTestJournal(openTestJournalHostDatabase(root), { + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: agent ?? 'codex', + providerHandle: + agent === 'claude' + ? claudeProviderHandle(HOST_TEST_THREAD, null) + : codexProviderHandle(HOST_TEST_THREAD) + }, + now: () => HOST_TEST_NOW + }) + // Attaching opens the journal; the pin keeps it writing inputs, as a build from before conversion did. + return (host) => + pinTestJournalInputMode(host.collaboratorsForTests().sessions.get(sessionId)!.journal) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts index 51c1bd9cda03..bae85f50c355 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts @@ -30,6 +30,7 @@ import { closeTestJournalHostDatabase, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { seedQueuedRigLegacyJournal } from './structured-agent-session-queued-legacy-journal.test-fixture' import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' import { createQueuedRigProvider, @@ -53,6 +54,7 @@ export type QueuedMessageTestRig = Awaited number /** Teardown records its restart offers, which `restartOffers` lists. */ @@ -100,7 +102,11 @@ export async function createQueuedMessageTestRig( } as const) : {}) }) + const pinLegacy = options.legacyInputs && seedQueuedRigLegacyJournal(root, SESSION, options.agent) expect(await host.attach(QUEUED_RIG_CALLER, firstAttach)).toMatchObject({ ok: true }) + if (pinLegacy) { + pinLegacy(host) + } function envelope( fields: Record, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts index 1f99738b249a..cdde63d6491f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts @@ -645,6 +645,11 @@ describe('a failed Stop', () => { try { // Post-interrupt failure cannot undo the committed Stop receipt. expect(await rig.stop()).toMatchObject({ ok: true }) + expect(failing).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ kind: 'status' }), + expect.anything() + ) } finally { failing.mockRestore() warned.mockRestore() diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts index c8567377e574..4c261cd23377 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' import { HOST_TEST_SESSION as SESSION, @@ -34,26 +37,9 @@ async function queuedDraft(text: string): Promise { } function queueRows(): { messageId: string; op: string }[] { - return openTestJournalHostDatabase(rig.root) - .db.prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(SESSION) - .flatMap((row) => { - const parsed: unknown = - typeof row === 'object' && row !== null && 'row_json' in row - ? JSON.parse(String(row.row_json)) - : null - return typeof parsed === 'object' && - parsed !== null && - 'kind' in parsed && - parsed.kind === 'queue' && - 'messageId' in parsed && - 'change' in parsed && - typeof parsed.change === 'object' && - parsed.change !== null && - 'op' in parsed.change - ? [{ messageId: String(parsed.messageId), op: String(parsed.change.op) }] - : [] - }) + return readTestQueueChanges(openTestJournalHostDatabase(rig.root).db, SESSION).map( + ({ messageId, op }) => ({ messageId, op }) + ) } async function expectNothingSent(...draftIds: string[]): Promise { @@ -92,8 +78,12 @@ it('holds the cards behind it through a rewind, a new epoch, a restart and a Res { messageId: c, state: 'waiting' } ] await eventually(async () => expect(await rig.drafts()).toEqual(held)) - // Refusal lives in dispatch state, without another card row. - expect(queueRows()).toEqual([a, b, c].map((messageId) => ({ messageId, op: 'queued' }))) + // Refusal returns the same card in place: its own state changes, and no card is added. + expect(queueRows()).toEqual([ + ...[a, b, c].map((messageId) => ({ messageId, op: 'queued' })), + { messageId: a, op: 'dispatched' }, + { messageId: a, op: 'returned' } + ]) const rewound = { itemId: target, expectedEpoch: journal().cursor().epoch } expect( diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts index 73c0d4ec979f..53f2b3ff411c 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts @@ -14,7 +14,7 @@ import { QUIT_CUT_NOTICE, readerNotes, statusNotes, - continuationCannotFold + continuationUnanswered } from './structured-agent-session-restart-interruption-test-harness' import { CALLER, envelope } from './structured-agent-session-host-test-harness' import { @@ -99,10 +99,11 @@ it("keeps the quit's notice through a continuation that carries the chat on", as }) it('keeps an unconfirmed failure while the agent the continuation started keeps running', async () => { - const { host } = await interruptedRestart() + const state = await interruptedRestart() + const { host } = state vi.spyOn(console, 'warn').mockImplementation(() => {}) await host.restartResume.list() - continuationCannotFold() + continuationUnanswered(state) const result = await host.restartResume.continueAfterRestart([SESSION], 'modal') diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts index 21610afa1e7e..a1f2794bd1db 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts @@ -186,21 +186,29 @@ export function throwAfterContinuationAccepted(): void { }) } -/** Fail folding after continuation commit to model uncertain readback; install immediately before sending. */ +/** Fail the continuation's fold; its row and receipt roll back before any dispatch. */ export function continuationCannotFold(): void { const fold = reducer.applyJournalRow vi.spyOn(reducer, 'applyJournalRow').mockImplementation((state, row) => { - if (row.kind !== 'submission') { - fold(state, row) - return + if (row.kind === 'submission') { + throw new Error('the continuation could not fold') } - // Advance sequence/fence before failure, matching reducer ordering. - state.lastSequence = Math.max(state.lastSequence, row.seq) - state.highestFence = Math.max(state.highestFence, row.fence) - throw new Error('the accepted continuation could not fold') + fold(state, row) }) } +/** The agent admits the continuation but no delivery proof arrives; only its later output can settle it. */ +export function continuationUnanswered(state: { + host: StructuredAgentSessionHost + dispatch: ReturnType['dispatch'] +}): void { + state.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const wait = state.host.waitForSendSettlement + vi.spyOn(state.host, 'waitForSendSettlement').mockImplementation(async (...args) => + args[2]?.until === 'handed-over' ? wait(...args) : undefined + ) +} + export async function statusNotes(host: StructuredAgentSessionHost) { return notesOf((await host.journalSnapshot(SESSION)).items) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts index da5c14366867..eaaad55032b5 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts @@ -5,9 +5,7 @@ import { AGENT_SESSION_RECOVERY_CAPSULE_FILE, AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' -import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' import { - insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, updateTestJournalRowJson @@ -27,26 +25,17 @@ afterEach(() => vi.restoreAllMocks()) function newerOrcaRow(root: string, sessionId: string = SESSION): void { const { db } = openTestJournalHostDatabase(root) - const last = liveTestJournalRows(db, sessionId).at(-1) - const parsed: unknown = last ? JSON.parse(last.rowJson) : null - if (!last || typeof parsed !== 'object' || parsed === null || !('epoch' in parsed)) { - throw new Error('the chat has no journal row to follow') + const first = liveTestJournalRows(db, sessionId)[0] + if (!first) { + throw new Error('the chat has no founding row') } - const { epoch } = parsed - const seq = last.seq + 1 - insertTestJournalRowJson( + const anchor = JSON.parse(first.rowJson) + db.prepare('UPDATE journal_outcome_epochs SET format = 99 WHERE session_id = ?').run(sessionId) + updateTestJournalRowJson( db, sessionId, - seq, - JSON.stringify({ - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: NOW - }), - NOW + 1, + JSON.stringify({ ...anchor, v: 99, outcomeFormat: 99 }) ) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts index 80ba77eaa0e0..f65f41633d40 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts @@ -142,8 +142,9 @@ it('replays the same logical continuation through the durable send ledger', asyn expect(dispatch).toHaveBeenCalledTimes(1) }) -it('keeps a continuation unconfirmed when its accepted message cannot be read back', async () => { - const { host, store } = await interruptedRestart() +// The row commits with its fold or not at all, and dispatch reads only committed sends. +it('refuses a continuation whose message cannot be recorded, without handing it to the agent', async () => { + const { host, dispatch } = await interruptedRestart() vi.spyOn(console, 'warn').mockImplementation(() => {}) expect(await host.restartResume.list()).toHaveLength(1) continuationCannotFold() @@ -152,17 +153,10 @@ it('keeps a continuation unconfirmed when its accepted message cannot be read ba .continueAfterRestart([SESSION], 'modal') .finally(() => vi.restoreAllMocks()) - expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'unknown' }]) - expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'unconfirmed' }]) - expect(await statusNotes(host)).toContainEqual({ - text: AGENT_SESSION_RESTART_CONTINUATION_UNCONFIRMED_NOTE, - tone: 'warning' - }) - expect( - store - .listOperationRows() - .find((row) => row.callerKey === STRUCTURED_AGENT_SESSION_RESTART_CONTINUATION_CALLER) - ).toMatchObject({ outcome: { status: 'succeeded' } }) + expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect((await host.journalSnapshot(SESSION)).submissions).toEqual([]) + expect(dispatch).not.toHaveBeenCalled() }) it('reports a continuation delivered when its send throws after its message is in the chat', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts index ef956f17cf84..e53253208264 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts @@ -4,7 +4,7 @@ import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wi import { AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' import { interruptedRestart, - continuationCannotFold, + continuationUnanswered, startAgent } from './structured-agent-session-restart-interruption-test-harness' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -165,7 +165,8 @@ it('publishes skipped for an offer started elsewhere and sends no continuation', it.each(['continued', 'refused', 'unconfirmed'] as const)( 'publishes %s before bookkeeping finishes, then clears progress on return', async (phase) => { - const { host, acquire } = await interruptedRestart() + const state = await interruptedRestart() + const { host, acquire } = state await host.restartResume.list() const summaries: AgentSessionStatusSummary[] = [] const release = host.subscribeStatus({ @@ -180,7 +181,7 @@ it.each(['continued', 'refused', 'unconfirmed'] as const)( acquire.mockRejectedValueOnce(new Error('start refused')) } if (phase === 'unconfirmed') { - continuationCannotFold() + continuationUnanswered(state) } const bookkeeping = Promise.withResolvers() const complete = AgentSessionRecoveryCapsule.prototype.completeResume diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts index 1316dd40fbbc..383ad1efec8f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts @@ -4,10 +4,7 @@ import { expectRetainedPrefixRewindReplay } from './structured-agent-session-rewind-replay.test-fixture' import { expectRawStopNoteRewindRecovery } from './structured-agent-session-rewind-stop-note.test-fixture' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody -} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -624,42 +621,6 @@ describe('host rewind', () => { expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.phase).toBe('completed') }) - it("keeps a newer Orca's item of an unknown kind, in its place, through a Codex provider hydration", async () => { - expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) - const message = (turnId: string) => ({ - provider: 'codex' as const, - threadId: HOST_TEST_THREAD, - turnId, - ordinal: 0 - }) - const newerRow = { provider: 'orca' as const, clientMessageId: 'newer-card' } - const newerBody: AgentJournalItemBody = JSON.parse( - JSON.stringify({ kind: 'plan-card', steps: [{ text: 'by a newer build' }] }) - ) - sink.appendItem(message('kept'), hostTestMessage('kept'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - sink.appendItem(newerRow, newerBody, { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - sink.appendItem(message('drop'), hostTestMessage('drop'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await host.flushStreamedEvents(HOST_TEST_SESSION) - - expect( - await host.rewind(caller, await params(agentJournalItemKey(message('drop')))) - ).toMatchObject({ ok: true }) - - expect( - (await host.journalSnapshot(HOST_TEST_SESSION)).items.map(({ itemId, body }) => ({ - itemId, - body - })) - ).toEqual([ - { itemId: agentJournalItemKey(message('kept')), body: hostTestMessage('kept') }, - { itemId: agentJournalItemKey(newerRow), body: newerBody } - ]) - }) - it('keeps each kept turn opened by the message that opened it, under its provider key', async () => { expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) const message = (turnId: string, ordinal = 0) => ({ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts index 66dbf8d7847c..e1454b350cb8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts @@ -2,6 +2,7 @@ import type { StructuredAgentSessionFirstMessage } from '../../../shared/structu import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { SendParams } from '../../../shared/rpc-contract/structured-agent-session-params' import { agentSessionMessagePayload, agentSessionSendBodyFingerprint @@ -271,6 +272,25 @@ describe('a send carrying its model and effort', () => { refusal: { code: 'agent_session_operation_conflict' } }) }) + + // Every client field the host keeps passes through a reader that drops what it does not know, so + // the chat holds only keys storage declares and reopens after a newer client's send. + it("sends a newer client's message with a choice this build does not know, storing it without that choice", async () => { + const body = hostTestMessage('from a newer client') + const fields = { body: agentSessionMessagePayload(body), options: { ...PICKED, later: 'on' } } + const params = { + envelope: rig.envelope(fields, 'agentSession.send', hostTestOperationId()), + ...fields, + body + } + expect(SendParams.safeParse(params).success).toBe(true) + expect(await rig.host.send(CALLER, params)).toMatchObject({ + ok: true, + value: { submission: { options: PICKED } } + }) + await rig.restartHostProcess() + expect((await rig.submission(params.envelope.clientOperationId))?.options).toEqual(PICKED) + }) }) describe('a send kept as a card because Orca stopped before handing it over', () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts index f90aee202848..f482e687badd 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts @@ -1,731 +1,244 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemIdentity, - AgentJournalRenderItem, - AgentJournalTurnScope -} from '../../../shared/agent-session-journal-types' -import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' -import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' import { runningTurnLifecycleRevisions, turnVerdictFromDeathEvidence, UNVERIFIABLE_TURN_VERDICT } from './structured-agent-session-stale-turn-verdict' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' - -const THREAD = 'thread-1' -const RUNNING_IDENTITY = { - provider: 'codex' as const, - threadId: THREAD, - turnId: 'turn-2', - ordinal: 0 -} - -function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { - return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } -} - -function lifecycleItem( - turnId: string, - state: 'running' | 'completed', - sequence: number, - extra: { startedAt?: number; completedAt?: number } = {} -): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), - revision: 1, - sequence, - observedAt: sequence, - body: { kind: 'turn', turnId, state, ...extra } - } -} - -/** Read legacy status-form lifecycle carriers without writing them back. */ -function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { - return { - ...lifecycleItem(turnId, 'running', 2), - body: { - kind: 'status', - text: 'Working', - turnLifecycle: { turnId, state: 'running', startedAt } - } - } -} - -function promptItem(state: 'pending' | 'resolved', sequence: number): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `approval-${state}` - }), - revision: 1, - sequence, - observedAt: sequence, - body: { - kind: 'approval', - title: 'Approve?', - detail: null, - options: [], - resolution: { - state, - selectedOptionId: state === 'resolved' ? 'allow' : null, - resolvedBy: state === 'resolved' ? 'client-1' : null, - resolvedAt: state === 'resolved' ? 10 : null - } - } - } -} - -describe('turn verdict from death evidence', () => { - const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => - turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) - - it('ends a watched exit at the exit', () => { - expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ - state: 'interrupted', - completedAt: 500 - }) - }) - - it.each(['pid-absent', 'identity-mismatch'] as const)( - 'ends a %s proof at the last proof of life, never after the probe', - (kind) => { - const proof = (lastProvenAliveAt?: number) => ({ - kind, - detail: 'gone', - observedAt: 9_000, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - }) - // Last proof of life bounds completion so downtime is never counted as work. - expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) - expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) - expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) - } - ) - - it('ends a watched exit at the exit even when a renewal is recorded', () => { - expect( - verdictForTurn({ - kind: 'exit-observed', - detail: 'exit', - observedAt: 500, - lastProvenAliveAt: 400 - }) - ).toEqual({ state: 'interrupted', completedAt: 500 }) - }) - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps proven exit without an invalid time %s', - (observedAt) => { - expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ - state: 'interrupted' - }) - } - ) - - it('leaves a release nothing proved unverifiable', () => { - expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) - expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) - }) - it('keeps the rule an older build applied to evidence that names no owner', () => { - // Legacy ownerless evidence proves only observed exit, never probe results. - const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ - state: 'interrupted', - completedAt: 9_000 - }) - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ - state: 'unverifiable' - }) +import { + RUNNING_IDENTITY, + journalWith, + legacyLifecycleItem, + lifecycleItem, + verdictForTurn +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('ends a watched exit at the exit', () => { + expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ + state: 'interrupted', + completedAt: 500 }) +}) - it('gives a turn no end from evidence about any other owner', () => { - const proof = { - kind: 'pid-absent' as const, +it.each(['pid-absent', 'identity-mismatch'] as const)( + 'ends a %s proof at the last proof of life, never after the probe', + (kind) => { + const proof = (lastProvenAliveAt?: number) => ({ + kind, detail: 'gone', observedAt: 9_000, - lastProvenAliveAt: 8_000 - } - // Another owner’s death or unknown turn provenance cannot prove this owner ended. - for (const [evidence, turnFence] of [ - [{ ...proof, ownerFence: 3 }, 1], - [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], - [{ ...proof, ownerFence: 1 }, undefined] - ] as const) { - expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) - } - }) + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) + }) + // Last proof of life bounds completion so downtime is never counted as work. + expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) + expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) + expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) + } +) + +it('ends a watched exit at the exit even when a renewal is recorded', () => { + expect( + verdictForTurn({ + kind: 'exit-observed', + detail: 'exit', + observedAt: 500, + lastProvenAliveAt: 400 + }) + ).toEqual({ state: 'interrupted', completedAt: 500 }) }) -describe('running turn lifecycle revisions', () => { - it('revises only running rows in place and carries an end time only for an observed exit', () => { - const items = [ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) - ] - expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual( - [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { - kind: 'turn', - turnId: 'turn-2', - state: 'interrupted', - startedAt: 30, - completedAt: 40 - }, - turnScope: { kind: 'thread' } - } - ] - ) - expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ - expect.objectContaining({ - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } - }) - ]) - }) - - it('keeps known turn fields and extensions in the rewrite', () => { - const contextUsage = { - used: { - kind: 'estimate' as const, - usage: { - inputTokens: 1, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 90_000, - outputTokens: 5 - }, - capturedAt: 35 - } - } - const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - const body = { - ...running.body, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true }, - outcome: 'success' as const, - durationMs: 7 - } - const items: AgentJournalRenderItem[] = [{ ...running, body }] - const kept = { - kind: 'turn', - turnId: 'turn-2', - startedAt: 30, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true } - } - expect( - runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] - ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) - expect(items[0]?.body).toHaveProperty('laterField') - const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] - expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ - ...kept, - state: 'unverifiable' +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps proven exit without an invalid time %s', + (observedAt) => { + expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ + state: 'interrupted' }) - }) + } +) - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps an untimed interruption for %s even when the saved turn has a start', - (completedAt) => { - const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) - expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) - const [mutation] = runningTurnLifecycleRevisions([item], { - state: 'interrupted', - completedAt - }) - expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') - } - ) +it('leaves a release nothing proved unverifiable', () => { + expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) + expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) +}) - it('never ends a turn before it began, when the last proof of life predates it', () => { - const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) - expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) +it('keeps the rule an older build applied to evidence that names no owner', () => { + // Legacy ownerless evidence proves only observed exit, never probe results. + const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ + state: 'interrupted', + completedAt: 9_000 }) - - it('revises a legacy status-form running row from an older host into a typed turn', () => { - expect( - runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) - ).toEqual([ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, - turnScope: { kind: 'thread' } - } - ]) - }) - - it('revises a saved row by its key even when its identity cannot be parsed', () => { - const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } - expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ - { - kind: 'item', - itemId: 'not-an-item-key', - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ + state: 'unverifiable' }) }) -const PROVEN: AgentSessionDeathEvidence = { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 100 -} - -describe('stale session state on a cold acquire', () => { - function journalWith(items: AgentJournalRenderItem[]) { - const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. - const journal = { - snapshot: () => ({ items }), - itemFence: () => 1, - lastProviderActivityAt: () => undefined, - stopMarks: { latest: () => null }, - cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), - submissions: () => [], - appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) - } as unknown as AgentSessionJournal - return { journal, appendLifecycleBatch } +it('gives a turn no end from evidence about any other owner', () => { + const proof = { + kind: 'pid-absent' as const, + detail: 'gone', + observedAt: 9_000, + lastProvenAliveAt: 8_000 } + // Another owner’s death or unknown turn provenance cannot prove this owner ended. + for (const [evidence, turnFence] of [ + [{ ...proof, ownerFence: 3 }, 1], + [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], + [{ ...proof, ownerFence: 1 }, undefined] + ] as const) { + expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) + } +}) - it('marks a running row from the dead generation unverifiable without an end time', async () => { - const { journal, appendLifecycleBatch } = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - ]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it('cancels only prompts whose callbacks were lost with the prior owner', async () => { - const pending = promptItem('pending', 1) - const resolved = promptItem('resolved', 2) - const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: pending.itemId, - body: { - ...pending.body, - resolution: { - state: 'cancelled', - selectedOptionId: null, - resolvedBy: null, - resolvedAt: null - } - }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { - // Producer-free cancellation revisions must retain original attribution. - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => 1_000 - }) - const child = { agentId: 'thread-child', producerKind: 'agent' as const } - const { body } = promptItem('pending', 1) - const prompt = (threadId: string) => ({ - provider: 'codex' as const, - threadId, - turnId: 'turn-1', - ordinal: 1 - }) - await journal.appendItem(prompt('thread-child'), body, { - fence: 1, - ...child, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(prompt(THREAD), body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - - expect( - journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) - ).toEqual([ - ['approval', 2, 'thread-child'], - ['approval', 2, undefined] - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('uses provider output after a renewal, excluding a later client message', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } - const turnScope = turnScopeOf({ ...command, ordinal: 0 }) - await journal.appendItem( - { ...command, ordinal: 0 }, - { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, - { fence: 1, turnScope } - ) - now = 200 - await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) - // Provider output can prove life after lease renewal. - now = 700 - await journal.appendItem( - command, - { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, - { fence: 1, turnScope } - ) - now = 800 - await journal.appendItem( - { provider: 'orca', clientMessageId: 'late-send' }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, - { fence: 1, turnScope } - ) - now = 9_000 - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 650 - } - }) - - const items = journal.snapshot().items - expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ +it('revises only running rows in place and carries an end time only for an observed exit', () => { + const items = [ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) + ] + expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { + kind: 'turn', + turnId: 'turn-2', state: 'interrupted', - completedAt: 700 - }) - expect( - items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : [])) - ).toEqual([ - 'The agent stopped while this response was in progress. You can continue in this conversation.' - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) + startedAt: 30, + completedAt: 40 + }, + turnScope: { kind: 'thread' } } - }) - - it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 200 - await journal.appendItem( - { ...RUNNING_IDENTITY, ordinal: 1 }, - { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 1, - acquisitionGeneration: null, - deathEvidence - }) - now = 3_600_000 - await settle(null) - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) - now = 3_605_000 - await journal.appendSubmission({ - clientMessageId: 'send-1', - payloadFingerprint: 'fingerprint-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, - fence: 1, - handoverRecorded: true - }) - await journal.resolveDispatch({ - clientMessageId: 'send-1', - state: 'pending', - turnScope: AGENT_JOURNAL_THREAD_SCOPE, - fence: 1 - }) - now = 3_606_000 - - await settle({ - kind: 'pid-absent', - detail: 'gone', - observedAt: 3_606_000, - ownerFence: 1, - lastProvenAliveAt: 210 - }) + ]) + expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ + expect.objectContaining({ + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } + }) + ]) +}) - expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) +it('keeps known turn fields and extensions in the rewrite', () => { + const contextUsage = { + used: { + kind: 'estimate' as const, + usage: { + inputTokens: 1, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 90_000, + outputTokens: 5 + }, + capturedAt: 35 } + } + const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + const body = { + ...running.body, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true }, + outcome: 'success' as const, + durationMs: 7 + } + const items: AgentJournalRenderItem[] = [{ ...running, body }] + const kept = { + kind: 'turn', + turnId: 'turn-2', + startedAt: 30, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true } + } + expect( + runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] + ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) + expect(items[0]?.body).toHaveProperty('laterField') + const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] + expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ + ...kept, + state: 'unverifiable' }) +}) - it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 400 - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence - }) - await settle(null) - now = 9_000 - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps an untimed interruption for %s even when the saved turn has a start', + (completedAt) => { + const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) + expect( + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) + const [mutation] = runningTurnLifecycleRevisions([item], { + state: 'interrupted', + completedAt + }) + expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') + } +) - const unrevised = journal.cursor() - await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) - const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN - await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) - expect(journal.cursor()).toEqual(unrevised) - expect(turn()).toMatchObject({ state: 'unverifiable' }) +it('never ends a turn before it began, when the last proof of life predates it', () => { + const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) + expect( + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) +}) - await expect(settle(PROVEN)).resolves.toBe(2) - expect(turn()).toEqual({ - turnId: 'turn-2', - state: 'interrupted', - startedAt: 100, - completedAt: 100 - }) - const revised = journal.cursor() - await expect(settle(PROVEN)).resolves.toBe(0) - expect(journal.cursor()).toEqual(revised) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) +it('revises a legacy status-form running row from an older host into a typed turn', () => { + expect( + runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) + ).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, + turnScope: { kind: 'thread' } } - }) - - it('adds one row for a death however many attempts its settle takes to write', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - for (let index = 0; index < 399; index++) { - const turnId = `turn-${index}` - await journal.appendItem( - { ...RUNNING_IDENTITY, turnId }, - { kind: 'turn', turnId, state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } - ) - } - now = 9_000 - const settle = () => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence: PROVEN - }) - const turns = () => - journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) - const statusRows = () => - journal.snapshot().items.filter((item) => item.body.kind === 'status') - const database = openTestJournalHostDatabase(root) - const cursor = journal.cursor() - database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} - AND json_extract(NEW.row_json, '$.recovered') = 1 - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - - await expect(settle()).rejects.toThrow('disk full') - database.db.exec('DROP TRIGGER reject_later_stale_settlement') - expect(journal.cursor()).toEqual(cursor) - expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) - expect(statusRows()).toHaveLength(0) + ]) +}) - await settle() - expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) - expect(statusRows()).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) +it('revises a saved row by its key even when its identity cannot be parsed', () => { + const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } + expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ + { + kind: 'item', + itemId: 'not-an-item-key', + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE } - }) + ]) +}) - it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { - const idle = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) - ]) - await expect( - settleStaleStructuredAgentSessionState({ - journal: idle.journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: null, - deathEvidence: null - }) - ).resolves.toBe(0) - expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() +it('marks a running row from the dead generation unverifiable without an end time', async () => { + const { journal, appendLifecycleBatch } = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + ]) - const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) - await settleStaleStructuredAgentSessionState({ - journal: running.journal, + await expect( + settleStaleStructuredAgentSessionState({ + journal, sessionId: 'session-1', fence: 14, - acquisitionGeneration: null, + acquisitionGeneration: 'generation-2', deathEvidence: null }) - expect(running.appendLifecycleBatch).toHaveBeenCalledWith( - expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) - ) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, + turnScope: { kind: 'thread' } + } + ] }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts new file mode 100644 index 000000000000..9620ca2989e4 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts @@ -0,0 +1,107 @@ +import { vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalRenderItem, + AgentJournalTurnScope +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' +import { turnVerdictFromDeathEvidence } from './structured-agent-session-stale-turn-verdict' + +export const THREAD = 'thread-1' + +export const RUNNING_IDENTITY = { + provider: 'codex' as const, + threadId: THREAD, + turnId: 'turn-2', + ordinal: 0 +} + +export function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { + return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } +} + +export function lifecycleItem( + turnId: string, + state: 'running' | 'completed', + sequence: number, + extra: { startedAt?: number; completedAt?: number } = {} +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), + revision: 1, + sequence, + observedAt: sequence, + body: { kind: 'turn', turnId, state, ...extra } + } +} + +/** Read legacy status-form lifecycle carriers without writing them back. */ + +export function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { + return { + ...lifecycleItem(turnId, 'running', 2), + body: { + kind: 'status', + text: 'Working', + turnLifecycle: { turnId, state: 'running', startedAt } + } + } +} + +export function promptItem( + state: 'pending' | 'resolved', + sequence: number +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `approval-${state}` + }), + revision: 1, + sequence, + observedAt: sequence, + body: { + kind: 'approval', + title: 'Approve?', + detail: null, + options: [], + resolution: { + state, + selectedOptionId: state === 'resolved' ? 'allow' : null, + resolvedBy: state === 'resolved' ? 'client-1' : null, + resolvedAt: state === 'resolved' ? 10 : null + } + } + } +} + +export const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => + turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) + +export const PROVEN: AgentSessionDeathEvidence = { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 100 +} + +export function journalWith(items: AgentJournalRenderItem[]) { + const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. + const journal = { + snapshot: () => ({ items }), + itemFence: () => 1, + lastProviderActivityAt: () => undefined, + stopMarks: { latest: () => null }, + cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), + submissions: () => [], + appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) + } as unknown as AgentSessionJournal + return { journal, appendLifecycleBatch } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts new file mode 100644 index 000000000000..9ec2aabca8b1 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts @@ -0,0 +1,167 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + PROVEN, + RUNNING_IDENTITY, + THREAD, + journalWith, + lifecycleItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 400 + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence + }) + await settle(null) + now = 9_000 + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + const unrevised = journal.cursor() + await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) + const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN + await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) + expect(journal.cursor()).toEqual(unrevised) + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + await expect(settle(PROVEN)).resolves.toBe(2) + expect(turn()).toEqual({ + turnId: 'turn-2', + state: 'interrupted', + startedAt: 100, + completedAt: 100 + }) + const revised = journal.cursor() + await expect(settle(PROVEN)).resolves.toBe(0) + expect(journal.cursor()).toEqual(revised) + expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('adds one row for a death however many attempts its settle takes to write', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + for (let index = 0; index < 399; index++) { + const turnId = `turn-${index}` + await journal.appendItem( + { ...RUNNING_IDENTITY, turnId }, + { kind: 'turn', turnId, state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } + ) + } + now = 9_000 + const settle = () => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence: PROVEN + }) + const turns = () => + journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) + const statusRows = () => journal.snapshot().items.filter((item) => item.body.kind === 'status') + const database = openTestJournalHostDatabase(root) + const cursor = journal.cursor() + database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} + AND json_extract(NEW.row_json, '$.recovered') = 1 + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + + await expect(settle()).rejects.toThrow('disk full') + database.db.exec('DROP TRIGGER reject_later_stale_settlement') + expect(journal.cursor()).toEqual(cursor) + expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) + expect(statusRows()).toHaveLength(0) + + await settle() + expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) + expect(statusRows()).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { + const idle = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) + ]) + await expect( + settleStaleStructuredAgentSessionState({ + journal: idle.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + ).resolves.toBe(0) + expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() + + const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) + await settleStaleStructuredAgentSessionState({ + journal: running.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + expect(running.appendLifecycleBatch).toHaveBeenCalledWith( + expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) + ) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts new file mode 100644 index 000000000000..6506e8a4326a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts @@ -0,0 +1,250 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + RUNNING_IDENTITY, + THREAD, + journalWith, + promptItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('cancels only prompts whose callbacks were lost with the prior owner', async () => { + const pending = promptItem('pending', 1) + const resolved = promptItem('resolved', 2) + const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) + + await expect( + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ + { + kind: 'item', + itemId: pending.itemId, + body: { + ...pending.body, + resolution: { + state: 'cancelled', + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + }, + turnScope: { kind: 'thread' } + } + ] + }) +}) + +it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { + // Producer-free cancellation revisions must retain original attribution. + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => 1_000 + }) + const child = { agentId: 'thread-child', producerKind: 'agent' as const } + const { body } = promptItem('pending', 1) + const prompt = (threadId: string) => ({ + provider: 'codex' as const, + threadId, + turnId: 'turn-1', + ordinal: 1 + }) + await journal.appendItem(prompt('thread-child'), body, { + fence: 1, + ...child, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(prompt(THREAD), body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + + expect( + journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) + ).toEqual([ + ['approval', 2, 'thread-child'], + ['approval', 2, undefined] + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('uses provider output after a renewal, excluding a later client message', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } + const turnScope = turnScopeOf({ ...command, ordinal: 0 }) + await journal.appendItem( + { ...command, ordinal: 0 }, + { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, + { fence: 1, turnScope } + ) + now = 200 + await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) + // Provider output can prove life after lease renewal. + now = 700 + await journal.appendItem( + command, + { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, + { fence: 1, turnScope } + ) + now = 800 + await journal.appendItem( + { provider: 'orca', clientMessageId: 'late-send' }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, + { fence: 1, turnScope } + ) + now = 9_000 + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 650 + } + }) + + const items = journal.snapshot().items + expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ + state: 'interrupted', + completedAt: 700 + }) + expect(items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : []))).toEqual([ + 'The agent stopped while this response was in progress. You can continue in this conversation.' + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 200 + await journal.appendItem( + { ...RUNNING_IDENTITY, ordinal: 1 }, + { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: null, + deathEvidence + }) + now = 3_600_000 + await settle(null) + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + now = 3_605_000 + await journal.appendSubmission({ + clientMessageId: 'send-1', + payloadFingerprint: 'fingerprint-1', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, + fence: 1, + handoverRecorded: true + }) + await journal.resolveDispatch({ + clientMessageId: 'send-1', + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + fence: 1 + }) + now = 3_606_000 + + await settle({ + kind: 'pid-absent', + detail: 'gone', + observedAt: 3_606_000, + ownerFence: 1, + lastProvenAliveAt: 210 + }) + + expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts index c7ee7dcb14ce..4178893ea746 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts @@ -29,13 +29,8 @@ function journal() { } function stopEvents(): JournalStopEvent[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [row.stopEvent] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [mark.event] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted', userId?: string) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts index 795498bb3060..89adad2dd816 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts @@ -64,13 +64,8 @@ it('does not treat completed submission history as a send in an empty reinitiali }) function stopEvents(): { sequence: number; event: JournalStopEvent }[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [{ sequence: row.seq, event: row.stopEvent }] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [{ sequence: mark.sequence, event: mark.event }] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted'): Promise { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts new file mode 100644 index 000000000000..2c978924622e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts @@ -0,0 +1,29 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' + +export const SESSION = 'subscriber-session' + +let root: string + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts new file mode 100644 index 000000000000..89bd9238006e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts @@ -0,0 +1,108 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, + serializeRemoteRuntimePayload +} from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import type { JournalRow } from '../agent-session-journal/journal-row-schema' +import { + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { + const journalDir = join(fixture.root, 'oversized-removal-journal') + const seeded = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. + const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + const resumeCursor = seeded.cursor() + const seq = resumeCursor.sequence + const rows: JournalRow[] = [ + { + kind: 'item', + itemId: hugeItemId, + revision: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 1, + fence: 1, + ts: 2_000 + }, + { + kind: 'tombstone', + itemId: hugeItemId, + revision: 2, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 2, + fence: 1, + ts: 2_001 + } + ] + // Direct writes model legacy persisted rows. + await seeded.close() + const opened = openTestJournalHostDatabase(journalDir) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of rows) { + insertTestJournalRow(opened.db, SESSION, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + cursor: resumeCursor, + emit: (event) => events.push(event) + }) + + for (const event of events) { + expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + } + const reset = events.find((event) => event.type === 'reset') + expect(reset).toBeDefined() + + // Reset must advance past the unsendable row so later publications make progress. + const settled = events.length + subscribers.publish(SESSION, journal) + expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts new file mode 100644 index 000000000000..96ea49631c19 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts @@ -0,0 +1,214 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { + AgentSessionBackgroundTaskState, + AgentSessionStatusEvent, + AgentSessionSubscribeEvent +} from '../../../shared/agent-session-wire' +import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('reports every content publication to the journal hook, subscribed or not', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'hook-journal') + }) + const published: string[] = [] + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published_journal) => { + expect(published_journal).toBe(journal) + published.push(sessionId) + } + }) + + subscribers.publish(SESSION, journal) + subscribers.snapshot(SESSION, journal, 1) + + expect(published).toEqual([SESSION, SESSION]) +}) + +it('settles a session nobody is reading, from running to idle', async () => { + // Never open a subscriber: status must publish independently of transcript readers. + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'unread-journal') + }) + const statusFeed = new StructuredAgentSessionStatusFeed({ + logger: createStructuredAgentSessionLogger(), + sessions: new Map([ + [ + SESSION, + { + journal, + params: { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'git-worktree' + }, + provider: 'codex' + } + } + ] + ]), + getConversation: () => null, + now: () => 1_000 + }) + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) + }) + const statuses: AgentSessionStatusEvent[] = [] + statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) + const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const + + await journal.appendItem( + { ...turn, ordinal: 1 }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem( + turn, + { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) + }) + + await journal.appendTombstone(turn, { fence: 1 }) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'idle' }) + }) +}) + +it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('provider-1', null) + }, + stateDirectory: join(fixture.root, 'background-journal') + }) + let roster: AgentSessionBackgroundTaskState | null = null + const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + const backgroundTasks: AgentSessionBackgroundTaskState = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + roster = backgroundTasks + subscribers.republishBackgroundTasks(SESSION, 2) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 2, + hostNow: expect.any(Number), + backgroundTasks + }) + + await journal.appendItem( + { provider: 'orca', clientMessageId: 'after-background-fence' }, + { kind: 'status', text: 'After background state' }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) +}) + +it('publishes latest turn activity without advancing or adding journal rows', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-journal') + }) + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + subscribers.publish(SESSION, journal, { + turnId: 'turn-1', + text: 'Inspecting the session wire' + }) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 1, + hostNow: expect.any(Number), + activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } + }) + + subscribers.close(SESSION, 'subscriber-1') + subscribers.publish(SESSION, journal, null) + subscribers.open({ + id: 'reconnected', + sessionId: SESSION, + journal, + fence: 1, + cursor, + emit: (event) => events.push(event) + }) + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toMatchObject({ activity: null }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts index 92983d8e23f0..8afeba008283 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts @@ -1,561 +1,250 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { AgentSessionBackgroundTaskState, - AgentSessionStatusEvent, AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import type { JournalRow } from '../agent-session-journal/journal-row-schema' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import * as journalReducer from '../agent-session-journal/journal-reducer' import { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' import { StructuredAgentSessionJournalProjections } from './structured-agent-session-status-journal-projection' -import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' import { MAX_RETAINED_SESSION_ACTIVITIES } from './structured-agent-session-activity-retention' import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' - -const SESSION = 'subscriber-session' - -let root: string -const journals = createTrackedJournalOpener() - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import * as journalReducer from '../agent-session-journal/journal-reducer' -describe('AgentSessionSubscribers', () => { - it('renders history once per source for N/10N items and one/three readers', async () => { - const render = vi.spyOn(journalReducer, 'renderJournalState') - try { - for (const size of [100, 1000]) { - for (const readers of [1, 3]) { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, `${size}-${readers}`) - }) - const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - const identity = (ordinal: number) => ({ - provider: 'codex' as const, - threadId: 'thread-1', - turnId: 'turn', - ordinal - }) - const body = (text: string) => ({ - kind: 'message' as const, - role: 'assistant' as const, - blocks: [{ type: 'text' as const, text }] - }) - for (let index = 0; index < size; index++) { - await journal.appendItem(identity(index), body('initial'), options) +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('renders history once per source for N/10N items and one/three readers', async () => { + const render = vi.spyOn(journalReducer, 'renderJournalState') + try { + for (const size of [100, 1000]) { + for (const readers of [1, 3]) { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, `${size}-${readers}`) + }) + const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const identity = (ordinal: number) => ({ + provider: 'codex' as const, + threadId: 'thread-1', + turnId: 'turn', + ordinal + }) + const body = (text: string) => ({ + kind: 'message' as const, + role: 'assistant' as const, + blocks: [{ type: 'text' as const, text }] + }) + for (let index = 0; index < size; index++) { + await journal.appendItem(identity(index), body('initial'), options) + } + const projections = new StructuredAgentSessionJournalProjections() + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), + onJournalPublished: () => { + projections.read(journal, null) } - const projections = new StructuredAgentSessionJournalProjections() - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), - onJournalPublished: () => { - projections.read(journal, null) - } + }) + for (let index = 0; index < readers; index++) { + subscribers.open({ + id: String(index), + sessionId: SESSION, + journal, + fence: 1, + boundedFrames: index === 1, + emit: (event) => events.push(event) }) - for (let index = 0; index < readers; index++) { - subscribers.open({ - id: String(index), - sessionId: SESSION, - journal, - fence: 1, - boundedFrames: index === 1, - emit: (event) => events.push(event) - }) - } + } + subscribers.publish(SESSION, journal) + for (const text of ['streamed', 'newer']) { + const prior = journal.snapshot() + await journal.appendItem(identity(size - 1), body(text), options) + render.mockClear() + events.length = 0 subscribers.publish(SESSION, journal) - for (const text of ['streamed', 'newer']) { - const prior = journal.snapshot() - await journal.appendItem(identity(size - 1), body(text), options) - render.mockClear() - events.length = 0 - subscribers.publish(SESSION, journal) - expect(render).toHaveBeenCalledTimes(1) - const current = journal.snapshot() - expect(current).not.toBe(prior) - expect(current.items).toHaveLength(size) - expect(current.items.at(-1)?.body).toEqual(body(text)) - expect(journal.publicRead().snapshot).toBe(current) - expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) - expect( - events - .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) - .map((item) => item.body) - ).toEqual(Array.from({ length: readers }, () => body(text))) - expect(render).toHaveBeenCalledTimes(1) - } + expect(render).toHaveBeenCalledTimes(1) + const current = journal.snapshot() + expect(current).not.toBe(prior) + expect(current.items).toHaveLength(size) + expect(current.items.at(-1)?.body).toEqual(body(text)) + expect(journal.publicRead().snapshot).toBe(current) + expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) + expect( + events + .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) + .map((item) => item.body) + ).toEqual(Array.from({ length: readers }, () => body(text))) + expect(render).toHaveBeenCalledTimes(1) } } - } finally { - render.mockRestore() } - }) - - it('bounds retained turn activity across session churn', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'activity-churn-journal') - }) - const subscribers = new AgentSessionSubscribers() - - for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { - subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) - } - - expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) - }) - - it('publishes the current fence when a resumed cursor is already caught up', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'checkpoint-journal') - }) - const events: AgentSessionSubscribeEvent[] = [] + } finally { + render.mockRestore() + } +}) - new AgentSessionSubscribers().open({ - id: 'subscriber-1', +it('bounds retained turn activity across session churn', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 7, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - - expect(events).toEqual([ - { - type: 'batch', - sessionId: SESSION, - batch: { - cursor: journal.cursor(), - items: [], - removedItemIds: [], - submissions: [] - }, - fence: 7, - hostNow: expect.any(Number), - activity: null - } - ]) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-churn-journal') }) + const subscribers = new AgentSessionSubscribers() - it('stamps the host clock once per published frame', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'clock-journal') - }) - let now = 1_000 - let roster: AgentSessionBackgroundTaskState | null = null - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - now: () => (now += 1), - readBackgroundTasks: () => roster - }) - const emit = (event: AgentSessionSubscribeEvent): void => { - events.push(event) - } - subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) - subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) - await journal.appendItem( - { provider: 'orca', clientMessageId: 'clocked' }, - { kind: 'status', text: 'Clocked' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - roster = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - subscribers.republishBackgroundTasks(SESSION, 1) - subscribers.snapshot(SESSION, journal, 1) + for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { + subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) + } - expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ - 1_001, 1_002, - // Both subscribers of one publication read the same clock sample. - 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 - ]) - expect(events.map((event) => event.type)).toEqual([ - 'snapshot', - 'snapshot', - 'batch', - 'batch', - 'batch', - 'batch', - 'snapshot', - 'snapshot' - ]) - }) + expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) +}) - it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'catalog-journal') - }) - let commands = [{ name: 'first', kind: 'skill' as const }] - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) - subscribers.open({ - id: 'one', +it('publishes the current fence when a resumed cursor is already caught up', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[0]).toMatchObject({ type: 'snapshot', commands }) - commands = [{ name: 'second', kind: 'skill' as const }] - subscribers.publish(SESSION, journal) - expect(events[1]).toEqual({ - type: 'batch', - sessionId: SESSION, - fence: 7, - hostNow: expect.any(Number), - commands, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - }) - subscribers.open({ - id: 'two', - sessionId: SESSION, - journal, - cursor: journal.cursor(), - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[2]).toMatchObject({ type: 'batch', commands }) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'checkpoint-journal') }) - - it('reports every content publication to the journal hook, subscribed or not', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'hook-journal') - }) - const published: string[] = [] - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published_journal) => { - expect(published_journal).toBe(journal) - published.push(sessionId) - } - }) - - subscribers.publish(SESSION, journal) - subscribers.snapshot(SESSION, journal, 1) - - expect(published).toEqual([SESSION, SESSION]) - }) - - it('settles a session nobody is reading, from running to idle', async () => { - // Never open a subscriber: status must publish independently of transcript readers. - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'unread-journal') - }) - const statusFeed = new StructuredAgentSessionStatusFeed({ - logger: createStructuredAgentSessionLogger(), - sessions: new Map([ - [ - SESSION, - { - journal, - params: { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'git-worktree' - }, - provider: 'codex' - } - } - ] - ]), - getConversation: () => null, - now: () => 1_000 - }) - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) - }) - const statuses: AgentSessionStatusEvent[] = [] - statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) - const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const - - await journal.appendItem( - { ...turn, ordinal: 1 }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem( - turn, - { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) - }) - - await journal.appendTombstone(turn, { fence: 1 }) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'idle' }) - }) + const events: AgentSessionSubscribeEvent[] = [] + + new AgentSessionSubscribers().open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 7, + cursor: journal.cursor(), + emit: (event) => events.push(event) }) - it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', null) - }, - stateDirectory: join(root, 'background-journal') - }) - let roster: AgentSessionBackgroundTaskState | null = null - const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - const backgroundTasks: AgentSessionBackgroundTaskState = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - roster = backgroundTasks - subscribers.republishBackgroundTasks(SESSION, 2) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ + expect(events).toEqual([ + { type: 'batch', sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 2, - hostNow: expect.any(Number), - backgroundTasks - }) - - await journal.appendItem( - { provider: 'orca', clientMessageId: 'after-background-fence' }, - { kind: 'status', text: 'After background state' }, - { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) - }) - - it('publishes latest turn activity without advancing or adding journal rows', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') + batch: { + cursor: journal.cursor(), + items: [], + removedItemIds: [], + submissions: [] }, - stateDirectory: join(root, 'activity-journal') - }) - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - subscribers.publish(SESSION, journal, { - turnId: 'turn-1', - text: 'Inspecting the session wire' - }) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ - type: 'batch', - sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 1, + fence: 7, hostNow: expect.any(Number), - activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } - }) + activity: null + } + ]) +}) - subscribers.close(SESSION, 'subscriber-1') - subscribers.publish(SESSION, journal, null) - subscribers.open({ - id: 'reconnected', +it('stamps the host clock once per published frame', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 1, - cursor, - emit: (event) => events.push(event) - }) - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toMatchObject({ activity: null }) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'clock-journal') }) + let now = 1_000 + let roster: AgentSessionBackgroundTaskState | null = null + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + now: () => (now += 1), + readBackgroundTasks: () => roster + }) + const emit = (event: AgentSessionSubscribeEvent): void => { + events.push(event) + } + subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) + subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) + await journal.appendItem( + { provider: 'orca', clientMessageId: 'clocked' }, + { kind: 'status', text: 'Clocked' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + roster = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + subscribers.republishBackgroundTasks(SESSION, 1) + subscribers.snapshot(SESSION, journal, 1) + + expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ + 1_001, 1_002, + // Both subscribers of one publication read the same clock sample. + 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 + ]) + expect(events.map((event) => event.type)).toEqual([ + 'snapshot', + 'snapshot', + 'batch', + 'batch', + 'batch', + 'batch', + 'snapshot', + 'snapshot' + ]) +}) - it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { - const journalDir = join(root, 'oversized-removal-journal') - const seeded = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. - const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - const resumeCursor = seeded.cursor() - const seq = resumeCursor.sequence - const rows: JournalRow[] = [ - { - kind: 'item', - itemId: hugeItemId, - revision: 1, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 1, - fence: 1, - ts: 2_000 - }, - { - kind: 'tombstone', - itemId: hugeItemId, - revision: 2, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 2, - fence: 1, - ts: 2_001 - } - ] - // Direct writes model legacy persisted rows. - await seeded.close() - const opened = openTestJournalHostDatabase(journalDir) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of rows) { - insertTestJournalRow(opened.db, SESSION, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', +it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 1, - cursor: resumeCursor, - emit: (event) => events.push(event) - }) - - for (const event of events) { - expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - } - const reset = events.find((event) => event.type === 'reset') - expect(reset).toBeDefined() - - // Reset must advance past the unsendable row so later publications make progress. - const settled = events.length - subscribers.publish(SESSION, journal) - expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'catalog-journal') + }) + let commands = [{ name: 'first', kind: 'skill' as const }] + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) + subscribers.open({ + id: 'one', + sessionId: SESSION, + journal, + fence: 7, + emit: (event) => events.push(event) + }) + expect(events[0]).toMatchObject({ type: 'snapshot', commands }) + commands = [{ name: 'second', kind: 'skill' as const }] + subscribers.publish(SESSION, journal) + expect(events[1]).toEqual({ + type: 'batch', + sessionId: SESSION, + fence: 7, + hostNow: expect.any(Number), + commands, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } + }) + subscribers.open({ + id: 'two', + sessionId: SESSION, + journal, + cursor: journal.cursor(), + fence: 7, + emit: (event) => events.push(event) }) + expect(events[2]).toMatchObject({ type: 'batch', commands }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts new file mode 100644 index 000000000000..5cb96331c66d --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts @@ -0,0 +1,84 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentJournalToolCallItem +} from '../../../shared/agent-session-journal-types' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionSinkWatermarks +} from './structured-agent-session-event-sink' +import { testEventSinkLogging } from './structured-agent-session-logger-test-support' +import type { StructuredAgentSessionTransitionStep } from './structured-agent-session-transition' + +export const SESSION = 'session-transition' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const roots: string[] = [] + +afterEach(async () => { + await journals.closeAll() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +export function identity(recordId: string): AgentJournalItemIdentity { + return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } +} + +export function tool( + name: string, + state: AgentJournalToolCallItem['state'] +): AgentJournalToolCallItem { + return { kind: 'tool-call', name, input: { name }, state } +} + +export function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { + return { + kind: 'item', + identity: id, + body: tool('read', 'failed'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } +} + +export function itemStep( + resolve: Extract['resolve'], + reservedBytes = 4096 +): StructuredAgentSessionTransitionStep { + return { + kind: 'item', + reservedBytes, + resolve, + options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } +} + +export async function rig(watermarks: Partial = {}) { + const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) + roots.push(root) + const journal: AgentSessionJournal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'grok', + providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } + }, + stateDirectory: root, + now: () => 1_000 + }) + const publishes: number[] = [] + const deferred = createDeferredStructuredAgentSessionEventSink({ + ...testEventSinkLogging(SESSION), + watermarks + }) + const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) + return { root, journal, deferred, sink: deferred.sink, publishes, bind } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts new file mode 100644 index 000000000000..b435d58256cb --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts @@ -0,0 +1,131 @@ +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' + +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' + +it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + await deferred.drained() + const before = journal.cursor().sequence + // Abort the second insert to verify settlement transaction atomicity. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk +BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} +BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + { + kind: 'settlement', + settlementId: 'settle-all', + reservedBytes: 1, + resolve: () => running.map(failedTool) + } + ] + }) + + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.cursor().sequence).toBe(before) + expect( + journal + .snapshot() + .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toEqual([]) +}) + +it('writes and announces nothing when a step resolves to nothing', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => null), + { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } + ] + }) + await deferred.drained() + + expect(journal.snapshot().items).toEqual([]) + expect(publishes).toEqual([]) +}) + +it('lands a write a step issues while it runs after the whole transition', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: false, + steps: [ + itemStep(() => { + // Nested writes must wait until the whole transition finishes. + sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + return { identity: identity('first'), body: tool('first', 'running') } + }), + itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) + ] + }) + await deferred.drained() + + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( + ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) + ) +}) + +it('refuses, before writing anything, a settlement that names one item twice', async () => { + const { journal } = await rig() + const before = journal.cursor().sequence + const twice = identity('twice') + + await expect( + journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: 'twice', + fence: 1, + resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] + } + } + ]) + ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') + expect(journal.cursor().sequence).toBe(before) +}) + +it('reports unwritten streams and owes nothing once the caller marks them written', () => { + const emitted: string[] = [] + const coalescer = createAgentSessionDeltaCoalescer({ + emit: (_key, text) => { + emitted.push(text) + }, + schedule: () => () => {} + }) + coalescer.append('a', 'Hel') + coalescer.append('b', 'Wor') + coalescer.append('a', 'lo') + + expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ + ['a', 'Hello'], + ['b', 'Wor'] + ]) + coalescer.markFlushed('a') + coalescer.flushAll() + expect(emitted).toEqual(['Wor']) + expect(coalescer.dirty()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts index 85003f8b311b..77745f29b374 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts @@ -1,318 +1,185 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemIdentity, - type AgentJournalToolCallItem -} from '../../../shared/agent-session-journal-types' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionSinkWatermarks -} from './structured-agent-session-event-sink' -import { testEventSinkLogging } from './structured-agent-session-logger-test-support' -import type { - StructuredAgentSessionTransition, - StructuredAgentSessionTransitionStep -} from './structured-agent-session-transition' - -const SESSION = 'session-transition' -const journals = createTrackedJournalOpener() -const roots: string[] = [] - -afterEach(async () => { - await journals.closeAll() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -function identity(recordId: string): AgentJournalItemIdentity { - return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } -} +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionTransition } from './structured-agent-session-transition' -function tool(name: string, state: AgentJournalToolCallItem['state']): AgentJournalToolCallItem { - return { kind: 'tool-call', name, input: { name }, state } -} - -function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { - return { - kind: 'item', - identity: id, - body: tool('read', 'failed'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } -} - -function itemStep( - resolve: Extract['resolve'], - reservedBytes = 4096 -): StructuredAgentSessionTransitionStep { - return { - kind: 'item', - reservedBytes, - resolve, - options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' + +it('lands its steps back to back, each resolved after the one before it', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const first = identity('first') + const transition: StructuredAgentSessionTransition = { + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: first, body: tool('read', 'running') })), + itemStep((view) => { + const before = view.itemBody(agentJournalItemKey(first)) + return before?.kind === 'tool-call' + ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } + : null + }) + ] } -} - -async function rig(watermarks: Partial = {}) { - const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) - roots.push(root) - const journal: AgentSessionJournal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'grok', - providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } - }, - stateDirectory: root, - now: () => 1_000 - }) - const publishes: number[] = [] - const deferred = createDeferredStructuredAgentSessionEventSink({ - ...testEventSinkLogging(SESSION), - watermarks - }) - const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) - return { root, journal, deferred, sink: deferred.sink, publishes, bind } -} - -describe('structured agent-session transitions', () => { - it('lands its steps back to back, each resolved after the one before it', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const first = identity('first') - const transition: StructuredAgentSessionTransition = { - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: first, body: tool('read', 'running') })), - itemStep((view) => { - const before = view.itemBody(agentJournalItemKey(first)) - return before?.kind === 'tool-call' - ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } - : null - }) - ] - } - expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() - - const items = journal.snapshot().items - const start = items[0]?.sequence ?? 0 - expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ - [agentJournalItemKey(first), 0], - [agentJournalItemKey(identity('second')), 1], - [agentJournalItemKey(identity('later')), 2] - ]) - expect(items[1]?.body).toMatchObject({ name: 'after-read' }) - expect(publishes).toHaveLength(1) + expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() + + const items = journal.snapshot().items + const start = items[0]?.sequence ?? 0 + expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ + [agentJournalItemKey(first), 0], + [agentJournalItemKey(identity('second')), 1], + [agentJournalItemKey(identity('later')), 2] + ]) + expect(items[1]?.body).toMatchObject({ name: 'after-read' }) + expect(publishes).toHaveLength(1) +}) - it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), - itemStep(() => { - throw new Error('resolver failed') - }) - ] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('kept')) - ]) - expect(publishes).toEqual([]) - expect( - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [itemStep(() => null)] +it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), + itemStep(() => { + throw new Error('resolver failed') }) - ).toEqual({ accepted: false, reason: 'failed' }) + ] }) - it('writes nothing after a step that overflows its reservation', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('kept')) + ]) + expect(publishes).toEqual([]) + expect( sink.tryAppendTransition?.({ lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), - itemStep( - () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), - 64 - ), - itemStep(after) - ] + publish: false, + steps: [itemStep(() => null)] }) + ).toEqual({ accepted: false, reason: 'failed' }) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) - expect(after).not.toHaveBeenCalled() - expect(publishes).toEqual([]) +it('writes nothing after a step that overflows its reservation', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), + itemStep( + () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), + 64 + ), + itemStep(after) + ] }) - it('opens no next-turn work after a settlement the journal refused', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - const old = identity('old-tool') - sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - await deferred.drained() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), - { - kind: 'settlement', - settlementId: 'settle', - reservedBytes: 1, - resolve: () => [failedTool(old), failedTool(old)] - }, - itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) - ] - }) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) + expect(after).not.toHaveBeenCalled() + expect(publishes).toEqual([]) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(old), - agentJournalItemKey(identity('before')) - ]) - expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +it('opens no next-turn work after a settlement the journal refused', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + const old = identity('old-tool') + sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), + { + kind: 'settlement', + settlementId: 'settle', + reservedBytes: 1, + resolve: () => [failedTool(old), failedTool(old)] + }, + itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) + ] }) - it('writes nothing after a step whose row the database refused', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - // Fail step two to verify step three never fills its place. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(old), + agentJournalItemKey(identity('before')) + ]) + expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +}) + +it('writes nothing after a step whose row the database refused', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + // Fail step two to verify step three never fills its place. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step BEFORE INSERT ON main.journal_rows WHEN instr(NEW.row_json, 'refused-step') > 0 BEGIN SELECT RAISE(ABORT, 'second step refused'); END`) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [step('first'), step('refused-step'), step('third')] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [step('first'), step('refused-step'), step('third')] }) - it('refuses a transition whole, so none of its steps ever lands', async () => { - const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - const admitted = { lifecycle: false, publish: false, steps: [step('a')] } - const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } - - expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) - expect(sink.tryAppendTransition?.(refused)).toEqual({ - accepted: false, - reason: 'backpressure' - }) - bind() - await deferred.drained() + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) +}) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('a')) - ]) +it('refuses a transition whole, so none of its steps ever lands', async () => { + const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + const admitted = { lifecycle: false, publish: false, steps: [step('a')] } + const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } + + expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) + expect(sink.tryAppendTransition?.(refused)).toEqual({ + accepted: false, + reason: 'backpressure' }) + bind() + await deferred.drained() - it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect( - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - { - kind: 'settlement', - settlementId: 'settle-all', - reservedBytes: 1, - // Include an already-settled candidate so the fold must exclude it. - resolve: (view) => - [...running, identity('done')].flatMap((id) => { - const body = view.itemBody(agentJournalItemKey(id)) - return body?.kind === 'tool-call' && body.state === 'running' - ? [ - { - kind: 'item' as const, - identity: id, - body: { ...body, state: 'failed' as const }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - : [] - }) - } - ] - }) - ).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('a')) + ]) +}) - const items = journal.snapshot().items - const sequenceOf = (recordId: string) => - items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 - expect( - items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toHaveLength(250) - expect( - items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body - ).toMatchObject({ state: 'completed' }) - expect(sequenceOf('after') - sequenceOf('done')).toBe(3) - expect(publishes).toHaveLength(1) +it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - - it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - await deferred.drained() - const before = journal.cursor().sequence - // Abort the second insert to verify settlement transaction atomicity. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk -BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} -BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + expect( sink.tryAppendTransition?.({ lifecycle: true, publish: true, @@ -321,104 +188,39 @@ BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) kind: 'settlement', settlementId: 'settle-all', reservedBytes: 1, - resolve: () => running.map(failedTool) + // Include an already-settled candidate so the fold must exclude it. + resolve: (view) => + [...running, identity('done')].flatMap((id) => { + const body = view.itemBody(agentJournalItemKey(id)) + return body?.kind === 'tool-call' && body.state === 'running' + ? [ + { + kind: 'item' as const, + identity: id, + body: { ...body, state: 'failed' as const }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + : [] + }) } ] }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.cursor().sequence).toBe(before) - expect( - journal - .snapshot() - .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toEqual([]) - }) - - it('writes and announces nothing when a step resolves to nothing', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => null), - { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } - ] - }) - await deferred.drained() - - expect(journal.snapshot().items).toEqual([]) - expect(publishes).toEqual([]) - }) - - it('lands a write a step issues while it runs after the whole transition', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [ - itemStep(() => { - // Nested writes must wait until the whole transition finishes. - sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - return { identity: identity('first'), body: tool('first', 'running') } - }), - itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) - ] - }) - await deferred.drained() - - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( - ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) - ) - }) -}) - -describe('resolved lifecycle batches', () => { - it('refuses, before writing anything, a settlement that names one item twice', async () => { - const { journal } = await rig() - const before = journal.cursor().sequence - const twice = identity('twice') - - await expect( - journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: 'twice', - fence: 1, - resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] - } - } - ]) - ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') - expect(journal.cursor().sequence).toBe(before) - }) -}) - -describe('coalescer text a caller writes itself', () => { - it('reports unwritten streams and owes nothing once the caller marks them written', () => { - const emitted: string[] = [] - const coalescer = createAgentSessionDeltaCoalescer({ - emit: (_key, text) => { - emitted.push(text) - }, - schedule: () => () => {} - }) - coalescer.append('a', 'Hel') - coalescer.append('b', 'Wor') - coalescer.append('a', 'lo') - - expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ - ['a', 'Hello'], - ['b', 'Wor'] - ]) - coalescer.markFlushed('a') - coalescer.flushAll() - expect(emitted).toEqual(['Wor']) - expect(coalescer.dirty()).toEqual([]) + ).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() + + const items = journal.snapshot().items + const sequenceOf = (recordId: string) => + items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 + expect( + items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toHaveLength(250) + expect( + items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body + ).toMatchObject({ state: 'completed' }) + expect(sequenceOf('after') - sequenceOf('done')).toBe(3) + expect(publishes).toHaveLength(1) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts index bc9804bbb25b..390d1fc550ac 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts @@ -75,7 +75,7 @@ async function relaunchWith( const damaged = (db: Database.Database) => updateTestJournalRowJson(db, SESSION, 1, '}{') const savedByNewerOrca = (db: Database.Database) => { const epochRow = liveTestJournalRows(db, SESSION).find((row) => row.seq === 1)! - const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 1 } + const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 2 } updateTestJournalRowJson(db, SESSION, 1, JSON.stringify(newer)) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts index 2da481da24ce..43dcc39382b4 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts @@ -32,7 +32,7 @@ const LARGE_TEXT = 'x'.repeat(250 * 1024) let root: string let journal: AgentSessionJournal -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-wire-admission-')) diff --git a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts index b6e580fc77e3..12c7725ea695 100644 --- a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts +++ b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts @@ -94,7 +94,21 @@ describe("a worker's journal page", () => { await append(`child-${index}`, subagent) } + const before = await readStructuredJournalPage('session-1') + await host.journal!.close() + host.journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-1', null) + }, + stateDirectory: root, + now: () => ++clock + }) const page = await readStructuredJournalPage('session-1') + expect(page).toStrictEqual(before) expect(page?.items.map((item) => item.body)).toEqual([ said('worker-older'), diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts new file mode 100644 index 000000000000..ee235da2f3cf --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts @@ -0,0 +1,30 @@ +import { afterEach, vi } from 'vitest' +import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' + +export const h = createOrchestrationRpcHarness() + +export const COORD = testOrcaSessionId('start-card-caller') + +export const WORKER = testOrcaSessionId('start-card-worker') + +let rig: QueuedMessageTestRig | undefined + +afterEach(async () => { + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + h.cleanup() + vi.restoreAllMocks() +}) + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts new file mode 100644 index 000000000000..5a36e37ddfb0 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts @@ -0,0 +1,307 @@ +import { + expectWorkerStartPopulation, + expectWorkerStartSourcePlans +} from './worker-start-card-population.test-fixture' +import { expect, it, vi } from 'vitest' +import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' +import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createQueuedMessageTestRig, + eventually +} from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' +import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' +import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' +import { getDefaultWorkspaceSession } from '../../../../../shared/constants' +import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' +import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' + +import { fixture, COORD, h } from './worker-start-card-contract-test-fixture' + +it.each([10, 100])( + 'counts populated producer source and journal operations for %i starts and duplicate publications', + async (count) => { + fixture.rig = await createQueuedMessageTestRig({ sessionId: COORD, legacyInputs: true }) + const current = fixture.rig + setStructuredAgentSessionHost(current.host) + const session = getDefaultWorkspaceSession() + const { runtime, db } = h.setup( + false, + partialRuntimeStore({ + getSettings: () => ({ agentDefaultSurface: 'terminal' }), + getWorkspaceSession: () => session + }) + ) + vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() + const run = db.createRun({ + objective: 'scale', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const tabs: ReturnType[] = [] + const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] + for (let index = 0; index < 10 * count; index++) { + const handle = `term_scale_${index}` + const tabId = `scale-tab-${index}` + const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` + tabs.push( + createMinimalPersistedTerminalTab({ + worktreeId: 'workspace-1', + tabId, + ptyId: `pty-${index}`, + existingTabCount: index + }) + ) + runtime.handles.set(handle, { + handle, + runtimeId: runtime.getRuntimeId(), + rendererGraphEpoch: 1, + worktreeId: 'workspace-1', + tabId, + leafId, + ptyId: null, + ptyGeneration: 0, + issuedForPaneKey: `${tabId}:${leafId}` + }) + const task = db.createTask({ + runId: run.id, + spec: `Task ${index}`, + displayName: `Scale worker ${index}` + }) + const { dispatch } = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {} + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle, + paneKey: `${tabId}:${leafId}`, + processIncarnation: `scale:${index}`, + worktreeId: 'workspace-1', + effects: [], + setupState: 'not_applicable' + }) + db.markWorkerDispatchReady(dispatch.id) + if (index >= 9 * count) { + facts.push({ + dispatchId: dispatch.id, + workerAddress: handle, + task: task.spec, + name: `Scale worker ${index}` + }) + } + } + let tabVisits = 0 + tabs.forEach((tab, index) => { + Object.defineProperty(tabs, index, { + get() { + tabVisits++ + return tab + } + }) + }) + session.tabsByWorktree['workspace-1'] = tabs + vi.mocked(runtime.getTerminalPaneKey).mockImplementation( + (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null + ) + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + for (let index = 0; index < 9 * count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `history-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: `History ${index}` }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const admitted = await resolveOrchestrationSessionCaller( + runtime, + { + id: 'scale', + authToken: 'test-token', + method: 'orchestration.workerStart', + params: { spec: 'Task' }, + orchestrationCompatibilityEvidence: { agentSessionId: COORD } + }, + undefined + ) + let dispatchVisits = 0 + let taskVisits = 0 + installSqlVisitCounters({ + start_dispatch_visit: () => { + dispatchVisits++ + return 1 + }, + start_task_visit: () => { + taskVisits++ + return 1 + } + }) + const prepareSource = db.db.prepare.bind(db.db) + const sourceQueries = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepareSource( + query + .replace( + 'WHERE assignee_handle = ?', + 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' + ) + .replace( + 'FROM tasks WHERE id = ?', + 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' + ) + ) + ) + const connection = openTestJournalHostDatabase(current.root).db + const epochReads = vi.spyOn( + connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), + 'get' + ) + const inserts = vi.spyOn( + connection.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ), + 'run' + ) + const journalQueries = vi.spyOn(connection, 'prepare') + const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') + const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') + const recordedSource = vi.spyOn(db, 'getDispatchContextById') + const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') + const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') + const dedupe = vi.spyOn(journal, 'hasRecordedItem') + const scan = vi.spyOn(journal, 'visitItemsWithLinkage') + const projection = StructuredAgentSessionJournalProjections.prototype + const readProjection = projection.read + let projecting = false + vi.spyOn(projection, 'read').mockImplementation(function ( + this: StructuredAgentSessionJournalProjections, + ...args + ) { + const previous = projecting + projecting = true + try { + return readProjection.apply(this, args) + } finally { + projecting = previous + } + }) + const snapshotSources: string[] = [] + const readSnapshot = journal.snapshot.bind(journal) + const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { + snapshotSources.push(projecting ? 'status-projection' : 'other') + return readSnapshot() + }) + const append = vi.spyOn(current.host, 'appendAgentStart') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const before = journal.snapshot() + snapshot.mockClear() + const fail = prepareWorkerStartCard(runtime, admitted.caller) + expect(epochReads).toHaveBeenCalledTimes(1) + inserts.mockImplementationOnce(() => { + throw new Error('fixture insert failed') + }) + fail(facts[0]) + await eventually(() => expect(append).toHaveBeenCalledTimes(1)) + await Promise.allSettled(append.mock.results.map((result) => result.value)) + await eventually(() => + expect(warn).toHaveBeenCalledWith( + '[orchestration] recording a started worker in its caller chat failed', + expect.any(Error) + ) + ) + expect(epochReads).toHaveBeenCalledTimes(4) + expect(serialized).toHaveBeenCalledTimes(1) + expect(inserts).toHaveBeenCalledTimes(1) + expect(sourceQueries).toHaveBeenCalledTimes(2) + expect(dispatchVisits).toBe(1) + expect(taskVisits).toBe(1) + expect(tabVisits).toBe(9 * count + 1) + expect(journal.snapshot()).toEqual(before) + expect( + connection + .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') + .get(COORD)?.count + ).toBe(before.cursor.sequence) + for (const counter of [ + epochReads, + serialized, + inserts, + sourceQueries, + journalQueries, + activeSource, + recordedSource, + sender, + names, + dedupe, + scan, + snapshot, + append, + warn + ]) { + counter.mockClear() + } + snapshotSources.length = 0 + tabVisits = dispatchVisits = taskVisits = 0 + const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) + expect(epochReads).toHaveBeenCalledTimes(count) + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(4 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(snapshotSources).toEqual(['status-projection']) + // Duplicate callbacks still name the sender but must stop before row serialization/insertion. + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(6 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(sender).toHaveBeenCalledTimes(2 * count) + expect(names).toHaveBeenCalledTimes(2 * count) + expect(activeSource).toHaveBeenCalledTimes(2 * count) + expect(recordedSource).not.toHaveBeenCalled() + expect(sourceQueries).toHaveBeenCalledTimes(4 * count) + expect(dispatchVisits).toBe(2 * count) + expect(taskVisits).toBe(2 * count) + const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) + expect(tabVisits).toBe(2 * visitsPerPass) + expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) + expect(dedupe).toHaveBeenCalledTimes(2 * count) + expect(scan).not.toHaveBeenCalled() + expect(snapshot).toHaveBeenCalledTimes(1) + expect(snapshotSources).toEqual(['status-projection']) + expect( + journalQueries.mock.calls.filter( + ([query]) => /FROM journal_rows/.test(query) && !/seq = 1/.test(query) + ) + ).toEqual([]) + expect(warn).not.toHaveBeenCalled() + expectWorkerStartSourcePlans(sourceQueries.mock.calls, prepareSource) + expectWorkerStartPopulation({ journal, facts, count, connection, before }) + console.info('start population/operations', { + count, + sourceRecords: 10 * count, + history: 9 * count, + epochReads: epochReads.mock.calls.length, + serializedRows: serialized.mock.calls.length, + inserts: inserts.mock.calls.length, + dispatchVisits, + taskVisits, + tabVisits + }) + } +) diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts new file mode 100644 index 000000000000..cf9aacd19eca --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts @@ -0,0 +1,52 @@ +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import { expect } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' +import type { JournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database' +import { COORD } from './worker-start-card-contract-test-fixture' + +export function expectWorkerStartPopulation(input: { + journal: AgentSessionJournal + count: number + connection: JournalHostDatabase['db'] + facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] + before: AgentJournalSnapshot +}): void { + const { journal, facts, count, connection, before } = input + const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') + expect(cards.map(({ body }) => body)).toEqual( + facts.map((fact) => ({ + kind: 'agent-start', + dispatchId: fact.dispatchId, + task: fact.task, + worker: { + party: { + address: fact.workerAddress, + terminalHandle: fact.workerAddress, + orcaSessionId: null + }, + name: fact.name + } + })) + ) + expect( + connection.prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?').get(COORD) + ?.count + ).toBe(before.cursor.sequence + count) +} + +export function expectWorkerStartSourcePlans( + queries: readonly (readonly [string])[], + prepareSource: ReturnType< + ReturnType['setup'] + >['db']['db']['prepare'] +): void { + for (const [query] of queries.slice(0, 2)) { + const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) + .all('unused') + .map((row) => row.detail) + .join(' | ') + expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) + expect(plan).not.toMatch(/SCAN/) + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts new file mode 100644 index 000000000000..8b4767ee877b --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts @@ -0,0 +1,164 @@ +import { expect, type MockInstance } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { closeTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' +import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { COORD } from './worker-start-card-contract-test-fixture' + +export async function verifyWorkerStartCardScenario(input: { + current: QueuedMessageTestRig + scenario: string + before: AgentJournalSnapshot + task: string + federated: boolean + db: ReturnType['setup']>['db'] + append: MockInstance +}): Promise { + const { current, scenario, before, task, federated, db, append } = input + const snapshot = await current.host.journalSnapshot(COORD) + const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') + if (scenario !== 'success' && scenario !== 'federated') { + expect(cards).toHaveLength(0) + return + } + expect(cards).toHaveLength(1) + const [card] = cards + expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ + ...before.items.map(({ itemId }) => itemId), + card.itemId + ]) + expect(card.body).toMatchObject({ + kind: 'agent-start', + task, + ...(!federated + ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } + : {}) + }) + if (card.body.kind !== 'agent-start') { + throw new Error('missing start body') + } + if (federated) { + expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) + } + const destination = append.mock.calls[0][0] + await Promise.all([ + current.host.appendAgentStart( + destination, + { ...card.body, task: 'replayed task' }, + card.observedAt + 10 + ), + current.host.appendAgentStart(destination, card.body, card.observedAt + 20) + ]) + expect( + (await current.host.journalSnapshot(COORD)).items.filter( + (item) => item.body.kind === 'agent-start' + ) + ).toEqual(cards) + expect(projectStructuredAgentStartItem(card)).toMatchObject({ + role: 'system', + agentStart: true, + timestamp: card.observedAt, + blocks: [{ type: 'text', text: task }] + }) + expect(projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions)).toEqual( + projectStructuredAgentSessionStatusSummary(before.items, before.submissions) + ) + // Full task survives removal of the orchestration rows it came from. + db.resetAll() + expect( + (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) + ).toEqual(card) + if (scenario === 'success') { + const context = await current.host.continuationContext({ + sessionId: COORD, + workspaceId: current.store.getConversation(COORD)!.location.workspaceId, + expectedCursor: snapshot.cursor + }) + expect(context).toMatchObject({ status: 'current' }) + if (context.status !== 'current' || !context.transcriptPath) { + throw new Error('saved context missing') + } + const saved = await readFile(context.transcriptPath, 'utf8') + expect(saved).toContain('Coordinate this work') + expect(saved).not.toContain(task) + expect(context.capturedText).not.toContain(task) + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + const reopened = await current.host.journalSnapshot(COORD) + expect(reopened.items.map(({ itemId }) => itemId)).toEqual( + snapshot.items.map(({ itemId }) => itemId) + ) + expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( + snapshot.items.filter(({ body }) => body.kind !== 'tool-call') + ) + const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') + expect(recovered).toEqual({ + ...snapshot.items[1], + revision: snapshot.items[1].revision + 1, + recovered: true, + recoveredAt: expect.any(Number), + body: { + kind: 'tool-call', + name: 'shell', + input: { command: 'inspect' }, + state: 'failed', + endedAs: 'interrupted' + } + }) + expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) + expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) + const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) + expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) + } + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + if (scenario === 'success') { + for (let index = 0; index < 3; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `pressure-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'x'.repeat(750000) }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) + if (!tail.ok) { + throw new Error('pressure tail missing') + } + expect(tail.page.hasOlder).toBe(true) + expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) + const older = await current.host.history({ + sessionId: COORD, + direction: 'before', + cursor: tail.page.window.nextCursor + }) + if (!older.ok) { + throw new Error('pressure older page missing') + } + expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) + } + await journal.appendTombstone( + { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, + { fence: current.store.getConversation(COORD)!.currentFence } + ) + if (scenario === 'success') { + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + } + await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) + expect( + (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) + ).toBe(false) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts index 72f2d8a48f1a..fbdc6a8042cd 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts @@ -1,54 +1,29 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { verifyWorkerStartCardScenario } from './worker-start-card-scenario.test-fixture' +import { expect, it, vi } from 'vitest' import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' import { createQueuedMessageTestRig, eventually, - QUEUED_RIG_CALLER, - type QueuedMessageTestRig + QUEUED_RIG_CALLER } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' import { hostTestAttachParams, hostTestOperationId } from '../../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody } from '../../../../../shared/agent-session-journal-types' -import { - closeTestJournalHostDatabase, - openTestJournalHostDatabase -} from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' -import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' -import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' -import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' -import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' -import { getDefaultWorkspaceSession } from '../../../../../shared/constants' -import { readFile } from 'node:fs/promises' -import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' -import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' -import * as placement from './worker/worker-start-agent-placement' -import * as topology from './worker/worker-topology' import { ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY } from '../../../../../shared/protocol-version' +import * as placement from './worker/worker-start-agent-placement' +import * as topology from './worker/worker-topology' -const h = createOrchestrationRpcHarness() -const COORD = testOrcaSessionId('start-card-caller') -const WORKER = testOrcaSessionId('start-card-worker') -let rig: QueuedMessageTestRig | undefined -afterEach(async () => { - setStructuredAgentSessionHost(null) - await rig?.dispose() - rig = undefined - h.cleanup() - vi.restoreAllMocks() -}) +import { fixture, COORD, WORKER, h } from './worker-start-card-contract-test-fixture' it.each([ 'success', @@ -66,8 +41,8 @@ it.each([ ] as const)( 'real worker-start records creation independently of launch: %s', async (scenario) => { - rig = await createQueuedMessageTestRig({ sessionId: WORKER }) - const current = rig + fixture.rig = await createQueuedMessageTestRig({ sessionId: WORKER }) + const current = fixture.rig if (scenario === 'readiness-failure') { current.dispatch.mockRejectedValueOnce(new Error('provider dispatch failed')) } @@ -308,457 +283,7 @@ it.each([ ).toBe(true) ) } - const snapshot = await current.host.journalSnapshot(COORD) - const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') - if (scenario !== 'success' && scenario !== 'federated') { - expect(cards).toHaveLength(0) - return - } - expect(cards).toHaveLength(1) - const [card] = cards - expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ - ...before.items.map(({ itemId }) => itemId), - card.itemId - ]) - expect(card.body).toMatchObject({ - kind: 'agent-start', - task, - ...(!federated - ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } - : {}) - }) - if (card.body.kind !== 'agent-start') { - throw new Error('missing start body') - } - if (federated) { - expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) - } - const destination = append.mock.calls[0][0] - await Promise.all([ - current.host.appendAgentStart( - destination, - { ...card.body, task: 'replayed task' }, - card.observedAt + 10 - ), - current.host.appendAgentStart(destination, card.body, card.observedAt + 20) - ]) - expect( - (await current.host.journalSnapshot(COORD)).items.filter( - (item) => item.body.kind === 'agent-start' - ) - ).toEqual(cards) - expect(projectStructuredAgentStartItem(card)).toMatchObject({ - role: 'system', - agentStart: true, - timestamp: card.observedAt, - blocks: [{ type: 'text', text: task }] - }) - expect( - projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions) - ).toEqual(projectStructuredAgentSessionStatusSummary(before.items, before.submissions)) - // Full task survives removal of the orchestration rows it came from. - db.resetAll() - expect( - (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) - ).toEqual(card) - if (scenario === 'success') { - const context = await current.host.continuationContext({ - sessionId: COORD, - workspaceId: current.store.getConversation(COORD)!.location.workspaceId, - expectedCursor: snapshot.cursor - }) - expect(context).toMatchObject({ status: 'current' }) - if (context.status !== 'current' || !context.transcriptPath) { - throw new Error('saved context missing') - } - const saved = await readFile(context.transcriptPath, 'utf8') - expect(saved).toContain('Coordinate this work') - expect(saved).not.toContain(task) - expect(context.capturedText).not.toContain(task) - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - const reopened = await current.host.journalSnapshot(COORD) - expect(reopened.items.map(({ itemId }) => itemId)).toEqual( - snapshot.items.map(({ itemId }) => itemId) - ) - expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( - snapshot.items.filter(({ body }) => body.kind !== 'tool-call') - ) - const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') - expect(recovered).toEqual({ - ...snapshot.items[1], - revision: snapshot.items[1].revision + 1, - recovered: true, - recoveredAt: expect.any(Number), - body: { - kind: 'tool-call', - name: 'shell', - input: { command: 'inspect' }, - state: 'failed', - endedAs: 'interrupted' - } - }) - expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) - expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) - const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) - expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) - } - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - if (scenario === 'success') { - for (let index = 0; index < 3; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `pressure-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'x'.repeat(750000) }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) - if (!tail.ok) { - throw new Error('pressure tail missing') - } - expect(tail.page.hasOlder).toBe(true) - expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) - const older = await current.host.history({ - sessionId: COORD, - direction: 'before', - cursor: tail.page.window.nextCursor - }) - if (!older.ok) { - throw new Error('pressure older page missing') - } - expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) - } - await journal.appendTombstone( - { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, - { fence: current.store.getConversation(COORD)!.currentFence } - ) - if (scenario === 'success') { - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - } - await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) - expect( - (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) - ).toBe(false) + await verifyWorkerStartCardScenario({ current, scenario, before, task, federated, db, append }) }, 20_000 ) - -it.each([10, 100])( - 'counts populated producer source and journal operations for %i starts and duplicate publications', - async (count) => { - rig = await createQueuedMessageTestRig({ sessionId: COORD }) - const current = rig - setStructuredAgentSessionHost(current.host) - const session = getDefaultWorkspaceSession() - const { runtime, db } = h.setup( - false, - partialRuntimeStore({ - getSettings: () => ({ agentDefaultSurface: 'terminal' }), - getWorkspaceSession: () => session - }) - ) - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() - const run = db.createRun({ - objective: 'scale', - coordinatorHandle: null, - coordinatorPaneKey: null - }) - const tabs: ReturnType[] = [] - const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] - for (let index = 0; index < 10 * count; index++) { - const handle = `term_scale_${index}` - const tabId = `scale-tab-${index}` - const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` - tabs.push( - createMinimalPersistedTerminalTab({ - worktreeId: 'workspace-1', - tabId, - ptyId: `pty-${index}`, - existingTabCount: index - }) - ) - runtime.handles.set(handle, { - handle, - runtimeId: runtime.getRuntimeId(), - rendererGraphEpoch: 1, - worktreeId: 'workspace-1', - tabId, - leafId, - ptyId: null, - ptyGeneration: 0, - issuedForPaneKey: `${tabId}:${leafId}` - }) - const task = db.createTask({ - runId: run.id, - spec: `Task ${index}`, - displayName: `Scale worker ${index}` - }) - const { dispatch } = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle, - paneKey: `${tabId}:${leafId}`, - processIncarnation: `scale:${index}`, - worktreeId: 'workspace-1', - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(dispatch.id) - if (index >= 9 * count) { - facts.push({ - dispatchId: dispatch.id, - workerAddress: handle, - task: task.spec, - name: `Scale worker ${index}` - }) - } - } - let tabVisits = 0 - tabs.forEach((tab, index) => { - Object.defineProperty(tabs, index, { - get() { - tabVisits++ - return tab - } - }) - }) - session.tabsByWorktree['workspace-1'] = tabs - vi.mocked(runtime.getTerminalPaneKey).mockImplementation( - (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null - ) - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - for (let index = 0; index < 9 * count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `history-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `History ${index}` }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const admitted = await resolveOrchestrationSessionCaller( - runtime, - { - id: 'scale', - authToken: 'test-token', - method: 'orchestration.workerStart', - params: { spec: 'Task' }, - orchestrationCompatibilityEvidence: { agentSessionId: COORD } - }, - undefined - ) - let dispatchVisits = 0 - let taskVisits = 0 - installSqlVisitCounters({ - start_dispatch_visit: () => { - dispatchVisits++ - return 1 - }, - start_task_visit: () => { - taskVisits++ - return 1 - } - }) - const prepareSource = db.db.prepare.bind(db.db) - const sourceQueries = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepareSource( - query - .replace( - 'WHERE assignee_handle = ?', - 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' - ) - .replace( - 'FROM tasks WHERE id = ?', - 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' - ) - ) - ) - const connection = openTestJournalHostDatabase(current.root).db - const epochReads = vi.spyOn( - connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), - 'get' - ) - const inserts = vi.spyOn( - connection.prepare( - 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' - ), - 'run' - ) - const journalQueries = vi.spyOn(connection, 'prepare') - const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') - const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') - const recordedSource = vi.spyOn(db, 'getDispatchContextById') - const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') - const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') - const dedupe = vi.spyOn(journal, 'hasRecordedItem') - const scan = vi.spyOn(journal, 'visitItemsWithLinkage') - const projection = StructuredAgentSessionJournalProjections.prototype - const readProjection = projection.read - let projecting = false - vi.spyOn(projection, 'read').mockImplementation(function ( - this: StructuredAgentSessionJournalProjections, - ...args - ) { - const previous = projecting - projecting = true - try { - return readProjection.apply(this, args) - } finally { - projecting = previous - } - }) - const snapshotSources: string[] = [] - const readSnapshot = journal.snapshot.bind(journal) - const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { - snapshotSources.push(projecting ? 'status-projection' : 'other') - return readSnapshot() - }) - const append = vi.spyOn(current.host, 'appendAgentStart') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const before = journal.snapshot() - snapshot.mockClear() - const fail = prepareWorkerStartCard(runtime, admitted.caller) - expect(epochReads).toHaveBeenCalledTimes(1) - inserts.mockImplementationOnce(() => { - throw new Error('fixture insert failed') - }) - fail(facts[0]) - await eventually(() => expect(append).toHaveBeenCalledTimes(1)) - await Promise.allSettled(append.mock.results.map((result) => result.value)) - await eventually(() => - expect(warn).toHaveBeenCalledWith( - '[orchestration] recording a started worker in its caller chat failed', - expect.any(Error) - ) - ) - expect(epochReads).toHaveBeenCalledTimes(3) - expect(serialized).toHaveBeenCalledTimes(1) - expect(inserts).toHaveBeenCalledTimes(1) - expect(sourceQueries).toHaveBeenCalledTimes(2) - expect(dispatchVisits).toBe(1) - expect(taskVisits).toBe(1) - expect(tabVisits).toBe(9 * count + 1) - expect(journal.snapshot()).toEqual(before) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence) - for (const counter of [ - epochReads, - serialized, - inserts, - sourceQueries, - journalQueries, - activeSource, - recordedSource, - sender, - names, - dedupe, - scan, - snapshot, - append, - warn - ]) { - counter.mockClear() - } - snapshotSources.length = 0 - tabVisits = dispatchVisits = taskVisits = 0 - const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) - expect(epochReads).toHaveBeenCalledTimes(count) - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(3 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(snapshotSources).toEqual(['status-projection']) - // Duplicate callbacks still name the sender but must stop before row serialization/insertion. - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(5 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(sender).toHaveBeenCalledTimes(2 * count) - expect(names).toHaveBeenCalledTimes(2 * count) - expect(activeSource).toHaveBeenCalledTimes(2 * count) - expect(recordedSource).not.toHaveBeenCalled() - expect(sourceQueries).toHaveBeenCalledTimes(4 * count) - expect(dispatchVisits).toBe(2 * count) - expect(taskVisits).toBe(2 * count) - const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) - expect(tabVisits).toBe(2 * visitsPerPass) - expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) - expect(dedupe).toHaveBeenCalledTimes(2 * count) - expect(scan).not.toHaveBeenCalled() - expect(snapshot).toHaveBeenCalledTimes(1) - expect(snapshotSources).toEqual(['status-projection']) - expect(journalQueries.mock.calls.filter(([query]) => /FROM journal_rows/.test(query))).toEqual( - [] - ) - expect(warn).not.toHaveBeenCalled() - for (const [query] of sourceQueries.mock.calls.slice(0, 2)) { - const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) - .all('unused') - .map((row) => row.detail) - .join(' | ') - expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) - expect(plan).not.toMatch(/SCAN/) - } - const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') - expect(cards.map(({ body }) => body)).toEqual( - facts.map((fact) => ({ - kind: 'agent-start', - dispatchId: fact.dispatchId, - task: fact.task, - worker: { - party: { - address: fact.workerAddress, - terminalHandle: fact.workerAddress, - orcaSessionId: null - }, - name: fact.name - } - })) - ) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence + count) - console.info('start population/operations', { - count, - sourceRecords: 10 * count, - history: 9 * count, - epochReads: epochReads.mock.calls.length, - serializedRows: serialized.mock.calls.length, - inserts: inserts.mock.calls.length, - dispatchVisits, - taskVisits, - tabVisits - }) - } -) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts new file mode 100644 index 000000000000..29eb1ab731e5 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts @@ -0,0 +1,299 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { readFile, rm } from 'node:fs/promises' +import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' +import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' +import type { + AgentJournalItemBody, + AgentJournalResolution, + AgentJournalQuestionItem +} from '../../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +import { + fixture, + actualFiles, + call, + restingChat +} from './structured-agent-session-rest-contract-test-fixture' + +it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { + await restingChat() + await fixture.rig.host.journalSnapshot(SESSION) + let journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const receipt = { write: () => {}, committed: () => {} } + let ordinal = 100 + const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => + journal.appendItem( + { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, + typeof text === 'string' ? hostTestMessage(text) : text, + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await append('PRE_CLEAR_SECRET') + await journal.context.clear( + { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: fixture.rig.clock.now }, + receipt + ) + await append('EARLY_SAVED_MARKER') + for (let index = 0; index < 205; index++) { + await append(`saved ${index} ${'context '.repeat(60)}`) + } + const floor = journal.cursor() + await append('DISCARDED_REWIND_SECRET') + await journal.context.rewind(floor, fence, [], () => receipt) + const resolution = ( + state: AgentJournalResolution['state'], + selectedOptionId: string | null = null + ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) + const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ + kind: 'question', + question: name, + options: [], + freeTextQuestionId: 'input', + freeTextInput: { allowEmpty: true }, + resolution: { + ...resolution('resolved'), + ...(answer !== undefined + ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } + : {}) + } + }) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + await append(question(name, value)) + } + await append(question('unreadable')) + await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) + await append({ + ...question('legacy answer'), + resolution: resolution('resolved', 'input:legacy%20deployment') + }) + await append({ + kind: 'question', + question: 'Release choices', + options: [], + questions: [ + { + id: 'regions', + header: 'Region group', + question: 'Which regions?', + multiSelect: true, + options: [ + { id: 'east', label: 'East', description: 'Primary region' }, + { id: 'west', label: 'West' } + ] + }, + { + id: 'details', + question: 'Release detail?', + multiSelect: true, + options: [{ id: 'known', label: 'Known' }], + freeTextQuestionId: 'details' + } + ], + resolution: { + ...resolution('resolved'), + answers: [ + { questionId: 'regions', optionIds: ['east', 'west'] }, + { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } + ] + } + }) + for (const choice of ['yes', 'no']) { + await append({ + kind: 'approval', + title: `Confirm ${choice}`, + detail: 'Deploy?', + options: [ + { id: 'yes', label: 'Yes' }, + { id: 'no', label: 'No' } + ], + resolution: resolution('resolved', choice) + }) + } + await append({ + kind: 'approval', + title: 'Review plan', + description: 'Saved description', + decisionReason: 'Saved reason', + matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, + blockedPath: '/work/target', + detail: 'Clipped detail', + subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, + options: [ + { id: 'plan', label: 'Approve plan' }, + { id: 'keep', label: 'Keep planning' } + ], + resolution: resolution('resolved', 'keep') + }) + const editor = piRpcDialogPresentation({ + id: 'editor', + method: 'editor', + title: 'Edit release notes', + prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', + placeholder: 'Keep migration details' + }) + if (editor?.body.kind !== 'question') { + throw new Error('Pi editor missing') + } + const editorOrdinal = ordinal++ + await append(editor.body, editorOrdinal) + const editorParams = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } + } + const pendingEditor = await fixture.rig.host.continuationContext(editorParams) + if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { + throw new Error('Pending editor snapshot missing') + } + for (const text of [ + await readFile(pendingEditor.transcriptPath, 'utf8'), + pendingEditor.capturedText ?? '' + ]) { + expect(text).toContain( + 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' + ) + expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') + expect(text).toContain('"placeholder":"Keep migration details"') + } + const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] + const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) + await append( + { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, + editorOrdinal + ) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) + journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await append({ ...question('pending ask'), resolution: resolution('pending') }) + const params = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } + } + await call('agentSession.options', { sessionId: SESSION }) + const gate = Promise.withResolvers() + const write = actualFiles.writeFile + const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { + await gate.promise + return write(...args) + }) + const pending = fixture.rig.host.continuationContext(params) + await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) + const currentJournal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await currentJournal.appendItem( + { provider: 'orca', clientMessageId: 'pr-31782-late' }, + hostTestMessage('LATER_SAVED_MARKER'), + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + gate.resolve() + const first = await pending + if (first.status !== 'current' || !first.transcriptPath) { + throw new Error('Snapshot missing') + } + const path = first.transcriptPath + try { + const file = await readFile(path, 'utf8') + expect(file).toContain('EARLY_SAVED_MARKER') + expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) + expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) + expect(first.capturedText).toContain('Earlier saved chat messages omitted') + expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') + for (const text of [file, first.capturedText ?? '']) { + const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => + JSON.parse(match[1]!) + ) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) + } + expect(text).toMatch( + /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ + ) + expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) + expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) + const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! + expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') + expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) + expect(text).toContain( + 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' + ) + expect(text).toContain('"question":"Which regions?"') + expect(text).toContain('"label":"East","description":"Primary region"') + expect(text).toContain( + 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' + ) + expect(text).toContain('"other":"partial text"') + expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) + expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) + expect(text).toContain( + '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' + ) + expect(text).toContain( + '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' + ) + expect(text).toContain('Selected choice: Keep planning') + const row = text + .split('\n\n') + .find((entry) => entry.includes('"question":"Edit release notes"'))! + expect(row).toContain('Prompt state: resolved') + expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) + expect(row).toContain(JSON.stringify(answers)) + expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) + expect(row.split('\n').slice(2).join('\n')).toBe( + 'Question "editor"\nSubmitted free text: resolution.answers[0].other' + ) + } + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { + ok: true, + result: { + status: 'current', + transcriptPath: path, + capturedText: expect.stringContaining('LATER_SAVED_MARKER') + } + } + ]) + expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') + expect(await fixture.rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual( + { + status: 'superseded' + } + ) + expect( + await fixture.rig.host.continuationContext({ + ...params, + expectedCursor: { epoch: 'other', sequence: 0 } + }) + ).toEqual({ status: 'superseded' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + writing.mockRejectedValueOnce(new Error('disk unavailable')) + expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) + } finally { + await rm(contextSnapshots.agentSessionContextSnapshotRoot(fixture.rig.root), { + recursive: true, + force: true + }) + } +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts new file mode 100644 index 000000000000..dff8078cf27b --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts @@ -0,0 +1,52 @@ +import '../unused-default-rpc-methods.test-fixture' +import { expect, it, vi } from 'vitest' +vi.mock('node:fs/promises', { spy: true }) +import { readFile } from 'node:fs/promises' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { + editPersistedTestAgentSessionStore, + readPersistedTestAgentSessionStore +} from '../../agent-session-record-store-test-harness' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { + await restingChat() + const { cursor } = await fixture.rig.host.journalSnapshot(SESSION) + await fixture.rig.host.flushAllStreamedEvents() + await editPersistedTestAgentSessionStore(fixture.rig.root, (persisted) => { + Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) + }) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') + const saved = (await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION] + const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } + const result = await fixture.rig.host.continuationContext(params) + expect(result).toMatchObject({ + status: 'current', + capturedText: expect.stringContaining('hello') + }) + if (result.status !== 'current' || !result.transcriptPath) { + throw new Error('Saved conversation snapshot missing') + } + expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { ok: true, result } + ]) + for (const stale of [ + { ...params, workspaceId: 'other' }, + { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, + { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } + ]) { + expect(await fixture.rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) + } + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect((await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION]).toEqual( + saved + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts new file mode 100644 index 000000000000..820494c34cec --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts @@ -0,0 +1,172 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' +import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { hostTestOperationId } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + foundRestTestChat, + REST_TEST_CALLER as CALLER, + REST_TEST_SESSION as SESSION, + REST_TEST_THREAD, + restTestSend +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' +import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' +import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('records a pick as intent and replays it at the next start (P2-16)', async () => { + await restingChat() + const fields = { key: 'model', value: 'gpt-picked' } + const [picked] = await call('agentSession.setOption', { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: SESSION, + fields + }) + }, + ...fields + }) + expect(picked).toMatchObject({ ok: true, result: { ok: true } }) + expect(fixture.rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await fixture.rig.host.send(CALLER, restTestSend('use the new model', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ + options: expect.objectContaining({ model: 'gpt-picked' }) + }) +}) + +it('answers the provider-level features of a chat at rest (P2-17)', async () => { + await restingChat() + setStructuredAgentSessionHost(await fixture.rig.restart({ agents: claudeAndCodexDeclared() })) + Object.assign(fixture.rig.host.deps.adapter, { + rewindSupport: (_id: string, agent?: string) => + agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } + }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + expect(options).toMatchObject({ + ok: true, + result: { threadGoal: { current: null }, rewind: { supported: true } } + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.readOptions).not.toHaveBeenCalled() +}) + +it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { + await foundRestTestChat(fixture.rig) + const running = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // ast-grep-ignore: test-no-real-time-wait -- proves no respawn follows the exit; an absence has no condition to wait on. + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect(fixture.rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + await fixture.rig.host.send(CALLER, restTestSend('again', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledTimes(2)) +}) + +it('whose settlement write failed is settled by the next send, which is delivered', async () => { + await foundRestTestChat(fixture.rig) + const open = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)! + const running = open.child! + // A turn in flight, so the exit has something to settle. + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, + { kind: 'turn', turnId: 'working', state: 'running' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await fixture.rig.host.flushStreamedEvents(SESSION) + // Refuse both the exit write and its queued retry to test retained death evidence. + vi.spyOn(open.journal, 'appendLifecycleBatch') + .mockRejectedValueOnce(new Error('disk full')) + .mockRejectedValueOnce(new Error('disk full')) + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // Released with its death evidence, not latched: the next acquire settles from that evidence. + await vi.waitFor(() => + expect(fixture.rig.store.getRecord(SESSION)?.lease).toMatchObject({ + claimStatus: 'released', + deathEvidence: { kind: 'exit-observed' } + }) + ) + await fixture.rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) + + const sent = await fixture.rig.host.send( + CALLER, + restTestSend('again', fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence) + ) + + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) + } + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledTimes(2) + expect( + activeStructuredAgentSessionTurnId((await fixture.rig.host.journalSnapshot(SESSION)).items) + ).not.toBe('working') +}) + +it.each([ + ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], + ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], + [ + 'a discarded worker', + () => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. + discardStructuredWorkerSession(SESSION, { + retireStructuredAgentSessionTabFromSnapshot: () => undefined + } as never) + ] +])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { + await restingChat() + const { loop } = fixture.rig.host.collaboratorsForTests().conversationDelivery + vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) + const reader: unknown[] = [] + await fixture.rig.host.subscribe({ + id: 'reader', + sessionId: SESSION, + emit: (event) => reader.push(event) + }) + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + (await fixture.rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok + ).toBe(true) + + await close() + // A close's rejection is a sentence with its fact beside it, never a marker. + await vi.waitFor(() => + expect(JSON.stringify(reader)).toContain( + '"reason":"The chat closed before this message was sent.","submittedAt"' + ) + ) + expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts index 541ed1a048e8..ebb84981a0d3 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts @@ -1,820 +1,262 @@ -import * as fileOperations from 'node:fs/promises' -import { readFile, rm } from 'node:fs/promises' -import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' -import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' -import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' -import type { - AgentJournalItemBody, - AgentJournalResolution, - AgentJournalQuestionItem -} from '../../../../shared/agent-session-journal-types' import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' -// Exercise real chat RPC: reads at rest start nothing; the first message starts the agent. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { expect, it, vi } from 'vitest' import { hostTestAttachParams, - hostTestMessage, - hostTestOperationId + hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' import { - createRestTestRig, foundRestTestChat, REST_TEST_CALLER as CALLER, REST_TEST_SESSION as SESSION, REST_TEST_THREAD, - restTestSend, - type RestTestRig + restTestSend } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' -import { - editPersistedTestAgentSessionStore, - readPersistedTestAgentSessionStore -} from '../../agent-session-record-store-test-harness' -import { OrcaRuntimeService } from '../../orca-runtime' import type { RpcResponse } from '../core' -import { RpcDispatcher } from '../dispatcher' -import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' -import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' -import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' -import { - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from '../../../native-chat/agent-session-journal/journal-host-database-test-support' -import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' - -vi.mock('node:fs/promises', { spy: true }) -const actualFiles = await vi.importActual('node:fs/promises') - -const CLIENT = { - clientId: 'device-1', - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], - connectionId: 'connection-1' -} - -let rig: RestTestRig -let dispatcher: RpcDispatcher -let requests = 0 - -async function call(method: string, params: unknown): Promise { - const replies: RpcResponse[] = [] - requests += 1 - await dispatcher.dispatchStreaming( - { id: `request-${requests}`, authToken: 'token', method, params }, - (raw) => replies.push(JSON.parse(raw) as RpcResponse), - CLIENT - ) - return replies -} - -/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ -async function restingChat(): Promise { - await foundRestTestChat(rig) - await rig.store.replaceSessionOptions({ - sessionId: SESSION, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - options: { model: 'gpt-saved', effort: 'high' }, - now: rig.clock.now - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - rig.adapter.dispatch.mockClear() - rig.adapter.readOptions.mockClear() -} +import { openTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/journal-host-database-test-support' -beforeEach(async () => { - requests = 0 - rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) - setStructuredAgentSessionHost(rig.host) - const runtime = new OrcaRuntimeService() - - dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) -}) +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' -afterEach(async () => { - vi.restoreAllMocks() - setStructuredAgentSessionHost(null) - await rig.dispose() - await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true +it('reads, subscribes and answers everything without starting an agent', async () => { + await restingChat() + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + + const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + const [commands] = await call('agentSession.commands', { sessionId: SESSION }) + const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) + + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(history).toMatchObject({ ok: true, result: { ok: true } }) + const snapshot = frames.find((frame) => frame.ok && 'result' in frame) + expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) + expect(options).toMatchObject({ + ok: true, + result: { current: { model: 'gpt-saved', effort: 'high' } } }) + // Absent, never an empty list: the composer keeps its own menu. + expect(commands).toMatchObject({ ok: true, result: {} }) + expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty('commands', []) + expect(outline).toMatchObject({ ok: true }) + expect(status).toMatchObject({ ok: true }) + expect(held).toMatchObject({ ok: true, result: { held: true } }) }) -describe('opening a chat at rest (P2-01)', () => { - it('reads, subscribes and answers everything without starting an agent', async () => { - await restingChat() - expect(rig.host.hasSession(SESSION)).toBe(false) - - const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - const [commands] = await call('agentSession.commands', { sessionId: SESSION }) - const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) - - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(history).toMatchObject({ ok: true, result: { ok: true } }) - const snapshot = frames.find((frame) => frame.ok && 'result' in frame) - expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) - expect(options).toMatchObject({ - ok: true, - result: { current: { model: 'gpt-saved', effort: 'high' } } - }) - // Absent, never an empty list: the composer keeps its own menu. - expect(commands).toMatchObject({ ok: true, result: {} }) - expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty( - 'commands', - [] - ) - expect(outline).toMatchObject({ ok: true }) - expect(status).toMatchObject({ ok: true }) - expect(held).toMatchObject({ ok: true, result: { held: true } }) - }) - - it('answers the owner check from the record without opening the chat', async () => { - await restingChat() +it('answers the owner check from the record without opening the chat', async () => { + await restingChat() - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) - expect(rig.host.hasSession(SESSION)).toBe(false) - }) + expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) - it('starts the agent on the first send (P2-01)', async () => { - await restingChat() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const sent = await rig.host.send(CALLER, restTestSend('wake up', fence)) - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - // Awaits the provider's answer itself rather than polling for it, however slow the start. - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - expect(rig.adapter.dispatch).toHaveBeenCalledOnce() - }) +it('starts the agent on the first send (P2-01)', async () => { + await restingChat() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const sent = await fixture.rig.host.send(CALLER, restTestSend('wake up', fence)) + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) + } + // Awaits the provider's answer itself rather than polling for it, however slow the start. + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce() }) -describe('the accessor', () => { - it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { - const attached = await rig.host.attach(CALLER, hostTestAttachParams(null)) - expect(attached.ok).toBe(true) - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, - hostTestMessage('from the provider'), - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - await Promise.all([ - ...Array.from({ length: 5 }, () => - call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - ), - call('agentSession.subscribe', { sessionId: SESSION }) - ]) - const openedJournals = new Set( - await Promise.all(open.mock.results.map((result) => result.value)) +it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { + const attached = await fixture.rig.host.attach(CALLER, hostTestAttachParams(null)) + expect(attached.ok).toBe(true) + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, + hostTestMessage('from the provider'), + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - expect(openedJournals.size).toBe(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) - - it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { - await restingChat() - // The host's per-session queue, held so the read waits behind it. - const { serialize, lifetime } = rig.host.collaboratorsForTests() - let release = (): void => undefined - const held = new Promise((started) => { - void serialize(SESSION, () => { - started() - return new Promise((resolve) => (release = resolve)) - }) - }) - await held - const read = rig.host.history({ sessionId: SESSION, direction: 'tail' }) - - // Disposed as quit's first teardown step does. - lifetime.dispose() - release() - - await expect(read).rejects.toThrow() - expect(rig.host.hasSession(SESSION)).toBe(false) - }) + await fixture.rig.host.flushStreamedEvents(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + fixture.rig.adapter.acquire.mockClear() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + await Promise.all([ + ...Array.from({ length: 5 }, () => + call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + ), + call('agentSession.subscribe', { sessionId: SESSION }) + ]) + const openedJournals = new Set(await Promise.all(open.mock.results.map((result) => result.value))) + expect(openedJournals.size).toBe(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) - it('refuses a read it cannot open with the reason, under the same code and message', async () => { - const [missing] = await call('agentSession.history', { - sessionId: 'session-never-created', - direction: 'tail' - }) - expect(missing).toMatchObject({ - ok: false, - error: { - code: 'agent_session_identity_required', - message: 'agent_session_identity_required', - data: { - refusal: { - code: 'agent_session_identity_required', - details: { reason: 'recordMissing' } - } - } - } +it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { + await restingChat() + // The host's per-session queue, held so the read waits behind it. + const { serialize, lifetime } = fixture.rig.host.collaboratorsForTests() + let release = (): void => undefined + const held = new Promise((started) => { + void serialize(SESSION, () => { + started() + return new Promise((resolve) => (release = resolve)) }) }) + await held + const read = fixture.rig.host.history({ sessionId: SESSION, direction: 'tail' }) - it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' - const failWith = (error: Error): void => { - open.mockRejectedValue(error) - } - const failures = async (): Promise => - [ - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.options', { sessionId: SESSION })) - ].filter((reply) => !reply.ok) + // Disposed as quit's first teardown step does. + lifetime.dispose() + release() - failWith( - Object.assign(new Error(`file is not a database: ${storagePath}`), { - code: 'ERR_SQLITE_ERROR', - errcode: 26 - }) - ) - const corrupt = await failures() - failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) - const unavailable = await failures() - - for (const [replies, reason] of [ - [corrupt, 'journalCorrupt'], - [unavailable, 'journalUnavailable'] - ] as const) { - expect(replies).toHaveLength(3) - for (const reply of replies) { - expect(reply).toMatchObject({ - ok: false, - error: { - // Released clients still read this refusal code from the message, not passthrough code. - code: 'runtime_error', - message: 'agent_session_journal_unreadable', - data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } - } - }) - expect(JSON.stringify(reply)).not.toContain(storagePath) - } - } - }) - - it('logs a reader reconnecting to a journal that will not open once per failure', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const logged = (): unknown[] => - warn.mock.calls - .filter( - ([line]) => - line === '[agent-session] open-for-read: opening the conversation for a read failed' - ) - .map(([, fields]) => fields?.error) - const reconnect = async (): Promise => [ - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) - ] - const denied = new Error('EACCES: permission denied') - const exhausted = new Error('EMFILE: too many open files') + await expect(read).rejects.toThrow() + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) - open.mockRejectedValue(denied) - for (let attempt = 0; attempt < 4; attempt += 1) { - // Every attempt is still refused with its reason; only the log is quiet. - expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) - } - expect(logged()).toEqual([denied]) - open.mockRejectedValue(exhausted) - await reconnect() - await reconnect() - expect(logged()).toEqual([denied, exhausted]) +it('refuses a read it cannot open with the reason, under the same code and message', async () => { + const [missing] = await call('agentSession.history', { + sessionId: 'session-never-created', + direction: 'tail' }) - - it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { - await foundRestTestChat(rig) - await rig.host.flushAllStreamedEvents() - updateTestJournalRowJson(openTestJournalHostDatabase(rig.root).db, SESSION, 2, '}{') - await rig.restart() - setStructuredAgentSessionHost(rig.host) - - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(frames.find((frame) => !frame.ok)).toMatchObject({ - error: { - data: { - refusal: { - code: 'agent_session_journal_unreadable', - details: { reason: 'journalCorrupt' } - } + expect(missing).toMatchObject({ + ok: false, + error: { + code: 'agent_session_identity_required', + message: 'agent_session_identity_required', + data: { + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' } } } - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(await rig.host.send(CALLER, restTestSend('after the damage', fence))).toMatchObject({ - ok: false, - refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } - }) - expect( - liveTestJournalRows(openTestJournalHostDatabase(rig.root).db, SESSION).find( - (row) => row.seq === 2 - )?.rowJson - ).toBe('}{') - }) - - it('subscribes an old mobile client that holds first even when no agent can start (P2-06)', async () => { - await restingChat() - rig.adapter.acquire.mockRejectedValue(new Error('auth expired')) - - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'mobile' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(held).toMatchObject({ ok: true }) - expect(frames.find((frame) => frame.ok)).toMatchObject({ result: { type: 'snapshot' } }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) -}) - -describe('options at rest', () => { - it('records a pick as intent and replays it at the next start (P2-16)', async () => { - await restingChat() - const fields = { key: 'model', value: 'gpt-picked' } - const [picked] = await call('agentSession.setOption', { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.setOption', - sessionId: SESSION, - fields - }) - }, - ...fields - }) - expect(picked).toMatchObject({ ok: true, result: { ok: true } }) - expect(rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await rig.host.send(CALLER, restTestSend('use the new model', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ - options: expect.objectContaining({ model: 'gpt-picked' }) - }) - }) - - it('answers the provider-level features of a chat at rest (P2-17)', async () => { - await restingChat() - setStructuredAgentSessionHost(await rig.restart({ agents: claudeAndCodexDeclared() })) - Object.assign(rig.host.deps.adapter, { - rewindSupport: (_id: string, agent?: string) => - agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } - }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - expect(options).toMatchObject({ - ok: true, - result: { threadGoal: { current: null }, rewind: { supported: true } } - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.readOptions).not.toHaveBeenCalled() + } }) }) -describe('an agent exit', () => { - it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { - await foundRestTestChat(rig) - const running = rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') - await rig.host.send(CALLER, restTestSend('again', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledTimes(2)) - }) +it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { + await restingChat() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' + const failWith = (error: Error): void => { + open.mockRejectedValue(error) + } + const failures = async (): Promise => + [ + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.options', { sessionId: SESSION })) + ].filter((reply) => !reply.ok) - it('whose settlement write failed is settled by the next send, which is delivered', async () => { - await foundRestTestChat(rig) - const open = rig.host.collaboratorsForTests().sessions.get(SESSION)! - const running = open.child! - // A turn in flight, so the exit has something to settle. - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - // Refuse both the exit write and its queued retry to test retained death evidence. - vi.spyOn(open.journal, 'appendLifecycleBatch') - .mockRejectedValueOnce(new Error('disk full')) - .mockRejectedValueOnce(new Error('disk full')) - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! + failWith( + Object.assign(new Error(`file is not a database: ${storagePath}`), { + code: 'ERR_SQLITE_ERROR', + errcode: 26 }) - // Released with its death evidence, not latched: the next acquire settles from that evidence. - await vi.waitFor(() => - expect(rig.store.getRecord(SESSION)?.lease).toMatchObject({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed' } + ) + const corrupt = await failures() + failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) + const unavailable = await failures() + + for (const [replies, reason] of [ + [corrupt, 'journalCorrupt'], + [unavailable, 'journalUnavailable'] + ] as const) { + expect(replies).toHaveLength(3) + for (const reply of replies) { + expect(reply).toMatchObject({ + ok: false, + error: { + // Released clients still read this refusal code from the message, not passthrough code. + code: 'runtime_error', + message: 'agent_session_journal_unreadable', + data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } + } }) - ) - await rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) - - const sent = await rig.host.send( - CALLER, - restTestSend('again', rig.store.getRecord(SESSION)!.lease.runtimeFence) - ) - - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) + expect(JSON.stringify(reply)).not.toContain(storagePath) } - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2) - expect( - activeStructuredAgentSessionTurnId((await rig.host.journalSnapshot(SESSION)).items) - ).not.toBe('working') - }) + } }) -describe('every close withdraws what is queued (P2-29)', () => { - it.each([ - ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], - ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], - [ - 'a discarded worker', - () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. - discardStructuredWorkerSession(SESSION, { - retireStructuredAgentSessionTabFromSnapshot: () => undefined - } as never) - ] - ])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { - await restingChat() - const { loop } = rig.host.collaboratorsForTests().conversationDelivery - vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) - const reader: unknown[] = [] - await rig.host.subscribe({ - id: 'reader', - sessionId: SESSION, - emit: (event) => reader.push(event) - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect((await rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok).toBe( - true - ) - - await close() - // A close's rejection is a sentence with its fact beside it, never a marker. - await vi.waitFor(() => - expect(JSON.stringify(reader)).toContain( - '"reason":"The chat closed before this message was sent.","submittedAt"' +it('logs a reader reconnecting to a journal that will not open once per failure', async () => { + await restingChat() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const logged = (): unknown[] => + warn.mock.calls + .filter( + ([line]) => + line === '[agent-session] open-for-read: opening the conversation for a read failed' ) - ) - expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') - expect(rig.host.hasSession(SESSION)).toBe(false) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) + .map(([, fields]) => fields?.error) + const reconnect = async (): Promise => [ + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) + ] + const denied = new Error('EACCES: permission denied') + const exhausted = new Error('EMFILE: too many open files') + + open.mockRejectedValue(denied) + for (let attempt = 0; attempt < 4; attempt += 1) { + // Every attempt is still refused with its reason; only the log is quiet. + expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) + } + expect(logged()).toEqual([denied]) + open.mockRejectedValue(exhausted) + await reconnect() + await reconnect() + expect(logged()).toEqual([denied, exhausted]) }) -it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { - await restingChat() - await rig.host.journalSnapshot(SESSION) - let journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const receipt = { write: () => {}, committed: () => {} } - let ordinal = 100 - const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => - journal.appendItem( - { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, - typeof text === 'string' ? hostTestMessage(text) : text, - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } +it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { + await foundRestTestChat(fixture.rig) + await fixture.rig.host.flushAllStreamedEvents() + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + "UPDATE journal_outcomes SET value_json = '}{' WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2" ) - await append('PRE_CLEAR_SECRET') - await journal.context.clear( - { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: rig.clock.now }, - receipt - ) - await append('EARLY_SAVED_MARKER') - for (let index = 0; index < 205; index++) { - await append(`saved ${index} ${'context '.repeat(60)}`) - } - const floor = journal.cursor() - await append('DISCARDED_REWIND_SECRET') - await journal.context.rewind(floor, fence, [], () => receipt) - const resolution = ( - state: AgentJournalResolution['state'], - selectedOptionId: string | null = null - ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) - const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ - kind: 'question', - question: name, - options: [], - freeTextQuestionId: 'input', - freeTextInput: { allowEmpty: true }, - resolution: { - ...resolution('resolved'), - ...(answer !== undefined - ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } - : {}) - } - }) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - await append(question(name, value)) - } - await append(question('unreadable')) - await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) - await append({ - ...question('legacy answer'), - resolution: resolution('resolved', 'input:legacy%20deployment') - }) - await append({ - kind: 'question', - question: 'Release choices', - options: [], - questions: [ - { - id: 'regions', - header: 'Region group', - question: 'Which regions?', - multiSelect: true, - options: [ - { id: 'east', label: 'East', description: 'Primary region' }, - { id: 'west', label: 'West' } - ] - }, - { - id: 'details', - question: 'Release detail?', - multiSelect: true, - options: [{ id: 'known', label: 'Known' }], - freeTextQuestionId: 'details' + .run(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + expect(frames.find((frame) => !frame.ok)).toMatchObject({ + error: { + data: { + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalCorrupt' } + } } - ], - resolution: { - ...resolution('resolved'), - answers: [ - { questionId: 'regions', optionIds: ['east', 'west'] }, - { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } - ] } }) - for (const choice of ['yes', 'no']) { - await append({ - kind: 'approval', - title: `Confirm ${choice}`, - detail: 'Deploy?', - options: [ - { id: 'yes', label: 'Yes' }, - { id: 'no', label: 'No' } - ], - resolution: resolution('resolved', choice) - }) - } - await append({ - kind: 'approval', - title: 'Review plan', - description: 'Saved description', - decisionReason: 'Saved reason', - matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, - blockedPath: '/work/target', - detail: 'Clipped detail', - subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, - options: [ - { id: 'plan', label: 'Approve plan' }, - { id: 'keep', label: 'Keep planning' } - ], - resolution: resolution('resolved', 'keep') - }) - const editor = piRpcDialogPresentation({ - id: 'editor', - method: 'editor', - title: 'Edit release notes', - prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', - placeholder: 'Keep migration details' + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + await fixture.rig.host.send(CALLER, restTestSend('after the damage', fence)) + ).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } }) - if (editor?.body.kind !== 'question') { - throw new Error('Pi editor missing') - } - const editorOrdinal = ordinal++ - await append(editor.body, editorOrdinal) - const editorParams = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } - } - const pendingEditor = await rig.host.continuationContext(editorParams) - if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { - throw new Error('Pending editor snapshot missing') - } - for (const text of [ - await readFile(pendingEditor.transcriptPath, 'utf8'), - pendingEditor.capturedText ?? '' - ]) { - expect(text).toContain( - 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' - ) - expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') - expect(text).toContain('"placeholder":"Keep migration details"') - } - const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] - const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) - await append( - { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, - editorOrdinal - ) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - const snapshot = await rig.host.journalSnapshot(SESSION) - journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await append({ ...question('pending ask'), resolution: resolution('pending') }) - const params = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } - } - await call('agentSession.options', { sessionId: SESSION }) - const gate = Promise.withResolvers() - const write = actualFiles.writeFile - const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { - await gate.promise - return write(...args) - }) - const pending = rig.host.continuationContext(params) - await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) - const currentJournal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await currentJournal.appendItem( - { provider: 'orca', clientMessageId: 'pr-31782-late' }, - hostTestMessage('LATER_SAVED_MARKER'), - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - gate.resolve() - const first = await pending - if (first.status !== 'current' || !first.transcriptPath) { - throw new Error('Snapshot missing') - } - const path = first.transcriptPath - try { - const file = await readFile(path, 'utf8') - expect(file).toContain('EARLY_SAVED_MARKER') - expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) - expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) - expect(first.capturedText).toContain('Earlier saved chat messages omitted') - expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') - for (const text of [file, first.capturedText ?? '']) { - const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => - JSON.parse(match[1]!) - ) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) - } - expect(text).toMatch( - /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ - ) - expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) - expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) - const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! - expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') - expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) - expect(text).toContain( - 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' + expect( + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + 'SELECT value_json FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2 LIMIT 1' ) - expect(text).toContain('"question":"Which regions?"') - expect(text).toContain('"label":"East","description":"Primary region"') - expect(text).toContain( - 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' - ) - expect(text).toContain('"other":"partial text"') - expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) - expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) - expect(text).toContain( - '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' - ) - expect(text).toContain( - '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' - ) - expect(text).toContain('Selected choice: Keep planning') - const row = text - .split('\n\n') - .find((entry) => entry.includes('"question":"Edit release notes"'))! - expect(row).toContain('Prompt state: resolved') - expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) - expect(row).toContain(JSON.stringify(answers)) - expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) - expect(row.split('\n').slice(2).join('\n')).toBe( - 'Question "editor"\nSubmitted free text: resolution.answers[0].other' - ) - } - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { - ok: true, - result: { - status: 'current', - transcriptPath: path, - capturedText: expect.stringContaining('LATER_SAVED_MARKER') - } - } - ]) - expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') - expect(await rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual({ - status: 'superseded' - }) - expect( - await rig.host.continuationContext({ - ...params, - expectedCursor: { epoch: 'other', sequence: 0 } - }) - ).toEqual({ status: 'superseded' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - writing.mockRejectedValueOnce(new Error('disk unavailable')) - expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) - } finally { - await rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true - }) - } + .get(SESSION)?.value_json + ).toBe('}{') }) -it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { +it('subscribes an old mobile client that holds first even when no agent can start (P2-06)', async () => { await restingChat() - const { cursor } = await rig.host.journalSnapshot(SESSION) - await rig.host.flushAllStreamedEvents() - await editPersistedTestAgentSessionStore(rig.root, (persisted) => { - Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') - const saved = (await readPersistedTestAgentSessionStore(rig.root)).records[SESSION] - const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } - const result = await rig.host.continuationContext(params) - expect(result).toMatchObject({ - status: 'current', - capturedText: expect.stringContaining('hello') - }) - if (result.status !== 'current' || !result.transcriptPath) { - throw new Error('Saved conversation snapshot missing') - } - expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { ok: true, result } - ]) - for (const stale of [ - { ...params, workspaceId: 'other' }, - { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, - { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } - ]) { - expect(await rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) - } - expect(rig.store.getRecord(SESSION)).toBeNull() - expect((await readPersistedTestAgentSessionStore(rig.root)).records[SESSION]).toEqual(saved) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + fixture.rig.adapter.acquire.mockRejectedValue(new Error('auth expired')) + + const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'mobile' }) + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + expect(held).toMatchObject({ ok: true }) + expect(frames.find((frame) => frame.ok)).toMatchObject({ result: { type: 'snapshot' } }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts new file mode 100644 index 000000000000..8213675518b5 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, vi } from 'vitest' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createRestTestRig, + foundRestTestChat, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcResponse } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' +import type * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +vi.mock('node:fs/promises', { spy: true }) +export const actualFiles = await vi.importActual('node:fs/promises') + +export const CLIENT = { + clientId: 'device-1', + clientKind: 'runtime' as const, + clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], + connectionId: 'connection-1' +} + +let rig: RestTestRig + +let dispatcher: RpcDispatcher + +let requests = 0 + +export async function call(method: string, params: unknown): Promise { + const replies: RpcResponse[] = [] + requests += 1 + await dispatcher.dispatchStreaming( + { id: `request-${requests}`, authToken: 'token', method, params }, + (raw) => replies.push(JSON.parse(raw) as RpcResponse), + CLIENT + ) + return replies +} + +/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ + +export async function restingChat(): Promise { + await foundRestTestChat(rig) + await rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + options: { model: 'gpt-saved', effort: 'high' }, + now: rig.clock.now + }) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + rig.adapter.acquire.mockClear() + rig.adapter.dispatch.mockClear() + rig.adapter.readOptions.mockClear() +} + +beforeEach(async () => { + requests = 0 + rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + setStructuredAgentSessionHost(rig.host) + const runtime = new OrcaRuntimeService() + dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) +}) + +afterEach(async () => { + vi.restoreAllMocks() + setStructuredAgentSessionHost(null) + await rig.dispose() + await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { + recursive: true, + force: true + }) +}) + +export const fixture = { + get dispatcher() { + return dispatcher + }, + set dispatcher(value: typeof dispatcher) { + dispatcher = value + }, + get requests() { + return requests + }, + set requests(value: typeof requests) { + requests = value + }, + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/structured-agent-runtime-registrations.ts b/src/main/runtime/structured-agent-runtime-registrations.ts index 67f68bbab6cc..3fe613b2500e 100644 --- a/src/main/runtime/structured-agent-runtime-registrations.ts +++ b/src/main/runtime/structured-agent-runtime-registrations.ts @@ -11,7 +11,7 @@ import { CODEX_STRUCTURED_AGENT } from '../codex/codex-structured-agent-definiti import { CLAUDE_STRUCTURED_AGENT } from '../claude/claude-structured-agent-definition' import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { createStructuredClaudeRuntimeAdapter } from './structured-claude-runtime-adapter' import type { AcpLaunchSpec } from '../acp/acp-launch-specs' import { acpStructuredAgentDefinition } from '../acp/acp-structured-agent-definitions' @@ -151,7 +151,7 @@ function createAcpAdapter( ): StructuredAgentRuntimeRegistration['createAdapter'] { return (context) => { const { deps, followUps } = context - const readJournal = (sessionId: string) => replayJournal(context.journalDatabase.db, sessionId) + const readJournal = (sessionId: string) => restoreJournal(context.journalDatabase.db, sessionId) const definition = acpStructuredAgentDefinition(spec) const sources = structuredAgentLaunchSources(context) const part = acpStructuredLaunchPart(spec, { diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts index 83b4eb2f2d30..0a43ac64fca1 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts @@ -6,8 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getAgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' +import * as attachmentSweeps from '../native-chat/agent-session-attachments/agent-session-attachment-sweep' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type Database from '../sqlite/sync-database' -import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' import type { AgentSessionRecordStore } from './agent-session-record-store' import { installAgentSessionAttachments, @@ -22,19 +26,26 @@ beforeEach(async () => { afterEach(async () => { stopAgentSessionAttachments() + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() await rm(stateDirectory, { recursive: true, force: true }) }) +const records: Pick = { + getRecord: () => null, + isSessionUnreadable: () => false +} + function install(directory = stateDirectory): void { - const records: Pick = { - getRecord: () => null, - isSessionUnreadable: () => false - } - // Written by a newer Orca: the sweep reads no claims, so nothing here touches the connection. - const journal: Pick = { + // Written by a newer Orca: the sweeps read no claims, so nothing here touches the connection. + const journal: Parameters[0]['journalDatabase'] = { writeAutocommit: () => { throw new Error('not opened in this test') }, + transaction: () => { + throw new Error('not opened in this test') + }, readOnly: true, isClosed: false, get db(): Database.Database { @@ -67,4 +78,41 @@ describe('installAgentSessionAttachments', () => { expect(getAgentSessionAttachmentStore()?.rootDir).toBe(agentSessionAttachmentStoreRoot(blocked)) warn.mockRestore() }) + + it("starts the chat database's sweep of retired records and stops it with the attachments", async () => { + vi.useFakeTimers() + vi.spyOn(attachmentSweeps, 'startAgentSessionAttachmentSweeps').mockReturnValue({ + stop: () => undefined + }) + const database = openTestJournalHostDatabase(stateDirectory) + const retire = () => + database.transaction((db) => { + const generation = db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', '"k"', 1, 's0000000000000001:0000000000000000', '["k","v"]', 0)`).run( + generation + ) + }) + const retired = () => + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + retire() + installAgentSessionAttachments({ + stateDirectory, + store: records, + journalDatabase: database, + logger: createStructuredAgentSessionLogger() + }) + await vi.advanceTimersByTimeAsync(59_999) + expect(retired()).toBe(1) + // The first pass a minute after launch: the records page, a rest, then the generation row. + await vi.advanceTimersByTimeAsync(1_000) + expect(retired()).toBe(0) + retire() + stopAgentSessionAttachments() + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retired()).toBe(1) + }) }) diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.ts b/src/main/runtime/structured-agent-session-attachment-wiring.ts index 81a9aa96473f..44f687e222de 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.ts @@ -1,5 +1,6 @@ // Keep chat attachment storage/sweeps beside the journal; its database owns upload claims the sweeps honor. +import { JournalOutcomeSweeper } from '../native-chat/agent-session-journal/journal-outcome-cleanup' import { mkdirSync } from 'node:fs' import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' import { @@ -19,14 +20,26 @@ const FIRST_SWEEP_DELAY_MS = 60 * 1000 const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000 let sweeper: AgentSessionAttachmentSweeper | null = null +let journalSweeper: JournalOutcomeSweeper | null = null export function installAgentSessionAttachments(deps: { stateDirectory: string store: Pick - journalDatabase: Pick + journalDatabase: Pick< + JournalHostDatabase, + 'readOnly' | 'isClosed' | 'db' | 'writeAutocommit' | 'transaction' + > logger: StructuredAgentSessionLogger }): void { stopAgentSessionAttachments() + journalSweeper = new JournalOutcomeSweeper({ + database: () => deps.journalDatabase, + onError: (error) => + deps.logger.warn('retired chat records could not be deleted', { + scope: 'journal-outcome-sweep', + error + }) + }).start() const root = agentSessionAttachmentStoreRoot(deps.stateDirectory) // Before any Claude starts: Claude drops an added directory that does not exist yet, for good. try { @@ -69,6 +82,8 @@ export function installAgentSessionAttachments(deps: { } export function stopAgentSessionAttachments(): void { + journalSweeper?.stop() + journalSweeper = null sweeper?.stop() sweeper = null setAgentSessionAttachmentStore(null) diff --git a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts index 5009cf0d909e..6fd3dbded9d9 100644 --- a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts @@ -24,10 +24,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { parseJournalRow } from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -98,21 +98,14 @@ async function stop(turnId?: string): Promise { /** Every end row written for turn-1, as a row or a lifecycle batch's mutation, in order. */ function turnEndRows(): AgentJournalTurnItem[] { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).flatMap((value) => { + if (value.field !== 'items' || value.deleted) { return [] } - const { row } = parsed - const bodies = row.kind === 'lifecycle-batch' ? row.mutations : [row] - return bodies.flatMap((entry) => - entry.kind === 'item' && - entry.body.kind === 'turn' && - entry.body.turnId === 'turn-1' && - entry.body.state !== 'running' - ? [entry.body] - : [] - ) + const { body } = fields.items.element.parse(JSON.parse(value.json)) + return body.kind === 'turn' && body.turnId === 'turn-1' && body.state !== 'running' + ? [body] + : [] }) } diff --git a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts index acfa3a122d60..1c969f14a64e 100644 --- a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts @@ -13,7 +13,8 @@ import { codexTurnLifecycleFake } from '../codex/codex-turn-lifecycle-fake' import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session-mutation-envelope' import type { AgentJournalDispatchState, - AgentJournalTurnItem + AgentJournalTurnItem, + AgentJournalItemBody } from '../../shared/agent-session-journal-types' import { HOST_TEST_SESSION as SESSION, @@ -24,14 +25,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - parseJournalRow, - type JournalLifecycleMutation, - type JournalRow -} from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -83,20 +80,27 @@ async function send(text: string): Promise { } /** A stored row, or one mutation of a lifecycle batch: what a settlement or a frame lands as. */ -type JournalEntry = JournalRow | JournalLifecycleMutation +type JournalEntry = + | { kind: 'item'; body: AgentJournalItemBody } + | { kind: 'dispatch'; clientMessageId: string; state: AgentJournalDispatchState } -/** The sequence of the first row that `matches`, or of the lifecycle batch carrying it. */ +/** Outcomes preserve the sequence at which a verdict or whole item committed. */ function seqOf(matches: (entry: JournalEntry) => boolean): number | undefined { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).find((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).find((value) => { + if (value.deleted) { return false } - const { row } = parsed - return ( - matches(row) || - (row.kind === 'lifecycle-batch' && row.mutations.some((mutation) => matches(mutation))) - ) + if (value.field === 'items') { + return matches({ + kind: 'item', + body: fields.items.element.parse(JSON.parse(value.json)).body + }) + } + if (value.field === 'submissions') { + const [id, submission] = fields.submissions.element.parse(JSON.parse(value.json)) + return matches({ kind: 'dispatch', clientMessageId: id, state: submission.dispatchState }) + } + return false })?.seq } diff --git a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts index 88e40db7e8d6..05955c8c88b4 100644 --- a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts +++ b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts @@ -1,10 +1,18 @@ import './rpc/unused-default-rpc-methods.test-fixture' +import { execFile } from 'node:child_process' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../shared/orca-session-address' import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' import { idOf } from './rpc/orchestration-session-caller-test-fixture' import { closeStructuredAgentSessionChild } from './agent-session/structured-agent-session-close' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { OrcaRuntimeRpcServer } from './runtime-rpc' +import { ORCHESTRATION_METHODS } from './rpc/methods/orchestration' import type { FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, @@ -13,17 +21,79 @@ import { call, clearChat, coordinatorRunAndTask, + codex, db, dispatcher, host, openChat, request, + root, + runtime, sendUserMessage, settleTurn, startClearedContext } from './structured-chat-coordinator-mail-rig.test-fixture' const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) +const cliPath = join(process.cwd(), 'src/cli/index.ts') +const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href + +async function readWorkerThroughCli(dispatchId: string): Promise { + const env = { ...process.env } + for (const name of [ + 'HOME', + 'USERPROFILE', + 'APPDATA', + 'LOCALAPPDATA', + 'XDG_CONFIG_HOME', + 'XDG_CACHE_HOME', + 'XDG_DATA_HOME', + 'XDG_STATE_HOME', + 'XDG_RUNTIME_DIR', + 'CLAUDE_CONFIG_DIR', + 'CODEX_HOME', + 'ORCA_E2E_HOME_DIR', + 'ORCA_E2E_USER_DATA_DIR', + 'ORCA_USER_DATA_PATH' + ]) { + env[name] = root + } + for (const name of [ + 'ORCA_ENVIRONMENT', + 'ORCA_PAIRING_CODE', + 'ORCA_REMOTE_PAIRING', + 'ORCA_RUNTIME_SOURCE_ID', + 'ORCA_RUNTIME_SOURCE_INCARNATION', + 'ORCA_RUNTIME_SOURCE_PROFILE_PATH', + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_STRUCTURED_SESSION' + ]) { + env[name] = '' + } + env.ORCA_AGENT_SESSION_ID = COORDINATOR + env.ORCA_BACKGROUND_LAUNCH = '1' + env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' + // execFile owns its child handle, bounds its lifetime, and awaits exit before server cleanup. + const { stdout } = await promisify(execFile)( + process.execPath, + [ + '--import', + tsxLoader, + '--conditions=orca-source', + cliPath, + 'orchestration', + 'worker-read', + '--dispatch', + dispatchId, + '--source', + 'transcript' + ], + { cwd: root, env, timeout: 15_000, windowsHide: true, encoding: 'utf8' } + ) + return stdout +} /** A Dispatch of the coordinator's task to the peer chat, both chats open. */ async function dispatchToChat(): Promise<{ @@ -226,9 +296,36 @@ describe("a chat assignee's liveness, stop and close", () => { await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) await settleTurn(PEER_CHAT, 0) - const read = await call('orchestration.workerRead', { dispatch: dispatchId }) - - expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) - expect(JSON.stringify(read.transcript)).toContain('working on it') + const journal = host.collaboratorsForTests().sessions.get(PEER_CHAT)?.journal + if (!journal) { + throw new Error('Worker conversation was not opened') + } + const prefix = journal.cursor() + await host.close(PEER_CHAT, 'evict') + expect(host.hasSession(PEER_CHAT)).toBe(false) + const saved = restoreJournal(host.deps.journalDatabase.db, PEER_CHAT)?.state + expect(saved?.lastSequence).toBeGreaterThanOrEqual(prefix.sequence) + const acquisitions = codex.connections.length + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath: root, + enableWebSocket: false, + methods: ORCHESTRATION_METHODS + }) + try { + await server.start() + const output = await readWorkerThroughCli(dispatchId) + expect(output).toContain('Source: transcript (provider=codex)') + expect(output).toContain('working on it') + expect(host.hasSession(PEER_CHAT)).toBe(true) + expect(codex.connections).toHaveLength(acquisitions) + + const read = await call('orchestration.workerRead', { dispatch: dispatchId }) + + expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) + expect(JSON.stringify(read.transcript)).toContain('working on it') + } finally { + await server.stop() + } }) }) diff --git a/src/main/sqlite/sqlite-read-failure.ts b/src/main/sqlite/sqlite-read-failure.ts index f5c51f75312c..ba6ef64334a2 100644 --- a/src/main/sqlite/sqlite-read-failure.ts +++ b/src/main/sqlite/sqlite-read-failure.ts @@ -18,7 +18,7 @@ function primaryErrcode(error: unknown): number | null { return typeof errcode === 'number' && Number.isFinite(errcode) ? errcode & 0xff : null } -function isSqliteDriverError(error: unknown): boolean { +export function isSqliteDriverError(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ERR_SQLITE_ERROR' } diff --git a/src/shared/agent-session-journal-open-union.ts b/src/shared/agent-session-journal-open-union.ts index 8d2e0e3b6ab0..d6d00142284a 100644 --- a/src/shared/agent-session-journal-open-union.ts +++ b/src/shared/agent-session-journal-open-union.ts @@ -18,6 +18,13 @@ export function knownTags(union: z.ZodDiscriminatedUnion): ReadonlySet { ) } +const fallbacks = new WeakSet() + +/** The arm that keeps an unknown tag; saved-outcome storage drops it, so an unknown tag refuses. */ +export function isJournalOpenUnionFallback(schema: z.core.$ZodType): boolean { + return fallbacks.has(schema) +} + /** Keep unknown nonblank tags as-is for readers to skip. Abort the catch-all for known malformed arms; blank tags are damage. */ export function openDiscriminatedUnion(known: T) { const key = known.def.discriminator @@ -25,5 +32,6 @@ export function openDiscriminatedUnion(known: const unknown = z .object({ [key]: z.string().regex(/\S/) }) .refine((value) => !tags.has(value[key] ?? ''), { abort: true }) + fallbacks.add(unknown) return z.union([known, unknown]) } diff --git a/src/shared/agent-session-journal-schemas.ts b/src/shared/agent-session-journal-schemas.ts index 5752081a18a3..221ef28ac862 100644 --- a/src/shared/agent-session-journal-schemas.ts +++ b/src/shared/agent-session-journal-schemas.ts @@ -302,6 +302,14 @@ export function isAdmissibleAgentJournalItemBody(value: unknown): value is Agent return AgentJournalItemBodySchema.safeParse(value).success } +/** The wire's known arms, in order; saved-outcome storage declares them in full + * (journal-storage-schema.ts). */ +export const AgentJournalKnownSchemas = { + blocks: Block.options[0].options, + bodies: KnownItemBody.options, + resolution: Resolution +} + /** Submission rows may only carry a user-authored message body. */ export function isAdmissibleAgentJournalMessageBody( value: unknown diff --git a/src/shared/wsl-move/wsl-move-storage-dispositions.ts b/src/shared/wsl-move/wsl-move-storage-dispositions.ts index c07f2b06d9fa..ee7e01843eb2 100644 --- a/src/shared/wsl-move/wsl-move-storage-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-storage-dispositions.ts @@ -117,6 +117,7 @@ export const SQLITE_SCHEMA_FILE_DATABASES: Record = { 'agent-session-journal', 'src/main/native-chat/agent-session-journal/command-receipt-schema.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-database-schema.ts': 'agent-session-journal', + 'src/main/native-chat/agent-session-journal/journal-outcome-format.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-pi-active-branch.ts': 'pi-branch-import', 'src/main/native-chat/agent-session-journal/queued-message-schema.ts': 'agent-session-journal', 'src/main/persistence/profile-state/profile-state-database-schema.ts': 'profile-state', @@ -160,6 +161,9 @@ export const SQLITE_TABLE_DISPOSITIONS: Record 'agent_session_attachment_claims', 'agent_session_attachment_sweeps', 'journal_imports', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations', 'journal_repairs', 'journal_rows', 'journal_sessions', diff --git a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts index ac2f88843ae2..ff2fec58e5dc 100644 --- a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts @@ -10,6 +10,7 @@ import { import type { AgentJournalItemIdentity } from '../../../src/shared/agent-session-journal-types' import { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -32,10 +33,19 @@ type OldRunOutcome = ( options: { activeTurnIsWorking?: boolean } ) => { failedCallCount: number; succeeded: boolean } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} // Loads a real old build, including cold extraction and transforms. test('an older host and client read a call a stop cut short as the failure they always showed', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-interrupted-tool-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: a call a stop cut short, with the partial output it left. const journal = await journals.open({ @@ -67,7 +77,7 @@ test('an older host and client read a call a stop cut short as the failure they if (!since.ok) { throw new Error(`expected rows, got reset ${since.reset}`) } - const rows: JournalRow[] = since.rows + const rows = inputRows(since.rows) const current = journal.snapshot().items expect(current.map((item) => item.body)).toMatchObject([ { state: 'failed', endedAs: 'interrupted' }, diff --git a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts index 8ad4e3781a6e..5322b956e7ce 100644 --- a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts @@ -27,7 +27,7 @@ import { } from './release-checkout' // Newer journals must yield the newer-Orca refusal to old clients, never damage wording. -// Unknown bodies remain writable here; also probe the older host’s handling of those rows. +// Unknown bodies refuse as a newer Orca's here; also probe the older host’s handling of those rows. const SUITE_TIMEOUT_MS = 180_000 // The last release that does not know the newer-Orca reason: its words fall back to the code's. const BEFORE_NEWER_REASON_REF = 'v1.4.218' @@ -58,7 +58,7 @@ type NoticeEnglish = (parts: unknown[]) => string type IsFinal = (refusal: AgentSessionRefusalReference | undefined) => boolean let directory: string -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeAll(() => { directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -191,7 +191,7 @@ describe('a chat a newer Orca saved, across versions', () => { ['body kind', NEWER_BODY_KIND], ['plan subject kind', NEWER_NESTED_LITERAL] ])( - "this build keeps a newer build's %s and stays writable; a build before it deletes it", + "this build refuses a newer build's %s as a newer Orca's and keeps it; a build before it deletes it", async (_value, body) => { rmSync(directory, { recursive: true, force: true }) directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -201,8 +201,9 @@ describe('a chat a newer Orca saved, across versions', () => { revision: 1, body }) - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: directory }) - expect(reopened.snapshot().items).toHaveLength(3) + await expect( + journals.open({ identity: IDENTITY, stateDirectory: directory }) + ).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) await journals.closeAll() expect(await storedRows()).toEqual(rows) diff --git a/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts new file mode 100644 index 000000000000..dfeaab769201 --- /dev/null +++ b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts @@ -0,0 +1,300 @@ +import { createHash } from 'node:crypto' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../src/shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../src/shared/agent-session-provider-handle-encoding' +import Database from '../../../src/main/sqlite/sync-database' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + SAVED_BY_NEWER_ORCA +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport, + resolveBaselineReleaseRef, + resolveRecentStableReleaseRefs +} from './release-checkout' + +// A chat this build has written, new or an existing one whose input rows an older build wrote, is +// refused by each of the two newest releases (the downgrade window) as a newer Orca's, which leaves +// every byte as it was; a build from before that reason opens it read-only, as it does any newer +// row, and changes no saved row (it only adds a table of its own). The existing chat's input rows +// stay byte for byte throughout, and this build reads the whole chat again afterwards. +const SUITE_TIMEOUT_MS = 180_000 +// A main build sharing this database and schema; the releases in the window are probed as well. +const WRITABLE_BASELINE_REF = '3727100cc9dbcea6201f8a3e506676a3c4b53b18' +const JOURNAL = 'src/main/native-chat/agent-session-journal' + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-outcome-chat', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +/** The identity as builds before the neutral provider handle took it. */ +const OLDER_HANDLE: AgentSessionJournalProviderHandle = { kind: 'codex', threadId: 'thread-1' } +const OLDER_IDENTITY = { ...IDENTITY, providerHandle: OLDER_HANDLE } + +type ReleasedJournal = { + snapshot: () => { items: unknown[] } + appendItem: (identity: unknown, body: unknown, options: unknown) => Promise +} +type ReleasedOpener = { + open: (options: { identity: unknown; stateDirectory: string }) => Promise + closeAll: () => Promise +} + +let directory: string +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'orca-outcome-chat-xv-')) +}) +afterEach(() => { + rmSync(directory, { recursive: true, force: true }) +}) + +const appendStatus = (journal: Pick, ordinal: number) => + journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }, + { kind: 'status', text: `item ${ordinal}` }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + +/** A chat this build writes: new, or existing with three input rows of items an older build wrote + * before this build's first write. Returns that prefix as stored. */ +async function savedChat(kind: 'new' | 'existing'): Promise { + let prefix: JournalStoredRow[] = [] + if (kind === 'existing') { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const journal = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(journal, ordinal) + } + await older.closeAll() + prefix = liveTestJournalRows(openTestJournalHostDatabase(directory).db, IDENTITY.sessionId) + expect(prefix).toHaveLength(4) + } + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 3; ordinal < 6; ordinal++) { + await appendStatus(journal, ordinal) + } + await journals.closeAll() + const database = openTestJournalHostDatabase(directory) + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toMatchObject({ + prefix: prefix.length + }) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + // One appended marker, after the prefix, where outcome records begin. + expect(rows.map((row) => row.seq)).toEqual([...prefix.map((row) => row.seq), prefix.length + 1]) + await closeTestJournalHostDatabase(directory) + return prefix +} + +/** The database file and its log, by content; SQLite's shared-memory index is not data. */ +function databaseBytes(): Record { + return Object.fromEntries( + ['agent-session-journal.db', 'agent-session-journal.db-wal'] + .filter((file) => existsSync(join(directory, file))) + .map((file) => [ + file, + createHash('sha256') + .update(readFileSync(join(directory, file))) + .digest('hex') + ]) + ) +} + +/** Every table's schema and rows, in a stable order. */ +function savedContent(): Map { + const db = new Database(join(directory, 'agent-session-journal.db'), { readonly: true }) + try { + const content = new Map() + for (const { name, sql } of db + .prepare("SELECT name, sql FROM sqlite_schema WHERE type = 'table' ORDER BY name") + .all()) { + content.set(String(name), { + sql, + rows: db.prepare(`SELECT * FROM "${String(name)}" ORDER BY rowid`).all() + }) + } + return content + } finally { + db.close() + } +} + +describe('a chat this build wrote, opened by a shipped build', () => { + it.each([ + ['new', 'the newest release'], + ['existing', 'the newest release'], + ['new', 'the release before it'], + ['existing', 'the release before it'], + ['new', 'the writable baseline'], + ['existing', 'the writable baseline'] + ] as const)( + 'keeps a %s chat from %s, leaving every byte as it was, and reads whole again after', + async (kind, build) => { + const prefix = await savedChat(kind) + const before = databaseBytes() + const saved = savedContent() + expect(before['agent-session-journal.db']).toBeDefined() + const inWindow = build !== 'the writable baseline' + const checkout = await materializeReleaseCheckout( + build === 'the newest release' + ? resolveBaselineReleaseRef() + : inWindow + ? resolveRecentStableReleaseRefs(2)[1]! + : WRITABLE_BASELINE_REF + ) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const older = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + const close = releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + ) + try { + if (inWindow) { + const failure = await older.open({ identity: IDENTITY, stateDirectory: directory }).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject(SAVED_BY_NEWER_ORCA) + } else { + const opened = await older.open({ identity: OLDER_IDENTITY, stateDirectory: directory }) + // It latches read-only at the marker, having read only the rows before it. + expect(opened.snapshot().items).toHaveLength(Math.max(prefix.length - 1, 0)) + await expect( + opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the older build' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).rejects.toMatchObject({ code: 'journal_read_only' }) + } + } finally { + await older.closeAll() + close(directory) + } + if (inWindow) { + expect(databaseBytes()).toEqual(before) + } else { + const after = savedContent() + expect( + [...saved].filter(([name, content]) => !isDeepStrictEqual(after.get(name), content)) + ).toEqual([]) + } + // Upgraded again, this build reads the prefix and its records, the rows still as they were. + const database = openTestJournalHostDatabase(directory) + try { + const reopened = restoreJournal(database.db, IDENTITY.sessionId) + expect(reopened).toMatchObject({ newer: null, damage: null }) + expect(reopened?.state.items.size).toBe(kind === 'existing' ? 6 : 3) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS + ) +}) + +// Checks out and loads the newest release's own journal code, which takes well past the default. +it( + 'leaves an existing chat whose first write from this build failed as it was, so the newest release opens and writes it', + async () => { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const seeded = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(seeded, ordinal) + } + await older.closeAll() + const prefix = liveTestJournalRows( + openTestJournalHostDatabase(directory).db, + IDENTITY.sessionId + ) + await closeTestJournalHostDatabase(directory) + + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + const database = openTestJournalHostDatabase(directory) + // The first write fails after its marker is in: at a record, then at COMMIT. + database.db.exec(`CREATE TEMP TRIGGER failure BEFORE INSERT ON main.journal_outcomes + BEGIN SELECT RAISE(ABORT, 'record failure'); END`) + await expect(appendStatus(journal, 3)).rejects.toThrow('record failure') + database.db.exec('DROP TRIGGER failure') + const exec = database.db.exec.bind(database.db) + const commit = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('commit failure') + } + exec(sql) + }) + await expect(appendStatus(journal, 4)).rejects.toThrow('commit failure') + commit.mockRestore() + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toBeNull() + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(0) + expect(liveTestJournalRows(database.db, IDENTITY.sessionId)).toEqual(prefix) + await journals.closeAll() + + const checkout = await materializeReleaseCheckout(resolveBaselineReleaseRef()) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const release = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + try { + const opened = await release.open({ identity: IDENTITY, stateDirectory: directory }) + expect(opened.snapshot().items).toHaveLength(3) + await opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the release' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } finally { + await release.closeAll() + releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + )(directory) + } + const reopened = openTestJournalHostDatabase(directory) + try { + expect(restoreJournal(reopened.db, IDENTITY.sessionId)?.state.items.size).toBe(4) + expect(liveTestJournalRows(reopened.db, IDENTITY.sessionId).slice(0, prefix.length)).toEqual( + prefix + ) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS +) diff --git a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts index f3a677c6cdc7..4f5cb4f7c581 100644 --- a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts @@ -21,6 +21,7 @@ import { SAVED_BY_NEWER_ORCA } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -59,11 +60,20 @@ const OLDER_IDENTITY: OlderJournalIdentity = { providerHandle: { kind: 'codex', threadId: 'thread-1' } } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( '%s replays current raw rows with the unconfirmed failure intact', async (ref) => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-note-raw-skew-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) const turn = { provider: 'orca', clientMessageId: 'turn-raw-skew' } as const @@ -103,10 +113,10 @@ test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( 'applyJournalRow' ) const old = create(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => fold(old, row)) + inputRows(since.rows).forEach((row) => fold(old, row)) expect(old.items.get(agentJournalItemKey(note))).toMatchObject({ body: unconfirmed }) const current = createJournalReducerState(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => applyJournalRow(current, row)) + inputRows(since.rows).forEach((row) => applyJournalRow(current, row)) expect(current.items.get(agentJournalItemKey(note))?.body).toEqual(unconfirmed) expect( renderJournalState(current).items.find((item) => item.itemId === agentJournalItemKey(note)) @@ -137,7 +147,7 @@ type OldReplay = { // Both downgrade probes load real old builds, including cold extraction and transforms. test("an older build keeps every row around a Stop's event, a Resume and a reopen mark, and folds the rows after them", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: history, a person's Stop, a Resume, then more history. const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) @@ -253,7 +263,7 @@ function storedRows(directory: string): string[] { test("an older build opens this build's journal writable and appends to it; the pause survives the round trip", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-writable-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const itemIds = (journal: Pick) => journal.snapshot().items.map((entry) => entry.itemId) try { @@ -301,7 +311,7 @@ test("an older build opens this build's journal writable and appends to it; the // Move the pinned baseline once a released reader preserves them. test("this build keeps a newer build's row kind and refuses the load; a build before it deletes it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-newer-kind-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const newerKinds = () => storedRows(directory).filter((row) => row.includes('"future-mark"')) try { const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } diff --git a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts index d99b91336c24..b6886719eb72 100644 --- a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts +++ b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts @@ -68,10 +68,11 @@ export function describeReleasedStopNoteProjection(port: ScenarioPort): void { const after = reduce(before, replies) expect(render(after)).toEqual({ type: 'text', text: ordinary.text }) expect(rig.journal.itemBody(noteId)).toEqual(unconfirmed) + // The turn end is one saved sequence that touches only the turn, whichever writer made it. const since = rig.journal.readSince(before.cursor!) expect(since).toMatchObject({ ok: true, - rows: [expect.objectContaining({ kind: batch ? 'lifecycle-batch' : 'item' })] + rows: [expect.objectContaining({ kind: 'outcome', itemIds: [turnItemId] })] }) } ) diff --git a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts index 56f88602e2c8..8bf07d39196c 100644 --- a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts @@ -94,7 +94,8 @@ async function acceptPersonSend( test("an older build reads the send this build's quit left queued, its source included, and settles it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-kept-leftover-downgrade-')) - const journals = createTrackedJournalOpener() + // A chat this build has not converted keeps input rows, so an older build can still read it. + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const quitting = await journals.open({ identity: IDENTITY, stateDirectory: directory }) await acceptPersonSend(quitting, 'left-queued') diff --git a/tests/e2e/cross-version-wire/release-checkout.ts b/tests/e2e/cross-version-wire/release-checkout.ts index f541ae5735df..759c68d96e99 100644 --- a/tests/e2e/cross-version-wire/release-checkout.ts +++ b/tests/e2e/cross-version-wire/release-checkout.ts @@ -74,6 +74,24 @@ export function resolveBaselineReleaseRef(): string { return latest } +/** The newest `count` stable desktop releases, newest first: the ones a downgrade can reach. */ +export function resolveRecentStableReleaseRefs(count: number): string[] { + let tags = git(['tag', '--list', 'v[0-9]*']).split('\n').filter(Boolean) + const recent: string[] = [] + while (recent.length < count) { + const latest = selectLatestStableReleaseTag(tags) + if (!latest) { + throw new Error( + `Cross-version harness found ${recent.length} of ${count} stable desktop release tags; ` + + 'a shallow CI clone needs `fetch-depth: 0`.' + ) + } + recent.push(latest) + tags = tags.filter((tag) => tag !== latest) + } + return recent +} + function resolveCommit(ref: string): string { try { return git(['rev-parse', `${ref}^{commit}`]) diff --git a/tests/e2e/cross-version-wire/released-chat-continuation.ts b/tests/e2e/cross-version-wire/released-chat-continuation.ts new file mode 100644 index 000000000000..561223ce3093 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-continuation.ts @@ -0,0 +1,94 @@ +import { agentJournalLinkageFields } from '../../../src/shared/agent-session-journal-producer' +import { parseAgentJournalItemKey } from '../../../src/shared/agent-session-journal-item-key' +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import type { JournalReplacementItem } from '../../../src/main/native-chat/agent-session-journal/journal-epoch-replacement' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// What a user does next with a chat a released build wrote: edit a card it queued (the first write, +// over a key the old rows hold), send, and rewind to before that send, which saves every kept message +// and card again. This build and a shipped build run the same steps. + +const FENCE = 1 + +export type ContinuedJournal = Pick< + AgentSessionJournal, + | 'queuedMessages' + | 'appendSubmission' + | 'resolveDispatch' + | 'replaceEpochItems' + | 'snapshot' + | 'itemBody' + | 'itemProvenance' +> + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** The first write: an edit of a card the release queued and still holds. */ +export async function editReleasedCard(journal: ContinuedJournal): Promise { + const card = journal.queuedMessages.list().find((entry) => entry.messageId === 'card-2') + if (!card) { + throw new Error('the release queued no card-2') + } + const edited = await journal.queuedMessages.update({ + messageId: 'card-2', + expectedBodyFingerprint: card.fingerprint, + text: 'second, edited after the upgrade' + }) + if (edited.status !== 'updated') { + throw new Error(`the card edit was ${edited.status}`) + } +} + +export async function sendAfterUpgrade(journal: ContinuedJournal): Promise { + await journal.appendSubmission({ + clientMessageId: 'after-upgrade', + payloadFingerprint: 'fp-after-upgrade', + body: message('after the upgrade'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' } + }) + await journal.resolveDispatch({ + clientMessageId: 'after-upgrade', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) +} + +/** A rewind to before the send: every message the release wrote is kept, as rewind keeps them. */ +export async function rewindReleasedChat( + journal: ContinuedJournal, + keptItemIds: ReadonlySet +): Promise { + const kept = journal + .snapshot() + .items.filter((item) => keptItemIds.has(item.itemId)) + .map(({ itemId, observedAt, turnScope, ...linkage }): JournalReplacementItem => { + const body = journal.itemBody(itemId) + const identity = parseAgentJournalItemKey(itemId) + if (!body || !identity) { + throw new Error(`no kept item ${itemId}`) + } + const { ownerFence, executionOwner, ...echo } = journal.itemProvenance(itemId) + return { + identity, + ...echo, + body, + observedAt, + ...(turnScope ? { turnScope } : {}), + ownerFence: ownerFence ?? 0, + ...(executionOwner === undefined ? {} : { executionOwner }), + ...agentJournalLinkageFields(linkage) + } + }) + if (kept.length !== keptItemIds.size) { + throw new Error('a kept item is missing from the chat') + } + await journal.replaceEpochItems('handle_forked', FENCE, kept) +} diff --git a/tests/e2e/cross-version-wire/released-chat-queue.ts b/tests/e2e/cross-version-wire/released-chat-queue.ts new file mode 100644 index 000000000000..5cc8491b26ae --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-queue.ts @@ -0,0 +1,57 @@ +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import { QUEUED_MESSAGE_PAUSED_SEND_FAILED } from '../../../src/shared/agent-session-queued-message-wire' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// Queue edits as each release's queue writes them: two cards, an edit, a move, a hold and a +// withdrawal. Releases before cards moved into the chat's rows kept them in a table of their own, +// with no edit or move. + +type TableQueue = { + insert: (input: { + messageId: string + body: AgentJournalMessageItem + fingerprint: string + hostInstance: string + }) => Promise + hold: (input: { messageIds: readonly string[]; reason: 'send_failed' }) => Promise + withdraw: (input: { messageIds: readonly string[]; settledByOp: string }) => Promise +} + +/** A table-backed queue answers an operation's replay from its stored rows. */ +function isTableQueue(queue: unknown): queue is TableQueue { + return typeof queue === 'object' && queue !== null && 'receipts' in queue +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +export async function queueReleasedCards( + queue: AgentSessionJournal['queuedMessages'] +): Promise { + const table: unknown = queue + if (isTableQueue(table)) { + const card = { fingerprint: 'fp-card', hostInstance: 'host-instance-1' } + await table.insert({ ...card, messageId: 'card-1', body: message('later') }) + await table.insert({ ...card, messageId: 'card-2', body: message('second') }) + await table.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await table.withdraw({ messageIds: ['card-1'], settledByOp: 'withdraw-card-1' }) + return + } + const first = await queue.insert({ + messageId: 'card-1', + body: message('later'), + options: { model: 'model-1' } + }) + await queue.insert({ messageId: 'card-2', body: message('second') }) + await queue.update({ + messageId: 'card-1', + expectedBodyFingerprint: first.fingerprint, + text: 'later, edited' + }) + await queue.move({ messageId: 'card-2', beforeMessageId: 'card-1' }) + await queue.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await queue.withdraw(['card-1']) +} diff --git a/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts new file mode 100644 index 000000000000..be6ba97f8839 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts @@ -0,0 +1,211 @@ +import { cpSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + type TrackedJournalOpener +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import { JOURNAL_PREFIX_ORDINAL } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-codec' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import type { AgentJournalSnapshot } from '../../../src/shared/agent-session-journal-types' +import { parseJournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import { JournalWriteProjection } from '../../../src/main/native-chat/agent-session-journal/journal-write-projection' +import { resolveRecentStableReleaseRefs } from './release-checkout' +import { + editReleasedCard, + rewindReleasedChat, + sendAfterUpgrade, + type ContinuedJournal +} from './released-chat-continuation' +import { + identityOf, + releasedJournalOpener, + writeReleasedChat, + type Agent +} from './released-chat-writers' + +// Each release in the downgrade window, and the oldest release whose chat database this build still +// reads, writes a Claude and a Codex chat through its own writers. This build admits every row as +// written, opens the chat as that release had it, then edits a queued card (its first write, over +// a key the old rows hold), sends, and rewinds, which saves the kept chat again in this build's +// form. Every commit restores to the live chat. What this build does after the open is checked on +// its own result, never against a release, so main stays free to change it. +const SUITE_TIMEOUT_MS = 180_000 +const RELEASES = { + 'the newest release': () => resolveRecentStableReleaseRefs(2)[0]!, + 'the release before it': () => resolveRecentStableReleaseRefs(2)[1]!, + // The first release with one chat database per host (schema 3, the oldest this build opens); + // earlier releases kept a file per chat, which nothing reads any more. It never changes. + 'the oldest release with this chat database': () => 'v1.4.219' +} as const +type Written = Awaited> + +beforeEach(() => { + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(() => { + JournalWriteProjection.verifyEachCommit = false +}) + +const view = (journal: ContinuedJournal) => ({ + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()] +}) + +/** What the release wrote: its items, sends and cards, in order. Fields a later build adds to them + * are not compared (`toMatchObject`), so main may add one; a changed value or order still fails. */ +const releaseWritten = ({ + snapshot, + cards +}: { + snapshot: AgentJournalSnapshot + cards: unknown[] +}) => ({ + items: snapshot.items, + submissions: snapshot.submissions, + cards +}) + +const kept = (items: ReturnType['items']) => + items.map(({ itemId, body }) => ({ itemId, body })) + +/** The chat as `opener`'s build opens it, over a copy so the original stays as the release left it. */ +async function openedBy(opener: TrackedJournalOpener, agent: Agent, stateDirectory: string) { + return opener + .open({ identity: identityOf(agent), stateDirectory }) + .then(view) + .finally(() => opener.closeAll()) +} + +/** Opens the chat, edits, sends and rewinds it, then reopens it; checks what the user sees. */ +async function carryOn( + opener: TrackedJournalOpener, + agent: Agent, + stateDirectory: string, + written: Written, + prefix?: JournalStoredRow[] +) { + const options = { + identity: identityOf(agent), + stateDirectory, + now: written.now, + mintEpoch: () => 'epoch-rewound' + } + const carried = await opener + .open(options) + .then(async (journal) => { + const opened = view(journal) + await editReleasedCard(journal) + if (prefix) { + // The release's rows stay byte for byte; one marker follows them, where records begin. + const database = openTestJournalHostDatabase(stateDirectory) + const rows = liveTestJournalRows(database.db, options.identity.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + expect(rows).toHaveLength(prefix.length + 1) + expect( + journalOutcomeSource(database.db, options.identity.sessionId, journal.epoch)?.prefix + ).toBe(prefix.length) + } + await sendAfterUpgrade(journal) + const sent = view(journal) + expect(sent.snapshot.submissions).toContainEqual( + expect.objectContaining({ clientMessageId: 'after-upgrade', dispatchState: 'accepted' }) + ) + await rewindReleasedChat(journal, new Set(opened.snapshot.items.map((item) => item.itemId))) + expect(journal.epoch).toBe('epoch-rewound') + const seen = view(journal) + // The rewind keeps every message the release wrote and every card not taken back, the edit + // included. + expect(kept(seen.snapshot.items)).toEqual(kept(opened.snapshot.items)) + expect(seen.cards.map((card) => card.messageId)).toEqual( + opened.cards.filter((card) => card.state !== 'withdrawn').map((card) => card.messageId) + ) + expect(seen.cards).toHaveLength(1) + for (const result of [sent, seen]) { + expect(result.cards.find((card) => card.messageId === 'card-2')?.body.blocks).toEqual([ + { type: 'text', text: 'second, edited after the upgrade' } + ]) + } + return { opened, seen } + }) + .finally(() => opener.closeAll()) + const reopened = await opener + .open(options) + .then(view) + .finally(() => opener.closeAll()) + expect(reopened).toEqual(carried.seen) + return carried +} + +describe('a chat a shipped release wrote, carried on by this build', () => { + it.each([ + ['the newest release', 'claude'], + ['the newest release', 'codex'], + ['the release before it', 'claude'], + ['the release before it', 'codex'], + ['the oldest release with this chat database', 'claude'], + ['the oldest release with this chat database', 'codex'] + ] as const)( + 'admits every row %s wrote for a %s chat, opens it as the newest release does, then edits, sends and rewinds it', + async (build, agent) => { + const directory = mkdtempSync(join(tmpdir(), 'orca-released-chat-upgrade-')) + const shipped = mkdtempSync(join(tmpdir(), 'orca-released-chat-shipped-')) + const identity = identityOf(agent) + try { + const written = await writeReleasedChat(RELEASES[build](), agent, directory) + // Anti-vacuous: the release's stream (beyond the two sends and the Stop turn), sends and + // queue all reached the chat. + expect(written.snapshot.items.length).toBeGreaterThan(3) + expect(written.snapshot.submissions.map((entry) => entry.clientMessageId)).toEqual( + expect.arrayContaining(['sent', 'refused']) + ) + expect(written.cards).toHaveLength(2) + + const database = openTestJournalHostDatabase(directory) + const rows = liveTestJournalRows(database.db, identity.sessionId) + expect(rows.filter((row) => !parseJournalRow(row.rowJson).ok)).toEqual([]) + // Anti-vacuous: the release wrote every row kind a chat holds (cards in their own table + // before they moved into the rows). + const kinds = new Set(rows.map((row) => JSON.parse(row.rowJson).kind)) + expect([...kinds].filter((kind) => kind !== 'queue').sort()).toEqual( + ['dispatch', 'epoch', 'item', 'lifecycle-batch', 'submission', 'tombstone'].sort() + ) + expect(kinds.has('queue')).toBe(build !== 'the oldest release with this chat database') + expect(restoreJournal(database.db, identity.sessionId)).toMatchObject({ + newer: null, + damage: null + }) + await closeTestJournalHostDatabase(directory) + cpSync(directory, shipped, { recursive: true }) + + const ours = await carryOn(createTrackedJournalOpener(), agent, directory, written, rows) + if (build !== 'the oldest release with this chat database') { + // A release in the window wrote the shapes this build reads, so it opens as written, + // and the edit records the card the old rows hold in its place among them. + expect(releaseWritten(ours.opened)).toMatchObject(releaseWritten(written)) + const edits = openTestJournalHostDatabase(directory) + .db.prepare(`SELECT ordinal FROM journal_outcomes + WHERE field = 'queue.cards' AND entry_key = '"card-2"'`) + .all() + expect(edits).toContainEqual({ ordinal: JOURNAL_PREFIX_ORDINAL }) + await closeTestJournalHostDatabase(directory) + } + // This build opens the chat as the newest release does. + const newest = await releasedJournalOpener(RELEASES['the newest release']()) + expect(releaseWritten(ours.opened)).toMatchObject( + releaseWritten(await openedBy(newest, agent, shipped)) + ) + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(shipped, { recursive: true, force: true }) + } + }, + SUITE_TIMEOUT_MS + ) +}) diff --git a/tests/e2e/cross-version-wire/released-chat-writers.ts b/tests/e2e/cross-version-wire/released-chat-writers.ts new file mode 100644 index 000000000000..fff6bff1afa4 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-writers.ts @@ -0,0 +1,301 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { expect, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem, + type AgentJournalSnapshot, + type AgentSessionJournalIdentity +} from '../../../src/shared/agent-session-journal-types' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../src/shared/agent-session-provider-handle-encoding' +import type { agentSessionFailureFact } from '../../../src/shared/agent-session-failure' +import type { agentSessionFailureWords } from '../../../src/shared/agent-session-failure-words' +import type { createClaudeJournalTranslator } from '../../../src/main/claude/claude-structured-journal-translation' +import type { createCodexJournalTranslator } from '../../../src/main/codex/codex-structured-journal-translation' +import type { createDeferredStructuredAgentSessionEventSink } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport +} from './release-checkout' +import { queueReleasedCards } from './released-chat-queue' + +// A released build's own writers, for a chat as its host writes one: its translators fed its own +// captured provider streams, sends with their dispatch results, queue edits, Stop and Resume, a +// Stop settlement and a removed item. + +const JOURNAL = 'src/main/native-chat/agent-session-journal' +const FENCE = 1 + +export type Agent = 'claude' | 'codex' +type Opener = ReturnType +type Journal = Awaited> +type Released = Awaited> + +export const identityOf = (agent: Agent): AgentSessionJournalIdentity => ({ + sessionId: `session-released-${agent}`, + workspaceId: 'ws-1', + hostId: 'host-1', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) +}) + +async function released(ref: string) { + const checkout = await materializeReleaseCheckout(ref) + const load = async (path: string, name: string): Promise => + releaseModuleExport(await importReleaseCheckoutModule(checkout, path), name) + const fact = await load( + 'src/shared/agent-session-failure.ts', + 'agentSessionFailureFact' + ) + const words = await load( + 'src/shared/agent-session-failure-words.ts', + 'agentSessionFailureWords' + ) + return { + root: checkout.root, + opener: await load( + `${JOURNAL}/journal-host-database-test-support.ts`, + 'createTrackedJournalOpener' + ), + claude: await load( + 'src/main/claude/claude-structured-journal-translation.ts', + 'createClaudeJournalTranslator' + ), + codex: await load( + 'src/main/codex/codex-structured-journal-translation.ts', + 'createCodexJournalTranslator' + ), + sink: await load( + 'src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts', + 'createDeferredStructuredAgentSessionEventSink' + ), + queueFull: () => words(fact('queueFull'), { surface: 'rejection' }), + /** Releases before Stop events record only the interrupted turn. */ + stopEvents: existsSync(join(checkout.root, JOURNAL, 'journal-stop-marks.ts')) + } +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** Sends, their dispatch results and queue edits, as the host's send and queue paths write them. */ +async function sendsAndQueue(journal: Journal, release: Released): Promise { + await journal.appendSubmission({ + clientMessageId: 'sent', + payloadFingerprint: 'fp-sent', + body: message('sent'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' }, + options: { model: 'model-1', effort: 'high' } + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) + await journal.appendSubmission({ + clientMessageId: 'refused', + payloadFingerprint: 'fp-refused', + body: message('refused'), + fence: FENCE + }) + await journal.resolveDispatch({ + clientMessageId: 'refused', + fence: FENCE, + state: 'rejected', + ...release.queueFull() + }) + await queueReleasedCards(journal.queuedMessages) +} + +const claudeCapture = z.object({ at: z.number(), frame: z.record(z.string(), z.unknown()) }) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) + +function capture(release: Released, path: string): unknown[] { + return readFileSync(join(release.root, path), 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +/** The release's translator, fed its own captured provider stream, writes through its event sink. */ +async function stream( + release: Released, + agent: Agent, + journal: Journal, + clock: { at: number } +): Promise { + const sessionId = identityOf(agent).sessionId + const failed = vi.fn() + const sink = release.sink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + sink.bind({ journal, fence: FENCE, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = [...pending] + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + try { + if (agent === 'claude') { + const translator = release.claude({ sink: sink.sink, schedule }) + for (const line of capture( + release, + 'src/main/claude/__fixtures__/claude-adapter-capture-miss.jsonl' + )) { + const record = claudeCapture.safeParse(line) + if (record.success) { + clock.at = 1_000 + record.data.at + translator.handle({ + type: 'message', + sessionId, + message: record.data.frame, + observedAt: clock.at + }) + await flush(translator) + } + } + translator.dispose() + } else { + const translator = release.codex({ sink: sink.sink, schedule, now: () => clock.at }) + const records = capture( + release, + 'src/main/codex/__fixtures__/codex-app-server-turn-endings.jsonl' + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(records.length).toBeGreaterThan(0) + for (const record of records) { + clock.at = 1_000 + record.t + const threadId = + typeof record.params.threadId === 'string' ? record.params.threadId : 'thread-1' + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: clock.at + }) + await flush(translator) + } + translator.dispose() + } + expect(failed).not.toHaveBeenCalled() + } finally { + sink.close() + } +} + +/** A Stop with its settlement, a Resume, and an item later removed. */ +async function stopAndRemove( + journal: Journal, + release: Released, + clock: { at: number } +): Promise { + const stopped = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(stopped, { kind: 'turn', turnId: 'stop-turn', state: 'running' }, scope) + if (release.stopEvents) { + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, FENCE) + } + const settle = release.stopEvents ? journal.stopMarks.beginSettle(true) : undefined + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: FENCE, + mutations: [ + { + kind: 'item', + identity: stopped, + body: { + kind: 'turn', + turnId: 'stop-turn', + state: 'interrupted', + completedAt: clock.at + 1 + }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + if (settle !== undefined) { + journal.stopMarks.settled(settle) + await journal.appendQueueResume(FENCE) + } + const removed = { provider: 'orca', clientMessageId: 'removed-note' } as const + await journal.appendItem(removed, { kind: 'status', text: 'removed' }, scope) + await journal.appendTombstone(removed, { fence: FENCE }) +} + +/** Writes a whole chat with the release at `ref`; returns the chat and queue as it closed them. */ +export async function writeReleasedChat( + ref: string, + agent: Agent, + stateDirectory: string +): Promise<{ snapshot: AgentJournalSnapshot; cards: unknown[]; now: () => number }> { + const release = await released(ref) + const clock = { at: 1_000 } + const journals = release.opener() + try { + const journal = await journals.open({ + identity: identityOf(agent), + stateDirectory, + now: () => clock.at + }) + if (agent === 'codex') { + // An imported conversation's epoch carries its history origin. + await journal.replaceEpochItems('legacy_import', FENCE, []) + } + await sendsAndQueue(journal, release) + await stream(release, agent, journal, clock) + await stopAndRemove(journal, release, clock) + return { + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()], + now: () => clock.at + } + } finally { + await journals.closeAll() + } +} + +/** The release's own journal opener, to carry a chat on as that release would. */ +export async function releasedJournalOpener(ref: string): Promise { + return (await released(ref)).opener() +} diff --git a/tests/e2e/journal-restored-consumers.unit.test.ts b/tests/e2e/journal-restored-consumers.unit.test.ts new file mode 100644 index 000000000000..6bdaf23f9694 --- /dev/null +++ b/tests/e2e/journal-restored-consumers.unit.test.ts @@ -0,0 +1,482 @@ +// @vitest-environment happy-dom + +import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture' +import '@testing-library/jest-dom/vitest' +import { createElement } from 'react' +import { cleanup, screen } from '@testing-library/react' +import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + type AgentJournalCursor, + type AgentJournalMessageItem +} from '../../src/shared/agent-session-journal-types' +import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../src/shared/agent-session-current-requests-capability' +import { + AGENT_SESSION_HISTORY_MAX_LIMIT, + type AgentSessionHistoryRequest, + type AgentSessionHistoryResult, + type AgentSessionSubscribeEvent +} from '../../src/shared/agent-session-wire' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../src/shared/mobile-bridge-frame-bytes' +import { + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY +} from '../../src/shared/protocol-version' +import type { RuntimeRpcResponse } from '../../src/shared/runtime-rpc-envelope' +import { withNativeChatCutTurnNotices } from '../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' +import { nativeChatRowsInDrawOrder } from '../../src/shared/native-chat/transcript/native-chat-turn-grouping' +import { nativeChatTurnMembership } from '../../src/shared/native-chat-turn-membership' +import { projectStructuredAgentSessionMessages } from '../../src/shared/structured-agent-session-message-projection' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + oldestStructuredAgentSessionCursor, + reduceStructuredAgentSession, + type StructuredAgentSessionState +} from '../../src/shared/structured-agent-session-reducer' +import { selectStructuredAgentSettledTurns } from '../../src/shared/structured-agent-session-turn-timing' +import { openTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../src/main/native-chat/agent-session-journal/journal-open' +import { journalOutcomeSource } from '../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { prepareJournalOutcomeWrite } from '../../src/main/native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../../src/main/native-chat/agent-session-journal/journal-row-schema' +import { hostTestAttachParams } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { seedQueuedRigLegacyJournal } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture' +import { + createRestTestRig, + REST_TEST_CALLER, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../src/main/native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { setStructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' +import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../src/main/runtime/rpc/methods/structured-agent-session' +import { + STRUCTURED_CLIENT, + STRUCTURED_MOBILE_CLIENT +} from '../../src/main/runtime/rpc/methods/structured-agent-session-rpc-client.test-fixture' +import { MAX_TIMER_DELAY_MS } from '../../src/shared/timer-delay' +import { + buildMobileNativeChatTransientData, + foldMobileNativeChatMessages +} from '../../mobile/src/session/mobile-native-chat-render-data' +import { NativeChatMessageList } from '../../src/renderer/src/components/native-chat/NativeChatMessageList' +import { render } from '../../src/renderer/src/components/native-chat/native-chat-tooltip-test-harness' +import { installNativeChatMessageListTestViewport } from '../../src/renderer/src/components/native-chat/native-chat-message-list-test-viewport' + +vi.mock('../../src/renderer/src/components/native-chat/NativeChatInlineVisual', () => ({ + NativeChatInlineVisual: () => { + throw new Error('Unexpected inline visual') + } +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ + openAgentMessageSender: () => { + throw new Error('Unexpected sender navigation') + } +})) + +const PROMPT = 'Keep the original question after restart' +const STALE = 'Saved answer before revision' +const ANSWER = 'Completed answer after restore' +const REMOVED = 'Disposable status before restart' +const OLDER = 'The earlier question' +const OLDER_ANSWER = 'The earlier completed answer' +const PUBLISHED = 'Published after restore' +const currentDesktop = { + ...STRUCTURED_CLIENT, + clientCapabilities: [ + ...STRUCTURED_CLIENT.clientCapabilities, + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY + ] +} +const clients = [ + ['bounded phone', STRUCTURED_MOBILE_CLIENT, true, true], + ['current paired desktop', currentDesktop, false, true], + ['legacy paired desktop', STRUCTURED_CLIENT, false, false] +] as const +// A new chat holds only records; an existing (mixed) chat holds old input rows up to the restart +// and records after its marker, so catch-up from a cursor inside the old rows crosses into records. +const cases = (['new', 'mixed'] as const).flatMap((kind) => + clients.map( + ([name, client, bounded, snapshotCatchUp]) => + [kind, name, client, bounded, snapshotCatchUp] as const + ) +) +const message = ( + text: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +let rig: RestTestRig | undefined +let controllers: AbortController[] = [] +let restoreViewport = () => {} +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) +afterAll(() => restoreViewport()) +afterEach(async () => { + cleanup() + for (const controller of controllers) { + controller.abort() + } + controllers = [] + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + vi.restoreAllMocks() +}) + +function desktop(state: StructuredAgentSessionState): void { + render( + createElement(NativeChatMessageList, { + session: { + messages: projectStructuredAgentSessionMessages(state.items, [], state.submissions), + status: 'ready', + sessionId: SESSION, + agent: 'codex', + hasMore: state.hasOlder, + loadingEarlier: false, + olderHistoryGeneration: 1, + loadEarlier: vi.fn(), + readPhase: 'ready' + }, + journalItems: state.items, + journalSubmissions: state.submissions, + settledTurns: selectStructuredAgentSettledTurns(state.items, state.submissions), + isWorking: false, + workingStartedAt: null, + expandSignal: false + }) + ) + const ordered = [OLDER, OLDER_ANSWER, PROMPT, ANSWER, PUBLISHED].map((text) => { + expect(screen.getAllByText(text)).toHaveLength(1) + return screen.getByText(text) + }) + expect(screen.queryByText(STALE)).toBeNull() + expect(screen.queryByText(REMOVED)).toBeNull() + let previous: HTMLElement | undefined + for (const row of ordered) { + if (previous) { + expect(previous.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) + } + previous = row + } + cleanup() +} + +function phone(state: StructuredAgentSessionState): void { + const items = withNativeChatCutTurnNotices(state.items, { agentName: 'Codex' }) + const messages = projectStructuredAgentSessionMessages(items, [], state.submissions) + const folded = foldMobileNativeChatMessages(messages, 'codex') + const { data } = buildMobileNativeChatTransientData({ folded, streaming: null, pending: [] }) + const membership = nativeChatTurnMembership(data, { items, submissions: state.submissions }) + const rows = nativeChatRowsInDrawOrder(data, membership.drawOrder) + const displayed = rows.flatMap((row) => + row.blocks.flatMap((block) => + block.type === 'text' ? [{ role: row.role, text: block.text }] : [] + ) + ) + const expected = [ + { role: 'user', text: OLDER }, + { role: 'assistant', text: OLDER_ANSWER }, + { role: 'user', text: PROMPT }, + { role: 'assistant', text: ANSWER }, + { role: 'assistant', text: PUBLISHED } + ] + expect(displayed.filter((row) => expected.some((target) => target.text === row.text))).toEqual( + expected + ) + expect(displayed.some((row) => row.text === STALE || row.text === REMOVED)).toBe(false) +} + +it.each(cases)( + 'draws a restored %s chat, prefix and tail, through %s history and subscriber delivery', + async (kind, _name, client, bounded, snapshotCatchUp) => { + const active = await createRestTestRig({ idleSweep: { intervalMs: MAX_TIMER_DELAY_MS } }) + rig = active + setStructuredAgentSessionHost(active.host) + const pinInputs = kind === 'mixed' ? seedQueuedRigLegacyJournal(active.root, SESSION) : null + const attached = await active.host.attach(REST_TEST_CALLER, hostTestAttachParams(null)) + if (!attached.ok) { + throw new Error('Fixture attach refused') + } + pinInputs?.(active.host) + const journal = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!journal) { + throw new Error('Fixture journal absent') + } + const options = { fence: attached.fence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const dispatcher = new RpcDispatcher({ + runtime: new OrcaRuntimeService(), + methods: STRUCTURED_AGENT_SESSION_METHODS + }) + let requestId = 0 + async function history(request: Omit) { + const frame: RuntimeRpcResponse = JSON.parse( + JSON.stringify( + await dispatcher.dispatch( + { + id: `history-${++requestId}`, + authToken: 'token', + method: 'agentSession.history', + params: { sessionId: SESSION, ...request } + }, + client + ) + ) + ) + if (!frame.ok) { + throw new Error(`History RPC failed: ${frame.error.code}`) + } + if (!frame.result.ok) { + throw new Error(`History reset: ${frame.result.reset}`) + } + return frame.result.page + } + const append = journal.appendItem.bind(journal) + async function completedTurn(id: string, prompt: string, answer: string) { + const user = await append( + { provider: 'orca', clientMessageId: `${id}-user` }, + message(prompt, 'user'), + options + ) + const turn = await append( + { provider: 'orca', clientMessageId: `${id}-turn` }, + { + kind: 'turn', + turnId: id, + userItemId: user.itemId, + state: 'completed', + outcome: 'success', + startedAt: active.clock.now - 2_000, + completedAt: active.clock.now - 1_000 + }, + options + ) + const turnScope = { kind: 'turn', turnItemId: turn.itemId } as const + const response = await append( + { provider: 'orca', clientMessageId: `${id}-answer` }, + message(answer), + { ...options, turnScope } + ) + return { response, turnScope } + } + await completedTurn('older', OLDER, OLDER_ANSWER) + for (let index = 0; index < AGENT_SESSION_HISTORY_MAX_LIMIT; index += 1) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `context-${index}` }, + message(`Context ${index}`), + options + ) + } + // The mixed reader resumes from here, inside the old rows. + const crossing = kind === 'mixed' ? await history({ direction: 'tail' }) : null + const { response, turnScope } = await completedTurn('current', PROMPT, STALE) + const disposable = await journal.appendItem( + { provider: 'orca', clientMessageId: 'disposable' }, + { kind: 'status', text: REMOVED }, + options + ) + const prefixPage = await history({ direction: 'tail' }) + expect(prefixPage.hasOlder).toBe(true) + expect(JSON.stringify(prefixPage.items)).toContain(STALE) + expect(JSON.stringify(prefixPage.items)).toContain(REMOVED) + expect(JSON.stringify(prefixPage.items)).not.toContain(OLDER) + const resumeFrom = crossing ?? prefixPage + const resumeCursor = resumeFrom.liveCursor + if (!resumeCursor) { + throw new Error('Missing pre-close history cursor') + } + await active.host.close(SESSION, 'evict') + expect(active.host.hasSession(SESSION)).toBe(false) + const database = openTestJournalHostDatabase(active.root) + const saved = restoreJournal(database.db, SESSION)?.state + if (!saved) { + throw new Error('Missing usable projection before tail append') + } + const prefix = { epoch: saved.epoch, sequence: saved.lastSequence } + expect(prefix.sequence).toBeGreaterThanOrEqual(resumeCursor.sequence) + database.transaction( + (db) => { + const rows: JournalRow[] = [] + for (let offset = 1; offset <= AGENT_SESSION_HISTORY_MAX_LIMIT; offset += 1) { + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + offset, + fence: attached.fence, + ts: active.clock.now + offset, + kind: 'item', + itemId: response.itemId, + revision: response.revision + offset, + body: message( + offset === AGENT_SESSION_HISTORY_MAX_LIMIT ? ANSWER : `Answer revision ${offset}` + ), + turnScope + }) + } + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + fence: attached.fence, + ts: active.clock.now + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + kind: 'tombstone', + itemId: disposable.itemId, + revision: disposable.revision + 1 + }) + return prepareJournalOutcomeWrite(db, saved, rows, active.clock.now) + }, + false, + (result) => { + result.adopt() + } + ) + // Anti-vacuous: the mixed chat's rows end at the restart and its records follow the marker. + expect(journalOutcomeSource(database.db, SESSION, prefix.epoch)?.prefix).toBe( + kind === 'mixed' ? prefix.sequence : 0 + ) + const restoredPage = await history({ direction: 'tail' }) + expect(restoredPage.liveCursor?.sequence).toBeGreaterThan(prefix.sequence) + expect(active.adapter.acquire).toHaveBeenCalledTimes(1) + const subscribe = vi.spyOn(active.host, 'subscribe') + async function stream(cursor?: AgentJournalCursor) { + const events: AgentSessionSubscribeEvent[] = [] + const rawFrames: string[] = [] + const controller = new AbortController() + controllers.push(controller) + await dispatcher.dispatchStreaming( + { + id: `stream-${++requestId}`, + authToken: 'token', + method: 'agentSession.subscribe', + params: { sessionId: SESSION, ...(cursor ? { cursor } : {}) } + }, + (raw) => { + const frame: RuntimeRpcResponse = JSON.parse(raw) + if (!frame.ok) { + throw new Error(`Subscription RPC failed: ${frame.error.code}`) + } + rawFrames.push(raw) + events.push(frame.result) + }, + { + ...client, + clientId: 'client-1', + connectionId: 'restored-reader', + signal: controller.signal + } + ) + expect(subscribe).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotCatchUp })) + expect(subscribe.mock.calls.at(-1)?.[0].boundedFrames === true).toBe(bounded) + return { events, rawFrames } + } + const hydrated = await stream() + expect(hydrated.events[0]?.type).toBe('snapshot') + const resumed = await stream(resumeCursor) + if (snapshotCatchUp) { + expect(resumed.events.some((event) => event.type === 'snapshot')).toBe(true) + } else if (kind === 'mixed') { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + // Old rows after the cursor, then records after the marker. + const batches = resumed.events.flatMap((event) => + event.type === 'batch' ? [event.batch] : [] + ) + expect(batches.some((batch) => JSON.stringify(batch.items).includes(PROMPT))).toBe(true) + expect(batches.some((batch) => batch.removedItemIds.includes(disposable.itemId))).toBe(true) + } else { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + expect( + resumed.events.filter( + (event) => + event.type === 'batch' && + (event.batch.items.length > 0 || event.batch.removedItemIds.length > 0) + ) + ).toHaveLength(2) + expect(resumed.events.some((event) => event.type === 'batch' && event.hasNewer)).toBe(true) + expect( + resumed.events.some( + (event) => + event.type === 'batch' && event.batch.removedItemIds.includes(disposable.itemId) + ) + ).toBe(true) + } + const restored = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!restored) { + throw new Error('History failed to reopen journal') + } + const priorHydrated = hydrated.events.length + const priorResumed = resumed.events.length + const published = await restored.appendItem( + { provider: 'orca', clientMessageId: 'published' }, + message(PUBLISHED), + options + ) + await vi.waitFor(() => { + for (const [reader, from] of [ + [hydrated, priorHydrated], + [resumed, priorResumed] + ] as const) { + expect( + reader.events + .slice(from) + .some( + (event) => + event.type === 'batch' && + event.batch.items.some((item) => item.itemId === published.itemId) + ) + ).toBe(true) + } + }) + for (const [reader, initial] of [ + [hydrated, EMPTY_STRUCTURED_AGENT_SESSION], + [ + resumed, + reduceStructuredAgentSession( + EMPTY_STRUCTURED_AGENT_SESSION, + { type: 'history-page', page: resumeFrom }, + 1_000 + ) + ] + ] as const) { + let state = reader.events.reduce( + (state, event) => reduceStructuredAgentSession(state, { type: 'event', event }, 1_000), + initial + ) + expect(state.status).toBe('ready') + expect(state.hasOlder).toBe(true) + expect(JSON.stringify(state.items)).not.toContain(OLDER) + expect(JSON.stringify(state.items)).not.toContain(OLDER_ANSWER) + const cursor = oldestStructuredAgentSessionCursor(state) + if (!cursor) { + throw new Error('Missing older-history cursor') + } + const before = await history({ + direction: 'before', + cursor, + limit: AGENT_SESSION_HISTORY_MAX_LIMIT + }) + expect(JSON.stringify(before.items)).toContain(OLDER) + expect(JSON.stringify(before.items)).toContain(OLDER_ANSWER) + state = reduceStructuredAgentSession( + state, + { type: 'older-page', requestedCursor: cursor, page: before }, + 1_000 + ) + if (bounded) { + for (const frame of reader.rawFrames) { + expect(Buffer.byteLength(frame)).toBeLessThanOrEqual(MOBILE_BRIDGE_MAX_FRAME_BYTES) + } + phone(state) + } else { + desktop(state) + } + } + } +)