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.

harnessd: dead agents stop showing as active when tmux's server dies; no turns replayed after a restart; round 17 (#767)

Deee3766b0f59a1
diff --git a/cli/e2e/machine.e2e.ts b/cli/e2e/machine.e2e.ts
new file mode 100644
index 000000000..deab0d19b
--- /dev/null
+++ b/cli/e2e/machine.e2e.ts
@@ -0,0 +1,123 @@
+/**
+ * What the machine does to the daemon, for Claude Code and Codex: the tmux server that holds every
+ * agent's pane dies at once (a `tmux kill-server`, or tmux crashing), with agents idle or mid-turn,
+ * and the machine restarts while the daemon is down, which takes every pane with it. When the server
+ * dies under it, the daemon must carry on, must not keep showing any agent as active or working, and
+ * must bring each back with its conversation when it is opened again. After a restart it brings them
+ * back on its own.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Row> {
+ const cwd = join(daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+/** Neither active nor working: what an agent whose pane is gone must read as. */
+const down = (agent: Row | undefined) => !agent || (agent.status !== 'active' && agent.activity?.state !== 'working')
+/** Opened again, it comes back with the same conversation, and takes a turn there. */
+async function reopen(client: LocalClient, agent: Row, content: string): Promise<void> {
+ const resumed = await client.request('agent_resume', { agentId: agent.id }, 90_000)
+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()
+ await until(`${agent.id.slice(0, 8)} back with its conversation`, async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)
+ await turn(client, agent.id, content)
+}
+
+describe('what the machine does to the daemon', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const fresh = async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => {
+ console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`)
+ // The runner swallows console output: MACHINE_LOG=<file> keeps the daemon's whole log for reading.
+ if (process.env.MACHINE_LOG) writeFileSync(process.env.MACHINE_LOG, d.log())
+ })
+ await d.start()
+ return d
+ }
+
+ it('the tmux server dies under idle agents: none reads as active, the next agent runs, and each comes back', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agents = [await create(d, client, 'claude', 'idle-claude'), await create(d, client, 'codex', 'idle-codex')]
+ for (const agent of agents) await turn(client, agent.id, `before the server died (${agent.engine})`)
+
+ await d.tmux.run('kill-server')
+ for (const agent of agents) {
+ await until(`${agent.engine} to stop reading as active`, async () => down(await row(client, agent.id)) || null, 45_000, 500)
+ }
+ // The daemon carries on: a new agent gets a new server, and runs.
+ const next = await create(d, client, 'claude', 'after-the-server')
+ await turn(client, next.id, 'on a new server')
+ // Each comes back with its conversation.
+ for (const agent of agents) await reopen(client, agent, `back after the server died (${agent.engine})`)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it.each(['claude', 'codex'] as const)('%s: the tmux server dies mid-turn: the turn does not stay working, and the agent comes back', async (engine) => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `mid-turn-${engine}`)
+ client.send('message', { agentId: agent.id, content: '!slow 8000' })
+ await client.next(isTurn('turn_started', agent.id), 30_000, 'turn_started')
+ await until('the agent to read as working', async () => (await row(client, agent.id))?.activity?.state === 'working' || null, 15_000, 250)
+
+ await d.tmux.run('kill-server')
+ await until('the agent to stop reading as working', async () => down(await row(client, agent.id)) || null, 45_000, 500)
+ await reopen(client, agent, 'back after the server died mid-turn')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('the machine restarts while the daemon is down: every agent comes back on its own, with its conversation', async () => {
+ const d = await fresh()
+ let client = await LocalClient.connect(d)
+ const agents = [await create(d, client, 'claude', 'reboot-claude'), await create(d, client, 'codex', 'reboot-codex')]
+ for (const agent of agents) await turn(client, agent.id, `before the restart (${agent.engine})`)
+ client.close()
+
+ // A reboot: the daemon stops, and so does every pane with it. Its next start restores each agent
+ // that was open into a new pane, resuming its conversation, with nobody opening it again.
+ await d.stop()
+ await d.tmux.run('kill-server')
+ await d.start()
+ client = await LocalClient.connect(d)
+ for (const agent of agents) {
+ await until(`${agent.engine} back on its own with its conversation`, async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)
+ }
+ for (const agent of agents) await turn(client, agent.id, `after the machine restarted (${agent.engine})`)
+ client.close()
+ })
+})
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
index 4ea8ebd3b..56a141505 100644
--- a/cli/src/core/transcripts/attach.spec.ts
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -271,6 +271,23 @@ describe('attaching a session', () => {
expect(run.deps.emit).not.toHaveBeenCalled()
})
+ it('never replays a conversation its engine was relaunched on, however new its transcript', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ // A restore after a restart: the transcript is minutes old and was born after its agent, which is
+ // what the first-turn rule asks, but its engine was relaunched on it, so it is history.
+ const lines = [CLAUDE_PROMPT, { type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }], stop_reason: 'end_turn' }, uuid: 'a1' }]
+ const s = session('claude', transcript(lines))
+ const take = vi.fn((_sessionId: string): number | undefined => statSync(s.transcriptPath!).size)
+ const run = setup({ relaunchMarks: { take } })
+ await run.attach.attachSession(s, false, false, true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('replayed the first turn'))).toBe(false)
+ // Cursor's own replay from the start is held to the same rule.
+ const cursor = session('cursor', undefined, { sessionId: 'cursor-relaunched' })
+ await run.attach.attachSession(cursor, false, true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ })
+
it('replays a Claude Code first turn live when born after its agent, unless a held tail already delivered it', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const run = setup()
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
index a51ee1a55..a26099f4a 100644
--- a/cli/src/core/transcripts/attach.ts
+++ b/cli/src/core/transcripts/attach.ts
@@ -141,8 +141,15 @@ export function createAttach({
// than history, and swallowing it loses the whole thing without a trace. `replayLive` routes the same
// fold to `initialEvents`, which is emitted below. Cursor has always done this for its own discovery
// path; the flag simply makes it available to every engine.
- const replayLive = (replayFromStart && !replayedFirstTurn.has(session.sessionId))
- || (session.engine === 'cursor' && replayCursorFromStart)
+ //
+ // Never for a conversation its engine was just relaunched on (a resume, a restart, a restore after
+ // the machine came back): everything before its relaunch mark existed before this launch, and is
+ // history. A restore is not a resume to `bind.ts`, so a transcript under ten minutes old
+ // (lib/firstTurnReplay.ts) went out live again after a daemon restart: its turns, and their recaps
+ // and notifications, a second time (found end to end, e2e/machine.e2e.ts).
+ const replayLive = relaunchedAt === undefined && (
+ (replayFromStart && !replayedFirstTurn.has(session.sessionId))
+ || (session.engine === 'cursor' && replayCursorFromStart))
const historyEvents: LiveEvent[] = []
let historyTurnOpen = false
const observe = device()?.needsTranscript(session.agentId, session.sessionId, session.engine)
diff --git a/cli/src/lib/tmux.paneLookup.spec.ts b/cli/src/lib/tmux.paneLookup.spec.ts
index decaa47c0..2416844c3 100644
--- a/cli/src/lib/tmux.paneLookup.spec.ts
+++ b/cli/src/lib/tmux.paneLookup.spec.ts
@@ -30,12 +30,23 @@ describe('asking tmux for a pane that is not in its list', () => {
expect(await lookupPaneEngineProcess('%9', 'claude')).toEqual({ ok: false, unknown: false, reason: 'tmux has no pane %9' })
})
- it('is unknown when tmux could not be asked: no server on this socket, or a timeout', async () => {
+ it('is gone when no tmux server is running, however tmux says it: with no server there is no pane', async () => {
+ // The inventory already read this as no panes; this check reading it as "could not ask" kept every
+ // agent active after the server died (e2e/machine.e2e.ts).
answer.err = new Error('Command failed')
answer.stderr = 'no server running on /tmp/tmux-501/default\n'
- expect(await lookupPaneEngineProcess('%9', 'claude')).toEqual({ ok: false, unknown: true, reason: 'tmux could not resolve pane %9' })
+ expect(await lookupPaneEngineProcess('%9', 'claude')).toEqual({ ok: false, unknown: false, reason: 'tmux has no pane %9' })
+ // What `kill-server`, a tmux crash and a reboot leave: the socket file itself gone.
+ answer.stderr = 'error connecting to /tmp/tmux-501/default (No such file or directory)\n'
+ expect(await lookupPaneEngineProcess('%9', 'claude')).toEqual({ ok: false, unknown: false, reason: 'tmux has no pane %9' })
+ })
+
+ it('is unknown when tmux could not be asked: a timeout, or a socket it may not use', async () => {
answer.err = Object.assign(new Error('timed out'), { killed: true })
answer.stderr = ''
+ expect(await lookupPaneEngineProcess('%9', 'claude')).toEqual({ ok: false, unknown: true, reason: 'tmux could not resolve pane %9' })
+ answer.err = new Error('Command failed')
+ answer.stderr = `error connecting to ${process.cwd()} (Permission denied)\n`
expect(await lookupPaneEngineProcess('%9', 'claude')).toMatchObject({ unknown: true })
})
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 066ccb1d0..2ab2afff5 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -10,6 +10,7 @@ import {
permissionModeFromArgv,
engineProcessMatch,
engineProcessMatchScore,
+ isNoTmuxServerError,
LSTART_MARKER_RE,
liveProcessRows,
parseProcessRow,
@@ -29,6 +30,29 @@ const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwne
grokCandidates: [],
})
+describe('telling no tmux server from a tmux that cannot be asked', () => {
+ it('reads both of tmux\'s ways of saying no server is running, as measured on 3.7c', () => {
+ // The socket file is there with nothing listening on it.
+ expect(isNoTmuxServerError('no server running on /tmp/tmux-501/default')).toBe(true)
+ // The socket file is gone: what kill-server, a tmux crash and a reboot leave.
+ expect(isNoTmuxServerError('Command failed: tmux list-panes -a -F #{pane_id}\nerror connecting to /tmp/tmux-501/default (No such file or directory)\n')).toBe(true)
+ })
+
+ it('reads a translated message by the socket file it names, and any other failure as no answer', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-no-server-'))
+ try {
+ // A localized libc: the words differ, but the socket file is not there.
+ expect(isNoTmuxServerError(`error connecting to ${join(dir, 'default')} (Datei oder Verzeichnis nicht gefunden)`)).toBe(true)
+ // The file is there and tmux could not use it: that says nothing about the panes.
+ expect(isNoTmuxServerError(`error connecting to ${dir} (Permission denied)`)).toBe(false)
+ expect(isNoTmuxServerError('Command failed: tmux list-panes\nserver exited unexpectedly')).toBe(false)
+ expect(isNoTmuxServerError('spawn tmux ENOENT')).toBe(false)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
+
describe('tmux process primitives', () => {
it('drops a zombie from the process table — it keeps the identity of the engine it no longer is', () => {
// The row the remote-machine rig showed for a stopped agent's Claude, orphaned to a pid 1 that
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index ca319d503..3a20f07d1 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -1,7 +1,7 @@
/** tmux process matching, runtime validation, pane capture, and input injection. */
import { execFile, spawn } from 'child_process'
-import { readFileSync } from 'node:fs'
+import { existsSync, readFileSync } from 'node:fs'
import { readlink } from 'node:fs/promises'
import { platform } from 'node:os'
import { basename } from 'path'
@@ -454,10 +454,31 @@ export function processTreePids(rows: readonly ProcessRow[], rootPids: readonly
/**
- * The pane's root pid; `'missing'` when tmux answered that it has no such pane; null when tmux could
- * not be asked (a timeout, no server, a socket it cannot reach) — which says nothing about the pane.
- * tmux 3.7 answers `display-message -t` for an unknown pane with an empty line and exit 0; older
- * versions say "can't find pane".
+ * Whether tmux failed because no server is running on its socket: then it has no panes at all, which
+ * is an answer, not a tmux that cannot be asked. tmux says it two ways (measured on 3.7c):
+ *
+ * - "no server running on <socket>": the socket file is there, with nothing listening on it.
+ * - "error connecting to <socket> (No such file or directory)": the file is gone. This is what
+ * `kill-server`, a tmux crash and a reboot all leave.
+ *
+ * Only the first was recognised. After the server died, every pane read as "tmux unavailable", so no
+ * agent was ever taken off and the apps showed dead agents as active until a new server happened to
+ * start. A fresh machine also published a scary "tmux unavailable" before its first agent
+ * (e2e/machine.e2e.ts). The socket file is checked too, so a translated message still counts. Any
+ * other failure (a timeout, "Permission denied") still says nothing either way.
+ */
+export function isNoTmuxServerError(error: string): boolean {
+ if (/no server running on\s+\S+/i.test(error)) return true
+ const connecting = /error connecting to (.+) \(([^)]*)\)\s*$/im.exec(error)
+ if (!connecting) return false
+ return /no such file or directory/i.test(connecting[2]) || !existsSync(connecting[1])
+}
+
+/**
+ * The pane's root pid; `'missing'` when tmux answered that it has no such pane, or that no server is
+ * running (then no pane is); null when tmux could not be asked (a timeout, a socket it cannot reach),
+ * which says nothing about the pane. tmux 3.7 answers `display-message -t` for an unknown pane with an
+ * empty line and exit 0; older versions say "can't find pane".
*/
function panePidLookup(pane: string): Promise<number | 'missing' | null> {
return new Promise((resolve) => {
@@ -467,6 +488,7 @@ function panePidLookup(pane: string): Promise<number | 'missing' | null> {
if (!err && Number.isSafeInteger(pid) && pid > 0) resolve(pid)
else if (!err && text === '') resolve('missing')
else if (err && /can't find pane/.test(String(stderr ?? ''))) resolve('missing')
+ else if (err && isNoTmuxServerError(String(stderr ?? ''))) resolve('missing')
else resolve(null)
})
})
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index 1b7acb9c6..0ea9e9817 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -27,6 +27,7 @@ import {
liveProcessRows,
parseProcessRow,
processTreePids,
+ isNoTmuxServerError,
resumeSessionId,
setPaneMouseOn,
type ProcessRow,
@@ -77,16 +78,8 @@ export interface TmuxAgentDiscoveryDeps {
const MISS_LIMIT = 2
-/**
- * `tmux list-panes` exits non-zero before the first server exists. That is an
- * empty inventory, not a missing tmux binary or an unusable backend: the
- * first `tmux new-session` starts the server itself. Keeping the distinction
- * here prevents daemon startup from publishing a scary, and inaccurate,
- * "tmux unavailable" state on a fresh machine.
- */
-export function isNoTmuxServerError(error: string): boolean {
- return /no server running on\s+\S+/i.test(error)
-}
+// The rule for "no server is running", shared with every other tmux read (lib/tmux.ts).
+export { isNoTmuxServerError } from './tmux.js'
function execText(
command: string,
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index f8127859c..8ced2e043 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -60,19 +60,20 @@ esac
])
})
- it.each(['gone', 'present', 'unknown', 'malformed', 'no server'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {
+ it.each(['gone', 'present', 'unknown', 'malformed', 'no server', 'no socket'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-close-'))
dirs.push(dir)
const inventory = mode === 'gone' ? "printf '%%43\\n'" : mode === 'present' ? "printf '%%42\\n'"
: mode === 'malformed' ? "printf 'not a pane\\n'" : mode === 'no server'
- ? "printf 'no server running on /tmp/fixture\\n' >&2; exit 1" : 'exit 1'
+ ? "printf 'no server running on /tmp/fixture\\n' >&2; exit 1"
+ : mode === 'no socket' ? `printf 'error connecting to ${join(dir, 'gone')} (No such file or directory)\\n' >&2; exit 1` : 'exit 1'
writeFileSync(join(dir, 'tmux'), `#!/bin/sh\nif [ "$1" = list-panes ]; then\n${inventory}\nelse\nexit 1\nfi\n`, { mode: 0o700 })
process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
const backend = new TmuxBackend()
// Even if discovery hides this pane (e.g. its session was renamed), the
// exact-pane check must see it and refuse a false successful pause.
const discovery = vi.spyOn(backend, 'inventory').mockResolvedValue({ state: 'available', roots: [] })
- expect((await backend.kill({ backend: 'tmux', paneId: '%42' })).state).toBe(mode === 'gone' || mode === 'no server' ? 'succeeded' : 'unknown')
+ expect((await backend.kill({ backend: 'tmux', paneId: '%42' })).state).toBe(mode === 'gone' || mode === 'no server' || mode === 'no socket' ? 'succeeded' : 'unknown')
expect(discovery).not.toHaveBeenCalled()
})
@@ -199,13 +200,17 @@ esac
])
})
- it('treats a fresh tmux installation with no server as an available empty inventory', async () => {
+ it.each([
+ ['a stale socket', 'no server running on /tmp/tmux-1000/default'],
+ // What `kill-server`, a tmux crash and a reboot leave: the socket file itself gone.
+ ['no socket', 'error connecting to /nonexistent/tmux-1000/default (No such file or directory)'],
+ ])('treats no tmux server (%s) as an available empty inventory', async (_name, message) => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-no-server-'))
dirs.push(dir)
const tmux = join(dir, 'tmux')
writeFileSync(tmux, `#!/bin/sh
if [ "$1" = list-panes ]; then
- printf 'no server running on /tmp/tmux-1000/default\\n' >&2
+ printf '${message}\\n' >&2
exit 1
fi
`)
@@ -218,6 +223,25 @@ fi
})
})
+ it('reads a pane as gone, not unknown, when no tmux server is running at all', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-validate-'))
+ dirs.push(dir)
+ const tmux = join(dir, 'tmux')
+ writeFileSync(tmux, `#!/bin/sh
+printf 'error connecting to ${join(dir, 'gone')} (No such file or directory)\\n' >&2
+exit 1
+`)
+ chmodSync(tmux, 0o700)
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ await expect(new TmuxBackend().validate({ backend: 'tmux', paneId: '%42' }, { engine: 'claude' })).resolves.toMatchObject({ state: 'gone' })
+ // A socket it cannot reach for another reason still says nothing about the pane.
+ writeFileSync(tmux, `#!/bin/sh
+printf 'error connecting to ${dir} (Permission denied)\\n' >&2
+exit 1
+`)
+ await expect(new TmuxBackend().validate({ backend: 'tmux', paneId: '%42' }, { engine: 'claude' })).resolves.toMatchObject({ state: 'unknown' })
+ })
+
it('respawns a pane in place with -k, an optional cwd, and the exact argv, no shell', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-respawn-'))
dirs.push(dir)