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.

A stop during a restart never leaves an agent with no engine; two restarts at once; grid probe; a supervised daemon waits out its orphan (#819)

Dee21491e79150e
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index cbdf395aa..723e155da 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -26,7 +26,9 @@
// Which release is installed is the config's business, so a test can update an engine in place by
// rewriting its wrapper: `version` is what it reports and writes, `without` lists the flags and
// subcommands that release no longer has, and `startDelayMs` is how long it takes, once started, before
-// it draws or announces anything (an engine's first run after an update).
+// it draws or announces anything (an engine's first run after an update). `firstHookDelayMs` is how long
+// its first SessionStart takes to reach the daemon once the engine is up: the hook command starting on a
+// loaded machine, while the daemon has already found the engine and its conversation.
import { execFileSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs'
@@ -196,6 +198,7 @@ export async function run(engine, config) {
process.stdout.write(`\x1b[?2004h${engine === 'claude' ? '✻ Welcome to Claude Code (fake)' : '>_ OpenAI Codex (fake)'}\r\n`)
process.stdout.write(` session ${sessionId}${resumed ? ' (resumed)' : ''}\r\n\r\n`)
draw()
+ if (config.firstHookDelayMs && !resumed) await new Promise((resolve) => setTimeout(resolve, config.firstHookDelayMs))
await hook('session-start', { hookEvent: resumed ? 'SessionStart' : 'SessionStart', source: resumed ? 'resume' : 'startup' })
let turn = 0
diff --git a/cli/e2e/races.e2e.ts b/cli/e2e/races.e2e.ts
index 14a2369b6..c6ef29f18 100644
--- a/cli/e2e/races.e2e.ts
+++ b/cli/e2e/races.e2e.ts
@@ -4,11 +4,12 @@
* message is being written, and two agents created in one folder at once. Whatever order they land in,
* every request is answered, an agent ends with one engine in one pane, and it takes the next message.
*/
-import { mkdirSync } from 'node:fs'
+import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
-import { IsolatedDaemon, until } from './harness/daemon.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
type Engine = 'claude' | 'codex'
const engines: Engine[] = ['claude', 'codex']
@@ -40,6 +41,15 @@ const active = (client: LocalClient, agentId: string, sessionId?: string) =>
const now = await row(client, agentId)
return now?.status === 'active' && now.sessionId && (!sessionId || now.sessionId === sessionId) ? now : null
}, 60_000, 500)
+/** The engine as it is installed for the agents created next: its config, plus what the test says
+ * (e2e/harness/fakeEngine.mjs), written beside the old wrapper and renamed over it. */
+function install(d: IsolatedDaemon, engine: Engine, extra: Record<string, unknown>): void {
+ const config = { port: d.port, dataDir: d.dataDir, claudeProjectsDir: d.env.CLAUDE_PROJECTS_DIR, codexHome: d.env.CODEX_HOME, ...extra }
+ const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).href
+ const wrapper = join(d.root, 'bin', engine)
+ writeFileSync(`${wrapper}.new`, `#!${process.execPath}\nimport(${JSON.stringify(module)}).then((m) => m.run(${JSON.stringify(engine)}, ${JSON.stringify(config)}))\n`, { mode: 0o755 })
+ renameSync(`${wrapper}.new`, wrapper)
+}
/** Engine processes in a pane: a pane must never end with two of them, or none while the agent is active. */
async function engineProcesses(daemon: IsolatedDaemon, pane: string): Promise<number> {
const panePid = Number(await daemon.tmux.run('display-message', '-p', '-t', pane, '#{pane_pid}').catch(() => '0'))
@@ -98,6 +108,28 @@ describe('lifecycle requests that race', () => {
client.close()
})
+ // The daemon finds the engine and its conversation before the engine's first SessionStart arrives, as on
+ // a loaded machine. The first restart kills that engine just as its hook lands: registered for the
+ // engine being killed, its attach found the pane's process gone and unbound the conversation, and the
+ // second restart, finding none, started a fresh one. Seen once in eighteen runs under load; with the hook
+ // this late, two of seven before round 35. Where the hook lands against the kill varies with the
+ // machine, so three delays.
+ it.each([700, 1_100, 1_500])('codex: two restarts at once, as the engine\'s first hook reaches the daemon %i ms late, bring it back on its conversation', async (delay) => {
+ const d = await fresh()
+ install(d, 'codex', { firstHookDelayMs: Number(process.env.RACE_FIRST_HOOK_DELAY_MS ?? delay) })
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'codex', `late-first-hook-${delay}`)
+ const answers = await Promise.all([1, 2].map(() => client.request('agent_restart', { agentId: agent.id }, 90_000)))
+ for (const answer of answers) if (answer.error) expect(['AGENT_BUSY'], JSON.stringify(answer)).toContain(answer.error)
+ expect(answers.some((answer) => !answer.error), JSON.stringify(answers)).toBe(true)
+ const back = await active(client, agent.id, agent.sessionId)
+ await until('one engine in the pane', async () => (await engineProcesses(d, back.tmuxPane)) === 1 || null, 20_000, 250)
+ await turn(client, agent.id, 'after two restarts at once')
+ expect((await row(client, agent.id))?.sessionId).toBe(agent.sessionId)
+ expect((await rows(client)).filter((one) => one.status === 'active')).toHaveLength(1)
+ client.close()
+ })
+
it.each(engines)('%s: two resumes at once resume it once', async (engine) => {
const d = await fresh()
const client = await LocalClient.connect(d)
diff --git a/cli/e2e/twodaemons.e2e.ts b/cli/e2e/twodaemons.e2e.ts
index bf636477a..b5bb574b1 100644
--- a/cli/e2e/twodaemons.e2e.ts
+++ b/cli/e2e/twodaemons.e2e.ts
@@ -20,6 +20,7 @@
* user's daemon does, and the release daemon keeps its port, its socket and its agents.
*/
import { spawn } from 'node:child_process'
+import { createServer } from 'node:http'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
@@ -201,6 +202,39 @@ describe('two daemons on one computer', () => {
client.close()
})
+ it('a master started again while the core of the one that died still serves waits for that core to leave; another live daemon is still refused', async () => {
+ // What launchd or systemd does when a master dies: the same master again, at once, while its old core
+ // has yet to notice and stop. Stood in for by a socket that answers as such a core does: its master's
+ // pid, long gone, and its own. Refused, the new core exited for good, its master with it, cleanly,
+ // and neither platform starts a clean exit again: the daemon stayed down until the next login.
+ const gone = 2_000_000_000
+ const restarted = await make('restarted', { env: { HARNESSD_INITIAL_BACKOFF_MS: '200' } })
+ const orphan = createServer((_req, res) => res.end(JSON.stringify({ pid: gone, corePid: process.pid })))
+ await new Promise<void>((resolve) => orphan.listen(restarted.socketPath, resolve))
+ setTimeout(() => orphan.close(), 3_000)
+ await restarted.start({ ready: 'none' })
+ await until('the new core to finish starting', () => /\[cli\] ready/.test(restarted.log()) || null, 90_000, 200)
+ expect(restarted.log()).toContain(`of a master that is gone (pid ${gone}) — waiting for it to leave`)
+ expect(restarted.log()).not.toMatch(/core stopped for good/)
+ const client = await LocalClient.connect(restarted)
+ const agent = await create(restarted, client, 'claude', 'after-the-orphan')
+ await turn(client, agent.id, 'served once the old core left')
+ client.close()
+
+ // A daemon that answers for itself, with no master that is gone, is another daemon: refused at once.
+ const refused = await make('refused', { env: { HARNESSD_INITIAL_BACKOFF_MS: '200' } })
+ const live = createServer((_req, res) => res.end(JSON.stringify({ pid: process.pid, corePid: process.pid })))
+ await new Promise<void>((resolve) => live.listen(refused.socketPath, resolve))
+ try {
+ await refused.start({ ready: 'none' })
+ await until('the refused master to leave', () => refused.child === null || null, 60_000, 250)
+ expect(refused.log()).toMatch(/\[harnessd\] core stopped for good/)
+ expect(refused.log()).not.toMatch(/waiting for it to leave/)
+ } finally {
+ await new Promise((resolve) => live.close(resolve))
+ }
+ })
+
it('a dev daemon started on the release daemon\'s port takes another, and the release daemon keeps its own', async () => {
const release = await make('release')
const dev = await make('dev', { beside: release, port: release.port })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d01d358b7..47a947ec8 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3682,6 +3682,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
relaunchMarks,
})
const stopJobs = lifecycle.stopJobs
+ binding.whileChanging((agentId) => restartJobs.busy(agentId) || stopJobs.has(agentId))
const stopAgent = lifecycle.stopAgent
backend.stopProvider = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })
backend.purgeAgentService = lifecycle.purgeAgentService
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index d0657d34e..053b0b9ac 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -99,7 +99,9 @@ function seedRunningDaemon(root: string): { pid: number; exited: Promise<void> }
async function daemonStatusServer(root: string, machineId: string): Promise<number> {
const handler: RequestListener = (_req, res) => {
res.setHeader('content-type', 'application/json')
- res.end(JSON.stringify({ machineId, version: '0.0.0-test', sessions: [] }))
+ // A daemon says its pid (and, under a master, the master's), as every release with the socket has:
+ // start-up tells a live daemon from the core of a master that is gone by it (lib/localSocket.ts).
+ res.end(JSON.stringify({ machineId, version: '0.0.0-test', sessions: [], pid: process.pid, corePid: process.pid }))
}
const server = createServer(handler)
servers.push(server)
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index ffd7a3edc..524bcedfd 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -135,6 +135,22 @@ describe('binding a registered session to its agent', () => {
expect(run.deps.syncRecapPool).not.toHaveBeenCalled()
})
+ it('keeps the binding of an agent a stop or a restart owns: its pane reads as gone only because of it', async () => {
+ // The old engine's late SessionStart, registered as a stop or a restart ended that engine. Unbound,
+ // the stop gave up with its engine already signalled, and a queued restart found nothing to resume.
+ const run = setup({ attachSession: vi.fn(async () => false) })
+ const changing = vi.fn((agentId: string) => agentId === 'a1')
+ run.binding.whileChanging(changing)
+ const entry = agent()
+ await run.binding.handleRegistered(entry, meta())
+ expect(changing).toHaveBeenCalledWith('a1')
+ expect(run.deps.registry.unbindSession).not.toHaveBeenCalled()
+ expect(run.deps.announceSession).toHaveBeenCalledWith(entry)
+ // An agent nothing owns is unbound as before.
+ await run.binding.handleRegistered(agent({ agentId: 'a2', sessionId: 's2' }), meta())
+ expect(run.deps.registry.unbindSession).toHaveBeenCalledWith('s2')
+ })
+
it('hands a rebound agent its name and recap, and lets the stale session go', async () => {
const run = setup()
await run.binding.handleRegistered(agent({ sessionId: 's2' }), meta({ rebound: 's1' }))
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index ecff132f4..6fcc80275 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -79,6 +79,8 @@ export function createBinding({
* over a hook. Settled the moment it binds, below.
*/
const pendingForkInherit = new Map<string, string>()
+ /** Whether a stop, restart, retarget or resume owns the agent right now (`whileChanging`). */
+ let changing: (agentId: string) => boolean = () => false
const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {
const forkSource = pendingForkInherit.get(entry.agentId)
@@ -157,7 +159,14 @@ export function createBinding({
)
const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)
if (!attached) {
- registry.unbindSession(entry.sessionId)
+ // A terminal reads as gone while a stop or a restart ends its engine. A registration that comes in
+ // then, such as the old engine's own SessionStart arriving late on a loaded machine, is still the
+ // agent's conversation, and the operation owns what happens to it. Unbound, a stop that had just
+ // signalled the engine found the conversation changed and gave up, leaving an active agent with no
+ // engine; and a second restart queued behind a first found no conversation to resume and started a
+ // fresh one (e2e/races.e2e.ts). The binding stands while one of them runs: a stop retires it, and a
+ // restart's new engine registers it again.
+ if (!changing(entry.agentId)) registry.unbindSession(entry.sessionId)
announceSession(entry)
return
}
@@ -325,5 +334,9 @@ export function createBinding({
await handleRegistered(result.entry, result)
console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} via ${observed.primaryRuntimeKey}`)
}
- return { pendingForkInherit, handleRegistered, bindObservedAgent }
+ return {
+ pendingForkInherit, handleRegistered, bindObservedAgent,
+ /** Set by cli.ts once the lifecycle operations exist: they are made long after the binding. */
+ whileChanging: (test: (agentId: string) => boolean): void => { changing = test },
+ }
}
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index 85bd6604f..1967671a8 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -8,7 +8,7 @@ import { probeGridAssignment } from '../../lib/gridAssignment.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { AgentRestartCoordinator, bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
-import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import { clearPaneRemainOnExit, processArgs } from '../../lib/tmux.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { createAgentRestarter, type RestartDeps } from './restart.js'
@@ -25,7 +25,10 @@ vi.mock('../../lib/restartAgent.js', async (real) => ({
bypassPermissionFor: vi.fn(async (_s: unknown, live: () => Promise<boolean>) => live()),
restartAgent: vi.fn(async () => ({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })),
}))
-vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))
+vi.mock('../../lib/tmux.js', async (real) => ({
+ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}),
+ processArgs: vi.fn(async () => '/bin/claude --model opus -c model_provider=grid'),
+}))
vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))
const runtime = { backend: 'tmux', paneId: '%4' }
@@ -234,7 +237,9 @@ describe('restarting an agent', () => {
expect(swapDeps.isCurrent?.()).toBe(true)
expect(run.deps.refreshGridWebSearch).toHaveBeenCalledWith('a1', { env: { GRID_KEY: 'k' } })
expect(probeGatewayRuntime).toHaveBeenCalledWith(newProcess)
- expect(probeGridAssignment).toHaveBeenCalledWith(newProcess, 'claude', '/bin/claude')
+ // Its command line, where a Codex or pi grid's address and model are: never its executable alone.
+ expect(processArgs).toHaveBeenCalledWith(newProcess)
+ expect(probeGridAssignment).toHaveBeenCalledWith(newProcess, 'claude', '/bin/claude --model opus -c model_provider=grid')
expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', newProcess, 'none', undefined)
expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)
expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index 49b78d40b..5150d14a1 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -16,7 +16,7 @@ import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
-import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import { clearPaneRemainOnExit, processArgs } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
@@ -179,7 +179,8 @@ export function createAgentRestarter({
// than left to the next scan, so the announce below already says where the engine came back.
const [gateway, assignment] = await Promise.all([
probeGatewayRuntime(outcome.processIdentity),
- probeGridAssignment(outcome.processIdentity, engine, outcome.processIdentity.executable),
+ // Its command line, which carries a Codex or pi grid's address and model: never its executable.
+ processArgs(outcome.processIdentity).then((args) => probeGridAssignment(outcome.processIdentity, engine, args)),
])
if (!current()) return changed
registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index d6d757b1a..5ffaba351 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -7,6 +7,7 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfile.js'
import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'
+import { probeGridAssignment } from '../../lib/gridAssignment.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { createAgentRetargeter, type RetargetDeps } from './retarget.js'
@@ -29,7 +30,10 @@ vi.mock('../../lib/restartAgent.js', async (real) => ({
}))
vi.mock('../../lib/runtimeProfile.js', async (real) => ({ ...await real<object>(), parseRuntimeProfile: vi.fn(() => ({ engine: 'claude', model: 'opus' })) }))
vi.mock('../../lib/runtimeProfileController.js', async (real) => ({ ...await real<object>(), inspectRuntimePane: vi.fn(() => ({ idle: true })) }))
-vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))
+vi.mock('../../lib/tmux.js', async (real) => ({
+ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}),
+ processArgs: vi.fn(async () => 'codex -c model_providers.grid.base_url=http://grid.local/v1'),
+}))
vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))
const pane = { backend: 'tmux', paneId: '%4' }
@@ -116,6 +120,8 @@ describe('retargeting an agent', () => {
expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalled()
expect(restartAgent).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1' }, true, {})
+ // The grid is read off the new process's command line, never its executable alone.
+ expect(probeGridAssignment).toHaveBeenCalledWith(expect.objectContaining({ pid: 2 }), 'claude', 'codex -c model_providers.grid.base_url=http://grid.local/v1')
expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', expect.objectContaining({ pid: 2 }), 'none', undefined)
expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', { override: grid, webSearch: 'off' })
expect(run.deps.registry.setSubscriptionModel).toHaveBeenCalledWith('a1', 'opus')
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 8e3f20df8..9a2a64f81 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -27,7 +27,7 @@ import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
-import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import { clearPaneRemainOnExit, processArgs } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
@@ -230,10 +230,11 @@ export function createAgentRetargeter({
console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)
return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }
}
- // Both are read from the one cached environment of the new pid, so this costs no extra `ps`.
+ // Both are read off the new pid: its cached environment, and for the grid its command line too.
const [gateway, assignment] = await Promise.all([
probeGatewayRuntime(outcome.processIdentity),
- probeGridAssignment(outcome.processIdentity, session.engine, outcome.processIdentity.executable),
+ // Its command line, which carries a Codex or pi grid's address and model: never its executable.
+ processArgs(outcome.processIdentity).then((args) => probeGridAssignment(outcome.processIdentity, session.engine, args)),
])
registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)
// The launch that just worked is the one a restart or a post-reboot restore must repeat — and
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index 14a12d8da..0f2dc9d48 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -59,7 +59,10 @@ describe('which agent a hook belongs to', () => {
const a1 = agent('a1', 100)
const { deps, hooks } = setup({ '%1': a1 })
vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)
- expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBe(a1)
+ const onWait = vi.fn()
+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300, onWait })).toBe(a1)
+ // Matched at once: nothing to wait for, and the hook is answered with its agent.
+ expect(onWait).not.toHaveBeenCalled()
expect(deps.agentReconciler.triggerHint).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')
expect(deps.registry.byRuntimeEngine).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')
expect(console.log).not.toHaveBeenCalled()
@@ -128,9 +131,9 @@ describe('which agent a hook belongs to', () => {
// killed; nothing in the table is it any more.
const newEngine = () => tree([300, 200], [200, 1])
/** Asks, and says when the hook has started waiting: after it read the process table once. */
- const ask = (hooks: ReturnType<typeof setup>['hooks'], panes = ['%1']) => {
+ const ask = (hooks: ReturnType<typeof setup>['hooks'], panes = ['%1'], onWait?: () => void) => {
let answer: RegisteredSession | null | undefined
- const asked = hooks.resolveHookAgent({ engine: 'claude', runtimeHints: panes.map(hint), callerPid: 300 }).then((agent) => { answer = agent })
+ const asked = hooks.resolveHookAgent({ engine: 'claude', runtimeHints: panes.map(hint), callerPid: 300, ...(onWait ? { onWait } : {}) }).then((agent) => { answer = agent })
const waiting = () => vi.waitFor(() => expect(processRows).toHaveBeenCalledTimes(1))
return { asked, waiting, answer: () => answer }
}
@@ -138,14 +141,19 @@ describe('which agent a hook belongs to', () => {
it('in a restart, waits while the recorded process is one that is gone, and belongs to the agent once the new one is recorded', async () => {
const onPane: Record<string, RegisteredSession> = { '%1': agent('a1', 100) }
vi.mocked(processRows).mockResolvedValue(newEngine() as never)
- const hook = ask(setup(onPane).hooks, ['%1', '%9'])
+ const onWait = vi.fn()
+ const hook = ask(setup(onPane).hooks, ['%1', '%9'], onWait)
await hook.waiting()
await new Promise((resolve) => setTimeout(resolve, 250))
expect(hook.answer()).toBeUndefined()
+ // Said before the wait, so the hook is answered then: its client gives up after 500ms and writes
+ // the registry itself (hook/notify.mjs).
+ expect(onWait).toHaveBeenCalledTimes(1)
// What restart.ts does once the new process is found and probed.
onPane['%1'] = agent('a1', 200)
await hook.asked
expect(hook.answer()).toEqual(agent('a1', 200))
+ expect(onWait).toHaveBeenCalledTimes(1)
expect(console.log).not.toHaveBeenCalled()
})
@@ -196,6 +204,27 @@ describe('which agent a hook belongs to', () => {
vi.useRealTimers()
}
})
+
+ it('is not cut short by a step of the wall clock, as a wake or an NTP correction makes', async () => {
+ // Round 29 steps the clock under working agents; a deadline on the wall clock ended this wait at
+ // the first poll after a step forward, and the hook was dropped as if its record never came.
+ vi.useFakeTimers()
+ try {
+ const onPane: Record<string, RegisteredSession> = { '%1': agent('a1', 100) }
+ vi.mocked(processRows).mockResolvedValue(newEngine() as never)
+ const hook = ask(setup(onPane).hooks)
+ await vi.advanceTimersByTimeAsync(1_000)
+ vi.setSystemTime(Date.now() + 3 * 3_600_000)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(hook.answer()).toBeUndefined()
+ onPane['%1'] = agent('a1', 200)
+ await vi.advanceTimersByTimeAsync(200)
+ await hook.asked
+ expect(hook.answer()).toEqual(agent('a1', 200))
+ } finally {
+ vi.useRealTimers()
+ }
+ })
})
it('a SessionEnd only asks for a reconcile: discovery decides whether the agent still exists', () => {
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index 962d84dba..c60447957 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -32,8 +32,9 @@ export interface EngineHookDeps {
* The longest a hook waits for the agent on its pane to record the process it came from. Every relaunch
* starts its engine before it records it: a resume looks for the process every 250ms, a create or a
* fork backs off to 750ms, and a restart finds it the same way and then probes it, twice over when it
- * falls back to a new conversation (two 8s discovery budgets, swap.ts). Bounded all the same: the engine
- * kills its own hook command at 5s, and an answer later than that only keeps the daemon's record.
+ * falls back to a new conversation (two 8s discovery budgets, swap.ts). The hook itself is answered
+ * before the wait (`onWait`): its client gives up on a reply after 500ms and then writes the registry
+ * itself (hook/notify.mjs), so only the daemon's record waits.
*/
export const PROCESS_RECORD_WAIT_MS = 20_000
/** How often a waiting hook reads the rows on its panes again: memory, not a process table. */
@@ -101,14 +102,16 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En
* pane), or when the wait is over. */
const recordChanged = async (resolved: TerminalRuntimeRef[], engine: HookQuery['engine']): Promise<void> => {
const before = resolved.map((runtime) => recordKey(registry.byRuntimeEngine(runtime, engine)))
- const deadline = Date.now() + PROCESS_RECORD_WAIT_MS
- while (Date.now() < deadline) {
+ // On the monotonic clock: a wall clock stepped forward (a wake, an NTP correction: round 29) ended
+ // the wait at its next poll and dropped the hook, and one stepped back kept it polling for the step.
+ const deadline = performance.now() + PROCESS_RECORD_WAIT_MS
+ while (performance.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, PROCESS_RECORD_POLL_MS))
if (resolved.some((runtime, i) => recordKey(registry.byRuntimeEngine(runtime, engine)) !== before[i])) return
}
}
- const resolveHookAgent: ResolveHookAgent = async ({ engine, runtimeHints, callerPid }) => {
+ const resolveHookAgent: ResolveHookAgent = async ({ engine, runtimeHints, callerPid, onWait }) => {
if (!callerPid) return null
const resolved: TerminalRuntimeRef[] = []
for (const hint of runtimeHints ?? []) {
@@ -126,6 +129,7 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En
// hook's pane has no live process recorded, the hook now waits for it to record one, and is matched
// again against that: one rule for every relaunch, with nothing for any of them to remember to do.
if (!choice.agent && choice.reason === 'none' && found.unrecorded.length) {
+ onWait?.()
await recordChanged(resolved, engine)
found = await matchCaller(resolved, engine, callerPid)
if (!found) return null
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index f36507631..b8050d06d 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -81,6 +81,7 @@ describe('process-owned hook server', () => {
expect(await response.json()).toEqual({ ignored: true, reason: 'no_matching_engine_process' })
expect(resolveHookAgent).toHaveBeenCalledWith({
engine: 'codex', tmuxPane: '%41', runtimeHints: [{ backend: 'tmux', paneId: '%41' }], callerPid: undefined,
+ onWait: expect.any(Function),
})
expect(handlers.onRegistered).not.toHaveBeenCalled()
})
@@ -105,9 +106,39 @@ describe('process-owned hook server', () => {
expect(response.status).toBe(200)
expect(resolveHookAgent).toHaveBeenCalledWith({
engine: 'codex', tmuxPane: '%41', runtimeHints: [{ backend: 'tmux', paneId: '%41' }], callerPid: undefined,
+ onWait: expect.any(Function),
})
})
+ it('answers a hook whose agent has yet to record its process before the wait, and only logs what the wait finds', async () => {
+ // The engine's hook command gives up on a reply after 500ms and then writes the registry itself, as for
+ // a daemon that is down (hook/notify.mjs, fallbackRegister): held for the wait, its own row took the
+ // agent's place under the running daemon. Answered first, it writes nothing.
+ let found!: (agent: RegisteredSession | null) => void
+ const resolveHookAgent = vi.fn(({ onWait }: { onWait?: () => void }) => {
+ onWait?.()
+ return new Promise<RegisteredSession | null>((resolve) => { found = resolve })
+ })
+ const { handlers, base, headers } = await start({ resolveHookAgent: resolveHookAgent as HookServerHandlers['resolveHookAgent'] })
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ const reply = await Promise.race([
+ fetch(`${base}/api/hook/session-start`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ engine: 'claude', tmuxPane: '%7', sessionId: 'session-7', callerPid: 4242 }),
+ }),
+ new Promise<'held'>((resolve) => setTimeout(() => resolve('held'), 2_000)),
+ ])
+ expect(reply).not.toBe('held')
+ expect(await (reply as Response).json()).toEqual({ pending: true })
+ // The wait ends with no agent for it: said in the log, and nothing is answered twice.
+ found(null)
+ await vi.waitFor(() => expect(log).toHaveBeenCalledWith('[hooks] session- session-start ignored · no_matching_engine_process'))
+ expect(handlers.onRegistered).not.toHaveBeenCalled()
+ } finally { log.mockRestore() }
+ })
+
it('ignores a hook whose only terminal is a Herdr pane', async () => {
const resolveHookAgent = vi.fn(async () => null)
const { base, headers } = await start({ resolveHookAgent })
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 97d24461f..18320b0cc 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -79,6 +79,9 @@ export interface HookServerHandlers {
tmuxPane?: string
runtimeHints: HookTerminalHint[]
callerPid?: number
+ /** Called once the resolution has to wait for the agent to record its process
+ * (core/engines/hooks.ts): the hook is answered then, before the wait. */
+ onWait?: () => void
}) => Promise<RegisteredSession | null>
/** A turn is now running (Command Code's PreToolUse — its only live turn-open signal). Idempotent:
* it fires once per tool call, and every call after the first in a turn must be a no-op. */
@@ -488,9 +491,16 @@ export function startHookServer(
// Every rejection below says WHY, out loud. They used to be silent, and a hook that arrives and
// is dropped looks exactly like a hook that never fired — which is precisely the confusion behind
// "the agent is running in my terminal but the list does not show it".
+ // Answered once: a hook answered before its resolution waited is only logged after it.
+ let answered = false
+ const answer = (code: number, reply: unknown): void => {
+ if (answered) return
+ answered = true
+ json(code, reply)
+ }
const ignore = (reason: string): void => {
console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · ${reason}`)
- json(200, { ignored: true, reason })
+ answer(200, { ignored: true, reason })
}
const runtimeHints = normalizedRuntimeHints(body)
if (!runtimeHints.length) { ignore('not_in_terminal'); return }
@@ -512,6 +522,13 @@ export function startHookServer(
tmuxPane: body.tmuxPane,
runtimeHints,
callerPid: Number.isSafeInteger(body.callerPid) && body.callerPid! > 0 ? body.callerPid : undefined,
+ // A relaunch records its engine's process a moment after the engine starts, and a hook in that
+ // moment waits for the record, up to 20s. Its client does not: the engine's hook command gives
+ // up on a reply after 500ms and then writes the registry itself, as for a daemon that is down
+ // (hook/notify.mjs, fallbackRegister), with a row of its own in place of the agent's, which
+ // the running daemon's next save took in. Told the registration is pending, it writes nothing,
+ // as for a transcript not yet written below, and the wait goes on here.
+ onWait: () => answer(200, { pending: true }),
})
: body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) ?? null : null
if (!processAgent || processAgent.engine !== engine) { ignore('no_matching_engine_process'); return }
@@ -534,7 +551,7 @@ export function startHookServer(
// Settled off the HTTP path entirely: the answer needs a SQLite read, and the row may not even
// be written yet (measured: a child's hook beat its own INSERT by 110ms). Registering
// optimistically would hand the parent's pane to a sub-agent.
- json(200, { pending: true })
+ answer(200, { pending: true })
void awaitHermesKind(body, handlers)
return
}
@@ -548,18 +565,18 @@ export function startHookServer(
// is only accepted with a real file behind it) and the agent stayed off the list until something
// else noticed it. Wait for the file instead of dropping the announcement — in the background,
// because a SessionStart hook blocks the CLI that is waiting on this reply.
- json(200, { pending: true })
+ answer(200, { pending: true })
void awaitTranscript(body, handlers)
return
}
if (!result) {
console.warn(`[hooks] ${sid(body.sessionId ?? '?')} REJECTED · engine=${body.engine} pane=${body.tmuxPane}`)
- json(400, { error: 'invalid session registration' })
+ answer(400, { error: 'invalid session registration' })
return
}
console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)
handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
- json(200, { ok: true })
+ answer(200, { ok: true })
return
}
diff --git a/cli/src/lib/localSocket.spec.ts b/cli/src/lib/localSocket.spec.ts
index 92ec78816..173e2e159 100644
--- a/cli/src/lib/localSocket.spec.ts
+++ b/cli/src/lib/localSocket.spec.ts
@@ -3,7 +3,10 @@ import { connect } from 'node:net'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, refuseServedDataFolder, type LocalSocketServer } from './localSocket.js'
+import {
+ askDataFolderServer, isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, ORPHAN_WAIT_MS,
+ refuseServedDataFolder, type DataFolderServer, type LocalSocketServer, type ServedFolderDeps,
+} from './localSocket.js'
const LOCAL_SOCKET_NAME = localSocketName(18473)
@@ -190,6 +193,10 @@ describe('listenLocalSocket', () => {
})
describe('refuseServedDataFolder', () => {
+ /** A daemon's answer to `GET /api/status`, as `harness start` gives it. */
+ const status = (pid: number, corePid?: number) => (_req: unknown, res: { end(body: string): void }) =>
+ res.end(JSON.stringify({ pid, ...(corePid === undefined ? {} : { corePid }) }))
+
it('refuses only a data folder a daemon is serving right now, as the bind would', async () => {
const dir = shortDir()
const path = join(dir, LOCAL_SOCKET_NAME)
@@ -203,9 +210,84 @@ describe('refuseServedDataFolder', () => {
writeFileSync(plain, 'not a socket')
await expect(refuseServedDataFolder(plain)).resolves.toBeUndefined()
- const running = await listenLocalSocket((_req, res) => res.end(), path)
- opened.push(running)
- const refused = await refuseServedDataFolder(path).catch((error: unknown) => error as NodeJS.ErrnoException)
- expect(refused).toMatchObject({ code: 'EADDRINUSE', message: `A Harness daemon is already serving ${path}` })
+ // A daemon with no master, and one whose master is this live process: refused at once.
+ for (const answer of [status(process.pid), status(process.pid, process.ppid)]) {
+ const running = await listenLocalSocket(answer as never, path)
+ const startedAt = Date.now()
+ const refused = await refuseServedDataFolder(path).catch((error: unknown) => error as NodeJS.ErrnoException)
+ expect(refused).toMatchObject({ code: 'EADDRINUSE', message: `A Harness daemon is already serving ${path}` })
+ expect(Date.now() - startedAt).toBeLessThan(2_000)
+ await running.close()
+ }
+ })
+
+ it('waits for the core of a master that is gone to leave, and starts once it has', async () => {
+ // Under launchd or systemd a master that died is started again at once, while its old core still
+ // serves until it notices. Refused, the new core exited for good and the daemon stayed down.
+ const path = join(shortDir(), LOCAL_SOCKET_NAME)
+ const orphan = await listenLocalSocket(status(2_000_000_000, process.pid) as never, path)
+ const lines: string[] = []
+ setTimeout(() => void orphan.close(), 600)
+ await expect(refuseServedDataFolder(path, 1_000, {
+ who: askDataFolderServer, alive: () => false, sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
+ now: () => performance.now(), log: (line) => lines.push(line),
+ })).resolves.toBeUndefined()
+ expect(lines).toEqual([
+ `[cli] this data folder is still served by the core (pid ${process.pid}) of a master that is gone (pid 2000000000) — waiting for it to leave`,
+ '[cli] the core whose master is gone has left — starting',
+ ])
+ })
+
+ it('reads who serves: a daemon and its master, one from before harnessd as its own, and anything else as unknown', async () => {
+ const path = join(shortDir(), LOCAL_SOCKET_NAME)
+ expect(await askDataFolderServer(path, 500)).toBe('none')
+ const answers: Array<[unknown, DataFolderServer]> = [
+ [status(10, 20), { pid: 10, corePid: 20 }],
+ [status(10), { pid: 10, corePid: 10 }],
+ [status(0, 20), 'unknown'],
+ [(_req: unknown, res: { end(body: string): void }) => res.end('not json'), 'unknown'],
+ ]
+ for (const [handler, expected] of answers) {
+ const server = await listenLocalSocket(handler as never, path)
+ expect(await askDataFolderServer(path, 500)).toEqual(expected)
+ await server.close()
+ }
+ // One that takes the connection and never answers.
+ const silent = await listenLocalSocket(() => {}, path)
+ expect(await askDataFolderServer(path, 200)).toBe('unknown')
+ await silent.close()
+ })
+
+ it('decides from who serves: waits on an orphan or a silence until it goes or the wait is over, refuses a live daemon at once', async () => {
+ const run = async (answers: DataFolderServer[], alive: (pid: number) => boolean = () => false) => {
+ let clock = 0
+ const lines: string[] = []
+ const deps: ServedFolderDeps = {
+ who: async () => answers.length > 1 ? answers.shift()! : answers[0], alive,
+ sleep: async (ms) => { clock += ms }, now: () => clock, log: (line) => lines.push(line),
+ }
+ const outcome = await refuseServedDataFolder('/data/daemon-1.sock', 1_000, deps).then(() => 'started', (error: NodeJS.ErrnoException) => error.code)
+ return { outcome, waited: clock, lines }
+ }
+ expect(await run(['none'])).toEqual({ outcome: 'started', waited: 0, lines: [] })
+ expect(await run([{ pid: 7, corePid: 8 }, { pid: 7, corePid: 8 }, 'none'])).toMatchObject({ outcome: 'started', waited: 500 })
+ // A daemon that does not say who it is is busy or hung, not leaving: every release with this socket
+ // says its pid. Refused at once, as before: a person waiting on a start never waits out the bound
+ // for it (the fake daemon of cliCommand.spec.ts answered without a pid, and each start took 20 s).
+ expect(await run(['unknown', 'none'])).toMatchObject({ outcome: 'EADDRINUSE', waited: 0, lines: [] })
+ // The orphan itself may go quiet while it stops, once it has been seen to be one.
+ const stopping = await run([{ pid: 7, corePid: 8 }, 'unknown', 'none'])
+ expect(stopping).toMatchObject({ outcome: 'started', waited: 500 })
+ expect(stopping.lines).toEqual([
+ '[cli] this data folder is still served by the core (pid 8) of a master that is gone (pid 7) — waiting for it to leave',
+ '[cli] the core whose master is gone has left — starting',
+ ])
+ // Its master alive, or no master at all: another daemon.
+ expect(await run([{ pid: 7, corePid: 8 }], () => true)).toMatchObject({ outcome: 'EADDRINUSE', waited: 0 })
+ expect(await run([{ pid: 8, corePid: 8 }])).toMatchObject({ outcome: 'EADDRINUSE', waited: 0 })
+ // One that never leaves is refused once the wait is over.
+ const lingering = await run([{ pid: 7, corePid: 8 }])
+ expect(lingering).toMatchObject({ outcome: 'EADDRINUSE', waited: ORPHAN_WAIT_MS })
+ expect(lingering.lines).toHaveLength(1)
})
})
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index 037676847..b2278f5a0 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -147,26 +147,105 @@ async function claim(staging: string, path: string): Promise<void> {
}
}
+/** What answers on a data folder's socket: nothing, something that does not say who it is, or a daemon
+ * and its master (`pid`, the pid file's: the master's under one, its own otherwise) and its core. */
+export type DataFolderServer = 'none' | 'unknown' | { pid: number; corePid: number }
+
+export interface ServedFolderDeps {
+ /** Who serves the socket at `path` (`GET /api/status` over it). */
+ who(path: string, timeoutMs: number): Promise<DataFolderServer>
+ alive(pid: number): boolean
+ sleep(ms: number): Promise<void>
+ now(): number
+ log(line: string): void
+}
+
+/** How long start-up waits for the core of a master that is gone to leave: well inside the minute the
+ * master gives a core to bind, and longer than such a core takes to stop. */
+export const ORPHAN_WAIT_MS = 20_000
+const ORPHAN_POLL_MS = 250
+
+/** Ask the daemon on a data folder's socket who it is. A socket that takes no connection serves nothing
+ * (no socket, a stale one, one that cannot be reached: start-up goes on, and the bind decides); one that
+ * takes it and does not say is `unknown`. */
+export function askDataFolderServer(path: string, timeoutMs: number): Promise<DataFolderServer> {
+ return new Promise((resolve) => {
+ let connected = false
+ // A connection of its own, never one kept alive from an earlier ask: that one may be to a daemon gone.
+ const request = http.request({ socketPath: path, path: '/api/status', method: 'GET', timeout: timeoutMs, agent: false }, (response) => {
+ let body = ''
+ response.setEncoding('utf8')
+ response.on('data', (chunk: string) => { if (body.length < 65_536) body += chunk })
+ response.on('end', () => {
+ try {
+ const status = JSON.parse(body) as { pid?: unknown; corePid?: unknown }
+ const pid = Number(status.pid)
+ // A daemon from before harnessd says no core of its own: it is its own master.
+ const corePid = status.corePid === undefined ? pid : Number(status.corePid)
+ resolve(Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(corePid) && corePid > 0 ? { pid, corePid } : 'unknown')
+ } catch { resolve('unknown') }
+ })
+ response.on('error', () => resolve('unknown'))
+ })
+ request.on('socket', (socket: Socket) => socket.once('connect', () => { connected = true }))
+ request.on('timeout', () => { request.destroy(); resolve(connected ? 'unknown' : 'none') })
+ request.on('error', () => resolve(connected ? 'unknown' : 'none'))
+ request.end()
+ })
+}
+
+const SERVED_FOLDER_DEFAULTS: ServedFolderDeps = {
+ who: askDataFolderServer,
+ alive: (pid) => { try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' } },
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ now: () => performance.now(),
+ log: (line) => console.log(line),
+}
+
/**
* Refuse to start a daemon whose data folder another daemon already serves: start-up asks this before it
* reads or writes anything of that daemon's. Rejects with `EADDRINUSE`, as the bind it spares would have.
- * Anything short of a live answer — no socket, a stale one, one that cannot be checked — lets start-up
- * go on, and the bind decides.
+ * No socket, or a stale one, lets start-up go on, and the bind decides.
*
* A second `harness start --foreground` (a launchd or systemd unit beside the app's daemon), and the core
* of a second master, used to get as far as that bind first: on the way they marked the running daemon's
* agents inactive on disk and reaped its harness viewers as the orphans of a daemon that had died
* (e2e/twodaemons.e2e.ts).
+ *
+ * ⚠️ Except the core of a master that is gone, which serves only until it notices and stops. Under launchd
+ * or systemd a master that died is started again at once, and its new core found the old one still
+ * there: refused, it exits for good, its master with it, cleanly, and neither launchd's
+ * `SuccessfulExit=false` nor systemd's `Restart=on-failure` starts a clean exit again, so the daemon stayed
+ * down until the next login. Such a core is waited for, a bounded while, and once it has said so, so is
+ * a silence from it while it stops. A daemon whose master is alive, or that runs without one, is another
+ * daemon, and refused at once as before. So is one that answers without saying who it is: every release
+ * with this socket has said its pid in `/api/status`, so a silence or an answer without one is a daemon
+ * that is busy or hung, not one that is leaving, and a person waiting on `harness start` or the app must
+ * not wait out the orphan's bound for it (cliCommand.spec.ts, the CI runs of #819).
*/
-export async function refuseServedDataFolder(path: string | null, timeoutMs = 1_000): Promise<void> {
+export async function refuseServedDataFolder(
+ path: string | null, timeoutMs = 1_000, deps: ServedFolderDeps = SERVED_FOLDER_DEFAULTS, waitMs = ORPHAN_WAIT_MS,
+): Promise<void> {
if (!path) return
- const served = await new Promise<boolean>((resolve) => {
- const socket = connect(path)
- socket.once('connect', () => { socket.destroy(); resolve(true) })
- socket.once('error', () => resolve(false))
- socket.setTimeout(timeoutMs, () => { socket.destroy(); resolve(false) })
- })
- if (served) throw alreadyServing(path)
+ const deadline = deps.now() + waitMs
+ let orphanSeen = false
+ for (;;) {
+ const server = await deps.who(path, timeoutMs)
+ if (server === 'none') {
+ if (orphanSeen) deps.log('[cli] the core whose master is gone has left — starting')
+ return
+ }
+ if (server === 'unknown') {
+ // Only the core already seen to be an orphan may go quiet while it stops.
+ if (!orphanSeen) throw alreadyServing(path)
+ } else {
+ if (server.pid === server.corePid || deps.alive(server.pid)) throw alreadyServing(path)
+ if (!orphanSeen) deps.log(`[cli] this data folder is still served by the core (pid ${server.corePid}) of a master that is gone (pid ${server.pid}) — waiting for it to leave`)
+ orphanSeen = true
+ }
+ if (deps.now() >= deadline) throw alreadyServing(path)
+ await deps.sleep(ORPHAN_POLL_MS)
+ }
}
async function refuseLiveSocket(path: string): Promise<void> {
diff --git a/cli/src/lib/processRows.spec.ts b/cli/src/lib/processRows.spec.ts
index cf26798a4..39f1ef878 100644
--- a/cli/src/lib/processRows.spec.ts
+++ b/cli/src/lib/processRows.spec.ts
@@ -2,7 +2,7 @@ import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import { processRows } from './tmux.js'
+import { processArgs, processRows } from './tmux.js'
/**
* A `ps` on PATH that records every spawn and answers one well-formed row after a short pause — long
@@ -32,6 +32,14 @@ printf ' 123 1 claude Mon Sep 21 10:00:00 2026 claude --resume\\n'
})
const spawns = (): number => { try { return readFileSync(calls, 'utf8').split('\n').filter(Boolean).length } catch { return 0 } }
+ it('reads one process\'s command line, and none for a process it is not, or when ps fails', async () => {
+ const [row] = (await processRows())!
+ expect(await processArgs(row)).toBe('claude --resume')
+ expect(await processArgs({ ...row, startMarker: 'another start' })).toBe('')
+ writeFileSync(join(dir, 'fail'), '')
+ expect(await processArgs(row)).toBe('')
+ })
+
// The first reconcile pass after a boot attaches a few agents at once, and each validates its pane
// against the table; a hook burst does the same. One `ps` for the burst, not one per caller.
it('callers that overlap share one ps, callers that follow get a fresh one', async () => {
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index a3713faca..abf7b7b1b 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -293,6 +293,12 @@ function readProcStat(pid: number): string | null {
*/
let processRowsInFlight: Promise<ProcessRow[] | null> | null = null
+/** A running process's command line as the process table shows it; '' once it is not that process. */
+export async function processArgs(identity: ProcessIdentity): Promise<string> {
+ const rows = await processRows()
+ return rows?.find((row) => row.pid === identity.pid && row.startMarker === identity.startMarker)?.args ?? ''
+}
+
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
export function processRows(): Promise<ProcessRow[] | null> {
if (processRowsInFlight) return processRowsInFlight