Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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,242 @@
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 { AgentSessionStatusEvent } from '../../../shared/agent-session-wire'
import { createTrackedJournalOpener } from '../agent-session-journal/journal-store-test-open'
import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed'

const SESSION = 'status-session'
const TURN_IDENTITY = {
provider: 'codex',
threadId: 'thread-1',
turnId: 'turn-1',
ordinal: 0
} as const
const USER_IDENTITY = {
provider: 'codex',
threadId: 'thread-1',
turnId: 'turn-1',
ordinal: 1
} as const

let root: string
const journals = createTrackedJournalOpener()

beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-agent-status-feed-'))
})

afterEach(async () => {
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})

async function openJournal(sessionId = SESSION) {
return journals.open({
identity: {
sessionId,
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'codex',
providerHandle: { kind: 'codex', threadId: 'thread-1' }
},
journalDir: join(root, sessionId)
})
}

function indexed(session: { journal: Awaited<ReturnType<typeof openJournal>> }) {
return {
journal: session.journal,
params: { location: { workspaceId: 'workspace-1' }, provider: 'codex' as const }
}
}

function feedFor(sessions: Map<string, { journal: Awaited<ReturnType<typeof openJournal>> }>) {
let now = 1_000
const feed = new StructuredAgentSessionStatusFeed({
sessions: {
get: (sessionId: string) => {
const session = sessions.get(sessionId)
return session ? indexed(session) : undefined
},
[Symbol.iterator]: function* () {
for (const [sessionId, session] of sessions) {
yield [sessionId, indexed(session)] as const
}
}
} as unknown as ReadonlyMap<string, ReturnType<typeof indexed>>,
getRecord: () => null,
now: () => (now += 1)
})
const events: AgentSessionStatusEvent[] = []
const dispose = feed.subscribe({ id: 'list-1', emit: (event) => events.push(event) })
return { feed, events, dispose }
}

describe('StructuredAgentSessionStatusFeed', () => {
it('opens with every readable session and reports no status before a persisted turn', async () => {
const journal = await openJournal()
const { events } = feedFor(new Map([[SESSION, { journal }]]))

expect(events).toEqual([
{
type: 'snapshot',
sessions: [
{
sessionId: SESSION,
workspaceId: 'workspace-1',
agent: 'codex',
status: null,
latestPrompt: '',
updatedAt: expect.any(Number)
}
]
}
])
})

it('publishes working, then idle once the running marker is tombstoned, and never a repeat', async () => {
const journal = await openJournal()
const { feed, events } = feedFor(new Map([[SESSION, { journal }]]))
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] },
{ fence: 1 }
)
await journal.appendItem(
TURN_IDENTITY,
{ kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } },
{ fence: 1 }
)

feed.publish(SESSION)
feed.publish(SESSION)
expect(events.slice(1)).toEqual([
{
type: 'status',
session: expect.objectContaining({
sessionId: SESSION,
status: 'working',
latestPrompt: 'write a poem'
})
}
])

await journal.appendTombstone(TURN_IDENTITY, { fence: 1 })
feed.publish(SESSION)
expect(events.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ sessionId: SESSION, status: 'idle' })
})
expect(events).toHaveLength(3)
})

it('reports a pending approval as attention', async () => {
const journal = await openJournal()
const { feed, events } = feedFor(new Map([[SESSION, { journal }]]))
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'run it' }] },
{ fence: 1 }
)
await journal.appendItem(
TURN_IDENTITY,
{
kind: 'approval',
title: 'Run command?',
detail: null,
options: [{ id: 'yes', label: 'Allow' }],
resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null }
},
{ fence: 1 }
)

feed.publish(SESSION)
expect(events.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ status: 'attention' })
})
})

it('keeps the last projection for an evicted session and serves it to a new subscriber', async () => {
const journal = await openJournal()
const sessions = new Map([[SESSION, { journal }]])
const { feed, events } = feedFor(sessions)
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] },
{ fence: 1 }
)
feed.publish(SESSION)
expect(events.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ status: 'idle', latestPrompt: 'hello' })
})

// Eviction drops the host's index entry; the projection it already made stays true.
sessions.delete(SESSION)
feed.publish(SESSION)
const late: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'list-late', emit: (event) => late.push(event) })

expect(events).toHaveLength(2)
expect(late).toEqual([
{
type: 'snapshot',
sessions: [expect.objectContaining({ sessionId: SESSION, status: 'idle' })]
}
])
})

it('tells the sitting subscribers about a change a new subscriber re-projected', async () => {
const journal = await openJournal()
const { feed, events } = feedFor(new Map([[SESSION, { journal }]]))
// Journal appends and the feed's publish are separate queue submissions, so the journal
// can already hold the turn when a second client connects and re-projects it.
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] },
{ fence: 1 }
)

const late: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'list-late', emit: (event) => late.push(event) })

expect(events.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ status: 'idle', latestPrompt: 'hello' })
})
// The arriving subscriber reads that same state once, from its snapshot.
expect(late).toEqual([
{
type: 'snapshot',
sessions: [expect.objectContaining({ status: 'idle', latestPrompt: 'hello' })]
}
])
// The cache is not left holding a value nobody was told about.
feed.publish(SESSION)
expect(events).toHaveLength(2)
})

it('ends a closed subscriber and keeps publishing to the rest', async () => {
const journal = await openJournal()
const { feed, events, dispose } = feedFor(new Map([[SESSION, { journal }]]))
const others: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'list-2', emit: (event) => others.push(event) })

dispose()
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] },
{ fence: 1 }
)
feed.publish(SESSION)

expect(events.at(-1)).toEqual({ type: 'end' })
expect(others.at(-1)).toEqual({
type: 'status',
session: expect.objectContaining({ status: 'idle' })
})
})
})
Loading
Loading