Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions src/main/agent-hooks/agent-hook-runtime-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export function agentHookRuntimeDeps(
readChildWorkHandles: (subject) => server.getStructuredChildWorkHandles(subject)
},
readHookCliWriterObservation: (row) => server.readCliWriterObservation(row),
readTerminalMailTarget: (paneKey) => server.readTerminalMailTarget(paneKey),
terminalMailTargetWasAbandoned: (target) => server.terminalMailTargetWasAbandoned(target),
checkHookAgentPresence: (paneKey, exitedSince) =>
exitedSince === undefined
? server.checkAgentPresence(paneKey)
Expand Down
33 changes: 33 additions & 0 deletions src/main/agent-hooks/server-agent-presence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,39 @@ function visible(server: AgentHookServer): boolean {
}

describe('host-owned hook presence', () => {
it('retains exact abandoned mail target proof across an idle successor, but not its next root turn', async () => {
const server = await createServer()
await hook(server, 'SessionStart')
await hook(server, 'UserPromptSubmit')
const target = server.readTerminalMailTarget(PANE)
expect(target).not.toBeNull()
if (!target) {
throw new Error('Missing open root target')
}
expect(server.terminalMailTargetWasAbandoned(target)).toBe(false)
probe.mockResolvedValue('exited')
expect(await server.checkAgentPresence(PANE)).toBe('exited')
expect(server.terminalMailTargetWasAbandoned(target)).toBe(true)
await hook(server, 'SessionStart', 'successor', undefined, 4002)
expect(server.terminalMailTargetWasAbandoned(target)).toBe(true)
await hook(server, 'UserPromptSubmit', 'successor', undefined, 4002)
expect(server.terminalMailTargetWasAbandoned(target)).toBe(false)
})

it('does not recover a mail target after its root completed normally before process exit', async () => {
const server = await createServer()
await hook(server, 'SessionStart')
await hook(server, 'UserPromptSubmit')
const target = server.readTerminalMailTarget(PANE)
if (!target) {
throw new Error('Missing open root target')
}
await hook(server, 'Stop')
probe.mockResolvedValue('exited')
await server.checkAgentPresence(PANE)
expect(server.terminalMailTargetWasAbandoned(target)).toBe(false)
})

it('keeps writer observations exact and topology local to the accepted row', async () => {
const server = await createServer()
await hook(server, 'SessionStart')
Expand Down
16 changes: 16 additions & 0 deletions src/main/agent-hooks/server/retained-provider-session-row.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { EnrichedAgentHookEventPayload } from './server-types'

// Resume identity survives retiring the pane's live status claims.
export function retainedProviderSessionRow(
entry: EnrichedAgentHookEventPayload | null | undefined
): EnrichedAgentHookEventPayload | null {
if (
!entry?.providerSession ||
!entry.payload.agentType ||
entry.payload.agentType === 'unknown'
) {
return null
}
const { launchToken: _launchToken, ...resumeIdentity } = entry
return { ...resumeIdentity, providerSessionOnly: true, retainedForLiveness: true }
}
47 changes: 24 additions & 23 deletions src/main/agent-hooks/server/server-cleanup.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { retainedProviderSessionRow } from './retained-provider-session-row'
import type { AgentProcessPresence } from '../../../shared/agent-process-presence'
import {
admitLegacyAgentStatus,
Expand All @@ -17,24 +18,26 @@ import { isLocalHookConnectionId } from '../../../shared/wsl-hook-relay-contract
import type { EnrichedAgentHookEventPayload } from './server-types'
import { AgentHookServerAuthorityFences } from './server-authority-fences'
import { recordAgentExit } from './agent-exit-evidence'
import { TerminalMailTargets, type TerminalMailTarget } from './terminal-mail-target'

export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFences {
/** The resume-identity remnant of a dropped row: a `providerSessionOnly` entry carries no state
* claim — it cannot gate a pane `working` — so it survives teardowns that end the pane's live
* claims. Returns null when the row has no resumable session to keep. */
protected toRetainedProviderSessionRow(
entry: EnrichedAgentHookEventPayload | null | undefined
): EnrichedAgentHookEventPayload | null {
if (
!entry?.providerSession ||
!entry.payload.agentType ||
entry.payload.agentType === 'unknown'
) {
return null
}
const { launchToken: _launchToken, ...resumeIdentity } = entry
return { ...resumeIdentity, providerSessionOnly: true, retainedForLiveness: true }
private readonly terminalMailTargets = new TerminalMailTargets()

readTerminalMailTarget(paneKey: string): TerminalMailTarget | null {
return this.terminalMailTargets.read(
this.state.lastStatusByPaneKey.get(this.resolvePaneKeyAlias(paneKey))
)
}

terminalMailTargetWasAbandoned(target: TerminalMailTarget): boolean {
const key = this.resolvePaneKeyAlias(target.paneKey)
return this.terminalMailTargets.wasAbandoned(
{ ...target, paneKey: key },
this.state.lastStatusByPaneKey.get(key),
this.agentExitedAtByPaneKey.get(key)?.process
)
}
protected toRetainedProviderSessionRow = retainedProviderSessionRow

/** Drop only the status row (user dismissal); do NOT wipe prompt/tool caches since the pane's agent may still be alive. Use clearPaneState for PTY-teardown. */
dropStatusEntry(
Expand Down Expand Up @@ -136,6 +139,10 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen
for (const paneKey of paneKeys) {
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
if (options?.endedPresence) {
this.terminalMailTargets.observeExit(
this.state.lastStatusByPaneKey.get(resolvedPaneKey),
options.endedPresence.process
)
// Why both: cleanup below drops the alias, and a reader may still hold the original key.
const paneKeys = new Set([resolvedPaneKey, paneKey])
for (const [aliasKey, alias] of this.legacyPaneKeyAliases) {
Expand All @@ -149,20 +156,14 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen
if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) {
continue
}
const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey)
const resumeRow = options?.preserveResumeIdentity
? this.toRetainedProviderSessionRow(
this.state.lastStatusByPaneKey.get(resolvedPaneKey) as
| EnrichedAgentHookEventPayload
| undefined
)
? this.toRetainedProviderSessionRow(previous)
: null
const retained =
resumeRow && options?.endedPresence
? { ...resumeRow, agentPresence: options.endedPresence }
: resumeRow
const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as
| EnrichedAgentHookEventPayload
| undefined
this.clearPaneState(resolvedPaneKey, { emitStatusRowMutation: false })
if (retained) {
admitLegacyAgentStatus(
Expand Down
122 changes: 122 additions & 0 deletions src/main/agent-hooks/server/terminal-mail-target.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event'
import {
isSameAgentProcess,
readAgentProcessIdentity,
type AgentProcessIdentity
} from '../../../shared/agent-process-presence'

export type TerminalMailTarget = {
paneKey: string
process: AgentProcessIdentity
owner: string
turnKey: string
}

export function openTerminalMailTarget(
row: AgentHookEventPayload | undefined
): TerminalMailTarget | null {
const turn = row?.hostTurn
const process = row?.agentPresence?.process
if (
!row ||
row.connectionId !== null ||
row.restoredUnconfirmed ||
!process ||
!turn ||
turn.currentTurnKey === 'seed' ||
turn.completed?.turnKey === turn.currentTurnKey ||
row.payload.mainAgent?.state !== 'working' ||
row.payload.mainAgent.stopping
) {
return null
}
return { paneKey: row.paneKey, process, owner: turn.owner, turnKey: turn.currentTurnKey }
}

export function sameTerminalMailTarget(a: TerminalMailTarget, b: TerminalMailTarget): boolean {
return (
a.paneKey === b.paneKey &&
a.owner === b.owner &&
a.turnKey === b.turnKey &&
isSameAgentProcess(a.process, b.process)
)
}

export function readTerminalMailTarget(value: unknown): TerminalMailTarget | null {
if (
!value ||
typeof value !== 'object' ||
!('paneKey' in value) ||
typeof value.paneKey !== 'string' ||
!('owner' in value) ||
typeof value.owner !== 'string' ||
!('turnKey' in value) ||
typeof value.turnKey !== 'string' ||
!('process' in value)
) {
return null
}
const process = readAgentProcessIdentity(value.process)
return process
? { paneKey: value.paneKey, owner: value.owner, turnKey: value.turnKey, process }
: null
}

export class TerminalMailTargets {
private readonly abandoned = new Map<string, TerminalMailTarget>()

read(row: AgentHookEventPayload | undefined): TerminalMailTarget | null {
return row?.agentPresence?.ended || row?.providerSessionOnly
? null
: openTerminalMailTarget(row)
}

observeExit(
row: AgentHookEventPayload | undefined,
process: AgentProcessIdentity | undefined
): void {
const target = openTerminalMailTarget(row)
if (!target || !process || !isSameAgentProcess(target.process, process)) {
return
}
this.abandoned.set(target.paneKey, target)
if (this.abandoned.size > 256) {
const oldest = this.abandoned.keys().next().value
if (oldest !== undefined) {
this.abandoned.delete(oldest)
}
}
}

wasAbandoned(
target: TerminalMailTarget,
row: AgentHookEventPayload | undefined,
exit: AgentProcessIdentity | undefined
): boolean {
const turn = row?.hostTurn
if (row?.payload.mainAgent?.outcome === 'cancellation') {
return false
}
if (
turn &&
turn.currentTurnKey !== 'seed' &&
(turn.owner !== target.owner ||
turn.currentTurnKey !== target.turnKey ||
turn.completed?.turnKey === target.turnKey)
) {
return false
}
const proof = this.abandoned.get(target.paneKey)
if (proof && sameTerminalMailTarget(proof, target)) {
return true
}
const retained = openTerminalMailTarget(row)
return Boolean(
row?.providerSessionOnly &&
retained &&
exit &&
sameTerminalMailTarget(retained, target) &&
isSameAgentProcess(exit, target.process)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export function applyJournalDispatchRow(
}
submission.resolvedAt = row.state === 'pending' ? null : row.ts
if (row.state === 'pending') {
state.submissionTurnScopes.set(row.clientMessageId, row.turnScope ?? null)
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
submission.handedOverAt = row.ts
placeHandedOverMessage(state, submission, row)
foldStoppedHistoryCarried(state, row)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import type {
AgentJournalAcceptanceReceipt,
AgentJournalRenderItem,
AgentJournalSnapshot,
AgentJournalSubmission
AgentJournalSubmission,
AgentJournalTurnScope
} from '../../../shared/agent-session-journal-types'
import { journalHistoryOrigin, type JournalHistoryOrigin } from './journal-history-origin'
import { journalBatchMutationProducer, journalRenderItem } from './journal-render-item'
Expand Down Expand Up @@ -66,6 +67,7 @@ export type JournalReducerState = {
/** Turn ids whose record a tombstone removed, as a rewind does: over, though no row shows it. */
removedTurnIds: Set<string>
submissions: Map<string, AgentJournalSubmission>
submissionTurnScopes: Map<string, AgentJournalTurnScope | null>
receipts: Map<string, AgentJournalAcceptanceReceipt>
/** Provider item id → the submission slot that adopted it. Stops an accepted
* echo from appending a second copy of the user's own message. */
Expand Down Expand Up @@ -100,6 +102,7 @@ export function createJournalReducerState(sessionId: string, epoch: string): Jou
tombstones: new Map(),
removedTurnIds: new Set(),
submissions: new Map(),
submissionTurnScopes: new Map(),
receipts: new Map(),
aliases: new Map(),
itemEchoes: new Map(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export function retireRewoundJournalSubmission(state: JournalReducerState, itemI
return
}
state.submissions.delete(identity.clientMessageId)
state.submissionTurnScopes.delete(identity.clientMessageId)
state.receipts.delete(identity.clientMessageId)
for (const [providerItemId, submissionItemId] of state.aliases) {
if (submissionItemId === itemId) {
Expand Down
4 changes: 4 additions & 0 deletions src/main/native-chat/agent-session-journal/journal-store.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { journalSubmissionHandoff } from './journal-submission-handoff'
// Append-only journal store for one agent session. It owns the chat's fold and write queue, and no
// connection: every statement goes through the host's one journal database.

Expand Down Expand Up @@ -266,6 +267,9 @@ export class AgentSessionJournal {

submission = (clientMessageId: string) => this.state.submissions.get(clientMessageId)

submissionHandoff = (clientMessageId: string) =>
journalSubmissionHandoff(this.state, clientMessageId)

pendingSubmissions = () => this.submissions().filter((entry) => entry.dispatchState === 'pending')

/** The durable answer to "did my send land?" — a reconnecting client asking
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function applyJournalSubmission(
state: JournalReducerState,
row: Extract<JournalRow, { kind: 'submission' }>
): void {
state.submissionTurnScopes.set(row.clientMessageId, row.turnScope ?? null)
const options = readAgentSessionExecutionOptions(row.options)
state.submissions.set(row.clientMessageId, {
clientMessageId: row.clientMessageId,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { expect, it } from 'vitest'
import { applyJournalRow, createJournalReducerState } from './journal-reducer'
import { journalSubmissionHandoff } from './journal-submission-handoff'

it('requires original handover scope or an exact opener, rather than reduced positional scope', () => {
const state = createJournalReducerState('session', 'epoch')
const base = (seq: number) => ({ v: 1, epoch: 'epoch', seq, fence: 1, ts: seq })
applyJournalRow(state, {
...base(1),
kind: 'item',
itemId: 'turn',
revision: 1,
body: { kind: 'turn', turnId: 'turn-1', state: 'running' }
})
applyJournalRow(state, {
...base(2),
kind: 'submission',
clientMessageId: 'notice',
payloadFingerprint: 'fingerprint',
providerHandle: { kind: 'codex', threadId: 'thread' },
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'notice' }] }
})
expect(journalSubmissionHandoff(state, 'notice')).toBeNull()
applyJournalRow(state, {
...base(3),
kind: 'dispatch',
clientMessageId: 'notice',
state: 'pending',
providerItemId: null,
reason: null,
turnScope: { kind: 'turn', turnItemId: 'turn' }
})
applyJournalRow(state, {
...base(4),
kind: 'dispatch',
clientMessageId: 'notice',
state: 'accepted',
providerItemId: null,
reason: null
})
expect(journalSubmissionHandoff(state, 'notice')).toMatchObject({ itemId: 'turn' })
applyJournalRow(state, {
...base(5),
kind: 'item',
itemId: 'unrelated',
revision: 1,
body: { kind: 'turn', turnId: 'turn-2', state: 'completed', outcome: 'failure' }
})
expect(journalSubmissionHandoff(state, 'notice')).toMatchObject({ itemId: 'turn' })
})
Loading