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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/main/ai-vault/cached-session-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ export function configureAiVaultSessionSources(next: AiVaultSessionSources): voi
sources = next
}

/** The extra Codex homes session discovery scans. Anything that decides what a listed row may be
* resumed from must read the same set, or a row can be listed and then refuse to resume. */
export function configuredAdditionalCodexHomePaths(): readonly string[] {
return sources.getAdditionalCodexHomePaths?.() ?? []
}

export async function listAiVaultSessions(
args?: AiVaultListArgs,
options: { signal?: AbortSignal } = {}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// Adopting a history row imports its transcript into the new session's journal.
//
// The import runs AFTER the provider is acquired, because for a create there is no earlier moment
// — the journal does not exist until the child does. That ordering is what makes the failure cases
// here load-bearing: by then the provider has already resumed and holds the conversation in
// context, so an attach that succeeds with an empty journal would show the user a blank chat beside
// an agent that can already answer from history.

import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope'
import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store'
import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter'
import {
attachFingerprintFields,
type AgentSessionAttachParams
} from './structured-agent-session-attach'
import { performAttach } from './structured-agent-session-attach-flow'

const NOW = 1_800_000_000_000
const SESSION = 'codex_adopting_session'
const THREAD = 'adopted-thread'
const OPERATION = `${NOW}-${'1'.padStart(32, '0')}`
let root: string | null = null

afterEach(async () => {
if (root) {
await rm(root, { recursive: true, force: true })
}
root = null
})

/** A minimal Codex rollout the legacy transcript decoder can read back. */
async function writeCodexRollout(path: string, text: string): Promise<void> {
const lines = [
JSON.stringify({
type: 'session_meta',
payload: { id: THREAD, timestamp: '2026-09-06T18:00:00.000Z', cwd: '/workspace' }
}),
JSON.stringify({
type: 'response_item',
timestamp: '2026-09-06T18:00:01.000Z',
payload: {
type: 'message',
role: 'user',
content: text
}
})
]
await writeFile(path, `${lines.join('\n')}\n`, 'utf8')
}

function attachParams(transcriptPath: string): AgentSessionAttachParams {
const params: AgentSessionAttachParams = {
envelope: {
sessionId: SESSION,
clientOperationId: OPERATION,
expectedRuntimeFence: null,
payloadFingerprint: ''
},
location: {
executionHostId: 'local',
wslDistro: null,
workspaceId: 'workspace-1',
workspaceKind: 'folder'
},
provider: 'codex',
agent: 'codex',
accountHome: { variable: 'CODEX_HOME', path: '/home/dev/.codex' },
runtimeKind: 'native',
adopt: {
providerHandle: { kind: 'codex', threadId: THREAD },
transcriptPath
}
}
return {
...params,
envelope: {
...params.envelope,
payloadFingerprint: computeAgentSessionPayloadFingerprint({
method: 'agentSession.attach',
sessionId: SESSION,
fields: attachFingerprintFields(params)
})
}
}
}

function adapter(): StructuredAgentSessionAdapter {
return {
acquire: vi
.fn<StructuredAgentSessionAdapter['acquire']>()
.mockImplementation(async ({ fence, spawnToken }) => ({
process: { hostId: 'local', pid: 4242, processStartTimeMs: NOW, spawnToken },
link: {
linkId: 'resumed-link',
handle: { provider: 'codex', threadId: THREAD },
origin: 'resumed',
mintedAtFence: fence,
observedAt: NOW
}
})),
// Proven released, so the failure rethrows its own cause rather than an unproven-exit wrapper.
releaseAcquisition: vi.fn(async () => true),
dispatch: vi.fn(),
cancelTurn: vi.fn(),
answerPrompt: vi.fn(),
setOption: vi.fn()
}
}

async function attach(transcriptPath: string, sessionAdapter: StructuredAgentSessionAdapter) {
return performAttach({
store: await AgentSessionRecordStore.open({
directory: join(root!, 'store'),
hostId: 'local'
}),
adapter: sessionAdapter,
journalRoot: root!,
authority: {
spawnToken: 'spawn-a',
claimKeyId: 'key-1',
handoffOperationId: OPERATION,
probe: { outcome: 'reservation-unused' }
},
callerKey: 'client-1',
params: attachParams(transcriptPath),
now: () => NOW,
onAttached: () => {}
})
}

describe('adopting a provider conversation on create', () => {
it('seeds the chain from the adopted handle and fills the journal from its transcript', async () => {
root = await mkdtemp(join(tmpdir(), 'orca-adopt-import-'))
const transcriptPath = join(root, 'rollout.jsonl')
await writeCodexRollout(transcriptPath, 'token ORCA-ADOPT-1')
const sessionAdapter = adapter()

const result = await attach(transcriptPath, sessionAdapter)

expect(result).toMatchObject({ ok: true })
// The adapter was asked to resume, not to start: the seeded chain is what tells it which
// conversation this session owns.
const page = (result as { value: { page: { items: unknown[] } } }).value.page
expect(JSON.stringify(page.items)).toContain('ORCA-ADOPT-1')
})

it('fails the attach when the adopted transcript cannot be read', async () => {
root = await mkdtemp(join(tmpdir(), 'orca-adopt-missing-'))
const sessionAdapter = adapter()

// A post-acquisition failure throws rather than answering a refusal — the same path a journal
// failure already takes — so the caller learns the outcome is unknown, not that nothing ran.
await expect(attach(join(root, 'does-not-exist.jsonl'), sessionAdapter)).rejects.toThrow(
/ENOENT|no such file/
)
// The provider had already resumed, so its acquisition is released rather than left holding a
// conversation no surface will ever show.
expect(sessionAdapter.releaseAcquisition).toHaveBeenCalled()
})

it('fails the attach when the adopted transcript decodes to no messages', async () => {
root = await mkdtemp(join(tmpdir(), 'orca-adopt-empty-'))
const transcriptPath = join(root, 'empty.jsonl')
// Well-formed but conversation-free: the row promised turns and the provider resumed them, so
// an empty journal here is a disagreement, not an empty chat.
await writeFile(
transcriptPath,
`${JSON.stringify({
type: 'session_meta',
payload: { id: THREAD, timestamp: '2026-09-06T18:00:00.000Z', cwd: '/workspace' }
})}\n`,
'utf8'
)
const sessionAdapter = adapter()

await expect(attach(transcriptPath, sessionAdapter)).rejects.toThrow(
'agent_session_identity_required'
)
expect(sessionAdapter.releaseAcquisition).toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import { readNativeSessionOptions } from './structured-agent-session-option-restoration'
import { resolveAgentSessionReplayOutcome } from './structured-agent-session-replay-outcome'
import { readAgentSessionHydrationPage } from './agent-session-history-page'
import { importLegacyTranscriptIntoJournal } from '../agent-session-journal/journal-legacy-import'

export type AttachFlowInput = {
store: AgentSessionRecordStore
Expand Down Expand Up @@ -181,6 +182,7 @@
journalRoot: input.journalRoot,
adapter: input.adapter
})
await importAdoptedTranscript(params, attached, record)
await input.onAttached(attached, acquisitionGeneration)
await store.recordOperationOutcome({
callerKey: input.callerKey,
Expand All @@ -206,6 +208,48 @@
}
}

/**
* Fill an adopting session's journal with the conversation so far.
*
* Runs here, and only here, because for a create there is no earlier moment: the provider is
* acquired before the journal exists. It must still land before `onAttached`, which binds the event
* sink and publishes the session — after that, streamed rows and client sends would race the import.
*
* A failure throws, and that is deliberate. By this point the provider has already resumed and holds
* the conversation in context; leaving the user an empty journal beside a context-carrying agent is
* the exact "claims continuity the provider never gave" inversion this feature must not produce.
* The throw reaches `settlePostAcquisitionAttachFailure`, which tears the child down, settles the
* operation failed, and publishes no tab.
*/
async function importAdoptedTranscript(
params: AgentSessionAttachParams,
attached: AttachedJournal,
record: AgentSessionRecord
): Promise<void> {
const adopt = params.adopt
if (!adopt) {
return
}
const imported = await importLegacyTranscriptIntoJournal({
journal: attached.journal,
agent: params.agent,
sessionId:
adopt.providerHandle.kind === 'claude'
? adopt.providerHandle.sessionId
: adopt.providerHandle.threadId,
fence: record.lease.runtimeFence,
options: { filePath: adopt.transcriptPath }
})
if (!imported.ok) {
throw new Error(imported.error)
}
// `replaced: false` means the transcript decoded to nothing. The row promised a conversation and
// the provider resumed one, so an empty journal here is a disagreement, not an empty chat.
if (!imported.replaced) {
throw new Error('agent_session_identity_required')
}
}

async function settlePostAcquisitionAttachFailure(
input: AttachFlowInput,
record: AgentSessionRecord,
Expand Down Expand Up @@ -317,4 +361,4 @@
}
return rethrowAfterAgentSessionAcquisitionCleanup(input.adapter, record.sessionId, error)
}
}

Check failure on line 364 in src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts

View workflow job for this annotation

GitHub Actions / static analysis

eslint(max-lines)

src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts:364:2: File has too many lines (317).
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import type {
AgentSessionProviderHandle
} from '../../../shared/agent-session-journal-types'
import type { AgentSessionOwnerProbe } from '../../../shared/agent-session-lease-adjudication'
import type { AgentSessionHandleProvider } from '../../../shared/agent-session-provider-handle'
import type {
AgentSessionHandleProvider,
AgentSessionProviderHandleLink
} from '../../../shared/agent-session-provider-handle'
import { claudeProviderHandleLink } from '../../claude/claude-structured-owner-identity'
import { codexProviderHandleLink } from '../../codex/codex-structured-owner-identity'
import type {
AgentSessionAccountHome,
AgentSessionExecutionLocation,
Expand Down Expand Up @@ -58,6 +63,18 @@ export type AgentSessionAttachParams = {
options?: Readonly<Record<string, string>>
/** Omitted only for create-by-intent; the adapter proves the durable handle. */
providerHandle?: Exclude<AgentSessionProviderHandle, { kind: 'opaque' }>
/**
* Host-resolved only. Present when this create adopts an existing provider conversation rather
* than starting one: it seeds the handle chain so the adapter resumes instead of creating, and
* names the transcript to import so the journal shows the conversation so far.
*
* Deliberately separate from `providerHandle`, which `agentSession.ensure` already supplies
* without adopting — presence of a handle must never be what triggers a resume.
*/
adopt?: {
providerHandle: Exclude<AgentSessionProviderHandle, { kind: 'opaque' }>
transcriptPath: string
}
}

/** Host-supplied half of the reservation. */
Expand All @@ -84,6 +101,10 @@ export function attachFingerprintFields(params: AgentSessionAttachParams): Recor
accountHome: params.accountHome,
runtimeKind: params.runtimeKind,
providerHandle: params.providerHandle,
// Which conversation this attaches to, so an adopting create and a blank one never share an
// identity. The transcript path is excluded: it is where the host found that conversation this
// time, not part of what the caller asked for.
adoptedProviderHandle: params.adopt?.providerHandle,
expectedRuntimeFence: params.envelope.expectedRuntimeFence
}
}
Expand Down Expand Up @@ -182,6 +203,38 @@ export async function attachJournal(input: {
}
}

/**
* The first link of an adopting session's chain.
*
* `adopted` is the only origin besides `created` a chain will accept at its head, and it is the
* honest one here: this session did not create the conversation. The adapter appends its own
* `resumed` link once the provider proves the same identity root — or, when it proves the identical
* handle at the same fence, the validator elides that as a retry and this link stays the head.
*/
const ADOPTED_HANDLE_FENCE = 1

function adoptedProviderHandleLink(
handle: Exclude<AgentSessionProviderHandle, { kind: 'opaque' }>,
observedAt: number
): AgentSessionProviderHandleLink {
return handle.kind === 'claude'
? claudeProviderHandleLink({
sessionId: handle.sessionId,
leafUuid: handle.leafUuid,
resumed: false,
origin: 'adopted',
fence: ADOPTED_HANDLE_FENCE,
observedAt
})
: codexProviderHandleLink({
threadId: handle.threadId,
resumed: false,
origin: 'adopted',
fence: ADOPTED_HANDLE_FENCE,
observedAt
})
}

export function reserveRequestFor(input: {
sessionId: string
params: AgentSessionAttachParams
Expand All @@ -200,6 +253,13 @@ export function reserveRequestFor(input: {
...(authority.launchArgs ? { launchArgs: authority.launchArgs } : {}),
...(authority.launchEnv ? { launchEnv: authority.launchEnv } : {}),
runtimeKind: params.runtimeKind,
...(params.adopt
? {
// Fence 1 is a new record's first, and the owner probe requires the head link to carry
// the record's current fence.
adoptedHandleLink: adoptedProviderHandleLink(params.adopt.providerHandle, input.now)
}
: {}),
expectedFence: params.envelope.expectedRuntimeFence,
spawnToken: authority.spawnToken,
claimKeyId: authority.claimKeyId,
Expand Down
Loading
Loading