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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
import type { AgentSessionJournal } from '../agent-session-journal/journal-store'
import { readAgentSessionHistory } from './agent-session-history-page'

function providerSessionMetadata(
export function structuredAgentSessionProviderSessionMetadata(
record: AgentSessionRecord | null
): AgentProviderSessionMetadata | undefined {
const head = record ? agentSessionProviderHandleChainHead(record.providerHandleChain) : null
Expand All @@ -27,7 +27,7 @@ export function readStructuredAgentSessionHistoryResult(input: {
}): AgentSessionHistoryResult {
const result = readAgentSessionHistory(input.journal, input.request)
const fence = input.record?.lease.runtimeFence
const providerSession = providerSessionMetadata(input.record)
const providerSession = structuredAgentSessionProviderSessionMetadata(input.record)
if (fence === undefined) {
return providerSession ? { ...result, providerSession } : result
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import type {
StructuredAgentSessionHostSession
} from './structured-agent-session-host-types'
import { releaseStoredStructuredAgentSessionOwner } from './structured-agent-session-lease-release'
import { resumeHeldStructuredAgentSession } from './structured-agent-session-hold-resume'
import type { AgentSessionWireRefusal } from '../../../shared/agent-session-wire'

export type StructuredAgentSessionLifetimeContext = {
deps: StructuredAgentSessionHostDeps
Expand Down Expand Up @@ -67,6 +69,27 @@ export async function evictHeldStructuredAgentSession(
)
}

/** The first hold on a childless session: reconcile the lease, settle recovery, then attach. */
export async function resumeStructuredAgentSessionForHold(
context: StructuredAgentSessionLifetimeContext & {
reconcileLeases: (sessionId: string) => Promise<AgentSessionWireRefusal | null>
},
sessionId: string,
attach: Parameters<typeof resumeHeldStructuredAgentSession>[0]['attach']
): Promise<void> {
const unreconciled = await context.reconcileLeases(sessionId)
if (unreconciled) {
throw new Error(unreconciled.code)
}
await context.runtimeState.resolveRecovery(sessionId)
await resumeHeldStructuredAgentSession({
sessionId,
deps: context.deps,
now: context.now,
attach
})
}

export function createStructuredAgentSessionHolds(
context: StructuredAgentSessionLifetimeContext,
input: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ import { attachStructuredAgentSession } from './structured-agent-session-attach-
import {
createStructuredAgentSessionHolds,
evictHeldStructuredAgentSession,
resumeStructuredAgentSessionForHold,
type StructuredAgentSessionLifetimeContext
} from './structured-agent-session-host-lifetime'
import type {
StructuredAgentSessionHolds,
StructuredAgentSessionHoldOptions
} from './structured-agent-session-holds'
import { resumeHeldStructuredAgentSession } from './structured-agent-session-hold-resume'
import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context'
import { listStructuredAgentSessionTabs } from './structured-agent-session-host-tabs'
import {
Expand All @@ -58,11 +58,19 @@ import type {
StructuredAgentSessionHostSession
} from './structured-agent-session-host-types'
import { readStructuredAgentSessionHistoryResult } from './structured-agent-session-history-result'
import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed'
import { StructuredAgentSessionEventRecovery } from './structured-agent-session-event-recovery'
export type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types'
export class StructuredAgentSessionHost {
private readonly sessions = new Map<string, StructuredAgentSessionHostSession>()
private readonly subscribers = new AgentSessionSubscribers()
private readonly statusFeed = new StructuredAgentSessionStatusFeed({
sessions: this.sessions,
getRecord: (sessionId) => this.deps.store.getRecord(sessionId),
now: () => this.now()
})
private readonly subscribers = new AgentSessionSubscribers({
onJournalPublished: (sessionId, journal) => this.statusFeed.publish(sessionId, journal)
})
private readonly tasks = new StructuredAgentSessionTaskQueue()
private readonly runtimeState: StructuredAgentSessionHostRuntimeState
private readonly reconcileLeases: (sessionId: string) => Promise<AgentSessionWireRefusal | null>
Expand Down Expand Up @@ -99,7 +107,12 @@ export class StructuredAgentSessionHost {
now: this.now
})
this.holds = createStructuredAgentSessionHolds(this.lifetimeContext(), {
resume: (sessionId) => this.resumeForHold(sessionId),
resume: (sessionId) =>
resumeStructuredAgentSessionForHold(
{ ...this.lifetimeContext(), reconcileLeases: this.reconcileLeases },
sessionId,
(params) => this.attach({ callerKey: 'trusted-local:surface-hold' }, params)
),
evict: (sessionId) => this.close(sessionId)
})
this.readableRestorer = new StructuredAgentSessionReadableRestorer({
Expand All @@ -112,7 +125,10 @@ export class StructuredAgentSessionHost {
hasSession: (sessionId) => this.sessions.has(sessionId),
// Site 10: cannot overwrite a live entry — the restorer returns early on
// `hasSession` inside the same serialized step as this `set`.
onReadable: (sessionId, restored) => this.sessions.set(sessionId, restored),
onReadable: (sessionId, restored) => {
this.sessions.set(sessionId, restored)
this.statusFeed.publish(sessionId)
},
restoreHandoff: (sessionId) => this.handoffs.restore(sessionId)
})
this.eventRecovery = new StructuredAgentSessionEventRecovery({
Expand Down Expand Up @@ -147,20 +163,6 @@ export class StructuredAgentSessionHost {
/** That surface is gone. The child outlives it by the release grace, and by any running turn. */
release = (sessionId: string, holderId: string): void => this.holds.release(sessionId, holderId)

private async resumeForHold(sessionId: string): Promise<void> {
const unreconciled = await this.reconcileLeases(sessionId)
if (unreconciled) {
throw new Error(unreconciled.code)
}
await this.runtimeState.resolveRecovery(sessionId)
await resumeHeldStructuredAgentSession({
sessionId,
deps: this.deps,
now: () => this.now(),
attach: (params) => this.attach({ callerKey: 'trusted-local:surface-hold' }, params)
})
}

handleAdapterEvent = (event: Parameters<StructuredAgentSessionEventRecovery['handle']>[0]) =>
this.eventRecovery.handle(event)

Expand Down Expand Up @@ -328,6 +330,11 @@ export class StructuredAgentSessionHost {
}
unsubscribe = (sessionId: string, id: string): void => this.subscribers.close(sessionId, id)

/** Every session's projected status for session lists; unlike `subscribe`, retains nothing. */
subscribeStatus = (
subscriber: Parameters<StructuredAgentSessionStatusFeed['subscribe']>[0]
): (() => void) => this.statusFeed.subscribe(subscriber)

private requireSession(sessionId: string): StructuredAgentSessionHostSession {
const session = this.sessions.get(sessionId)
if (!session) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Startup restore has to publish status, not just index the session.
//
// A tab nobody reopens after a restart still owes the sidebar a row. The host restores such a
// session read-only, without a provider child, so the only thing that can surface its state is
// the status publication the restore wiring makes.

import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type {
AgentSessionMutationEnvelope,
AgentSessionStatusEvent
} from '../../../shared/agent-session-wire'
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 { 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'

const CALLER = { callerKey: 'client-1' }

const hosts: StructuredAgentSessionHost[] = []
let root = ''

function adapter(): StructuredAgentSessionAdapter {
return {
acquire: async ({ fence, spawnToken }) => ({
process: { hostId: 'local', pid: 4242, processStartTimeMs: 1_700_000_000_000, spawnToken },
link: {
linkId: `link-${fence}`,
handle: { provider: 'codex', threadId: THREAD },
origin: 'created',
mintedAtFence: fence,
observedAt: NOW
}
}),
dispatch: async () => ({
state: 'accepted',
providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 }
}),
cancelTurn: async () => ({ cancelled: true }),
answerPrompt: async () => undefined,
setOption: async () => undefined
}
}

function createHost(store: AgentSessionRecordStore): StructuredAgentSessionHost {
const host = new StructuredAgentSessionHost({
store,
adapter: adapter(),
journalRoot: root,
claimKeyId: 'key-1',
mintSpawnToken: () => 'spawn-a',
probeOwner: async () => ({
outcome: 'indeterminate',
reason: 'read does not need ownership'
}),
now: () => NOW
})
hosts.push(host)
return host
}

function sendEnvelope(
store: AgentSessionRecordStore,
fields: Record<string, unknown>
): AgentSessionMutationEnvelope {
return {
sessionId: SESSION,
clientOperationId: hostTestOperationId(),
expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1,
payloadFingerprint: computeAgentSessionPayloadFingerprint({
method: 'agentSession.send',
sessionId: SESSION,
fields
})
}
}

/** Persists one turn, then hands back a restarted host over the same directories. */
async function restartWithPersistedTurn(): Promise<StructuredAgentSessionHost> {
root = await mkdtemp(join(tmpdir(), 'orca-restart-status-'))
resetHostTestOperationIds()
const directory = join(root, 'store')
const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' })
const host = createHost(store)
expect(await host.attach(CALLER, hostTestAttachParams(null))).toMatchObject({ ok: true })
const body = hostTestMessage('persisted conversation')
await host.send(CALLER, { envelope: sendEnvelope(store, { body }), body })
await host.flushAllStreamedEvents()
return createHost(await AgentSessionRecordStore.open({ directory, hostId: 'local' }))
}

afterEach(async () => {
await Promise.all(hosts.splice(0).map((host) => host.flushAllStreamedEvents()))
await rm(root, { recursive: true, force: true })
root = ''
})

describe('structured session restart status publication', () => {
// Served by the subscribe-time re-projection rather than the restore's own publish, so this
// covers what a restored journal projects — not the restore wiring. The test below pins that.
it('projects the persisted turn of a session restored without a provider', async () => {
const restarted = await restartWithPersistedTurn()

await restarted.restoreReadableSessions()
const events: AgentSessionStatusEvent[] = []
restarted.subscribeStatus({ id: 'session-list', emit: (event) => events.push(event) })

expect(events).toEqual([
{
type: 'snapshot',
sessions: [
expect.objectContaining({
sessionId: SESSION,
workspaceId: 'workspace-1',
agent: 'codex',
status: 'idle',
latestPrompt: 'persisted conversation'
})
]
}
])
})

it('publishes a restored session to a list already sitting on the stream', async () => {
const restarted = await restartWithPersistedTurn()
const events: AgentSessionStatusEvent[] = []
restarted.subscribeStatus({ id: 'session-list', emit: (event) => events.push(event) })
expect(events).toEqual([{ type: 'snapshot', sessions: [] }])

await restarted.restoreReadableSessions()

// The restore wiring publishes; without it this list never hears about the session at all.
expect(events.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ sessionId: SESSION, status: 'idle' })
})
})
})
Loading