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.

turns: a Stop hook closes only the turn it is about (#970)

Deeff9dc34ba9c1
diff --git a/cli/e2e/questions-edges.e2e.ts b/cli/e2e/questions-edges.e2e.ts
index 49cc82fa5..fe47b1c77 100644
--- a/cli/e2e/questions-edges.e2e.ts
+++ b/cli/e2e/questions-edges.e2e.ts
@@ -1,8 +1,8 @@
/**
* An agent's question at its edges, for Claude Code and Codex: asked while no window is open, answered
* in the terminal by hand, answered by two windows at once, cancelled with Esc, and still open across a
- * daemon restart. Every window ends with the same answer to "is this question still open?", and the
- * agent gets exactly one answer.
+ * daemon restart, and asked in a turn the previous turn's late Stop hook arrives in. Every window ends with
+ * the same answer to "is this question still open?", and the agent gets exactly one answer.
*/
import { mkdirSync } from 'node:fs'
import { join } from 'node:path'
@@ -43,14 +43,45 @@ async function pickInPane(daemon: IsolatedDaemon, engine: Engine, pane: string,
describe('a question at its edges', () => {
let daemon: IsolatedDaemon | undefined
afterEach(async () => { await daemon?.close(); daemon = undefined })
- const fresh = async () => {
- const d = await IsolatedDaemon.create()
+ const fresh = async (env: Record<string, string> = {}) => {
+ const d = await IsolatedDaemon.create({ env })
daemon = d
onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
await d.start()
return d
}
+ // Found by the soak run (e2e/endurance.e2e.ts): under load a turn's Stop reached the daemon 6 s late, after the
+ // next prompt's turn had opened, and force-closed that turn with its question open, which no window was shown.
+ it('claude: a turn\'s Stop that arrives after the next turn opened leaves that turn, and its question, open', async () => {
+ // Each turn's Stop is acted on 2.5 s after it reached the daemon, as its verification took under load.
+ const d = await fresh({ HARNESSD_TEST_STOP_HOOK_DELAY_MS: '2500' })
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'ask-late-stop')
+ const first = client.next(isTurn('turn_ended', agent.id), 45_000, 'the first turn ending')
+ const stops = () => d.log().split(`${String(agent.sessionId).slice(0, 8)} turn-stop`).length
+ const stopsBefore = stops()
+ client.send('message', { agentId: agent.id, content: 'before the question' })
+ await first
+ // At once, the question; the first turn's Stop arrives in it.
+ const question = client.next(asked(agent.id), 30_000, 'commander_question')
+ const started = client.next(isTurn('turn_started', agent.id), 30_000, 'the question\'s turn starting')
+ client.send('message', { agentId: agent.id, content: '!ask' })
+ await started
+ const shown = await question
+ const since = client.frames.length
+ await until('the first turn\'s Stop to arrive', () => stops() > stopsBefore || null, 15_000, 100)
+ // Past its hold and the Stop hook's grace: the question's turn is still open.
+ await new Promise((resolve) => setTimeout(resolve, 6_000))
+ expect(client.frames.slice(since).filter(isTurn('turn_ended', agent.id))).toEqual([])
+ const ended = client.next(isTurn('turn_ended', agent.id), 45_000, 'the question\'s turn ending once answered')
+ const result = await answer(client, agent.id, shown.payload!.requestId, { [shown.payload!.questions[0].q]: 'Coffee' })
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ await ended
+ expect(await d.capture(agent.tmuxPane)).toContain('you chose Coffee')
+ client.close()
+ })
+
it.each(engines)('%s: asked while no window is open, it reaches the window that opens next, and its answer is the one used', async (engine) => {
const d = await fresh()
const first = await LocalClient.connect(d)
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index f8de6c910..1b6622862 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -271,6 +271,9 @@ function boundedPrompt(prompt) {
* permission mode or close plan the daemon kept, merged over its own at its next save
* (e2e/stall.e2e.ts).
*/
+/** This process's start, epoch ms: the engine ran the hook then. */
+const FIRED_AT = Date.now() - Math.round(process.uptime() * 1000)
+
function post(port, path, body, onResponse) {
return new Promise((resolve) => {
const payload = JSON.stringify(body)
@@ -287,6 +290,9 @@ function post(port, path, body, onResponse) {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
'X-Harness-Hook-Token': credential,
+ // When the engine ran this hook: this process's start, not its arrival, which can be seconds later on
+ // a loaded machine, after the engine has moved on to its next prompt (src/hookServer.ts hookFiredAt).
+ 'X-Harness-Hook-Fired-At': String(FIRED_AT),
},
timeout: Math.max(1, Math.min(500, remainingBudget())),
},
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index b79c855c2..f8a5b0476 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1701,6 +1701,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onTurnStart: turnHooks.onTurnStart,
onToolStart: turnHooks.onToolStart,
onTurnStop: turnHooks.onTurnStop,
+ onPromptHook: turnHooks.onPromptHook,
+ stopHookDelayMs: Number(process.env.HARNESSD_TEST_STOP_HOOK_DELAY_MS) || 0,
// `harness pair`, `unpair`, `remote-password`, `link connect`, `group` and `devices`: the keys are the
// gateway's, and so are these answers (gateway/start.ts).
onPair: (code) => gatewayOps.pair(code),
diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.ts
index f0b5ff5e7..e97d16efb 100644
--- a/cli/src/core/turns/turnHooks.spec.ts
+++ b/cli/src/core/turns/turnHooks.spec.ts
@@ -127,6 +127,67 @@ describe('turn hooks', () => {
expect(String(log.mock.calls[0][0])).toContain('force-closed by StopFailure hook')
})
+ // Found by the soak run (e2e/endurance.e2e.ts): a turn's Stop reached the daemon 6 s late under load, after
+ // the next prompt's turn had opened, and force-closed that turn with a question open in it.
+ it('leaves a turn that opened after the Stop arrived, the next prompt\'s, to its own end, unless the Stop is a failure', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('claude')
+ // The Stop's own turn closed already; the drain reads the next prompt's turn opening.
+ const state = { turnOpen: false, opened: 1, pendingTools: new Map() } as unknown as TurnState
+ run.normalizers.turnStates.set('s1', state)
+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => { state.turnOpen = true; state.opened = 2 })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(state.turnOpen).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ // Open as the Stop arrived, closed by the transcript in the drain, and the next one opened: left too.
+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => { state.opened = 3 })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(state.turnOpen).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ // The engine's state started over meanwhile (the session attached again): not the turn the Stop found.
+ run.normalizers.turnStates.set('s1', { turnOpen: true, opened: 3, pendingTools: new Map() } as unknown as TurnState)
+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => { run.normalizers.turnStates.set('s1', { ...state }) })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ // A StopFailure closes whatever is open.
+ run.normalizers.turnStates.set('s1', state)
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(state.turnOpen).toBe(false)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by StopFailure hook')
+ })
+
+ it('closes nothing with a Stop its engine ran before the session\'s latest prompt hook, a failure included', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('claude')
+ const state = { turnOpen: true, opened: 2, pendingTools: new Map() } as unknown as TurnState
+ run.normalizers.turnStates.set('s1', state)
+ run.hooks.onPromptHook('s1', 2_000)
+ // An older prompt hook, arriving late, does not move it back.
+ run.hooks.onPromptHook('s1', 1_500)
+ for (const status of [undefined, 'error']) {
+ run.hooks.onTurnStop({ sessionId: 's1', status, firedAt: 1_000 })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ }
+ expect(state.turnOpen).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ // Run after it: about the open turn, which it closes once the grace is over, as before.
+ run.hooks.onTurnStop({ sessionId: 's1', firedAt: 3_000 })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(state.turnOpen).toBe(false)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by Stop hook')
+ // Remembered for a bounded number of sessions: the oldest goes first.
+ for (let i = 0; i < 600; i++) run.hooks.onPromptHook(`s${i + 2}`, 5_000)
+ state.turnOpen = true
+ run.hooks.onTurnStop({ sessionId: 's1', firedAt: 1_000 })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)
+ expect(state.turnOpen).toBe(false)
+ })
+
it('says Stop for a clean stop', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const run = setup('claude')
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
index 8ca435f5f..f636a460b 100644
--- a/cli/src/core/turns/turnHooks.ts
+++ b/cli/src/core/turns/turnHooks.ts
@@ -22,6 +22,8 @@ import type { SessionNormalizers } from '../transcripts/normalizers.js'
// only if the turn is still open after this grace + a re-poll do we force-close (by then the assistant
// text is on disk, so the natural close usually wins and the recap isn't empty).
export const STOP_HOOK_GRACE_MS = 1_500
+/** How many sessions' latest prompt hooks are remembered. */
+const PROMPT_HOOKS_KEPT = 512
export interface TurnHookDeps {
resolve: (id: string) => RegisteredSession | undefined
@@ -54,10 +56,19 @@ export function createTurnHooks({
if (!normalizer) return
emit(sessionId, normalizer.openTurn()) // no-op after the turn's first tool call
}
+ /** When each session's latest prompt hook was run by its engine: a Stop run before it is about an earlier
+ * turn. Bounded: a session's entry outlives it only until enough newer ones come. */
+ const promptFiredAt = new Map<string, number>()
+ const onPromptHook = (sessionId: string, firedAt: number): void => {
+ if (firedAt <= (promptFiredAt.get(sessionId) ?? 0)) return
+ promptFiredAt.delete(sessionId)
+ promptFiredAt.set(sessionId, firedAt)
+ if (promptFiredAt.size > PROMPT_HOOKS_KEPT) promptFiredAt.delete(promptFiredAt.keys().next().value!)
+ }
const onToolStart = ({ sessionId, toolUseId, toolName, input: toolInput }: { sessionId: string; toolUseId: string; toolName: string; input: unknown }): void => {
if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)
}
- const onTurnStop = ({ sessionId, status }: { sessionId: string; status?: string }): void => {
+ const onTurnStop = ({ sessionId, status, firedAt }: { sessionId: string; status?: string; firedAt?: number }): void => {
const session = resolve(sessionId)
if (!session) return
if (session.engine === 'cursor') {
@@ -195,6 +206,18 @@ export function createTurnHooks({
// turn_duration: the Stop of the pass before it reached the daemon 520 ms after it began (end to end,
// under load) and force-closed it while it ran. Only a StopFailure still closes one here.
const leftToTranscript = (st: TurnState): boolean => st.continued === true && status !== 'error'
+ // A Stop closes only the turn it is about. Found by the soak run (e2e/endurance.e2e.ts): under load a turn's
+ // Stop reached the daemon 6 s late, after the next prompt's turn had opened, and force-closed that turn
+ // with a question open in it, which was then never shown. So:
+ // - a Stop its engine ran before the session's latest prompt hook is about an earlier turn, and closes
+ // nothing (the time each hook was run comes with it, hook/notify.mjs);
+ // - otherwise it is about the turn open as it arrives, and not one opened after that (read in the drain
+ // below), whose prompt hook has not come in yet; a StopFailure closes whichever turn is open.
+ // A turn left open with no end of its own is closed by the next prompt (lib/normalize.ts).
+ const stale = firedAt !== undefined && (promptFiredAt.get(sessionId) ?? 0) > firedAt
+ const arrived = turnStates.get(sessionId)
+ const about = arrived?.turnOpen ? arrived.opened ?? 0 : null
+ const itsTurn = (st: TurnState): boolean => !stale && (status === 'error' || (st === arrived && about !== null && (st.opened ?? 0) === about))
void (async () => {
await drain(sessionId)
// A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is
@@ -203,13 +226,13 @@ export function createTurnHooks({
// to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).
mirror.noteEngineStopped(sessionId)
const open = turnStates.get(sessionId)
- if (!open?.turnOpen || leftToTranscript(open)) return // natural JSONL close already won → nothing to do
+ if (!open?.turnOpen || leftToTranscript(open) || !itsTurn(open)) return // natural JSONL close already won → nothing to do
// Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close
// if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
await drain(sessionId)
const st = turnStates.get(sessionId)
- if (st?.turnOpen && !leftToTranscript(st)) {
+ if (st?.turnOpen && !leftToTranscript(st) && itsTurn(st)) {
st.turnOpen = false
st.pendingTools.clear()
console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)
@@ -219,5 +242,5 @@ export function createTurnHooks({
console.error('[hooks] claude stop hook failed:', err instanceof Error ? err.message : err)
})
}
- return { onTurnStart, onToolStart, onTurnStop }
+ return { onTurnStart, onToolStart, onTurnStop, onPromptHook }
}
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 52ccb487d..4c8e2bca1 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -156,8 +156,9 @@ function runHook(opts: RunHookOpts): Promise<string> {
}
/** A throwaway localhost adapter that records every hook POST. */
-async function collect(response: Record<string, unknown> = {}, credential?: string): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {
+async function collect(response: Record<string, unknown> = {}, credential?: string): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }>; firedAts: Array<string | undefined> }> {
const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const firedAts: Array<string | undefined> = []
const server = createServer((req, res) => {
// Local service discovery may probe a test port. Only hook POSTs belong to this fixture.
if (req.method !== 'POST') { res.writeHead(405).end(); return }
@@ -166,6 +167,7 @@ async function collect(response: Record<string, unknown> = {}, credential?: stri
req.on('data', (chunk) => { raw += chunk.toString() })
req.on('end', () => {
requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
+ firedAts.push(req.headers['x-harness-hook-fired-at'] as string | undefined)
res.end(JSON.stringify(response))
})
})
@@ -176,7 +178,7 @@ async function collect(response: Record<string, unknown> = {}, credential?: stri
})
const address = server.address()
if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
- return { port: address.port, requests }
+ return { port: address.port, requests, firedAts }
}
describe('hook notify terminal scope', () => {
@@ -208,6 +210,18 @@ describe('hook notify terminal scope', () => {
expect(requests[0]?.body.prompt).toBe(input.prompt)
expect(await runHook({ port, engine, tmuxPane: '%42', input: { ...input, hook_event_name: 'SessionStart' } })).toBe('')
})
+ // What tells a late Stop from the turn the next prompt opened (src/hookServer.ts hookFiredAt).
+ it('says when its engine ran it: its own start, no later than it sends', async () => {
+ const { port, firedAts } = await collect()
+ const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))
+ const before = Date.now()
+ await runHook({ port, engine: 'claude', tmuxPane: '%42', input: recordings.claude.input })
+ const firedAt = Number(firedAts[0])
+ expect(Number.isSafeInteger(firedAt)).toBe(true)
+ expect(firedAt).toBeGreaterThanOrEqual(before - 1_000)
+ expect(firedAt).toBeLessThanOrEqual(Date.now())
+ })
+
it.each(['claude', 'codex', 'grok'] as const)('forwards the actual %s accepted prompt without changing the model input', async engine => {
const { port, requests } = await collect()
const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 92d9277ee..f1df2732f 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -3,7 +3,7 @@ import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { startHookServer, type HookServerHandlers, chooseHookAgent, knownTranscriptFor } from './hookServer.js'
+import { startHookServer, type HookServerHandlers, chooseHookAgent, hookFiredAt, knownTranscriptFor } from './hookServer.js'
import { registry, type RegisteredSession } from './lib/registry.js'
import { env } from './config/env.js'
import { readHookCredential } from './lib/hookAuth.js'
@@ -255,6 +255,33 @@ describe('process-owned hook server', () => {
expect(handler).not.toHaveBeenCalled()
})
+ it('hands a Stop on with when its engine ran it, and holds it as long as a test asks', async () => {
+ const onTurnStop = vi.fn()
+ const resolveHookAgent = vi.fn(async () => ({ engine: 'claude', sessionId: 'real-session', agentId: 'agent-1' } as never))
+ const stop = (base: string, headers: Record<string, string>) => fetch(`${base}/api/hook/turn-stop`, {
+ method: 'POST', headers, body: JSON.stringify({ engine: 'claude', sessionId: 'real-session', tmuxPane: '%1', callerPid: 123 }),
+ })
+ const { base, headers } = await start({ onTurnStop, resolveHookAgent })
+ expect((await stop(base, { ...headers, 'x-harness-hook-fired-at': '1700000000000' })).status).toBe(200)
+ expect(onTurnStop).toHaveBeenLastCalledWith({ sessionId: 'real-session', status: undefined, transcriptPath: undefined, firedAt: 1_700_000_000_000 })
+ // A hook client too old to say: as before.
+ expect((await stop(base, headers)).status).toBe(200)
+ expect(onTurnStop).toHaveBeenLastCalledWith({ sessionId: 'real-session', status: undefined, transcriptPath: undefined })
+ server?.close()
+ const held = await start({ onTurnStop, resolveHookAgent, stopHookDelayMs: 50 })
+ onTurnStop.mockClear()
+ expect((await stop(held.base, held.headers)).status).toBe(200)
+ expect(onTurnStop).not.toHaveBeenCalled()
+ await vi.waitFor(() => expect(onTurnStop).toHaveBeenCalledOnce())
+ })
+
+ it('reads when a hook was run from its header, and nothing else as that', () => {
+ expect(hookFiredAt({ headers: { 'x-harness-hook-fired-at': '1700000000000' } })).toBe(1_700_000_000_000)
+ for (const value of [undefined, '', 'soon', '-5', '0', '1.5', '1e400']) {
+ expect(hookFiredAt({ headers: { 'x-harness-hook-fired-at': value } })).toBeUndefined()
+ }
+ })
+
it('answers a proxied control-plane read whose handler throws, instead of hanging it', async () => {
// The handler is a void-discarded async: a throw used to be an unhandledRejection and a request
// with no response, which the desktop app reported 30s later as its own receive timeout.
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 6badc3724..1da265692 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -85,6 +85,9 @@ export interface HookServerHandlers {
* it fires once per tool call, and every call after the first in a turn must be a no-op. */
onTurnStart?: (body: { sessionId: string }) => void
onPromptSubmitted?: (agentId: string, prompt: string) => void
+ /** A session's UserPromptSubmit hook, and when its engine ran it (`X-Harness-Hook-Fired-At`): what a Stop
+ * that arrives late is told apart from the turn the prompt opened by (core/turns/turnHooks.ts). */
+ onPromptHook?: (sessionId: string, firedAt: number) => void
onToolStart?: (body: {
sessionId: string
toolUseId: string
@@ -95,7 +98,12 @@ export interface HookServerHandlers {
sessionId: string
status?: string
transcriptPath?: string
+ /** When the engine ran the hook; absent from a hook client too old to say. */
+ firedAt?: number
}) => void
+ /** For the end-to-end suite only: how long a Stop hook is held before it is acted on, as the hook's own
+ * verification can take under load (`HARNESSD_TEST_STOP_HOOK_DELAY_MS`). */
+ stopHookDelayMs?: number
/** `harness pair <code>` from a second CLI process: run CPace toward the waiting browser. */
onPair?: (code: string) => Promise<PairOutcome>
/** `harness pairings` — list E2EE-paired browsers. */
@@ -174,6 +182,17 @@ function optionalBoundedJson(value: unknown, max: number): boolean {
try { return Buffer.byteLength(JSON.stringify(value)) <= max } catch { return false }
}
+/**
+ * When the engine ran a hook: the hook process's own start (hook/notify.mjs sends it as a header, which a
+ * daemon that does not read it ignores, where an unknown body field is refused). Undefined from a client too
+ * old to say. Not the hook's arrival: under load a hook reached the daemon seconds after its engine had
+ * moved on to the next prompt (found by the soak run, e2e/endurance.e2e.ts).
+ */
+export function hookFiredAt(req: Pick<http.IncomingMessage, 'headers'>): number | undefined {
+ const value = Number(req.headers['x-harness-hook-fired-at'])
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined
+}
+
function validHookBody(value: unknown): value is BoundHookBody {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
const body = value as Record<string, unknown>
@@ -544,6 +563,8 @@ export function startHookServer(
}
if (body.hookEvent === 'UserPromptSubmit') {
handlers.onPromptSubmitted?.(processAgent.agentId, body.prompt ?? '')
+ const fired = hookFiredAt(req)
+ if (fired && body.sessionId) handlers.onPromptHook?.(body.sessionId, fired)
}
let result = registry.register(body)
if (!result && body.transcriptPath && !existsSync(body.transcriptPath)) {
@@ -631,11 +652,10 @@ export function startHookServer(
if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId) {
console.log(`[hooks] ${sid(body.sessionId)} turn-stop${body.status ? ` · status=${body.status}` : ''}`)
- handlers.onTurnStop?.({
- sessionId: body.sessionId,
- status: body.status,
- transcriptPath: body.transcriptPath,
- })
+ const fired = hookFiredAt(req)
+ const stop = { sessionId: body.sessionId, status: body.status, transcriptPath: body.transcriptPath, ...(fired ? { firedAt: fired } : {}) }
+ if (handlers.stopHookDelayMs) setTimeout(() => handlers.onTurnStop?.(stop), handlers.stopHookDelayMs)
+ else handlers.onTurnStop?.(stop)
}
json(200, { ok: true })
return
diff --git a/cli/src/lib/normalize.spec.ts b/cli/src/lib/normalize.spec.ts
index 7171a4b56..3dbe41012 100644
--- a/cli/src/lib/normalize.spec.ts
+++ b/cli/src/lib/normalize.spec.ts
@@ -253,3 +253,19 @@ describe('harness web tools render as the native cards', () => {
expect(events.find((e) => e.type === 'tool_start')).toMatchObject({ payload: { tool: 'mcp__github__get_issue', input: { number: 1 } } })
})
})
+
+describe('the turns a transcript opens, counted', () => {
+ // What a Stop hook checks it closes only the turn it arrived during (core/turns/turnHooks.ts).
+ it('counts each turn a prompt or a blocking Stop hook opens, and nothing else', () => {
+ const state = newTurnState()
+ lineToEvents(userPrompt('one'), state)
+ lineToEvents(assistantText('done', 'end_turn'), state)
+ expect(state.opened).toBe(1)
+ lineToEvents(userPrompt('two'), state)
+ lineToEvents(JSON.stringify({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition: 'tests pass', reason: 'one fails' } }), state)
+ expect(state.opened).toBe(2)
+ lineToEvents(assistantText('passed', 'end_turn'), state)
+ lineToEvents(JSON.stringify({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition: 'tests pass', reason: 'one fails' } }), state)
+ expect(state.opened).toBe(3)
+ })
+})
diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.ts
index 72213251c..5416e348f 100644
--- a/cli/src/lib/normalize.ts
+++ b/cli/src/lib/normalize.ts
@@ -823,6 +823,9 @@ export interface TurnState {
thinkingPrefix?: string
/** The open turn is one a blocking Stop hook continued (`stopHookContinuation`), not a prompt's. */
continued?: boolean
+ /** How many turns this state has opened: a Stop hook closes only the turn that was open as it arrived
+ * (core/turns/turnHooks.ts). */
+ opened?: number
}
/**
@@ -950,6 +953,7 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
if (continued !== null) {
if (state.turnOpen) return []
state.turnOpen = true
+ state.opened = (state.opened ?? 0) + 1
state.pendingTools.clear()
state.continued = true
return [{ type: 'turn_started', payload: { userMessage: continued } }]
@@ -982,6 +986,7 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
// New prompt (typed in the terminal OR injected from the web) — starts a turn.
if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })
state.turnOpen = true
+ state.opened = (state.opened ?? 0) + 1
state.pendingTools.clear()
state.continued = false
events.push({ type: 'turn_started', payload: { userMessage: userText } })