Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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 @@ -165,10 +165,12 @@ export async function evictOwnedStructuredAgentSessions(
}
}

/** The first hold on a childless session: reconcile the lease, settle recovery, then attach. */
/** The first hold on a childless session: reconcile the lease, settle recovery, make it readable,
* then attach. */
export async function resumeStructuredAgentSessionForHold(
context: StructuredAgentSessionLifetimeContext & {
reconcileLeases: (sessionId: string) => Promise<AgentSessionWireRefusal | null>
makeReadable: (sessionId: string) => Promise<unknown>
},
sessionId: string,
attach: Parameters<typeof resumeHeldStructuredAgentSession>[0]['attach']
Expand All @@ -178,6 +180,11 @@ export async function resumeStructuredAgentSessionForHold(
throw new Error(unreconciled.code)
}
await context.runtimeState.resolveRecovery(sessionId)
// Why first: attach keeps the session's task queue for the whole provider start, so a read
// arriving meanwhile would wait on the child. Best effort; the attach decides the hold.
await context
.makeReadable(sessionId)
.catch((error: unknown) => context.deps.onEventSinkError?.({ sessionId, error }))
await resumeHeldStructuredAgentSession({
sessionId,
deps: context.deps,
Comment on lines 180 to 190

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '168,198p' src/main/native-chat/agent-session-wire/structured-agent-session-host-lifetime.ts
sed -n '1,75p' src/main/native-chat/agent-session-wire/structured-agent-session-hold-resume.ts
sed -n '1,80p' src/main/native-chat/agent-session-wire/structured-agent-session-resume-eligibility.ts
rg -n 'createStructuredAgentSessionHolds|resumeStructuredAgentSessionForHold|makeReadable|hold' src/main/native-chat/agent-session-wire

Repository: stablyai/orca

Length of output: 41768


Do not attach when makeReadable returns false.

ensureReadable returns false when the persisted session is no longer visible. The hold path discards that result and still calls resumeHeldStructuredAgentSession, which can attach the provider for the released record. This violates the hold/close contract: a closed or hidden session can regain a provider without a readable surface.

Return after the readability check, while preserving error reporting.

Suggested fix
-  await context
+  const readable = await context
     .makeReadable(sessionId)
     .catch((error: unknown) => context.deps.onEventSinkError?.({ sessionId, error }))
+  if (readable !== true) return
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
throw new Error(unreconciled.code)
}
await context.runtimeState.resolveRecovery(sessionId)
// Why first: attach keeps the session's task queue for the whole provider start, so a read
// arriving meanwhile would wait on the child. Best effort; the attach decides the hold.
await context
.makeReadable(sessionId)
.catch((error: unknown) => context.deps.onEventSinkError?.({ sessionId, error }))
await resumeHeldStructuredAgentSession({
sessionId,
deps: context.deps,
throw new Error(unreconciled.code)
}
await context.runtimeState.resolveRecovery(sessionId)
// Why first: attach keeps the session's task queue for the whole provider start, so a read
// arriving meanwhile would wait on the child. Best effort; the attach decides the hold.
const readable = await context
.makeReadable(sessionId)
.catch((error: unknown) => context.deps.onEventSinkError?.({ sessionId, error }))
if (readable !== true) return
await resumeHeldStructuredAgentSession({
sessionId,
deps: context.deps,

Expand All @@ -190,14 +197,15 @@ export function createStructuredAgentSessionHolds(
context: StructuredAgentSessionLifetimeContext,
input: {
reconcileLeases: (sessionId: string) => Promise<AgentSessionWireRefusal | null>
makeReadable: (sessionId: string) => Promise<unknown>
attach: Parameters<typeof resumeHeldStructuredAgentSession>[0]['attach']
close: (sessionId: string) => Promise<void>
}
): StructuredAgentSessionHolds {
return new StructuredAgentSessionHolds({
resume: (sessionId) =>
resumeStructuredAgentSessionForHold(
{ ...context, reconcileLeases: input.reconcileLeases },
{ ...context, reconcileLeases: input.reconcileLeases, makeReadable: input.makeReadable },
sessionId,
input.attach
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export class StructuredAgentSessionHost {
})
this.holds = createStructuredAgentSessionHolds(this.lifetimeContext(), {
reconcileLeases: this.reconcileLeases,
makeReadable: (sessionId) => this.restore.ensureReadable(sessionId),
attach: (params) => this.attach({ callerKey: 'trusted-local:surface-hold' }, params),
close: (sessionId) => this.close(sessionId)
})
Expand Down Expand Up @@ -233,6 +234,9 @@ export class StructuredAgentSessionHost {
revealSession = (sessionId: string): Promise<StructuredAgentSessionReveal> =>
this.restore.revealSession(sessionId)

/** Opens a visible persisted chat for reading, never a provider child; see the readable restorer. */
ensureReadable = (sessionId: string): Promise<boolean> => this.restore.ensureReadable(sessionId)

private serialize = this.tasks.serialize.bind(this.tasks)

private restoreRenewedHandoff(sessionId: string): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/**
* Reading a persisted chat before the startup sweep reaches it.
*
* A restored chat pane subscribes as soon as its workspace paints, which can be long before the
* startup sweep runs. The read opens the journal itself; the sweep still owns the handoff recovery.
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentSessionRecord } from '../../../shared/agent-session-record'
import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store'
import {
agentSessionLeaseFixture,
agentSessionRecordFixture
} from '../../../shared/agent-session-record.test-fixture'
import { StructuredAgentSessionReadableRestorer } from './structured-agent-session-readable-restorer'
import * as readRestore from './structured-agent-session-read-restore'
import { StructuredAgentSessionTaskQueue } from './structured-agent-session-task-queue'

const readable = { journal: {}, params: {}, fence: 1 } as never

function harness(options: {
records: AgentSessionRecord[]
visible?: { present: boolean; sessionIds: string[] }
supports?: (record: AgentSessionRecord) => boolean
reconcile?: (live: Map<string, unknown>) => Promise<null>
}) {
const live = new Map<string, unknown>()
const tasks = new StructuredAgentSessionTaskQueue()
const onReadable = vi.fn((sessionId: string, restored: unknown) => live.set(sessionId, restored))
const restoreHandoff = vi.fn(async () => undefined)
const restorer = new StructuredAgentSessionReadableRestorer({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the restorer reads only these three store methods.
store: {
getRecord: (sessionId: string) =>
options.records.find((record) => record.sessionId === sessionId) ?? null,
listRecords: () => options.records,
getVisibleSessionTabIndex: () =>
options.visible ?? {
present: true,
sessionIds: options.records.map((record) => record.sessionId)
}
} as unknown as AgentSessionRecordStore,
journalRoot: '/journals',
supportsRecord: options.supports ?? (() => true),
reconcile: async () => (options.reconcile ? options.reconcile(live) : null),
resolveRecovery: async () => undefined,
serialize: (sessionId, task) => tasks.serialize(sessionId, task),
hasSession: (sessionId) => live.has(sessionId),
onReadable,
retrySettlement: async () => true,
restoreHandoff
})
return { restorer, live, tasks, onReadable, restoreHandoff }
}

function record(sessionId: string): AgentSessionRecord {
return agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId }))
}

afterEach(() => {
vi.restoreAllMocks()
})

describe('an on-demand read of a persisted chat', () => {
beforeEach(() => {
vi.spyOn(readRestore, 'restoreStructuredAgentSessionRead').mockResolvedValue(readable)
})

it('opens a visible chat without running the handoff recovery', async () => {
const { restorer, live, restoreHandoff } = harness({ records: [record('session-1')] })

await expect(restorer.ensureReadable('session-1')).resolves.toBe(true)

expect(live.has('session-1')).toBe(true)
expect(restoreHandoff).not.toHaveBeenCalled()
})

it('leaves the handoff to the startup sweep, which runs it exactly once', async () => {
const { restorer, onReadable, restoreHandoff } = harness({ records: [record('session-1')] })

await restorer.ensureReadable('session-1')
await restorer.restore(['session-1'])

expect(onReadable).toHaveBeenCalledOnce()
expect(restoreHandoff).toHaveBeenCalledOnce()
expect(readRestore.restoreStructuredAgentSessionRead).toHaveBeenCalledOnce()
})

it('opens the journal once when a read races the startup sweep', async () => {
const opened = Promise.withResolvers<void>()
vi.mocked(readRestore.restoreStructuredAgentSessionRead).mockImplementation(async () => {
await opened.promise
return readable
})
const { restorer, onReadable, restoreHandoff } = harness({ records: [record('session-1')] })

const sweep = restorer.restore(['session-1'])
const read = restorer.ensureReadable('session-1')
opened.resolve()

await expect(read).resolves.toBe(true)
await sweep
expect(readRestore.restoreStructuredAgentSessionRead).toHaveBeenCalledOnce()
expect(onReadable).toHaveBeenCalledOnce()
expect(restoreHandoff).toHaveBeenCalledOnce()
})

it('does not queue behind a provider start once another surface made the chat readable', async () => {
// A hold opens the chat, then keeps the task queue for its whole provider start. A read that
// saw the chat closed at its first check must not then wait that start out.
const providerStart = Promise.withResolvers<void>()
const { restorer, live, tasks } = harness({
records: [record('session-1')],
reconcile: async (sessions) => {
sessions.set('session-1', readable)
void tasks.serialize('session-1', () => providerStart.promise)
return null
}
})

try {
await expect(restorer.ensureReadable('session-1')).resolves.toBe(true)
expect(live.has('session-1')).toBe(true)
expect(readRestore.restoreStructuredAgentSessionRead).not.toHaveBeenCalled()
} finally {
providerStart.resolve()
}
})

it('does not reopen a chat the user closed', async () => {
// Close hides the tab before it drops the session, so a read retry landing after it must not
// bring the chat back.
const { restorer, live } = harness({
records: [record('session-closed')],
visible: { present: true, sessionIds: [] }
})

await expect(restorer.ensureReadable('session-closed')).resolves.toBe(false)

expect(live.size).toBe(0)
expect(readRestore.restoreStructuredAgentSessionRead).not.toHaveBeenCalled()
})

it('does not reopen a chat closed while the read was already past its visibility check', async () => {
// Close hides the tab, then queues its eviction; a read held up in reconcile queues after it.
const visible = { present: true, sessionIds: ['session-1'] }
const reconciled = Promise.withResolvers<null>()
const { restorer, live, tasks } = harness({
records: [record('session-1')],
visible,
reconcile: () => reconciled.promise
})

const read = restorer.ensureReadable('session-1')
visible.sessionIds = []
const close = tasks.serialize('session-1', async () => undefined)
reconciled.resolve(null)

await expect(read).resolves.toBe(false)
await close
expect(live.size).toBe(0)
expect(readRestore.restoreStructuredAgentSessionRead).not.toHaveBeenCalled()
})

it('reads any supported record when the store keeps no visible-tab index', async () => {
const { restorer } = harness({
records: [record('session-1')],
visible: { present: false, sessionIds: [] }
})

await expect(restorer.ensureReadable('session-1')).resolves.toBe(true)
})

it('answers a live session without reopening it', async () => {
const { restorer, live } = harness({ records: [], visible: { present: true, sessionIds: [] } })
live.set('session-live', readable)

await expect(restorer.ensureReadable('session-live')).resolves.toBe(true)
expect(readRestore.restoreStructuredAgentSessionRead).not.toHaveBeenCalled()
})

it('refuses a record no adapter supports, and one this host has no record for', async () => {
const { restorer } = harness({ records: [record('session-1')], supports: () => false })

await expect(restorer.ensureReadable('session-1')).resolves.toBe(false)
await expect(restorer.ensureReadable('session-absent')).resolves.toBe(false)
expect(readRestore.restoreStructuredAgentSessionRead).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { AgentSessionRecordStore } from '../../runtime/agent-session-record
import type { RestoredStructuredAgentSessionRead } from './structured-agent-session-read-restore'
import {
restoreOneStructuredAgentSessionRead,
restoreStructuredAgentSessionReadPhase,
restoreStructuredAgentSessionsOnRestart
} from './structured-agent-session-restart-restore'

Expand Down Expand Up @@ -56,6 +57,34 @@ export class StructuredAgentSessionReadableRestorer {
return this.input.hasSession(sessionId)
}

/**
* Opens a persisted chat's journal for a surface that is reading it, without waiting for the
* startup sweep. Read phase only: the handoff recovery stays the sweep's, which runs it once the
* PTY census it depends on exists.
*
* Only for a chat the user still has a tab for, when the store keeps that index: a read retry
* landing after a close must not reopen the chat it just closed. Asked again inside the task
* queue, because a read already past this check can still queue behind that close.
*/
async ensureReadable(sessionId: string): Promise<boolean> {
if (this.input.hasSession(sessionId)) {
return true
}
const record = this.input.store.getRecord(sessionId)
if (!record || !this.input.supportsRecord(record)) {
return false
}
const tabVisible = (): boolean => {
const visible = this.input.store.getVisibleSessionTabIndex()
return !visible.present || visible.sessionIds.includes(sessionId)
}
if (!tabVisible()) {
return false
}
await restoreStructuredAgentSessionReadPhase(this.input, sessionId, tabVisible)
return this.input.hasSession(sessionId)
}

private async restoreReadableSessions(sessionIds?: readonly string[]): Promise<void> {
const targetOrder = sessionIds
? new Map(sessionIds.map((sessionId, index) => [sessionId, index]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,28 @@ vi.mock('./structured-agent-session-read-restore', () => ({

import {
restoreOneStructuredAgentSessionRead,
restoreStructuredAgentSessionsOnRestart
restoreStructuredAgentSessionReadPhase,
restoreStructuredAgentSessionsOnRestart,
type StructuredAgentSessionReadRestoreDeps
} from './structured-agent-session-restart-restore'

function phaseDeps(
overrides: Partial<StructuredAgentSessionReadRestoreDeps> = {}
): StructuredAgentSessionReadRestoreDeps {
return {
store: {} as never,
journalRoot: '/tmp/journals',
reconcile: async () => null,
resolveRecovery: async () => undefined,
serialize: async (_sessionId, task) => task(),
hasSession: () => false,
onReadable: () => undefined,
retrySettlement: async () => true,
restoreHandoff: async () => undefined,
...overrides
}
}

describe('restart journal restoration', () => {
beforeEach(() => restoreRead.mockReset())

Expand Down Expand Up @@ -99,7 +118,7 @@ describe('restart journal restoration', () => {
calls.push('resolveRecovery')
},
serialize: async (_sessionId, task) => task(),
hasSession: () => false,
hasSession: () => calls.includes('onReadable'),
onReadable: () => {
calls.push('onReadable')
},
Expand Down Expand Up @@ -153,4 +172,38 @@ describe('restart journal restoration', () => {
expect(retrySettlement).not.toHaveBeenCalled()
expect(restoreHandoff).toHaveBeenCalledOnce()
})

it('opens the journal on the read phase alone, never the handoff recovery', async () => {
// The handoff re-proves a live agent terminal against startup's PTY census; a read must not
// run it early, or wait for it.
const live = new Set<string>()
const restoreHandoff = vi.fn(async () => undefined)
restoreRead.mockResolvedValue({ journal: {}, params: {}, fence: 1 })

await restoreStructuredAgentSessionReadPhase(
phaseDeps({
hasSession: (sessionId) => live.has(sessionId),
onReadable: (sessionId) => live.add(sessionId),
restoreHandoff
}),
'session-1'
)

expect(live.has('session-1')).toBe(true)
expect(restoreHandoff).not.toHaveBeenCalled()
})

it('skips the handoff when the journal is missing or corrupt', async () => {
const onReadable = vi.fn()
const restoreHandoff = vi.fn(async () => undefined)
restoreRead.mockResolvedValue(null)

await restoreOneStructuredAgentSessionRead(
phaseDeps({ onReadable, restoreHandoff }),
'session-1'
)

expect(onReadable).not.toHaveBeenCalled()
expect(restoreHandoff).not.toHaveBeenCalled()
})
})
Loading
Loading