Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(core): reject stale pane captures through profile publication (#1093)

Dee74c27333e8de
diff --git a/cli/e2e/paneCapture.e2e.ts b/cli/e2e/paneCapture.e2e.ts
new file mode 100644
index 000000000..733bdb159
--- /dev/null
+++ b/cli/e2e/paneCapture.e2e.ts
@@ -0,0 +1,70 @@
+/** Agy's real attach, private daemon/home/tmux, and its recorded transcript/footer shapes. */
+import { appendFileSync, mkdirSync, readFileSync, utimesSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+let daemon: IsolatedDaemon | undefined
+let client: LocalClient | undefined
+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+
+it('an idle Agy pane settles old history and still follows the next live turn', async () => {
+ const d = daemon = await IsolatedDaemon.create()
+ onTestFailed(() => console.log(d.log()))
+ d.env.AGY_PATH = join(d.root, 'bin', 'agy')
+ d.env.AGY_HOME = join(d.root, 'agy')
+ // Nothing invokes an installed engine. The process and pane are real, including discovery.
+ writeFileSync(d.env.AGY_PATH, `#!${process.execPath}
+if (process.argv.includes('--version')) { console.log('1.1.14'); process.exit(0) }
+if (process.argv.includes('models')) { console.log('gemini-3.7-flash-high\\tGemini 3.7 Flash (High)'); process.exit(0) }
+process.title = 'agy'
+require('node:fs').writeFileSync(${JSON.stringify(join(d.root, 'agy.pid'))}, String(process.pid))
+console.log('Old answer\\n>\\n? for shortcuts Gemini 3.7 Flash · high')
+setInterval(() => {}, 1000)
+`, { mode: 0o755 })
+ const cwd = join(d.projectsDir, 'agy'); mkdirSync(cwd, { recursive: true })
+ const sessionId = 'a9510000-0000-4000-8000-000000000001'
+ const transcriptPath = join(d.env.AGY_HOME, 'brain', sessionId, '.system_generated', 'logs', 'transcript_full.jsonl')
+ mkdirSync(dirname(transcriptPath), { recursive: true })
+ const step = (type: string, index: number, content: string) => JSON.stringify({ type, step_index: index, status: 'DONE', content }) + '\n'
+ writeFileSync(transcriptPath, step('USER_INPUT', 0, '<USER_REQUEST>Old prompt</USER_REQUEST>') + step('PLANNER_RESPONSE', 1, 'Old answer'))
+ const old = new Date(Date.now() - 600_000); utimesSync(transcriptPath, old, old)
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ const created = await c.request('agent_create', { engine: 'agy', cwd, bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agentId: string = created.agent.id
+ const pane = String(created.agent.terminal?.runtimes?.[0]?.paneId ?? created.agent.tmuxPane)
+ await until('the private Agy pane to be idle', async () => (await d.capture(pane)).includes('? for shortcuts') || null, 15_000, 100)
+ const callerPid = Number(readFileSync(join(d.root, 'agy.pid'), 'utf8'))
+ const hook = async (path: string, extra: Record<string, unknown> = {}) => {
+ const response = await fetch(`http://127.0.0.1:${d.port}/api/hook/${path}`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-harness-hook-token': d.hookCredential() },
+ body: JSON.stringify({ engine: 'agy', sessionId, tmuxPane: pane, cwd, transcriptPath, callerPid, ...extra }),
+ })
+ const body = await response.json()
+ expect(response.status, JSON.stringify(body)).toBe(200)
+ expect(body.ignored, JSON.stringify(body)).not.toBe(true)
+ return body
+ }
+ await hook('session-start', { hookEvent: 'SessionStart' })
+ await until('Agy history to attach', () => d.log().includes('attached · engine=agy') || null, 30_000, 100)
+ const rows = async () => (await c.request('agents_list', {})).agents as Array<Record<string, any>>
+ const attached = (await rows()).find(row => row.id === agentId)
+ expect(attached?.sessionId).toBe(sessionId)
+ expect(attached?.activity?.state).not.toBe('working')
+ expect(c.frames.filter(frame => frame.type === 'turn_started' && frame.agentId === agentId)).toHaveLength(0)
+ const history = await c.request('session_get', { sessionId: agentId, limit: 10 })
+ expect(history.error, JSON.stringify(history)).toBeUndefined()
+ expect(JSON.stringify(history.events)).toContain('Old answer')
+
+ const started = c.next(frame => frame.type === 'turn_started' && frame.agentId === agentId, 15_000, 'the next live Agy turn')
+ appendFileSync(transcriptPath, step('USER_INPUT', 2, '<USER_REQUEST>New prompt</USER_REQUEST>'))
+ expect((await started).replay).toBeFalsy()
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agentId, 15_000, 'the live Agy Stop')
+ appendFileSync(transcriptPath, step('PLANNER_RESPONSE', 3, 'New answer'))
+ await hook('turn-stop', { hookEvent: 'Stop' })
+ await ended
+ expect(d.coresStarted()).toBe(1)
+}, 90_000)
diff --git a/cli/src/core/engines/runtimeProfiles.spec.ts b/cli/src/core/engines/runtimeProfiles.spec.ts
index 881f82821..47c828e63 100644
--- a/cli/src/core/engines/runtimeProfiles.spec.ts
+++ b/cli/src/core/engines/runtimeProfiles.spec.ts
@@ -60,6 +60,17 @@ describe('runtime profile routing', () => {
expect(t.read).not.toHaveBeenCalled()
})
+ it.each([false, true])('routes a profile capture with its authority intact (worker: %s)', async isolated => {
+ const t = setup(isolated), capture = vi.fn(async () => 'vendor pane')
+ const inline = vi.spyOn(t.local, 'capturePane').mockResolvedValue('vendor pane')
+ expect(await t.profiles.capturePane(t.session, capture)).toBe('vendor pane')
+ if (isolated) {
+ expect(capture).toHaveBeenCalledWith(t.session.agentId, undefined)
+ expect(t.read).toHaveBeenCalledWith('codex', expect.anything(), { kind: 'pane', text: 'vendor pane' })
+ expect(inline).not.toHaveBeenCalled()
+ } else expect(inline).toHaveBeenCalledWith(t.session, capture, undefined, false)
+ })
+
it('stages compact evidence atomically and rejects frames from unsupported workers', async () => {
const t = setup(), { profiles: p, session: s } = t
const stage = p.beginHydrate(s)
diff --git a/cli/src/core/engines/runtimeProfiles.ts b/cli/src/core/engines/runtimeProfiles.ts
index 02a9c08da..0f84a4a5a 100644
--- a/cli/src/core/engines/runtimeProfiles.ts
+++ b/cli/src/core/engines/runtimeProfiles.ts
@@ -86,6 +86,8 @@ export function createRuntimeProfiles({ local, handles, resolve, transport }: Ru
ingestPane(session: RegisteredSession, text: string, silent = false): boolean | Promise<boolean> {
return handles(session.engine) ? observe(session, { kind: 'pane', text }, silent) : local.ingestPane(session, text, silent)
},
+ capturePane: (session: RegisteredSession, capture: (id: string, historyLines?: number) => Promise<string | null>,
+ historyLines?: number, silent = false) => forSession(session).capturePane(session, capture, historyLines, silent),
ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {
return handles(session.engine) ? observe(session, { kind: 'config' }, silent) : local.ingestConfig(session, silent)
},
diff --git a/cli/src/core/engines/runtimeSessions.spec.ts b/cli/src/core/engines/runtimeSessions.spec.ts
index 25e8bb657..f07cfaea6 100644
--- a/cli/src/core/engines/runtimeSessions.spec.ts
+++ b/cli/src/core/engines/runtimeSessions.spec.ts
@@ -4,6 +4,7 @@ import type { RuntimeContext, RuntimeProfile } from '../../engines/facets/runtim
import type { RuntimeAnswer, RuntimeOperation } from '../../engines/worker/runtimeProtocol.js'
import { blankRuntimeState, encodeRuntimeProfile } from '../../engines/kit/runtime.js'
import { createRuntimeSessions, type RuntimeSessions } from './runtimeSessions.js'
+import { EngineReadError } from '../../engines/worker/protocol.js'
const active: RuntimeSessions[] = []
const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }
@@ -43,6 +44,50 @@ function setup() {
afterEach(() => { active.splice(0).forEach(s => s.stop()); vi.useRealTimers(); vi.restoreAllMocks() })
describe('core runtime profile authority', () => {
+ it.each(['binding', 'route', 'control', 'version', 'forget', 'unchanged'] as const)(
+ 'keeps pane capture tied to the authority that dispatched it: %s', async change => {
+ const t = setup(); await t.seed()
+ t.s.runtimes = [{ backend: 'tmux', paneId: '%1' }]
+ await t.seed()
+ const captured = deferred<string | null>()
+ const pending = t.sessions.capturePane(t.s, () => captured.promise)
+ if (change === 'binding') t.s.boundAt = 2
+ if (change === 'route') t.s.runtimes[0]!.paneId = '%2'
+ if (change === 'control') { t.sessions.beginControl(t.s, profile(t.s)); t.sessions.cancelControl(t.s.agentId) }
+ if (change === 'version') t.s.cliVersion = 'new-version'
+ if (change === 'forget') t.sessions.forget(t.s.agentId)
+ captured.resolve('captured-model')
+ expect(await pending).toBe(change === 'unchanged' ? 'captured-model' : null)
+ expect(t.sessions.getState(t.s.agentId).model === 'captured-model').toBe(change === 'unchanged')
+ },
+ )
+
+ it('discards capture authority superseded while queued or while its worker replies', async () => {
+ for (const during of ['queue', 'worker'] as const) {
+ const t = setup(); await t.seed()
+ const entered = deferred<void>(), release = deferred<void>()
+ t.read.mockImplementationOnce(async (_e, c, o) => { entered.resolve(); await release.promise; return result(c, o) })
+ const ahead = during === 'queue' ? t.sessions.read(t.s, { kind: 'config' }) : undefined
+ const pending = t.sessions.capturePane(t.s, async () => 'captured-model', 60, true)
+ await entered.promise
+ if (during === 'worker') t.sessions.beginControl(t.s, profile(t.s))
+ release.resolve()
+ await ahead
+ expect(await pending, during).toBeNull()
+ expect(t.sessions.getState(t.s.agentId).model).toBe('old')
+ }
+ })
+
+ it('preserves empty-capture and worker-unavailable outcomes', async () => {
+ const t = setup(); await t.seed()
+ expect(await t.sessions.capturePane(t.s, async () => null)).toBeNull()
+ for (const error of [new Error('worker failed'), new EngineReadError('ENGINE_UNAVAILABLE')]) {
+ t.read.mockRejectedValueOnce(error)
+ await expect(t.sessions.capturePane(t.s, async () => 'pane')).rejects.toBe(error)
+ expect(t.sessions.getState(t.s.agentId).model).toBe('old')
+ }
+ })
+
it('stages bounded evidence and installs profile and live cursor together only once', async () => {
const t = setup(); await t.seed()
const staged = t.sessions.stage(t.s, true, true)
diff --git a/cli/src/core/engines/runtimeSessions.ts b/cli/src/core/engines/runtimeSessions.ts
index 9921296af..863eb5436 100644
--- a/cli/src/core/engines/runtimeSessions.ts
+++ b/cli/src/core/engines/runtimeSessions.ts
@@ -31,7 +31,8 @@ export interface RuntimeStage {
commit(install?: () => boolean): boolean
}
-const binding = (s: RegisteredSession | undefined): string => s ? JSON.stringify([transcriptReadIdentity(s), s.cwd, !!s.gateway]) : ''
+const binding = (s: RegisteredSession | undefined): string => s ? JSON.stringify([transcriptReadIdentity(s), s.cwd, !!s.gateway,
+ s.active, s.tmuxPane, s.primaryRuntimeKey, s.runtimes]) : ''
const snapshot = (s: RegisteredSession): RuntimeSession => ({ agentId: s.agentId, sessionId: s.sessionId, engine: s.engine,
model: typeof s.model === 'string' ? s.model : null, cliVersion: s.cliVersion, cwd: s.cwd, transcriptPath: s.transcriptPath, codexHome: s.codexHome })
const controlCopy = (control: RuntimeControl | undefined): RuntimeControl | undefined => control && { ...control, target: { ...control.target } }
@@ -128,10 +129,10 @@ export function createRuntimeSessions(deps: RuntimeSessionDeps) {
wake(view.sessionId)
if (!silent && !suppressed && before !== view.selected && !view.control) notify(view)
}
- const read = (s: RegisteredSession, operation: RuntimeOperation, silent = false): Promise<RuntimeAnswer> => {
+ const read = (s: RegisteredSession, operation: RuntimeOperation, silent = false, stillCurrent = () => true): Promise<RuntimeAnswer> => {
const identity = binding(s), view = viewFor(s)
return slot(s.engine, async () => {
- if (!valid(view) || view.identity !== identity) unavailable()
+ if (!valid(view) || view.identity !== identity || !stillCurrent()) unavailable()
const current = deps.resolve(view.agentId)!, version = current.cliVersion, revision = view.revision
const answer = await deps.transport.read(current.engine, contextFor(current, view), operation)
if (!valid(view) || revision !== view.revision || deps.resolve(view.agentId)?.cliVersion !== version) unavailable()
@@ -192,6 +193,21 @@ export function createRuntimeSessions(deps: RuntimeSessionDeps) {
}
return {
read,
+ async capturePane(s: RegisteredSession, capture: (id: string, historyLines?: number) => Promise<string | null>,
+ historyLines?: number, silent = false): Promise<string | null> {
+ const view = viewFor(s), revision = view.revision, version = s.cliVersion
+ const current = () => valid(view) && view.revision === revision && deps.resolve(view.agentId)?.cliVersion === version
+ const text = await capture(s.agentId, historyLines)
+ if (!text || !current()) return null
+ try {
+ // Authority can also change while this observation waits behind another worker request.
+ await read(s, { kind: 'pane', text }, silent, current)
+ return text
+ } catch (error) {
+ if (error instanceof EngineReadError && error.code === 'ENGINE_STALE_REPLY') return null
+ throw error
+ }
+ },
stage,
async prepare(s: RegisteredSession, records: readonly RuntimeRecord[]): Promise<() => boolean> {
const pending = stage(s, false, false)
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 4103d2a49..e106635a1 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1066,6 +1066,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// (core/transcripts/attach.ts).
const attach = createAttach({
liveFor,
+ resolve: id => registry.resolve(id),
remoteLive: engineLive,
terminalGone: terminalControl.terminalGone,
normalizers,
@@ -2128,10 +2129,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
await runtimeProfiles.withoutChangeEvents(async () => {
await Promise.all(registry.advertised().map((session) => runtimeProfiles.ingestConfig(session, true)))
await watcher.pollAll()
- await Promise.all(registry.advertised().map(async (session) => {
- const capture = await captureTerminal(session.agentId, 120)
- if (capture) await runtimeProfiles.ingestPane(session, capture, true)
- }))
+ await Promise.all(registry.advertised().map(session => runtimeProfiles.capturePane(session, captureTerminal, 120, true)))
})
await syncTerminalTitles()
const includeDevice = reconcileNeedsDeviceAnnouncement
@@ -2176,9 +2174,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
setInterval(() => {
for (const session of registry.list()) {
if (!PANE_POLLED_ENGINES.has(session.engine)) continue
- void captureTerminal(session.agentId, 60)
- .then((capture) => capture ? runtimeProfiles.ingestPane(session, capture) : undefined)
- .catch(() => undefined)
+ void runtimeProfiles.capturePane(session, captureTerminal, 60).catch(() => undefined)
}
}, PANE_POLL_MS)
diff --git a/cli/src/core/terminals/control.spec.ts b/cli/src/core/terminals/control.spec.ts
index 44e33e9ec..3d8945db0 100644
--- a/cli/src/core/terminals/control.spec.ts
+++ b/cli/src/core/terminals/control.spec.ts
@@ -84,6 +84,43 @@ describe('terminal control', () => {
])
})
+ it.each([false, true])('discards an old pane after its binding changes while capture is pending (leased: %s)', async leased => {
+ for (const change of ['session', 'route', 'process', 'replacement', 'removed'] as const) {
+ const { terminals } = backend()
+ let current: RegisteredSession | undefined = { ...session, engine: 'codex', boundAt: 1,
+ tmuxPane: '%1', primaryRuntimeKey: 'tmux\u0000%1', runtimes: [{ backend: 'tmux', paneId: '%1' }],
+ processIdentity: { pid: 123, startMarker: 'before', executable: 'codex' } }
+ const control = createTerminalControl({ resolve: () => current, terminals })
+ if (leased) await control.submitTerminal(current.agentId, 'first')
+ let finish!: (result: { state: 'succeeded'; value: string }) => void
+ const pending = new Promise<{ state: 'succeeded'; value: string }>(resolve => { finish = resolve })
+ const capture = vi.mocked(leased ? terminals.captureLease : terminals.capture).mockReturnValueOnce(pending)
+ const reading = control.captureTerminal(current.agentId)
+ await vi.waitFor(() => expect(capture).toHaveBeenCalled())
+ if (change === 'session') { current.sessionId = 'session-2'; current.boundAt = 2 }
+ if (change === 'route') current.runtimes[0]!.paneId = '%2'
+ if (change === 'process') current.processIdentity!.startMarker = 'after'
+ if (change === 'replacement') current = { ...current, engine: 'claude' }
+ if (change === 'removed') current = undefined
+ finish({ state: 'succeeded', value: 'old pane' })
+ await expect(reading, change).resolves.toBeNull()
+ }
+ })
+
+ it('does not begin a capture after the binding changes during lease validation', async () => {
+ const { terminals } = backend()
+ const current = { ...session }
+ const control = createTerminalControl({ resolve: () => current, terminals })
+ await control.submitTerminal(current.agentId, 'first')
+ vi.mocked(terminals.validateLease).mockImplementationOnce(async () => {
+ current.sessionId = 'session-2'
+ return true
+ })
+ expect(await control.captureTerminal(current.agentId)).toBeNull()
+ expect(terminals.captureLease).not.toHaveBeenCalled()
+ expect(terminals.capture).not.toHaveBeenCalled()
+ })
+
it('keeps a lease while it is used, and takes a new one once it lapses or stops validating', async () => {
const { fake, terminals } = backend()
const control = createTerminalControl({ resolve, terminals })
diff --git a/cli/src/core/terminals/control.ts b/cli/src/core/terminals/control.ts
index 0d9c55901..62a484157 100644
--- a/cli/src/core/terminals/control.ts
+++ b/cli/src/core/terminals/control.ts
@@ -10,6 +10,7 @@
import type { RegisteredSession } from '../../lib/registry.js'
import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'
import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type SubmitOptions, type TerminalActionResult } from '../../lib/terminalTypes.js'
+import { paneReadIdentity } from '../transcripts/readIdentity.js'
export type TerminalControlBackend = Pick<TerminalBackendCoordinator,
'acquireLease' | 'validateLease' | 'capture' | 'captureLease' | 'submitText' | 'submitTextLease'
@@ -65,6 +66,10 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep
const captureTerminal = async (target: string, historyLines?: number): Promise<string | null> => {
const session = terminalSession(target)
if (!session) return null
+ // Registry rows (including their runtime/process objects) can change in place while tmux reads.
+ // Copy the identity before yielding so no caller interprets an old pane as the new conversation.
+ const agentId = session.agentId, identity = paneReadIdentity(session)
+ const current = () => paneReadIdentity(resolve(agentId)) === identity
const pinned = pinnedControls.has(session.agentId)
if (pinned && invalidControls.has(session.agentId)) return null
let activeLease = controlLeases.get(session.agentId)
@@ -74,10 +79,11 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep
}
const leased = activeLease || pinned ? await leasedTerminal(session) : null
if ((activeLease || pinned) && !leased) return null
+ if (!current()) return null
const result = leased
? await terminals.captureLease(leased.value, { historyLines })
: await terminals.capture(session, { historyLines })
- return result.state === 'succeeded' ? result.value : null
+ return result.state === 'succeeded' && current() ? result.value : null
}
const terminalActionSucceeded = (result: Awaited<ReturnType<typeof terminals.submitText>>): boolean =>
result.state === 'succeeded'
diff --git a/cli/src/core/transcripts/attach.runtime.spec.ts b/cli/src/core/transcripts/attach.runtime.spec.ts
index e27ca87e5..ba78b4920 100644
--- a/cli/src/core/transcripts/attach.runtime.spec.ts
+++ b/cli/src/core/transcripts/attach.runtime.spec.ts
@@ -34,7 +34,7 @@ function setup() {
normalizers.liveParsers.set(session.sessionId, oldParser)
const hold = { offset: statSync(path).size, expired: false, release: vi.fn() }
const emit = vi.fn(), addSession = vi.fn(async () => {})
- const attach = createAttach({ liveFor, normalizers, runtimeProfiles: profiles,
+ const attach = createAttach({ liveFor, normalizers, runtimeProfiles: profiles, resolve: () => session,
terminalGone: async () => false, watcher: { hold: async () => hold, tails: () => true, addSession },
cursorDiscovery: { add: async () => {} }, device: () => undefined,
captureTerminal: async () => null, emit, announceTurnAborted: vi.fn(),
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
index 7c2a2ec28..122bbbe76 100644
--- a/cli/src/core/transcripts/attach.spec.ts
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -21,16 +21,18 @@ const fakes = vi.hoisted(() => {
const made: Array<{ kind: string; args: unknown[]; instance: Record<string, any> }> = []
const normalizer = (kind: string) => class {
turnOpen = false
+ turnRevision = 0
thinkingPrefix = ''
args: unknown[]
constructor(...args: unknown[]) { this.args = args; made.push({ kind, args, instance: this as Record<string, any> }) }
ingest(line: string) {
+ this.turnRevision++
const record = JSON.parse(line || '{}') as { events?: unknown[]; open?: boolean; close?: boolean }
if (record.open) this.turnOpen = true
if (record.close) this.turnOpen = false
return record.events ?? []
}
- closeTurn() { this.turnOpen = false; return [] }
+ closeTurn() { this.turnRevision++; this.turnOpen = false; return [] }
}
const reader = (kind: string) => class {
turnOpen = false
@@ -59,6 +61,7 @@ vi.mock('../../engines/hermes/reader.js', async (real) => ({ ...await real<objec
vi.mock('../../engines/devin/reader.js', async (real) => ({ ...await real<object>(), DevinReader: fakes.reader('devin') }))
const dirs: string[] = []
+const bindings = new Map<string, RegisteredSession>()
const transcript = (lines: unknown[] = []): string => {
const dir = mkdtempSync(join(tmpdir(), 'core-attach-'))
dirs.push(dir)
@@ -66,8 +69,11 @@ const transcript = (lines: unknown[] = []): string => {
writeFileSync(file, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + (lines.length ? '\n' : ''))
return file
}
-const session = (engine: string, transcriptPath?: string, over: Partial<RegisteredSession> = {}): RegisteredSession =>
- ({ agentId: `${engine}-agent`, sessionId: `${engine}-s`, engine, transcriptPath, ...over }) as RegisteredSession
+const session = (engine: string, transcriptPath?: string, over: Partial<RegisteredSession> = {}): RegisteredSession => {
+ const value = { agentId: `${engine}-agent`, sessionId: `${engine}-s`, engine, transcriptPath, ...over } as RegisteredSession
+ bindings.set(value.agentId, value)
+ return value
+}
// Each engine's code is loaded in this process before an attach folds; a test may say it could not be.
vi.mock('../../engines/inProcess.js', async (real) => {
@@ -85,6 +91,7 @@ function setup(over: Partial<AttachDeps> = {}) {
const profile = { ingest: vi.fn(), commit: vi.fn() }
const deps: AttachDeps = {
liveFor,
+ resolve: id => bindings.get(id),
terminalGone: vi.fn(async () => false),
normalizers,
watcher: { addSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },
@@ -94,9 +101,14 @@ function setup(over: Partial<AttachDeps> = {}) {
transcriptFields: vi.fn(() => []),
beginHydrate: vi.fn(() => profile),
hydrate: vi.fn(),
- ingestConfig: vi.fn(async () => {}),
- ingestPane: vi.fn(),
- } as unknown as AttachDeps['runtimeProfiles'],
+ ingestConfig: vi.fn(async () => false),
+ ingestPane: vi.fn(() => false),
+ capturePane: vi.fn(async (session, capture, lines, silent) => {
+ const text = await capture(session.agentId, lines)
+ if (text) await deps.runtimeProfiles.ingestPane(session, text, silent)
+ return text
+ }),
+ } as AttachDeps['runtimeProfiles'],
captureTerminal: vi.fn(async () => 'pane'),
emit: vi.fn(),
announceTurnAborted: vi.fn(),
@@ -178,6 +190,7 @@ describe('attaching a session', () => {
vi.useRealTimers()
fakes.made.length = 0
fakes.copilotOpen.value = true
+ bindings.clear()
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
@@ -647,6 +660,67 @@ describe('attaching a session', () => {
expect(vi.mocked(run.deps.emit).mock.calls.filter((call) => call[2]?.resumed).map((call) => call[0])).toEqual(['agy-2', 'copilot-2'])
})
+ it('closes an idle agy history turn even when newer profile evidence discards the chip update', async () => {
+ const run = setup({ settled: vi.fn() })
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue(IDLE_AGY)
+ vi.mocked(run.deps.runtimeProfiles.capturePane).mockImplementationOnce(async (_session, capture, lines) => {
+ await capture('agy-agent', lines)
+ return null
+ })
+ await run.attach.attachSession(session('agy', transcript([{ events: [started()], open: true }])))
+ expect(made('agy')[0].turnOpen).toBe(false)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.settled).toHaveBeenCalledExactlyOnceWith('agy-s')
+ })
+
+ it.each(['binding', 'forgotten', 'new turn', 'later binding', 'later normalizer', 'later turn'] as const)(
+ 'does not close or replay agy history after %s supersedes its capture', async change => {
+ const run = setup({ settled: vi.fn() }), s = session('agy', transcript([{ events: [started()], open: true }]))
+ let finish!: (value: string) => void
+ vi.mocked(run.deps.captureTerminal).mockReturnValueOnce(new Promise<string>(resolve => { finish = resolve }))
+ const mutate = () => {
+ if (change.includes('binding')) bindings.set(s.agentId, { ...s, boundAt: 2 })
+ if (change === 'forgotten' || change === 'later normalizer') run.normalizers.agyNormalizers.delete(s.sessionId)
+ if (change.includes('turn')) made('agy')[0].ingest(JSON.stringify({ open: true }))
+ }
+ if (change.startsWith('later')) vi.mocked(run.deps.runtimeProfiles.capturePane).mockImplementationOnce(async (_s, capture) => {
+ await capture(s.agentId)
+ queueMicrotask(mutate)
+ return null
+ })
+ const pending = run.attach.attachSession(s)
+ await vi.waitFor(() => expect(run.deps.captureTerminal).toHaveBeenCalled())
+ const normalizer = made('agy')[0], close = vi.spyOn(normalizer, 'closeTurn')
+ if (!change.startsWith('later')) mutate()
+ finish(change.startsWith('later') ? 'working\n esc to cancel' : IDLE_AGY)
+ await pending
+ expect(close).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.settled).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each(['new turn', 'binding', 'forgotten'] as const)(
+ 'keeps captured agy history fenced through watcher installation: %s', async change => {
+ for (const pane of [IDLE_AGY, 'working\n esc to cancel']) {
+ const run = setup({ settled: vi.fn() }), s = session('agy', transcript([{ events: [started()], open: true }]))
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue(pane)
+ let finish!: () => void
+ vi.mocked(run.deps.watcher.addSession).mockReturnValueOnce(new Promise<void>(resolve => { finish = resolve }))
+ const pending = run.attach.attachSession(s)
+ await vi.waitFor(() => expect(run.deps.watcher.addSession).toHaveBeenCalled())
+ const normalizer = run.normalizers.agyNormalizers.get(s.sessionId)!
+ if (change === 'new turn') normalizer.ingest(JSON.stringify({ open: true }))
+ if (change === 'binding') bindings.set(s.agentId, { ...s, boundAt: 2 })
+ if (change === 'forgotten') run.normalizers.agyNormalizers.delete(s.sessionId)
+ finish()
+ await pending
+ expect(run.deps.emit, pane).not.toHaveBeenCalled()
+ expect(run.deps.settled, pane).not.toHaveBeenCalled()
+ }
+ },
+ )
+
it('tells the recaps when the last turn was already over at attach, never for one open or killed', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const settled = vi.fn()
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
index 9448c6790..6436ad266 100644
--- a/cli/src/core/transcripts/attach.ts
+++ b/cli/src/core/transcripts/attach.ts
@@ -26,10 +26,12 @@ import type { TailHold, Watcher } from '../../watcher/watcher.js'
import type { SessionNormalizers } from './normalizers.js'
import type { RelaunchMarks } from './relaunch.js'
import { createSideReads } from './sideReads.js'
+import { paneReadIdentity } from './readIdentity.js'
import type { LiveSessions, PreparedLive } from '../engines/liveSessions.js'
export interface AttachDeps {
liveFor: LiveFor
+ resolve: (agentId: string) => RegisteredSession | undefined
remoteLive?: Pick<LiveSessions, 'handles' | 'current' | 'prepare' | 'install' | 'discard' | 'retry'>
/** Whether the session's terminal is known to be gone (core/terminals/control.ts `terminalGone`). */
terminalGone: (session: RegisteredSession) => Promise<boolean>
@@ -38,7 +40,7 @@ export interface AttachDeps {
cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>
/** The Wi-Fi device's service, wherever it runs (core/wifi.ts): it proves its turns by the raw transcript. */
device: () => Pick<WifiFeed, 'needsTranscript' | 'observeTranscript'> | undefined
- runtimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'hydrate' | 'ingestConfig'> & {
+ runtimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'hydrate' | 'ingestConfig' | 'capturePane'> & {
beginHydrate(session: RegisteredSession): ProfileHydration
ingestPane(session: RegisteredSession, text: string, silent?: boolean): boolean | Promise<boolean>
}
@@ -64,7 +66,7 @@ export interface AttachDeps {
}
export function createAttach({
- liveFor, remoteLive, terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
+ liveFor, resolve, remoteLive, terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,
wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled,
}: AttachDeps) {
@@ -171,6 +173,8 @@ export function createAttach({
|| (session.engine === 'cursor' && replayCursorFromStart))
const historyEvents: LiveEvent[] = []
let historyTurnOpen = false
+ let historySuperseded = false
+ let historyCurrent: (() => boolean) | undefined
let observed = false
sideRead('device', session.sessionId, () => { observed = !!device()?.needsTranscript(session.agentId, session.sessionId, session.engine) })
const observe = observed
@@ -302,8 +306,7 @@ export function createAttach({
const normalizer = new (engine('cursor')!).CursorNormalizer('live', session.sessionId)
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
cursorNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 100)
- if (capture) await runtimeProfiles.ingestPane(session, capture, true)
+ await runtimeProfiles.capturePane(session, captureTerminal, 100, true)
} else if (engine('opencode')) {
// OpenCode has no transcript file — poll its SQLite DB. The reader hydrates silently, then
// streams new activity into the funnel (the same one the file engines use).
@@ -318,8 +321,7 @@ export function createAttach({
// The composer footer is the ONLY place OpenCode names its model and reasoning level, so
// without this a freshly opened agent showed empty chips until the five-minute reconcile came
// round — which is exactly how long it looked broken for.
- const ocPane = await captureTerminal(session.agentId, 100)
- if (ocPane) await runtimeProfiles.ingestPane(session, ocPane, true)
+ await runtimeProfiles.capturePane(session, captureTerminal, 100, true)
} else if (engine('kilo')) {
// Kilo is opencode's fork and keeps the same store shape, so it is polled the same way — but from
// its OWN db and through its own reader, so the two can diverge without one breaking the other.
@@ -346,8 +348,7 @@ export function createAttach({
const normalizer = new (engine('grok')!).GrokNormalizer()
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
grokNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 60)
- if (capture) await runtimeProfiles.ingestPane(session, capture, true)
+ await runtimeProfiles.capturePane(session, captureTerminal, 60, true)
} else if (engine('agy')) {
const agy = engine('agy')!
// A JSONL tail like claude/grok. agy announces its model only in the hook payload and its pane
@@ -355,15 +356,35 @@ export function createAttach({
const normalizer = new agy.AgyNormalizer()
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
agyNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 60)
- if (capture) await runtimeProfiles.ingestPane(session, capture, true)
// agy's transcript has no end-of-turn record - only its Stop hook does - so a fold of a FINISHED
// conversation still reports the last turn as open, and after a daemon restart nothing is ever
// coming to close it. The pane is the one place the answer exists; ask it.
- if (historyTurnOpen && capture && agy.agyPaneIdle(capture)) {
- normalizer.closeTurn()
- historyTurnOpen = false
+ const agentId = session.agentId, sessionId = session.sessionId, identity = paneReadIdentity(session)
+ const revision = normalizer.turnRevision
+ let observedRevision = revision
+ let current = true
+ historyCurrent = () => paneReadIdentity(resolve(agentId)) === identity
+ && agyNormalizers.get(sessionId) === normalizer && normalizer.turnRevision === observedRevision
+ const capturing = captureTerminal(agentId, 60)
+ await Promise.all([
+ runtimeProfiles.capturePane(session, () => capturing, 60, true),
+ capturing.then(capture => {
+ // Turn closing owns its own authority: accepting a chip update is not a prerequisite.
+ current = paneReadIdentity(resolve(agentId)) === identity && agyNormalizers.get(sessionId) === normalizer
+ if (!current) return
+ if (normalizer.turnRevision !== revision) { historySuperseded = true; return }
+ if (historyTurnOpen && capture && agy.agyPaneIdle(capture)) {
+ normalizer.closeTurn()
+ historyTurnOpen = false
+ }
+ observedRevision = normalizer.turnRevision
+ }),
+ ])
+ if (!current || paneReadIdentity(resolve(agentId)) !== identity || agyNormalizers.get(sessionId) !== normalizer) {
+ if (agyNormalizers.get(sessionId) === normalizer) agyNormalizers.delete(sessionId)
+ return keepLiveNormalizer('changed binding while its pane was read')
}
+ if (normalizer.turnRevision !== observedRevision) historySuperseded = true
} else if (engine('copilot')) {
const copilot = engine('copilot')!
// A JSONL tail like claude/agy. Its turn lifecycle comes from the agentStop hook, not the file —
@@ -412,8 +433,7 @@ export function createAttach({
await reader.start()
// Devin's model/effort exist ONLY in its pane footer, so read it now. Without this the chip stayed
// on Auto until the 5-minute reconcile happened to run — the attach itself said nothing about it.
- const devinPane = await captureTerminal(session.agentId, 60)
- if (devinPane) await runtimeProfiles.ingestPane(session, devinPane, true)
+ await runtimeProfiles.capturePane(session, captureTerminal, 60, true)
} else if (engine('commandcode')) {
const normalizer = new (engine('commandcode')!).CommandCodeNormalizer('live')
// Hydrate state silently; never replay history live — except a turn left open, below.
@@ -422,7 +442,7 @@ export function createAttach({
}
// Close the old engine's turn before starting the tail: addSession may synchronously deliver a
// new turn written after resume. Closing afterward would abandon that new turn instead.
- const abandonedHistory = historyTurnOpen && relaunch?.engineStarted
+ const abandonedHistory = !historySuperseded && historyTurnOpen && relaunch?.engineStarted
if (abandonedHistory) {
console.log(`[agent] ${sid(session.agentId)} left the turn open at attach as history · it began before its engine was started again`)
const folds: Array<Map<string, { closeTurn(): unknown }>> = [cursorNormalizers, museNormalizers, ampNormalizers,
@@ -458,7 +478,9 @@ export function createAttach({
// Any fold of a transcript with content counts too: the watcher now tails it from the end, so a later
// replay could only send history out again as if it were live.
if (replayLive || lines.length || fromEnd?.content) replayedFirstTurn.add(session.sessionId)
- if (initialEvents.length) {
+ // Installing the file watcher also yields. The final history consumer must still own the capture.
+ if (historyCurrent && !historyCurrent()) historySuperseded = true
+ if (!historySuperseded && initialEvents.length) {
emit(session.sessionId, initialEvents)
console.log(`[agent] ${sid(session.agentId)} replayed the first turn its transcript already held · ${initialEvents.length} events`)
}
@@ -473,7 +495,7 @@ export function createAttach({
// Nor for a turn left open before a new engine was started on the conversation (a resume, or a restore
// that rebuilt the pane): that turn died with the engine before, and announcing it showed the
// interrupted message starting anew (core/transcripts/relaunch.ts).
- if (historyTurnOpen && !handover.hold && !abandonedHistory) {
+ if (!historySuperseded && historyTurnOpen && !handover.hold && !abandonedHistory) {
const opened = historyEvents.findLast((event) => event.type === 'turn_started')
if (opened) {
console.log(`[agent] ${sid(session.agentId)} resumed the turn already open at attach`)
@@ -496,7 +518,7 @@ export function createAttach({
// A fold from the end keeps only the last turn's start as history (lib/normalize.ts TranscriptFold), so a turn
// that is no longer open is one that ended; a fold from the start keeps its end too, and says if it was killed.
const last = historyEvents.findLast((event) => event.type === 'turn_started' || event.type === 'turn_ended')
- if (!historyTurnOpen && last && !(last.type === 'turn_ended' && last.payload.aborted)) settled?.(session.sessionId)
+ if (!historySuperseded && !historyTurnOpen && last && !(last.type === 'turn_ended' && last.payload.aborted)) settled?.(session.sessionId)
return true
}
diff --git a/cli/src/core/transcripts/readIdentity.ts b/cli/src/core/transcripts/readIdentity.ts
index 24a50659a..cee5abda5 100644
--- a/cli/src/core/transcripts/readIdentity.ts
+++ b/cli/src/core/transcripts/readIdentity.ts
@@ -7,3 +7,9 @@ export function transcriptReadIdentity(session: RegisteredSession | undefined):
session.codexHome, session.boundAt,
session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined]) : ''
}
+
+/** A pane belongs to its process, conversation and current terminal routes. Copy before capture. */
+export function paneReadIdentity(session: RegisteredSession | undefined): string {
+ return session ? JSON.stringify([transcriptReadIdentity(session), session.active, session.cwd, session.hermesHome,
+ session.tmuxPane, session.primaryRuntimeKey, session.runtimes]) : ''
+}
diff --git a/cli/src/engines/agy/normalizer.spec.ts b/cli/src/engines/agy/normalizer.spec.ts
index 80f4dde58..92ca8e6f9 100644
--- a/cli/src/engines/agy/normalizer.spec.ts
+++ b/cli/src/engines/agy/normalizer.spec.ts
@@ -173,6 +173,23 @@ describe('agy normalizer, over a real recorded session', () => {
expect(normalizer.ingest('[]')).toEqual([])
expect(agyStep('{"step_index":1}')).toBeNull()
})
+
+ it('invalidates an earlier pane observation when the turn changes, even across close and reopen', () => {
+ const normalizer = new AgyNormalizer()
+ const initial = normalizer.turnRevision
+ normalizer.ingest('not json')
+ expect(normalizer.turnRevision).toBe(initial)
+ normalizer.ingest(JSON.stringify({ type: 'USER_INPUT', content: 'hello' }))
+ const captured = normalizer.turnRevision
+ expect(captured).toBeGreaterThan(initial)
+ normalizer.closeTurn()
+ normalizer.ingest(JSON.stringify({ type: 'USER_INPUT', content: 'hello' }))
+ expect(normalizer.turnOpen).toBe(true)
+ expect(normalizer.turnRevision).toBeGreaterThan(captured)
+ const reopened = normalizer.turnRevision
+ normalizer.abortTurn()
+ expect(normalizer.turnRevision).toBeGreaterThan(reopened)
+ })
})
describe('agy pure mappings', () => {
diff --git a/cli/src/engines/agy/normalizer.ts b/cli/src/engines/agy/normalizer.ts
index 5988d6170..3bda1dff6 100644
--- a/cli/src/engines/agy/normalizer.ts
+++ b/cli/src/engines/agy/normalizer.ts
@@ -322,12 +322,16 @@ export function agyStepToEvents(step: AgyStep, state: AgyTurnState, mode: 'live'
export class AgyNormalizer implements EngineNormalizer {
private state = newAgyTurnState()
+ private revision = 0
get turnOpen(): boolean { return this.state.open }
+ /** A capture dispatched before newer transcript or turn evidence cannot close this state. */
+ get turnRevision(): number { return this.revision }
/** The `Stop` hook fired: close every row this turn opened, then the turn. */
closeTurn(): LiveEvent[] {
if (!this.state.open) return []
+ this.revision++
const events: LiveEvent[] = []
closeRows(this.state, events, 'completed')
this.state.open = false
@@ -339,6 +343,7 @@ export class AgyNormalizer implements EngineNormalizer {
abortTurn(): LiveEvent[] {
if (!this.state.open) return []
+ this.revision++
const events: LiveEvent[] = []
closeRows(this.state, events, 'failed')
this.state.open = false
@@ -350,6 +355,7 @@ export class AgyNormalizer implements EngineNormalizer {
ingest(line: string): LiveEvent[] {
const step = agyStep(line)
+ if (step) this.revision++
return step ? agyStepToEvents(step, this.state, 'live') : []
}
diff --git a/cli/src/engines/otherTranscripts.golden.spec.ts b/cli/src/engines/otherTranscripts.golden.spec.ts
index f5d216d6a..5456f5238 100644
--- a/cli/src/engines/otherTranscripts.golden.spec.ts
+++ b/cli/src/engines/otherTranscripts.golden.spec.ts
@@ -221,6 +221,7 @@ function livePath(core: Core, session: RegisteredSession, pane: string | null) {
const announceTurnAborted = (...args: unknown[]): void => { out.push(['aborted', ...args]) }
const attach = core.createAttach({
liveFor: () => undefined,
+ resolve: () => session,
terminalGone: async () => false,
normalizers,
watcher: {
@@ -233,6 +234,7 @@ function livePath(core: Core, session: RegisteredSession, pane: string | null) {
runtimeProfiles: {
transcriptFields: () => [], beginHydrate: () => ({ ingest: () => {}, commit: () => {} }), hydrate: () => {},
ingestConfig: async () => {}, ingestPane: () => false,
+ capturePane: async () => pane,
} as never,
captureTerminal: async () => pane,
emit: emit as never,
diff --git a/cli/src/lib/runtimeProfileState.spec.ts b/cli/src/lib/runtimeProfileState.spec.ts
index a1431bd59..30303a335 100644
--- a/cli/src/lib/runtimeProfileState.spec.ts
+++ b/cli/src/lib/runtimeProfileState.spec.ts
@@ -10,6 +10,7 @@ import { RuntimeProfileManager } from './runtimeProfile.js'
import { parseRuntimeProfile } from './runtimeProfileWire.js'
import { engineNow, loadEngine, OTHER_ENGINES } from '../engines/inProcess.js'
import type { InlineRuntimeContext } from '../engines/facets/inlineRuntime.js'
+import { createTerminalControl } from '../core/terminals/control.js'
// A test may say an engine's code could not be loaded.
vi.mock('../engines/inProcess.js', async (real) => {
@@ -71,6 +72,42 @@ describe('another engine whose code could not be loaded', () => {
})
describe('late optional profile observations', () => {
+ it.each(['binding', 'process', 'route', 'confirmation', 'forget', 'unchanged'] as const)(
+ 'fences a pane through the promise handoff to its profile consumer: %s', async change => {
+ const agent = { ...session('claude'), active: true, boundAt: 1, runtimes: [{ backend: 'tmux' as const, paneId: '%1' }],
+ processIdentity: { pid: 7, startMarker: 'before', executable: 'claude' } }
+ const manager = new RuntimeProfileState(() => ({ ...claudeRuntime, pane: ({ state }, text) => { state.model = text } }), () => agent)
+ manager.hydrate(agent, [])
+ let finish!: (value: { state: 'succeeded'; value: string }) => void
+ const backend = { capture: vi.fn(() => new Promise<{ state: 'succeeded'; value: string }>(resolve => { finish = resolve })) }
+ const terminal = createTerminalControl({ resolve: () => agent, terminals: backend as never })
+ const pending = manager.capturePane(agent, terminal.captureTerminal, 60, true)
+ finish({ state: 'succeeded', value: 'captured-model' })
+ // Runs after captureTerminal's own guard, but before its awaiting profile consumer resumes.
+ queueMicrotask(() => {
+ if (change === 'binding') { agent.sessionId = 'new-conversation'; agent.boundAt++ }
+ if (change === 'process') agent.processIdentity.startMarker = 'after'
+ if (change === 'route') agent.runtimes[0]!.paneId = '%2'
+ if (change === 'confirmation') manager.confirmEffort(agent.sessionId, 'high')
+ if (change === 'forget') manager.forget(agent.sessionId)
+ })
+ expect(await pending).toBe(change === 'unchanged' ? 'captured-model' : null)
+ expect(manager.getState(agent.sessionId).model === 'captured-model').toBe(change === 'unchanged')
+ manager.forget('conversation'); manager.forget(agent.sessionId)
+ },
+ )
+
+ it('does not capture for an unbound or detached profile, or ingest an empty pane', async () => {
+ const agent = session('claude'), capture = vi.fn(async () => null)
+ const manager = new RuntimeProfileState(() => claudeRuntime, () => agent)
+ expect(await manager.capturePane({ ...agent, sessionId: '' }, capture)).toBeNull()
+ expect(await manager.capturePane({ ...agent, boundAt: 2 }, capture)).toBeNull()
+ expect(capture).not.toHaveBeenCalled()
+ expect(await manager.capturePane(agent, capture)).toBeNull()
+ expect(capture).toHaveBeenCalledOnce()
+ manager.forget(agent.sessionId)
+ })
+
it.each(['explicit read', 'confirmation'] as const)('does not let a queued refresh supersede a newer %s', async newer => {
const config = vi.fn(async ({ state }: InlineRuntimeContext) => { state.effort = 'low'; return true })
const module = { createRuntimeProfileReader: () => ({ engine: 'commandcode', target: () => null, config,
diff --git a/cli/src/lib/runtimeProfileState.ts b/cli/src/lib/runtimeProfileState.ts
index 40330f5d4..611bac25d 100644
--- a/cli/src/lib/runtimeProfileState.ts
+++ b/cli/src/lib/runtimeProfileState.ts
@@ -8,6 +8,7 @@ export type { RuntimeProfile, RuntimeModelOption, RuntimeState, RuntimeField } f
import { encodeRuntimeProfile, record, stripAnsi, transcriptFields, RUNTIME_EFFORTS } from '../engines/kit/runtime.js'
export { encodeRuntimeProfile, runtimeModelLabel } from '../engines/kit/runtime.js'
import { engineNow, isOtherEngine, loadEngine } from '../engines/inProcess.js'
+import { processIdentityKey } from './terminalRuntime.js'
const blankState = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })
@@ -32,7 +33,8 @@ const EFFORTS = RUNTIME_EFFORTS
const CHANGE_DEBOUNCE_MS = 120
const readIdentity = (session: RegisteredSession): string => JSON.stringify([session.agentId, session.sessionId,
session.engine, session.cwd, session.transcriptPath, session.codexHome, session.hermesHome,
- session.model, session.cliVersion, session.boundAt, session.tmuxPane, session.primaryRuntimeKey, session.runtimes])
+ session.model, session.cliVersion, session.boundAt, session.tmuxPane, session.primaryRuntimeKey, session.runtimes,
+ session.active, session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined])
const copyControl = (control: RuntimeControl | undefined): RuntimeControl | undefined => control && {
...control, target: { ...control.target },
}
@@ -154,6 +156,18 @@ export class RuntimeProfileState {
return this.observed(session, before, silent)
}
+ /** Capture and consume one observation under the binding and authority that requested it. */
+ async capturePane(session: RegisteredSession, capture: (id: string, historyLines?: number) => Promise<string | null>,
+ historyLines?: number, silent = false): Promise<string | null> {
+ if (this.unbound(session.sessionId) || !this.currentSession(session)) return null
+ const id = session.sessionId, identity = readIdentity(session)
+ const state = this.state(id), version = this.version(state)
+ const text = await capture(session.agentId, historyLines)
+ if (!text || this.states.get(id) !== state || this.version(state) !== version || !this.currentSession(session, identity)) return null
+ this.ingestPane(session, text, silent)
+ return text
+ }
+
async ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {
if (this.unbound(session.sessionId) || !this.currentSession(session)) return false
const state = this.state(session.sessionId), version = this.version(state)
diff --git a/docs/research/2026-10-09-pane-capture-authority.md b/docs/research/2026-10-09-pane-capture-authority.md
new file mode 100644
index 000000000..4ada8e20d
--- /dev/null
+++ b/docs/research/2026-10-09-pane-capture-authority.md
@@ -0,0 +1,61 @@
+# Pane capture authority
+
+Runtime review found that pane polling and reconcile passed a mutable registry row
+through an awaited capture. A rebind during that read let an old footer update the
+new conversation. The same capture pattern was present at native-reader attach.
+This is a pre-existing race, separate from the runtime profile extraction.
+
+Commit `b73c05997` records failing tests against main: both leased and unleased
+captures return an old pane after the session changes. The terminal boundary now
+copies binding, process and route identity before waiting, and refuses changed
+identity after lease validation or capture. Ordinary activity updates do not
+invalidate the read.
+
+Independent design review identified a second window: the registry can change in
+a queued microtask after the terminal guard but before the profile consumer runs.
+Profile owners therefore capture and consume under one operation. They retain the
+original binding, state object and monotonically increasing evidence revision.
+The local owner checks before ingestion; the worker owner checks before joining
+its request queue, at dispatch, and when the worker returns. Forget, rebinding,
+route/process changes and newer control/evidence invalidate the capture. An empty
+or stale capture publishes nothing; an unavailable worker leaves accepted state
+unchanged. No core control depends on a worker becoming available.
+
+Reconcile, periodic profile polling and the five attach captures all use this
+operation. Agy turn closing consumes the raw capture under separate binding, normalizer
+identity and transcript/turn revision checks, before waiting for profile acceptance.
+A newer chip update cannot suppress a valid idle-history close; a newer turn or
+rebind cannot authorize closing or replaying the old history. The check is repeated
+after the profile promise settles. Superseded history is distinct from a finished
+turn: it produces neither replay nor a historical settlement notification. Returned
+profile text is not an authority receipt. Native interpretation stays with the same owner; fixture bytes for
+the runtime and transcript goldens stay unchanged.
+
+Validation is planned before running: typecheck; architecture; core and harnessd
+coverage at 100% statements and branches; affected terminal/profile/attach specs
+and unchanged goldens; isolated e2e for readers, model control, models, core,
+lifecycle and machine crash/resume. Deferred tests exercise the real terminal
+boundary plus local profile owner, including the promise handoff window. Worker
+tests cover control changes during capture, while queued and during its reply.
+All runs use UTC, `/tmp` and private daemon/tmux/native-home fixtures. The first final-head run passed typecheck, core/harnessd at 100% and 205 affected
+tests (`20261009T064606.422437Z-31957`). Independent review then required the
+separate Agy turn decision above, covered by seven new attach races and a real
+normalizer close/reopen revision test. Final receipts, exact-head review and merge
+timing follow in the PR body.
+
+## Previous follow-up completed
+
+The same-millisecond pane fix (#1091) merged as `47d2f5a6b` at 06:38:42 UTC.
+Its final head `c8650aa1f` was independently approved against `a9895b02c`.
+Typecheck, core/harnessd/resume coverage, 137 affected tests and 22 complete
+core/lifecycle/machine e2e cases passed. The earlier affected suite and Linux shard
+failed an old migration assertion that expected timestamp-only labels; the final
+test requires the correct prefix and UUID and exact returned rename arguments.
+[Final CI](https://github.com/autonomous-ai/openharness/actions/runs/37894181341)
+passed every selected check and `ci/required`.
+
+Implementation/regression work ran approximately 06:24–06:28 UTC; the migration
+expectation correction finished at 06:33. Validation and e2e ran 06:28–06:34,
+overlapping independent review. CI waiting followed; merge ran 06:38:28–06:38:42.
+The follow-up took about 15 minutes; total request elapsed through that merge was
+7 hours 12 minutes 1 second. Publication remains zero.