Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
Keep chats stopped by a delivered kill readable after downgrading (#36142)
Brennan Benson70209b9b1197
diff --git a/src/main/wsl/wsl-drive-unc-conversion-startup.test.ts b/src/main/wsl/wsl-drive-unc-conversion-startup.test.tsindex 4aa9d8ea601..51ec1a0f534 100644--- a/src/main/wsl/wsl-drive-unc-conversion-startup.test.ts+++ b/src/main/wsl/wsl-drive-unc-conversion-startup.test.ts@@ -3,6 +3,11 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { getDefaultPersistedState } from '../../shared/constants'+import {+ agentSessionLeaseFixture,+ agentSessionRecordFixture+} from '../../shared/agent-session-record.test-fixture'+import { encodeAgentSessionRecord } from '../../shared/agent-session-record-stored-form'import type { PersistedState } from '../../shared/persisted-state-types'import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../shared/wsl-host-internal-gate'import { getHistorySessionDirName } from '../daemon/history-paths'@@ -11,6 +16,8 @@ import { getOrcaProfileStateDatabaseFile } from '../orca-profiles/profile-storagimport { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database'import { importProfileStateJson } from '../persistence/profile-state/profile-state-documents'import Database from '../sqlite/sync-database'+import { loadAgentSessionStoreRows } from '../runtime/agent-session-record-rows'+import { getAgentSessionConversation } from '../runtime/agent-session-store-state'import { hashWorktreeId } from '../terminal-history-id'import type * as Journal from './wsl-drive-unc-conversion-journal'import {@@ -155,6 +162,27 @@ function run(stores = realStores()) {})}+function stoppedChat(workspaceId = OLD_ID) {+ const record = agentSessionRecordFixture(+ agentSessionLeaseFixture({+ sessionId: 'chat-alpha-1',+ runtimeFence: 8,+ claimStatus: 'released',+ ownerProcess: null,+ reservedSpawnToken: null,+ deathEvidence: {+ kind: 'kill-delivered',+ detail: 'killed',+ observedAt: 40_000,+ ownerFence: 7,+ lastProvenAliveAt: 30_000,+ runtimeEnd: 'quit'+ }+ })+ )+ return { ...record, location: { ...record.location, workspaceId, wslDistro: 'Ubuntu' } }+}+function seedOutside(): void {const session = join(root, 'terminal-history', getHistorySessionDirName(OLD_SESSION))mkdirSync(session, { recursive: true })@@ -165,11 +193,15 @@ function seedOutside(): void {writeFileSync(join(shell, '.bash_history'), 'make test\n')const db = new Database(join(root, 'agent-session-journal.db'))db.exec(`CREATE TABLE journal_sessions (session_id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, epoch TEXT NOT NULL);-CREATE TABLE agent_session_records (session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL);`)- db.prepare('INSERT INTO journal_sessions VALUES (?, ?, ?)').run('chat-1', OLD_ID, 'e1')+CREATE TABLE agent_session_records (session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL);+CREATE TABLE agent_session_operations (operation_key TEXT PRIMARY KEY, row_json TEXT);+CREATE TABLE agent_session_retired_claim_keys (key_id TEXT PRIMARY KEY, retired_at INTEGER);+CREATE TABLE agent_session_tabs (tab_id TEXT PRIMARY KEY, session_id TEXT, position INTEGER);+CREATE TABLE agent_session_store_meta (key TEXT PRIMARY KEY, value TEXT);`)+ db.prepare('INSERT INTO journal_sessions VALUES (?, ?, ?)').run('chat-alpha-1', OLD_ID, 'e1')db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run(- 'chat-1',- JSON.stringify({ id: 'chat-1', location: { workspaceId: OLD_ID, wslDistro: 'Ubuntu' } })+ 'chat-alpha-1',+ JSON.stringify(encodeAgentSessionRecord(stoppedChat())))db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('chat-2', '{not json')db.close()@@ -240,14 +272,28 @@ describe('runWslDriveUncConversionsAtStartup', () => {})expect(chatRows()).toEqual([{ workspace_id: NEW_ID },+ { record_json: '{not json' },{- record_json: JSON.stringify({- id: 'chat-1',- location: { workspaceId: NEW_ID, wslDistro: 'Ubuntu' }- })- },- { record_json: '{not json' }+ record_json: JSON.stringify(encodeAgentSessionRecord(stoppedChat(NEW_ID)))+ }])+ const db = new Database(join(root, 'agent-session-journal.db'))+ try {+ const loaded = loadAgentSessionStoreRows(db)+ expect(loaded.records.get('chat-alpha-1')?.lease.deathEvidence).toEqual(+ stoppedChat().lease.deathEvidence+ )+ expect(getAgentSessionConversation(loaded, 'chat-alpha-1')).toMatchObject({+ location: { workspaceId: NEW_ID, wslDistro: 'Ubuntu' },+ currentFence: 8,+ ownerObservation: {+ claimStatus: 'released',+ deathEvidence: { kind: 'kill-delivered', ownerFence: 7 }+ }+ })+ } finally {+ db.close()+ }// The window's stores record themselves once it opens.expect(listWslDriveUncConversions(root)).toEqual([expect.objectContaining({diff --git a/src/shared/agent-session-record-stored-form.test.ts b/src/shared/agent-session-record-stored-form.test.tsindex 1372c8ae468..0f0c3c50acc 100644--- a/src/shared/agent-session-record-stored-form.test.ts+++ b/src/shared/agent-session-record-stored-form.test.ts@@ -447,3 +447,46 @@ it('preserves the saved turn and unknown JSON through a record transition', () =laterField: 'keep'})})++it('stores a delivered kill in the form older builds read and reads only that exact pair back', () => {+ const evidence = { detail: 'killed', observedAt: 40, ownerFence: 7 } as const+ const withEvidence = (deathEvidence: unknown) => ({+ ...encodeAgentSessionRecord(agentSessionRecordFixture()),+ lease: { ...agentSessionLeaseFixture({ claimStatus: 'released' }), deathEvidence }+ })+ const killed = agentSessionRecordFixture(+ agentSessionLeaseFixture({+ claimStatus: 'released',+ deathEvidence: { kind: 'kill-delivered', ...evidence }+ })+ )+ const stored = encodeAgentSessionRecord(killed)+ expect(stored.lease.deathEvidence).toEqual({ kind: 'pid-absent', delivery: 'kill', ...evidence })+ expect(isPersistedAgentSessionRecord(stored)).toBe(true)+ expect(decodePersistedAgentSessionRecord(stored).record).toEqual(killed)+ // Rows written before this encoding, a plain absent pid, and stale or foreign markers.+ for (const [saved, read] of [+ [+ { kind: 'kill-delivered', ...evidence },+ { kind: 'kill-delivered', ...evidence }+ ],+ [+ { kind: 'pid-absent', ...evidence },+ { kind: 'pid-absent', ...evidence }+ ],+ [+ { kind: 'pid-absent', delivery: 'signal', ...evidence },+ { kind: 'pid-absent', ...evidence }+ ],+ [+ { kind: 'exit-observed', delivery: 'kill', ...evidence },+ { kind: 'exit-observed', ...evidence }+ ]+ ]) {+ const row: unknown = withEvidence(saved)+ if (!isPersistedAgentSessionRecord(row)) {+ throw new Error('the stored evidence fixture must pass record validation')+ }+ expect(decodePersistedAgentSessionRecord(row).record.lease.deathEvidence).toEqual(read)+ }+})diff --git a/src/shared/agent-session-record-stored-form.ts b/src/shared/agent-session-record-stored-form.tsindex b2f8774e9af..c24154dbeeb 100644--- a/src/shared/agent-session-record-stored-form.ts+++ b/src/shared/agent-session-record-stored-form.ts@@ -11,7 +11,34 @@ import {encodePersistedAgentSessionProviderHandleChain} from './agent-session-provider-handle'import { isAgentSessionLastTurn } from './agent-session-last-turn'-import type { AgentSessionRecord } from './agent-session-record'+import type { AgentSessionDeathEvidence, AgentSessionRecord } from './agent-session-record'++// Older builds accept only exit-observed, pid-absent and identity-mismatch and set aside any other+// row, so a delivered kill is stored as the absent pid their restart probe would itself record.+const KILL_DELIVERY_MARKER = 'kill'++type PersistedDeathEvidence = AgentSessionDeathEvidence & { delivery?: unknown }++function encodeDeathEvidence(+ evidence: AgentSessionDeathEvidence | null+): PersistedDeathEvidence | null {+ return evidence?.kind === 'kill-delivered'+ ? { ...evidence, kind: 'pid-absent', delivery: KILL_DELIVERY_MARKER }+ : evidence+}++/** Only the exact stored pair means a delivered kill; any other marker is dropped unread. */+function decodeDeathEvidence(+ evidence: PersistedDeathEvidence | null+): AgentSessionDeathEvidence | null {+ if (!evidence || !Object.hasOwn(evidence, 'delivery')) {+ return evidence+ }+ const { delivery, ...rest } = evidence+ return delivery === KILL_DELIVERY_MARKER && rest.kind === 'pid-absent'+ ? { ...rest, kind: 'kill-delivered' }+ : rest+}/** Report decode changes needing writeback; handle encoding alone is unchanged across builds and needs none. */export function decodePersistedAgentSessionRecord<L extends PersistedAgentSessionObservationLease>(@@ -25,23 +52,25 @@ export function decodePersistedAgentSessionRecord<L extends PersistedAgentSessio}const { sleptAt, lastTurn, ...rest } = recordconst validSleep = typeof sleptAt === 'number' && Number.isFinite(sleptAt) && sleptAt > 0+ const lease = normalizeLegacyHandoffLease(record.lease)return {record: {...rest,...(validSleep ? { sleptAt } : {}),...(isAgentSessionLastTurn(lastTurn) ? { lastTurn } : {}),providerHandleChain,- lease: normalizeLegacyHandoffLease(record.lease)+ lease: { ...lease, deathEvidence: decodeDeathEvidence(lease.deathEvidence) }},normalized:leaseCarriesLegacyHandoffValues(record.lease) || (sleptAt !== undefined && !validSleep)}}-/** The record as a row stores it; Claude and Codex handles keep the typed form older builds read. */+/** The record as a row stores it; Claude and Codex handles and death evidence keep the forms older builds read. */export function encodeAgentSessionRecord(record: AgentSessionRecord): PersistedAgentSessionRecord {return {...record,+ lease: { ...record.lease, deathEvidence: encodeDeathEvidence(record.lease.deathEvidence) },providerHandleChain: encodePersistedAgentSessionProviderHandleChain(record.providerHandleChain)}}diff --git a/tests/e2e/cross-version-wire/agent-session-kill-delivered-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-kill-delivered-downgrade.unit.test.tsnew file mode 100644index 00000000000..19bfbacea6f--- /dev/null+++ b/tests/e2e/cross-version-wire/agent-session-kill-delivered-downgrade.unit.test.ts@@ -0,0 +1,269 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { expect, test } from 'vitest'+import { agentSessionConversationView } from '../../../src/shared/agent-session-conversation-view'+import {+ agentSessionLeaseOwnerVerdict,+ agentSessionLeasePossiblyWriting+} from '../../../src/shared/agent-session-lease-adjudication'+import { agentSessionRecordFixture } from '../../../src/shared/agent-session-record.test-fixture'+import { agentModelCatalogReleasedOwner } from '../../../src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot'+import {+ closeTestJournalHostDatabase,+ openTestJournalHostDatabase+} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support'+import { structuredAgentSessionLiveFence } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-current-work'+import { upgradeStoredStructuredAgentSessionOwnerExitEvidence } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-lease-release'+import { turnVerdictFromDeathEvidence } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict'+import { releaseStoredAgentSessionOwnerAfterSurfaceClose } from '../../../src/main/runtime/agent-session/ownership/agent-session-surface-release-transition'+import { loadAgentSessionStoreRows } from '../../../src/main/runtime/agent-session-record-rows'+import {+ openTestAgentSessionRecordStore,+ seedTestAgentSessionRecordStore+} from '../../../src/main/runtime/agent-session-record-store-test-harness'+import { importReleaseCheckoutModule, materializeReleaseCheckout } from './release-checkout'++// The last release before Stop recorded a delivered kill; it knows three death kinds.+const RELEASE_REF = 'v1.4.244'++type OldStoreMaps = {+ records: Map<unknown, unknown>+ unreadableRecords: Map<unknown, unknown>+}++function exported(module: Record<string, unknown>, name: string): (...args: unknown[]) => unknown {+ const value = module[name]+ if (typeof value !== 'function') {+ throw new Error(`${RELEASE_REF} exports no ${name}`)+ }+ return (...args) => value(...args)+}++function storeMaps(value: unknown): OldStoreMaps {+ if (+ typeof value !== 'object' ||+ value === null ||+ !('records' in value) ||+ !(value.records instanceof Map) ||+ !('unreadableRecords' in value) ||+ !(value.unreadableRecords instanceof Map)+ ) {+ throw new Error(`${RELEASE_REF} store must expose its readable and unreadable rows`)+ }+ return { records: value.records, unreadableRecords: value.unreadableRecords }+}++function oldRecord(value: unknown) {+ if (+ typeof value !== 'object' ||+ value === null ||+ !('lease' in value) ||+ typeof value.lease !== 'object' ||+ value.lease === null ||+ !('deathEvidence' in value.lease)+ ) {+ throw new Error('the old build must expose the chat and its lease')+ }+ return { ...value, lease: value.lease }+}++// Materializing the historical source checkout and importing its modules can exceed the default timeout.+test(`${RELEASE_REF} keeps a stopped chat readable through restart, resume and evidence replacement`, async () => {+ const directory = await mkdtemp(join(tmpdir(), 'orca-kill-downgrade-'))+ try {+ const live = agentSessionRecordFixture()+ const sessionId = live.sessionId+ await seedTestAgentSessionRecordStore(directory, { records: [live] })+ const current = await openTestAgentSessionRecordStore(directory)+ // Seed the host's already-attached owner; the Stop itself uses the real transition and commit.+ await current.transitionHandoff(sessionId, () => live)+ await releaseStoredAgentSessionOwnerAfterSurfaceClose(current, {+ sessionId,+ expectedFence: 7,+ now: 40_000,+ deathEvidenceKind: 'kill-delivered',+ exitReason: 'killed'+ })+ // Include optional proof facts in the same production serialization contract.+ await current.transitionHandoff(sessionId, (record) => ({+ ...record,+ lease: {+ ...record.lease,+ deathEvidence: record.lease.deathEvidence && {+ ...record.lease.deathEvidence,+ lastProvenAliveAt: 35_000,+ runtimeEnd: 'quit'+ }+ }+ }))+ const evidence = current.getRecord(sessionId)?.lease.deathEvidence+ expect(evidence).toEqual({+ kind: 'kill-delivered',+ detail: 'killed',+ observedAt: 40_000,+ ownerFence: 7,+ lastProvenAliveAt: 35_000,+ runtimeEnd: 'quit'+ })+ const db = openTestJournalHostDatabase(directory).db+ const saved = db+ .prepare('SELECT record_json FROM agent_session_records WHERE session_id = ?')+ .get(sessionId)+ if (typeof saved?.record_json !== 'string') {+ throw new Error('the current store must save the chat')+ }+ const raw = JSON.parse(saved.record_json)+ expect(raw.lease.deathEvidence).toEqual({ ...evidence, kind: 'pid-absent', delivery: 'kill' })++ const checkout = await materializeReleaseCheckout(RELEASE_REF)+ const [records, rows, drafts, restart, adjudication, transitions, views] = await Promise.all([+ importReleaseCheckoutModule(checkout, 'src/shared/agent-session-record.ts'),+ importReleaseCheckoutModule(checkout, 'src/main/runtime/agent-session-record-rows.ts'),+ importReleaseCheckoutModule(checkout, 'src/main/runtime/agent-session-store-draft.ts'),+ importReleaseCheckoutModule(+ checkout,+ 'src/main/runtime/agent-session/ownership/agent-session-restart-lease-transitions.ts'+ ),+ importReleaseCheckoutModule(checkout, 'src/shared/agent-session-lease-adjudication.ts'),+ importReleaseCheckoutModule(+ checkout,+ 'src/main/runtime/agent-session/ownership/agent-session-lease-transitions.ts'+ ),+ importReleaseCheckoutModule(checkout, 'src/main/runtime/agent-session-store-state.ts')+ ])+ expect(exported(records, 'isPersistedAgentSessionRecord')(raw)).toBe(true)+ const loaded = exported(rows, 'loadAgentSessionStoreRows')(db)+ expect(storeMaps(loaded).unreadableRecords.size).toBe(0)+ const old = oldRecord(storeMaps(loaded).records.get(sessionId))+ expect(+ exported(+ adjudication,+ 'adjudicateAgentSessionRestart'+ )({+ lease: old.lease,+ probe: { outcome: 'indeterminate', reason: 'no child after restart' },+ observedAt: 50_000+ })+ ).toMatchObject({ disposition: 'free' })+ const reconciled = oldRecord(+ exported(+ restart,+ 'applyAgentSessionRestartAdjudication'+ )({+ record: old,+ probe: { outcome: 'indeterminate', reason: 'no child after restart' },+ now: 50_000+ })+ )+ expect(reconciled.lease).toMatchObject({+ unreconciled: false,+ runtimeFence: 8,+ deathEvidence: raw.lease.deathEvidence+ })+ const writeOld = (record: unknown) => {+ const before = exported(rows, 'loadAgentSessionStoreRows')(db)+ const draft = exported(drafts, 'draftAgentSessionStoreState')(before)+ storeMaps(draft).records.set(sessionId, record)+ exported(rows, 'writeAgentSessionStoreRows')(+ db,+ exported(drafts, 'agentSessionStoreDraftRowWrites')(before, draft)+ )+ return draft+ }+ const oldState = writeOld(reconciled)+ expect(exported(views, 'listAgentSessionConversations')(oldState)).toMatchObject([+ { sessionId, currentFence: 8 }+ ])+ expect(exported(views, 'getAgentSessionConversation')(oldState, sessionId)).toMatchObject({+ sessionId,+ ownerObservation: { unreconciled: false, claimStatus: 'released' }+ })+ expect(exported(views, 'requireWritableAgentSessionRecord')(oldState, sessionId)).toEqual(+ reconciled+ )++ const upgraded = await openTestAgentSessionRecordStore(directory)+ const restored = upgraded.getRecord(sessionId)+ if (!restored) {+ throw new Error('the upgraded chat must remain readable')+ }+ expect(restored.lease.deathEvidence).toEqual(evidence)+ expect(restored.lease.runtimeFence).toBe(8)+ const conversation = agentSessionConversationView(restored)+ expect(agentSessionLeaseOwnerVerdict(restored.lease)).toBe('exited')+ expect(agentSessionLeasePossiblyWriting(restored.lease)).toBe(false)+ expect(structuredAgentSessionLiveFence({ record: conversation })).toBeNull()+ expect(agentModelCatalogReleasedOwner(conversation)).toBe(true)+ expect(turnVerdictFromDeathEvidence(restored.lease.deathEvidence, 7)).toEqual({+ state: 'interrupted',+ completedAt: 35_000+ })+ await upgradeStoredStructuredAgentSessionOwnerExitEvidence(+ upgraded,+ {+ type: 'ended',+ sessionId,+ fence: 7,+ acquisitionGeneration: 'stopped-writer',+ cause: 'requested-close',+ reason: 'late exit',+ observedAt: 60_000+ },+ 61_000+ )+ expect(loadAgentSessionStoreRows(db).records.get(sessionId)?.lease).toMatchObject({+ runtimeFence: 8,+ deathEvidence: { ...evidence, kind: 'exit-observed', observedAt: 60_000 }+ })++ // Starting again in the old build ends the previous proof, including its marker.+ const reservation = exported(+ transitions,+ 'reserveAgentSessionOwner'+ )({+ record: reconciled,+ expectedFence: 8,+ probe: { outcome: 'pid-absent' },+ reservation: {+ spawnToken: 'next-owner',+ claimKeyId: 'key-1',+ handoffOperationId: null,+ leaseTtlMs: 30_000,+ now: 70_000+ }+ })+ if (typeof reservation !== 'object' || reservation === null || !('record' in reservation)) {+ throw new Error('the old build must reserve a successor')+ }+ const reserved = oldRecord(reservation.record)+ writeOld(reserved)+ expect(loadAgentSessionStoreRows(db).records.get(sessionId)?.lease).toMatchObject({+ runtimeFence: 9,+ claimStatus: 'reserved',+ deathEvidence: null+ })+ const replaced = oldRecord(+ exported(+ restart,+ 'applyAgentSessionRestartAdjudication'+ )({+ record: reserved,+ probe: { outcome: 'reservation-unused' },+ now: 80_000+ })+ )+ writeOld(replaced)+ const replacement = loadAgentSessionStoreRows(db).records.get(sessionId)?.lease.deathEvidence+ expect(replacement).toEqual({+ kind: 'pid-absent',+ detail: 'reservation never spawned',+ observedAt: 80_000,+ ownerFence: 9+ })+ expect(replaced.lease.deathEvidence).not.toHaveProperty('delivery')+ } finally {+ closeTestJournalHostDatabase(directory)+ await rm(directory, { recursive: true, force: true })+ }+}, 300_000)