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: two daemons on one computer, and agents whose tmux panes the person moves (round 28) (#789)

Dee68975712f90d
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 49cafe880..e1b35a05a 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -32,6 +32,13 @@ export interface DaemonOptions {
/** Keep the daemon's data folder here instead of under the throwaway root (a test volume). The fake
* engines read their hook credential from it, so it is set for them too. */
dataDir?: string
+ /** Run beside this daemon, as a dev daemon runs beside the release one on one computer: its home, its
+ * tmux server, the engines' transcript folders and the projects, with a data folder, port and engines
+ * of its own (`dataDir` and `port` can name the other's instead). Closing it leaves the shared tmux
+ * server to the daemon it runs beside. */
+ beside?: IsolatedDaemon
+ /** Ask for this port instead of a free one: a daemon started on another daemon's port. */
+ port?: number
}
async function freePort(): Promise<number> {
@@ -56,6 +63,9 @@ export const until = async <T>(what: string, probe: () => Promise<T | null | und
throw new Error(`timed out after ${ms}ms waiting for ${what}${last ? ` (last error: ${String(last)})` : ''}`)
}
+/** How many daemons have been started beside another in this process: each gets its own folder. */
+let besideCount = 0
+
export class IsolatedDaemon {
child: ChildProcess | null = null
private output = ''
@@ -69,12 +79,16 @@ export class IsolatedDaemon {
) {}
static async create(options: DaemonOptions = {}): Promise<IsolatedDaemon> {
- const tmux = await isolatedTmux()
+ const beside = options.beside
+ const tmux = beside?.tmux ?? await isolatedTmux()
const root = tmux.root
- const port = await freePort()
+ const port = options.port ?? await freePort()
+ // What a daemon beside another keeps for itself; everything else is the computer's, and shared. Short
+ // names: the socket lives in the data folder, and a Unix socket's path has room for 96 bytes.
+ const own = beside ? join(root, `b${++besideCount}`) : root
const dirs = {
- home: join(root, 'home'), data: options.dataDir ?? join(root, 'data'), runtime: join(root, 'runtime'), auth: join(root, 'auth'),
- bin: join(root, 'bin'), dsh: join(root, 'dsh'), claudeProjects: join(root, 'claude', 'projects'), codexHome: join(root, 'codex'),
+ home: join(root, 'home'), data: options.dataDir ?? join(own, beside ? 'd' : 'data'), runtime: join(own, 'runtime'), auth: join(own, 'auth'),
+ bin: join(own, 'bin'), dsh: join(own, 'dsh'), claudeProjects: join(root, 'claude', 'projects'), codexHome: join(root, 'codex'),
projects: join(root, 'projects'),
}
for (const dir of Object.values(dirs)) await mkdir(dir, { recursive: true })
@@ -243,6 +257,7 @@ export class IsolatedDaemon {
try { process.kill(core, 'SIGKILL') } catch { /* gone */ }
}
}
- await this.tmux.close()
+ // A daemon beside another shares its tmux server: that one closes it.
+ if (!this.options.beside) await this.tmux.close()
}
}
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 8b4e163d2..6028bd4cd 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -109,11 +109,20 @@ export async function run(engine, config) {
codex('session_meta', { id: sessionId, cli_version: '0.159.0', cwd, source: 'cli' })
}
+ // The port the daemon actually bound, which it saves beside its data (lib/daemonEndpoint.ts) and
+ // writes into the hook command it installs: a daemon whose configured port was taken serves another.
+ const daemonPort = () => {
+ try {
+ const { port } = JSON.parse(readFileSync(join(config.dataDir, `daemon-${config.port}.json`), 'utf8'))
+ if (Number.isInteger(port) && port > 0) return port
+ } catch { /* not bound yet, or bound where it was asked to */ }
+ return config.port
+ }
const hook = async (path, body) => {
if (!hooksInstalled()) return
const token = readFileSync(join(config.dataDir, 'hook-credential'), 'utf8').trim()
const pane = process.env.TMUX_PANE
- const response = await fetch(`http://127.0.0.1:${config.port}/api/hook/${path}`, {
+ const response = await fetch(`http://127.0.0.1:${daemonPort()}/api/hook/${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },
body: JSON.stringify({
diff --git a/cli/e2e/tmuxmoves.e2e.ts b/cli/e2e/tmuxmoves.e2e.ts
new file mode 100644
index 000000000..ea43de433
--- /dev/null
+++ b/cli/e2e/tmuxmoves.e2e.ts
@@ -0,0 +1,90 @@
+/**
+ * The person reaching into the agents' tmux, for Claude Code and Codex. Harness is built on tmux, and hn
+ * (`tmux improved`) puts its people in tmux all day: they attach to an agent's session, rename it, and
+ * move its pane into a window of their own. Discovery adopts only panes in sessions Harness named, so a
+ * session the person opened by hand is never taken for an agent (autonomous-harness-desktop#6). A pane
+ * the daemon already runs an agent in is still that agent wherever it moves: it must stay active, take
+ * turns, and come back after a restart.
+ */
+import { mkdirSync } 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(d: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Row> {
+ const cwd = join(d.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
+}
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+const paneOf = (agent: Row): string => String(agent.terminal?.runtimes?.[0]?.paneId ?? agent.tmuxPane)
+
+describe('the person reaching into the agents\' tmux', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it.each([
+ ['renames its session', async (d: IsolatedDaemon, pane: string, engine: Engine) => {
+ const session = await d.tmux.run('display-message', '-p', '-t', pane, '#{session_name}')
+ await d.tmux.run('rename-session', '-t', session, `my-${engine}-work`)
+ }],
+ ['renames its window', async (d: IsolatedDaemon, pane: string, _engine: Engine) => {
+ await d.tmux.run('rename-window', '-t', pane, 'review')
+ }],
+ ['moves its pane into a window of their own', async (d: IsolatedDaemon, pane: string, engine: Engine) => {
+ await d.tmux.run('new-session', '-d', '-s', `mine-${engine}`, '-x', '120', '-y', '40')
+ await d.tmux.run('join-pane', '-d', '-s', pane, '-t', `mine-${engine}:`)
+ }],
+ ['breaks its pane out into a window of its own', async (d: IsolatedDaemon, pane: string, _engine: Engine) => {
+ await d.tmux.run('break-pane', '-d', '-s', pane)
+ }],
+ ] as const)('the person %s: the agent stays active, works, and comes back after a restart', async (_what, move) => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ let client = await LocalClient.connect(d)
+ const agents = [await create(d, client, 'claude', 'moved-claude'), await create(d, client, 'codex', 'moved-codex')]
+ for (const agent of agents) await move(d, paneOf(agent), agent.engine)
+ // Several reconcile passes (5 s each here).
+ await sleep(15_000)
+ for (const agent of agents) {
+ const now = await row(client, agent.id)
+ expect(now?.status, `${agent.engine} after the move`).toBe('active')
+ expect(now?.sessionId).toBe(agent.sessionId)
+ await turn(client, agent.id, `after the move (${agent.engine})`)
+ }
+ client.close()
+ await d.restart()
+ client = await LocalClient.connect(d)
+ for (const agent of agents) {
+ await until(`${agent.engine} back after the restart`, 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, `after the restart (${agent.engine})`)
+ }
+ expect(d.coresStarted()).toBe(2)
+ client.close()
+ }, 300_000)
+})
diff --git a/cli/e2e/twodaemons.e2e.ts b/cli/e2e/twodaemons.e2e.ts
new file mode 100644
index 000000000..bf636477a
--- /dev/null
+++ b/cli/e2e/twodaemons.e2e.ts
@@ -0,0 +1,232 @@
+/**
+ * Two daemons on one computer. On 2026-10-03 a dev daemon and the release daemon ran at once and fought
+ * over the person's panes. Reproduced here on that code: each opened an agent for every pane the other
+ * ran and bound the other's conversations, and an agent stopped in the dev app killed the release
+ * daemon's pane.
+ *
+ * Four ways two daemons meet, and what correct is for each. Throughout: no pane is ever taken from the
+ * daemon that owns it, no agent is lost or listed twice, no conversation is bound by two daemons, and a
+ * daemon that must not run leaves, saying why.
+ *
+ * - Dev beside release (another port and data folder; one home and one tmux server): both run, each with
+ * its own agents. Neither opens an agent for the other's pane, binds its conversation or hears its
+ * turns, and a dev restart and a dev agent stopped leave the release daemon's agents as they were.
+ * - A second `harness start` while one runs (same data folder): a plain start says the daemon is running
+ * and leaves; a foreground one (a launchd or systemd unit's) leaves at once, naming the daemon it found,
+ * and touches nothing of that daemon's: its pid file, socket, agents, panes and viewers.
+ * - Two masters racing for one pid file: one daemon serves and owns the pid file; the other master leaves,
+ * saying why, rather than restarting a core that cannot bind for as long as it lives.
+ * - A dev daemon started on the release daemon's port: it serves on a port of its own, as a second OS
+ * user's daemon does, and the release daemon keeps its port, its socket and its agents.
+ */
+import { spawn } from 'node:child_process'
+import { existsSync, mkdirSync, readFileSync, 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 { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))
+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)
+/** What a daemon lists as running: its agents, by id, pane and conversation. */
+const running = async (client: LocalClient) =>
+ (await rows(client)).filter((agent) => agent.status !== 'stopped').map((agent) => [agent.id, agent.tmuxPane, agent.sessionId])
+
+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 ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+/** The agents a client was told turns of. */
+const turnsSeen = (client: LocalClient) =>
+ new Set(client.frames.filter((frame) => frame.type === 'turn_started' || frame.type === 'turn_ended').map((frame) => frame.agentId))
+
+/** A pane's root process, or null once the pane is gone: the same pid later means nobody replaced it. */
+async function panePid(daemon: IsolatedDaemon, pane: string): Promise<number | null> {
+ const line = (await daemon.tmux.run('list-panes', '-a', '-F', '#{pane_id} #{pane_pid}')).split('\n').find((l) => l.startsWith(`${pane} `))
+ return line ? Number(line.split(' ')[1]) : null
+}
+
+const pidFile = (daemon: IsolatedDaemon) => {
+ try { return Number(readFileSync(join(daemon.dataDir, 'adapter.pid'), 'utf8').trim()) || null } catch { return null }
+}
+const status = async (port: number) => (await (await fetch(`http://127.0.0.1:${port}/api/status`)).json()) as Record<string, any>
+
+/** Run the CLI of this checkout with a daemon's environment, as a person (or a unit file) would. */
+function cli(daemon: IsolatedDaemon, args: string[], ms = 90_000): Promise<{ code: number | null; output: string }> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { cwd: CLI_ROOT, env: daemon.env, stdio: ['ignore', 'pipe', 'pipe'] })
+ let output = ''
+ child.stdout.on('data', (chunk: Buffer) => { output += chunk.toString('utf8') })
+ child.stderr.on('data', (chunk: Buffer) => { output += chunk.toString('utf8') })
+ const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`harness ${args.join(' ')} did not end within ${ms} ms:\n${output.slice(-3000)}`)) }, ms)
+ child.once('exit', (code) => { clearTimeout(timer); resolve({ code, output }) })
+ })
+}
+
+describe('two daemons on one computer', () => {
+ const daemons: IsolatedDaemon[] = []
+ const strays: number[] = []
+ afterEach(async () => {
+ // The daemons beside the first go first: the first owns the tmux server they share.
+ for (const daemon of daemons.reverse()) await daemon.close()
+ daemons.length = 0
+ for (const pid of strays.splice(0)) { try { process.kill(-pid, 'SIGKILL') } catch { /* already gone */ } }
+ })
+ const make = async (name: string, options: Parameters<typeof IsolatedDaemon.create>[0] = {}) => {
+ const daemon = await IsolatedDaemon.create(options)
+ daemons.push(daemon)
+ onTestFailed(() => { console.log(`---- ${name} log\n${daemon.log().split('\n').slice(-100).join('\n')}`) })
+ return daemon
+ }
+
+ it('a dev daemon beside the release one: each keeps its own agents, panes, conversations and turns', async () => {
+ const release = await make('release')
+ const dev = await make('dev', { beside: release })
+ await release.start()
+ const atRelease = await LocalClient.connect(release)
+ const ours = await create(release, atRelease, 'claude', 'release-claude')
+ await dev.start()
+ let atDev = await LocalClient.connect(dev)
+ const theirs = await create(dev, atDev, 'codex', 'dev-codex')
+ const oursPid = await panePid(release, ours.tmuxPane)
+ // Two reconcile passes on each (TERMINAL_RECONCILE_INTERVAL_MS is 5 s here): time enough for either to
+ // open an agent for the other's pane, as both did on 2026-10-03.
+ await sleep(12_000)
+ expect(await running(atRelease)).toEqual([[ours.id, ours.tmuxPane, ours.sessionId]])
+ expect(await running(atDev)).toEqual([[theirs.id, theirs.tmuxPane, theirs.sessionId]])
+
+ // A turn on each through its own daemon, at once: neither daemon tells its app of the other's turn.
+ await Promise.all([turn(atRelease, ours.id, 'a release turn'), turn(atDev, theirs.id, 'a dev turn')])
+ expect([...turnsSeen(atRelease)]).toEqual([ours.id])
+ expect([...turnsSeen(atDev)]).toEqual([theirs.id])
+
+ // A dev daemon restarts often. Back, it still keeps to its own.
+ atDev.close()
+ await dev.restart()
+ atDev = await LocalClient.connect(dev)
+ await until('the dev agent to be back', async () => (await row(atDev, theirs.id))?.status === 'active' || null, 60_000, 500)
+ await sleep(6_000)
+ expect(await running(atDev)).toEqual([[theirs.id, theirs.tmuxPane, theirs.sessionId]])
+
+ // The dev agent stopped: its pane goes; the release agent's pane is the same process it was.
+ expect((await atDev.request('agent_delete', { agentId: theirs.id }, 60_000)).error).toBeUndefined()
+ await until('the dev agent\'s pane to go', async () => (await panePid(dev, theirs.tmuxPane)) === null || null, 30_000, 250)
+ await sleep(6_000)
+ expect(await panePid(release, ours.tmuxPane)).toBe(oursPid)
+ expect(await running(atRelease)).toEqual([[ours.id, ours.tmuxPane, ours.sessionId]])
+ await turn(atRelease, ours.id, 'still the release daemon\'s')
+ atRelease.close()
+ atDev.close()
+ })
+
+ it('a second harness start while one runs leaves it alone; a foreground one leaves at once, touching nothing', async () => {
+ const daemon = await make('running')
+ await daemon.start()
+ const client = await LocalClient.connect(daemon)
+ const agent = await create(daemon, client, 'claude', 'already-running')
+ const before = { master: daemon.pid, core: daemon.corePid(), pidFile: pidFile(daemon), pane: await panePid(daemon, agent.tmuxPane) }
+ expect(before.pidFile).toBe(daemon.pid)
+ // A viewer the running daemon started for a harness agent (dsh/viewerLedger.ts), as its ledger records
+ // it: a duplicate daemon must not take it for an orphan of a daemon that died.
+ const viewer = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' })
+ strays.push(viewer.pid!)
+ await sleep(1_000)
+ writeFileSync(join(daemon.dataDir, 'viewers.json'), JSON.stringify([{ pid: viewer.pid, startedAt: Date.now() - 1_000, agentId: agent.id, dshId: 'acme/viewer', viewerDir: '/nowhere' }]))
+
+ const plain = await cli(daemon, ['start'])
+ expect(plain.output).toContain(`machine already running (pid ${daemon.pid})`)
+ expect(plain.code).toBe(0)
+
+ const foreground = await cli(daemon, ['start', '--foreground'])
+ expect(foreground.code, foreground.output).not.toBe(0)
+ expect(foreground.output).toMatch(/already serving .*daemon-\d+\.sock/)
+ // It left before it did anything: no restore, no services, no reaped viewers.
+ expect(foreground.output).not.toMatch(/\[discovery\]|\[restore\]|\[dsh\] reaped|\[services\]/)
+ expect(IsolatedDaemon.alive(viewer.pid!), 'the running daemon\'s viewer').toBe(true)
+
+ // The running daemon is as it was: its master, core, pid file, socket, agent and pane.
+ expect({ master: daemon.pid, core: daemon.corePid(), pidFile: pidFile(daemon), pane: await panePid(daemon, agent.tmuxPane) }).toEqual(before)
+ expect(existsSync(join(daemon.dataDir, 'adapter.safe-mode'))).toBe(false)
+ expect(await running(client)).toEqual([[agent.id, agent.tmuxPane, agent.sessionId]])
+ await turn(client, agent.id, 'after two starts')
+ expect(daemon.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('two masters racing for one pid file: one daemon serves, and the other master leaves saying why', async () => {
+ const first = await make('first', { env: { HARNESSD_INITIAL_BACKOFF_MS: '200' } })
+ const second = await make('second', { beside: first, dataDir: first.dataDir, port: first.port, env: { HARNESSD_INITIAL_BACKOFF_MS: '200' } })
+ await Promise.all([first.start({ ready: 'none' }), second.start({ ready: 'none' })])
+ await until('a daemon to serve', async () => {
+ const ok = (await fetch(`http://127.0.0.1:${first.port}/api/health`).catch(() => null))?.ok
+ return ok && existsSync(first.socketPath) && pidFile(first) ? true : null
+ }, 90_000, 200)
+ const winner = [first, second].find((daemon) => daemon.pid === pidFile(first))
+ expect(winner, `the pid file names ${pidFile(first)}; the masters are ${first.pid} and ${second.pid}`).toBeDefined()
+ const loser = winner === first ? second : first
+ await until('the losing master to leave', () => loser.child === null || null, 60_000, 250)
+ expect(loser.log()).toMatch(/another daemon|already serving/)
+ expect(loser.log()).toMatch(/\[harnessd\] core stopped for good/)
+ await until('the winner to finish starting', () => /\[cli\] ready/.test(winner!.log()) || null, 60_000, 200)
+
+ // One daemon, and it is the one the pid file names: its master and core answer, the loser's core is gone.
+ expect(pidFile(first)).toBe(winner!.pid)
+ const answer = await status(first.port)
+ expect([answer.pid, answer.corePid]).toEqual([winner!.pid, winner!.corePid()])
+ expect(IsolatedDaemon.alive(loser.corePid())).toBe(false)
+ expect(existsSync(join(first.dataDir, 'adapter.safe-mode'))).toBe(false)
+ const client = await LocalClient.connect(winner!)
+ const agent = await create(winner!, client, 'codex', 'after-the-race')
+ await turn(client, agent.id, 'one daemon')
+ expect(await running(client)).toEqual([[agent.id, agent.tmuxPane, agent.sessionId]])
+ expect(winner!.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ 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 })
+ await release.start()
+ const atRelease = await LocalClient.connect(release)
+ const ours = await create(release, atRelease, 'claude', 'release-claude')
+ const oursPid = await panePid(release, ours.tmuxPane)
+ await dev.start()
+ expect(dev.log()).toContain(`[hooks] control port ${release.port} unavailable; assigning a separate port`)
+ const devPort = JSON.parse(readFileSync(join(dev.dataDir, `daemon-${release.port}.json`), 'utf8')).port as number
+ expect(devPort).not.toBe(release.port)
+ // The release daemon still answers on its port, as itself.
+ const answer = await status(release.port)
+ expect([answer.pid, answer.corePid]).toEqual([release.pid, release.corePid()])
+ expect((await status(devPort)).corePid).toBe(dev.corePid())
+
+ // Each runs its own agents, and only its own.
+ const atDev = await LocalClient.connect(dev)
+ const theirs = await create(dev, atDev, 'codex', 'dev-codex')
+ await sleep(12_000)
+ expect(await running(atRelease)).toEqual([[ours.id, ours.tmuxPane, ours.sessionId]])
+ expect(await running(atDev)).toEqual([[theirs.id, theirs.tmuxPane, theirs.sessionId]])
+ await Promise.all([turn(atRelease, ours.id, 'release'), turn(atDev, theirs.id, 'dev')])
+ expect(await panePid(release, ours.tmuxPane)).toBe(oursPid)
+ expect(release.coresStarted()).toBe(1)
+ atRelease.close()
+ atDev.close()
+ })
+})
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 6b1afe6ad..8b9f66391 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -179,7 +179,7 @@ import { MODELS_REQUESTS, startModels } from './services/models.js'
import { startWorkspaces } from './services/workspaces.js'
import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'
-import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'
+import { isLocalSocketName, localSocketPath, refuseServedDataFolder, type LocalSocketServer } from './lib/localSocket.js'
import { legacyDaemonStatus, localDaemonStatus, saveDaemonPort } from './lib/daemonEndpoint.js'
import { commandBarService } from './lib/commandBar.js'
import { BackendSocket, isLocalClientId } from './backendSocket.js'
@@ -1646,6 +1646,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
slotSecond: env.ADAPTER_UPDATE_SLOT_SEC,
})
+ // Another daemon serves this data folder: leave before reading or writing anything of its — its
+ // registry, its viewers, its panes. Just after the updaters, never before them (startupOrder.spec.ts);
+ // their first check is a slot away, and a daemon that leaves here is gone long before it.
+ await refuseServedDataFolder(localSocketPath(env.ADAPTER_DATA_DIR, env.PORT))
+
// harnessd's master saw this core crash again and again: start nothing that could do it again. The
// updaters above keep running, so a published fix still lands (`enterSafeMode`).
if (process.env.HARNESSD_SAFE_MODE) throw new SafeModeRequest(process.env.HARNESSD_SAFE_MODE)
@@ -5484,12 +5489,12 @@ function withoutFirst(argv: string[], token: string): string[] {
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') usage()
if (cmd === 'version' || cmd === '--version' || cmd === '-v') { console.log(VERSION); process.exit(0) }
-const onError = (err: unknown): never => {
+const onError = (err: unknown, code = 1): never => {
console.error('Failed to start adapter:', err)
// A daemon that claimed the pid file (port bound) and then failed to finish starting must not leave
// that file naming a corpse — the next `harness start` would refuse on it. Only ours, though.
removePidFileIf(process.pid)
- process.exit(1)
+ process.exit(code)
}
/**
@@ -5511,7 +5516,9 @@ const enterSafeMode = (err: unknown): void => {
const disposition = safeModeDisposition(err, { selfPid: process.pid, masterPid: coreLink.masterPid, readPid, isAlive })
if (!disposition.stay) {
console.error(`[safe-mode] not staying up — ${disposition.reason}`)
- onError(err)
+ // Under harnessd, said for good: any other exit, the master restarts, and a core that another daemon
+ // keeps from running was restarted for as long as its master lived (e2e/twodaemons.e2e.ts).
+ onError(err, coreLink.supervised ? CORE_EXIT_STOP : 1)
}
const detail = err instanceof Error ? (err.stack ?? err.message) : String(err)
console.error('Failed to start adapter:', err)
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index aa647445d..c207c2f2d 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -124,8 +124,9 @@ export function createAgentCreator({
// Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
// retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
// before the grid block because a file-configured engine keys its config directory on it.
- // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
- // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
+ // The `harness-` prefix is also discovery's whitelist for a pane nobody tagged (see `ownedHere` /
+ // `TmuxBackend.inventory()`): the panes this daemon creates carry its tag, which goes with them into
+ // any session the person moves them to.
const label = buildHarnessSessionLabel(engine)
// Prepare the harness workspace, then bind its session context to the selected engine.
// Missing packages or invalid runtimes refuse the launch before the agent is started.
diff --git a/cli/src/lib/daemonSafeMode.spec.ts b/cli/src/lib/daemonSafeMode.spec.ts
index 44555f7b1..4f079e723 100644
--- a/cli/src/lib/daemonSafeMode.spec.ts
+++ b/cli/src/lib/daemonSafeMode.spec.ts
@@ -25,6 +25,11 @@ describe('safeModeDisposition', () => {
.toMatchObject({ stay: false })
expect(safeModeDisposition(new Error('boom'), { selfPid: 100, readPid: () => 200, isAlive: () => true }))
.toMatchObject({ stay: false, reason: 'another daemon (pid 200) owns this machine' })
+ // The data folder's socket already served, before any pid file names the daemon serving it.
+ const served = Object.assign(new Error('A Harness daemon is already serving /data/daemon-18473.sock'), { code: 'EADDRINUSE' })
+ expect(safeModeDisposition(served, nobody)).toEqual({ stay: false, reason: 'A Harness daemon is already serving /data/daemon-18473.sock' })
+ expect(safeModeDisposition(Object.assign(new Error('boom'), { code: 'ENOENT' }), nobody).stay).toBe(true)
+ expect(safeModeDisposition(null, nobody).stay).toBe(true)
})
it('stays when the pid file names us, or names a corpse', () => {
diff --git a/cli/src/lib/daemonSafeMode.ts b/cli/src/lib/daemonSafeMode.ts
index cf5c46399..c58491cad 100644
--- a/cli/src/lib/daemonSafeMode.ts
+++ b/cli/src/lib/daemonSafeMode.ts
@@ -52,6 +52,11 @@ export function safeModeDisposition(
if (/EADDRINUSE|address already in use/i.test(message)) {
return { stay: false, reason: 'the control port belongs to another daemon' }
}
+ // The data folder's socket refusing us (lib/localSocket.ts): another daemon serves it now, whether or
+ // not it has claimed the pid file yet. Read off the code, which the message does not carry: a second
+ // master's core that lost the race before the winner's claim would otherwise stay up in safe mode, and
+ // its master claim the pid file over the daemon that is serving (e2e/twodaemons.e2e.ts).
+ if ((error as { code?: unknown } | null | undefined)?.code === 'EADDRINUSE') return { stay: false, reason: message }
const owner = deps.readPid()
// Under harnessd the pid file names the master that runs this core: that daemon is this one.
if (owner !== null && owner !== deps.selfPid && owner !== deps.masterPid && deps.isAlive(owner)) {
diff --git a/cli/src/lib/harnessSessionLabel.spec.ts b/cli/src/lib/harnessSessionLabel.spec.ts
new file mode 100644
index 000000000..0573b8c37
--- /dev/null
+++ b/cli/src/lib/harnessSessionLabel.spec.ts
@@ -0,0 +1,51 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { harnessPaneOwner, ownedHere } from './harnessSessionLabel.js'
+
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+describe('which daemon a pane belongs to', () => {
+ it('is one tag per data folder: the same for one daemon every time, another for a daemon beside it', () => {
+ const root = mkdtempSync(join(tmpdir(), 'pane-owner-'))
+ dirs.push(root)
+ const release = join(root, 'release')
+ const dev = join(root, 'dev')
+ mkdirSync(release)
+ mkdirSync(dev)
+ expect(harnessPaneOwner(release)).toMatch(/^[0-9a-f]{16}$/)
+ expect(harnessPaneOwner(release)).toBe(harnessPaneOwner(`${release}/`))
+ expect(harnessPaneOwner(dev)).not.toBe(harnessPaneOwner(release))
+ })
+
+ it('is the same before the data folder exists as after, and through a symlink to it', () => {
+ // A first start computes it before anything creates the folder; macOS's temporary folders sit
+ // behind a symlink (`/var` is `/private/var`). A tag that changed between the two would hide a
+ // daemon's own panes from it after its first restart.
+ const root = mkdtempSync(join(tmpdir(), 'pane-owner-'))
+ dirs.push(root)
+ const data = join(root, 'later', 'data')
+ const before = harnessPaneOwner(data)
+ mkdirSync(data, { recursive: true })
+ expect(harnessPaneOwner(data)).toBe(before)
+ const link = join(root, 'link')
+ symlinkSync(join(root, 'later'), link)
+ expect(harnessPaneOwner(join(link, 'data'))).toBe(before)
+ expect(harnessPaneOwner(join(link, 'data', 'not-yet'))).toBe(harnessPaneOwner(join(data, 'not-yet')))
+ })
+
+ it('lets a daemon see the panes it tagged wherever they moved, untagged ones only in its sessions, never another daemon\'s', () => {
+ expect(ownedHere('aaaa', 'harness-claude-1', 'aaaa')).toBe(true)
+ // The person renamed its session, or joined the pane into a window of their own: still its pane.
+ expect(ownedHere('aaaa', 'my-claude-work', 'aaaa')).toBe(true)
+ // Created by a build from before the tag: in a session Harness named, as every pane used to be; never
+ // in a session the person opened by hand (autonomous-harness-desktop#6).
+ expect(ownedHere('', 'harness-codex-2', 'aaaa')).toBe(true)
+ expect(ownedHere('', 'my-shell', 'aaaa')).toBe(false)
+ // Another daemon's, in whatever session.
+ expect(ownedHere('bbbb', 'harness-claude-1', 'aaaa')).toBe(false)
+ expect(ownedHere('bbbb', 'my-claude-work', 'aaaa')).toBe(false)
+ })
+})
diff --git a/cli/src/lib/harnessSessionLabel.ts b/cli/src/lib/harnessSessionLabel.ts
index 7887f580a..cb2ba9ff6 100644
--- a/cli/src/lib/harnessSessionLabel.ts
+++ b/cli/src/lib/harnessSessionLabel.ts
@@ -6,9 +6,60 @@
* session isn't named this way is invisible to the daemon, whether it's a session the user opened
* by hand or one an agent spawned itself with a nested `tmux new-session` — neither went through
* `agent_create`, so neither should ever appear as a discovered agent (issue autonomous-harness-desktop#6).
+ *
+ * The name says a pane is Harness's, not WHICH daemon's: see `HARNESS_OWNER_OPTION`.
*/
+import { createHash } from 'node:crypto'
+import { realpathSync } from 'node:fs'
+import { basename, dirname, join, resolve } from 'node:path'
+
export const HARNESS_SESSION_PREFIX = 'harness-'
+/**
+ * The tmux pane option every pane a daemon creates is tagged with: which daemon on this computer it
+ * belongs to. Set in the very tmux call that creates the session, so no scan ever sees the pane untagged.
+ *
+ * Two daemons can share one tmux server — a dev daemon beside the release one, each with its own data
+ * folder — and both name their sessions `harness-…`. Each opened an agent for the other's panes and bound
+ * the other's conversations, and an agent stopped in the dev app killed the pane the release daemon was
+ * running it in (e2e/twodaemons.e2e.ts, the 2026-10-03 incident).
+ *
+ * And a pane moves. The person renames its session or joins it into a window of their own (hn's people
+ * live in tmux), and a session name stops saying whose it is; a pane option goes with the pane, where a
+ * window option stays behind with the window (e2e/tmuxmoves.e2e.ts). Read through the window too, which
+ * is how a format resolves a pane option nobody set: a tag a build set on the window still counts.
+ */
+export const HARNESS_OWNER_OPTION = '@harness_daemon'
+
+/** A path with its symlinks resolved, including one whose last parts do not exist yet: the same answer
+ * before a data folder is created as after (macOS's `/var` is `/private/var`). */
+function canonicalPath(path: string): string {
+ const absolute = resolve(path)
+ const missing: string[] = []
+ for (let at = absolute; ; at = dirname(at)) {
+ try { return join(realpathSync(at), ...missing.reverse()) } catch { /* not there (yet): look one level up */ }
+ if (dirname(at) === at) return absolute
+ missing.push(basename(at))
+ }
+}
+
+/** This daemon's tag: its data folder, which no two daemons share, hashed (a path can hold the `|` the
+ * pane listing splits on, and the tag is all a pane needs to carry). */
+export function harnessPaneOwner(dataDir: string): string {
+ return createHash('sha256').update(canonicalPath(dataDir)).digest('hex').slice(0, 16)
+}
+
+/**
+ * Whether a pane is this daemon's (`self`): one it tagged, in any session, wherever the person moved it;
+ * one nobody tagged only in a session Harness named, as before the tag (a build from before it made the
+ * pane, and a session the person opened by hand is never taken for an agent: autonomous-harness-desktop#6);
+ * one another daemon tagged, never. Never the pane id alone: a new tmux server reuses `%N`, and a stale id
+ * can name someone's shell.
+ */
+export function ownedHere(owner: string, sessionName: string, self: string): boolean {
+ return owner ? owner === self : isHarnessSession(sessionName)
+}
+
export function buildHarnessSessionLabel(engine: string, now: number = Date.now()): string {
return `${HARNESS_SESSION_PREFIX}${engine}-${now}`.replace(/[^A-Za-z0-9_-]/g, '-')
}
diff --git a/cli/src/lib/localSocket.spec.ts b/cli/src/lib/localSocket.spec.ts
index 258e6d654..92ec78816 100644
--- a/cli/src/lib/localSocket.spec.ts
+++ b/cli/src/lib/localSocket.spec.ts
@@ -1,12 +1,25 @@
import { request } from 'node:http'
import { connect } from 'node:net'
-import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
-import { afterEach, describe, expect, it } from 'vitest'
-import { isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, type LocalSocketServer } from './localSocket.js'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, refuseServedDataFolder, type LocalSocketServer } from './localSocket.js'
const LOCAL_SOCKET_NAME = localSocketName(18473)
+/** A filesystem without hard links, when a test says so. */
+const fsState = vi.hoisted(() => ({ noLinks: false }))
+vi.mock('node:fs', async (importOriginal) => {
+ const real = await importOriginal<typeof import('node:fs')>()
+ return {
+ ...real,
+ linkSync: (...args: Parameters<typeof real.linkSync>) => {
+ if (fsState.noLinks) throw Object.assign(new Error('EPERM: operation not permitted, link'), { code: 'EPERM' })
+ return real.linkSync(...args)
+ },
+ }
+})
+
// Socket paths are capped near 104 bytes; the test tmpdir on macOS is far longer.
const dirs: string[] = []
const opened: LocalSocketServer[] = []
@@ -126,6 +139,40 @@ describe('listenLocalSocket', () => {
expect(statSync(path).mode & 0o777).toBe(0o600)
})
+ it('gives the socket to one of two daemons claiming it at once, and refuses the other', async () => {
+ // Two masters racing (e2e/twodaemons.e2e.ts): both used to "claim" it, the second's socket replacing
+ // the first's, which went on listening where nothing could reach it.
+ for (let round = 0; round < 10; round++) {
+ const path = join(shortDir(), LOCAL_SOCKET_NAME)
+ const claims = await Promise.allSettled([
+ listenLocalSocket((_req, res) => res.end('first'), path),
+ listenLocalSocket((_req, res) => res.end('second'), path),
+ ])
+ const won = claims.flatMap((claim, i) => claim.status === 'fulfilled' ? [{ socket: claim.value, body: i ? 'second' : 'first' }] : [])
+ const lost = claims.flatMap((claim) => claim.status === 'rejected' ? [claim.reason as NodeJS.ErrnoException] : [])
+ expect(won).toHaveLength(1)
+ opened.push(won[0]!.socket)
+ expect(lost).toMatchObject([{ code: 'EADDRINUSE', message: `A Harness daemon is already serving ${path}` }])
+ expect((await get(path, '/')).body).toBe(won[0]!.body)
+ // Nothing staged is left behind.
+ expect(readdirSync(join(path, '..'))).toEqual([LOCAL_SOCKET_NAME])
+ }
+ })
+
+ it('takes its name the way it always did where the filesystem has no hard links', async () => {
+ fsState.noLinks = true
+ try {
+ const path = join(shortDir(), LOCAL_SOCKET_NAME)
+ const socket = await listenLocalSocket((_req, res) => res.end('renamed'), path)
+ opened.push(socket)
+ expect((await get(path, '/')).body).toBe('renamed')
+ expect(statSync(path).mode & 0o777).toBe(0o600)
+ expect(readdirSync(join(path, '..'))).toEqual([LOCAL_SOCKET_NAME])
+ } finally {
+ fsState.noLinks = false
+ }
+ })
+
it('removes the socket file when it closes', async () => {
const path = join(shortDir(), LOCAL_SOCKET_NAME)
const socket = await listenLocalSocket((_req, res) => res.end(), path)
@@ -141,3 +188,24 @@ describe('listenLocalSocket', () => {
expect(existsSync(path)).toBe(false)
})
})
+
+describe('refuseServedDataFolder', () => {
+ 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)
+ // No socket at all, a crashed daemon's, a file that is not one, and no path where there is none.
+ await expect(refuseServedDataFolder(path)).resolves.toBeUndefined()
+ const crashed = await listenLocalSocket((_req, res) => res.end(), path)
+ crashed.server.close()
+ await expect(refuseServedDataFolder(path)).resolves.toBeUndefined()
+ await expect(refuseServedDataFolder(null)).resolves.toBeUndefined()
+ const plain = join(dir, 'plain')
+ 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}` })
+ })
+})
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index 38f69dbd0..037676847 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -10,12 +10,13 @@
* TCP stays: the CLI, engine hooks and the dashboard (a browser cannot reach a socket file) still use
* it, as do app builds that predate this. Windows has no socket here; there everything is TCP.
*/
+import { randomBytes } from 'node:crypto'
import http from 'node:http'
import { connect } from 'node:net'
import type { IncomingMessage } from 'node:http'
import type { Socket } from 'node:net'
-import { chmodSync, lstatSync, renameSync, unlinkSync } from 'node:fs'
-import { join } from 'node:path'
+import { chmodSync, linkSync, lstatSync, renameSync, unlinkSync, type Stats } from 'node:fs'
+import { dirname, join } from 'node:path'
/**
* One socket per configured port in this OS user's data directory: `daemon-<port>.sock`. Its name
@@ -62,13 +63,13 @@ export interface LocalSocketServer {
/**
* Serve `handler` on a Unix socket at `path`. Refuse a live listener or a non-socket file, and remove
- * only a stale socket. CLI startup is serialized by the per-user spawn lock.
+ * only a stale socket. CLI startup is serialized by the per-user spawn lock; two daemons that start at
+ * once anyway (two masters) get one socket between them, never one each.
*/
export async function listenLocalSocket(handler: http.RequestListener, path: string): Promise<LocalSocketServer> {
// A TCP collision can now move this user to another port. Holding a TCP port no longer proves
// an existing Unix socket is stale: never unlink a live daemon belonging to this user.
await refuseLiveSocket(path)
- removeStaleSocket(path)
const server = http.createServer(handler)
server.on('connection', (socket) => trustedSockets.add(socket))
const unlink = (): void => {
@@ -83,28 +84,89 @@ export async function listenLocalSocket(handler: http.RequestListener, path: str
unlink()
}
// `listen` creates the file with the process umask. It is made owner-only under a private name and
- // only then renamed into place — atomically — so no client ever sees it looser than 0600, and the
- // umask (process-wide, shared with whatever fs work is in flight) is never touched.
- // CLI startup holds the per-user spawn lock while claiming this stable socket name.
- const staging = `${path}.new`
- try { if (lstatSync(staging).isSocket()) unlinkSync(staging) } catch { /* nothing left over */ }
+ // only then put in place, so no client ever sees it looser than 0600, and the umask (process-wide,
+ // shared with whatever fs work is in flight) is never touched.
+ //
+ // Put in place by a hard link, which fails when the name is taken, where a rename replaces it. Two
+ // claims at once (two masters racing) both got the socket before — measured, every time in
+ // localSocket.spec.ts: they staged under one shared name and each renamed into place, and the one
+ // replaced kept listening where nothing could reach it, bound as far as its master knew. A private
+ // staging name per claim, no longer than the socket's own (a socket path has 96 bytes: localSocketPath).
+ const staging = join(dirname(path), `.claim-${randomBytes(3).toString('hex')}`)
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(staging, () => {
server.off('error', reject)
- try {
- chmodSync(staging, 0o600)
+ void (async () => {
+ try {
+ chmodSync(staging, 0o600)
+ await claim(staging, path)
+ } catch (error) {
+ server.closeAllConnections()
+ server.close()
+ try { unlinkSync(staging) } catch { /* never created, or already moved */ }
+ reject(error)
+ return
+ }
+ // The socket is at `path` now; the staged name goes (a rename already took it).
+ try { unlinkSync(staging) } catch { /* renamed into place */ }
+ resolve({ server, path, close: async () => closeNow(), closeSync: closeNow })
+ })()
+ })
+ })
+}
+
+const alreadyServing = (path: string): Error =>
+ Object.assign(new Error(`A Harness daemon is already serving ${path}`), { code: 'EADDRINUSE' })
+
+/**
+ * Put the staged socket at `path`. The name taken: by a daemon serving it (refused), or by the socket of
+ * one that crashed (replaced). Decided here, at the claim, never earlier: a liveness check made before
+ * the listen is stale by the time a second daemon claims, and the unlink that followed it removed the
+ * first daemon's live socket. Only the very file found dead is removed: a socket another daemon has put
+ * there since is a different file, and is left to it.
+ */
+async function claim(staging: string, path: string): Promise<void> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ linkSync(staging, path)
+ return
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
+ // A filesystem without hard links: the rename it always used, which replaces rather than refuses.
renameSync(staging, path)
- } catch (error) {
- server.closeAllConnections()
- server.close()
- try { unlinkSync(staging) } catch { /* never created, or already moved */ }
- reject(error)
return
}
- resolve({ server, path, close: async () => closeNow(), closeSync: closeNow })
- })
+ }
+ if (attempt > 0) throw alreadyServing(path)
+ let found: Stats
+ try { found = lstatSync(path) } catch { continue } // gone meanwhile: try the name again
+ if (!found.isSocket()) throw new Error(`${path} exists and is not a socket; not replacing it`)
+ await refuseLiveSocket(path)
+ try { if (lstatSync(path).ino === found.ino) unlinkSync(path) } catch { /* gone meanwhile */ }
+ }
+}
+
+/**
+ * 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.
+ *
+ * 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).
+ */
+export async function refuseServedDataFolder(path: string | null, timeoutMs = 1_000): 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)
}
async function refuseLiveSocket(path: string): Promise<void> {
@@ -112,7 +174,7 @@ async function refuseLiveSocket(path: string): Promise<void> {
const socket = connect(path)
socket.once('connect', () => {
socket.destroy()
- reject(Object.assign(new Error(`A Harness daemon is already serving ${path}`), { code: 'EADDRINUSE' }))
+ reject(alreadyServing(path))
})
socket.once('error', (error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED' || error.code === 'ENOTSOCK') resolve()
@@ -124,14 +186,3 @@ async function refuseLiveSocket(path: string): Promise<void> {
})
})
}
-
-function removeStaleSocket(path: string): void {
- let isSocket: boolean
- try {
- isSocket = lstatSync(path).isSocket()
- } catch {
- return // nothing there
- }
- if (!isSocket) throw new Error(`${path} exists and is not a socket; not replacing it`)
- unlinkSync(path)
-}
diff --git a/cli/src/lib/sessionSearch/externals/support.spec.ts b/cli/src/lib/sessionSearch/externals/support.spec.ts
index b00aa6054..9cb2509ad 100644
--- a/cli/src/lib/sessionSearch/externals/support.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/support.spec.ts
@@ -234,9 +234,12 @@ describe('processes', () => {
])
})
- it("knows Harness's own panes by their tmux session names", async () => {
- const out = '/dev/ttys001\tharness-claude-1\n/dev/ttys002\tmy-own\n\n/dev/ttys003\n'
- expect(await harnessTtys(async () => ({ stdout: out, failed: false, stderr: '' }))).toEqual(new Set(['/dev/ttys001']))
+ it("knows Harness's own panes by their tmux session names, and by a daemon's tag wherever they moved", async () => {
+ const out = '/dev/ttys001\tharness-claude-1\t\n/dev/ttys002\tmy-own\t\n\n/dev/ttys003\n'
+ // A daemon's pane the person moved into a session of their own, and one another daemon tagged:
+ // either way an agent, never a process a take-over stops.
+ + '/dev/ttys004\tmy-claude-work\t0123456789abcdef\n/dev/ttys005\ttheirs\tfedcba9876543210\n'
+ expect(await harnessTtys(async () => ({ stdout: out, failed: false, stderr: '' }))).toEqual(new Set(['/dev/ttys001', '/dev/ttys004', '/dev/ttys005']))
// No server running: no panes of Harness's. Could not ask: nobody can say.
expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'no server running on /tmp/tmux-501/default' }))).toEqual(new Set())
expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'error connecting to /tmp/x (No such file or directory)' }))).toEqual(new Set())
diff --git a/cli/src/lib/sessionSearch/externals/support.ts b/cli/src/lib/sessionSearch/externals/support.ts
index a635be5c0..4df4ef983 100644
--- a/cli/src/lib/sessionSearch/externals/support.ts
+++ b/cli/src/lib/sessionSearch/externals/support.ts
@@ -8,7 +8,7 @@ import type { Dirent } from 'node:fs'
import { open, readdir, readFile, stat } from 'node:fs/promises'
import { isAbsolute, relative, resolve } from 'node:path'
-import { isHarnessSession } from '../../harnessSessionLabel.js'
+import { HARNESS_OWNER_OPTION, isHarnessSession } from '../../harnessSessionLabel.js'
import { processRows } from '../../tmux.js'
import { type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'
@@ -248,17 +248,19 @@ const ask: Ask = (command, args, timeout) => new Promise((resolve) => {
})
/**
- * The terminals of Harness's own panes: tmux sessions named `harness-…`. A process there is one of
- * Harness's agents, whatever its session looks like while the daemon is still binding it. None when
- * no tmux server is running; null when tmux could not be asked (a timeout): then nobody can say.
+ * The terminals of Harness's own panes: the ones a daemon tagged (`HARNESS_OWNER_OPTION`), in whatever
+ * session the person has moved them into, and any in a tmux session named `harness-…`. A process there
+ * is one of Harness's agents — any daemon's — whatever its session looks like while the daemon is still
+ * binding it, and a take-over never stops it. None when no tmux server is running; null when tmux could
+ * not be asked (a timeout): then nobody can say.
*/
export async function harnessTtys(exec: Ask = ask): Promise<Set<string> | null> {
- const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', '#{pane_tty}\t#{session_name}'], 3_000)
+ const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', `#{pane_tty}\t#{session_name}\t#{${HARNESS_OWNER_OPTION}}`], 3_000)
if (failed && !/no server running|error connecting to/i.test(stderr)) return null
const ttys = new Set<string>()
for (const line of stdout.split('\n')) {
- const [tty, session] = line.split('\t')
- if (tty && session && isHarnessSession(session)) ttys.add(tty)
+ const [tty, session, tag] = line.split('\t')
+ if (tty && (tag || (session && isHarnessSession(session)))) ttys.add(tty)
}
return ttys
}
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 1045ce6fc..2b2e43b6d 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -26,10 +26,14 @@ const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwne
grokCandidates: [],
})
-it('parses printable tmux separators without truncating a pipe in cwd', () => {
- expect(parsePanes('%1|42|harness-claude-1|/work/a|b\n%2|84|mysession|/tmp\n')).toEqual([
- { tmuxPane: '%1', rootPid: 42, tmuxSessionName: 'harness-claude-1', cwd: '/work/a|b' },
- { tmuxPane: '%2', rootPid: 84, tmuxSessionName: 'mysession', cwd: '/tmp' },
+it('parses printable tmux separators without truncating a pipe in cwd, and the owner tag after it', () => {
+ expect(parsePanes('%1|42|harness-claude-1|/work/a|b|\n%2|84|mysession|/tmp|0123abcd\n')).toEqual([
+ { tmuxPane: '%1', rootPid: 42, tmuxSessionName: 'harness-claude-1', cwd: '/work/a|b', owner: '' },
+ { tmuxPane: '%2', rootPid: 84, tmuxSessionName: 'mysession', cwd: '/tmp', owner: '0123abcd' },
+ ])
+ // A listing in the format before the tag: a pane nobody tagged.
+ expect(parsePanes('%3|7|harness-codex-1|/work\n')).toEqual([
+ { tmuxPane: '%3', rootPid: 7, tmuxSessionName: 'harness-codex-1', cwd: '/work', owner: '' },
])
})
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index f3c4740a1..38d22c35e 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -17,7 +17,10 @@ import type { AgentEngine } from '../engines/types.js'
import { probeGatewayRuntime } from './gatewayRuntime.js'
import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'
import { probeCodexHome } from './codexHomeProbe.js'
-import { buildHarnessSessionLabel, isHarnessSession, isLegacyHarnessSession } from './harnessSessionLabel.js'
+import { env } from '../config/env.js'
+import {
+ buildHarnessSessionLabel, HARNESS_OWNER_OPTION, harnessPaneOwner, isLegacyHarnessSession, ownedHere,
+} from './harnessSessionLabel.js'
import { psEnv } from './childLocale.js'
import type { ProcessIdentity, RegisteredSession } from './registry.js'
import {
@@ -40,6 +43,8 @@ export interface TmuxPaneSnapshot {
rootPid: number
tmuxSessionName: string
cwd: string
+ /** The daemon that created the pane (`HARNESS_OWNER_OPTION`); empty when no daemon tagged it. */
+ owner?: string
}
export interface DiscoveredTmuxAgent {
@@ -97,6 +102,10 @@ function execText(
})
}
+/** What every pane listing asks tmux for. The owner tag goes last: a folder's path can hold `|`, the tag
+ * never does, so the last `|` is always the one before it. */
+export const PANE_FORMAT = `#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}|#{${HARNESS_OWNER_OPTION}}`
+
export function parsePanes(stdout: string): TmuxPaneSnapshot[] {
const panes: TmuxPaneSnapshot[] = []
for (const line of stdout.split('\n')) {
@@ -108,11 +117,15 @@ export function parsePanes(stdout: string): TmuxPaneSnapshot[] {
const pidText = line.slice(first + 1, second)
const rootPid = Number(pidText)
if (!/^%\d+$/.test(tmuxPane) || !Number.isSafeInteger(rootPid) || rootPid <= 0) continue
+ // A listing without the owner field (an older format) is a pane nobody tagged.
+ const rest = line.slice(third + 1)
+ const tag = rest.lastIndexOf('|')
panes.push({
tmuxPane,
rootPid,
tmuxSessionName: line.slice(second + 1, third),
- cwd: line.slice(third + 1),
+ cwd: tag < 0 ? rest : rest.slice(0, tag),
+ owner: tag < 0 ? '' : rest.slice(tag + 1),
})
}
return panes
@@ -125,14 +138,16 @@ export type TmuxPaneInventory =
/**
* One bounded tmux inventory read, shared by discovery and the neutral backend adapter.
*
- * Only panes from sessions this daemon itself named via `agent_create` are returned — a session
- * the user opened by hand, or one an agent spawned itself with a nested `tmux new-session`, is
- * invisible to every discovery path (autonomous-harness-desktop#6).
+ * Only this daemon's panes are returned (`ownedHere`): the ones it tagged, in whatever session the
+ * person has since renamed or moved them into, and untagged ones only in sessions Harness named. A
+ * session the user opened by hand, or one an agent spawned itself with a nested `tmux new-session`, is
+ * invisible to every discovery path (autonomous-harness-desktop#6); so is a pane another daemon on this
+ * tmux server created (`HARNESS_OWNER_OPTION`): a dev daemon beside the release one opened an agent for
+ * every one of the release daemon's panes, and could stop them (e2e/twodaemons.e2e.ts).
*/
-export async function listTmuxPanes(): Promise<TmuxPaneInventory> {
- // Printable delimiters survive tmux's POSIX-locale output sanitiser. Split only the three fixed
- // separators so a legitimate `|` in pane_current_path remains part of the path.
- const read = () => execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}'], 2_000)
+export async function listTmuxPanes(owner: string = harnessPaneOwner(env.ADAPTER_DATA_DIR)): Promise<TmuxPaneInventory> {
+ // Printable delimiters survive tmux's POSIX-locale output sanitiser (see PANE_FORMAT).
+ const read = () => execText('tmux', ['list-panes', '-a', '-F', PANE_FORMAT], 2_000)
let result = await read()
// A server whose socket was removed still runs its panes: asked back, it is read again, once.
if (!result.ok && isNoTmuxServerError(result.error) && await reviveRemovedTmuxSocket()) result = await read()
@@ -144,7 +159,10 @@ export async function listTmuxPanes(): Promise<TmuxPaneInventory> {
if (isNoTmuxServerError(result.error)) return { ok: true, panes: [] }
return result
}
- return { ok: true, panes: parsePanes(result.stdout).filter((pane) => isHarnessSession(pane.tmuxSessionName)) }
+ return {
+ ok: true,
+ panes: parsePanes(result.stdout).filter((pane) => ownedHere(pane.owner ?? '', pane.tmuxSessionName, owner)),
+ }
}
export interface AdoptedLegacySession { from: string; to: string; paneId: string }
@@ -165,7 +183,7 @@ export async function adoptLegacyHarnessSessions(
now: number = Date.now(),
): Promise<AdoptedLegacySession[]> {
if (!ownedPanes.size) return []
- const result = await execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}'], 2_000)
+ const result = await execText('tmux', ['list-panes', '-a', '-F', PANE_FORMAT], 2_000)
if (!result.ok) return []
const adopted: AdoptedLegacySession[] = []
const seen = new Set<string>()
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index e7e71e6fb..18d41fe4e 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -40,7 +40,7 @@ esac
chmodSync(tmux, 0o700)
process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
process.env.TMUX_BACKEND_CALLS = calls
- const backend = new TmuxBackend()
+ const backend = new TmuxBackend(undefined, () => 'daemon-a')
const created = await backend.create({ cwd: '/tmp/work', label: 'harness-test' })
expect(created).toEqual({
@@ -53,8 +53,9 @@ esac
// exits immediately would otherwise take its session down before a follow-up call landed,
// and its error text with it.
// `window-style` rides the same invocation for the same reason: the engine asks its
- // terminal for its colours (OSC 10/11) once, at startup, and never again.
- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5',
+ // terminal for its colours (OSC 10/11) once, at startup, and never again. And so does the
+ // daemon's tag: another daemon on this tmux server must never see the pane untagged.
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',
'set-option -t %42 mouse on',
'kill-pane -t %42',
])
@@ -77,6 +78,26 @@ esac
expect(discovery).not.toHaveBeenCalled()
})
+ it('sees the panes it tagged wherever they moved, untagged ones only in its sessions, never another daemon\'s', async () => {
+ // A dev daemon beside the release one, on one tmux server (2026-10-03): each opened an agent for the
+ // other's panes until a pane said whose it was. And the person moves panes: a renamed session, a pane
+ // joined into a window of their own (e2e/tmuxmoves.e2e.ts).
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-owner-'))
+ dirs.push(dir)
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh
+case "$1" in
+ list-panes) printf '%%1|100|harness-claude-1|/work/mine|daemon-a\\n%%2|101|harness-codex-2|/work/theirs|daemon-b\\n%%3|102|harness-claude-3|/work/old|\\n%%4|103|my-claude-work|/work/moved|daemon-a\\n%%5|104|my-shell|/work/shell|\\n%%6|105|their-work|/work/their-moved|daemon-b\\n' ;;
+esac
+`, { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ const inventory = await new TmuxBackend(undefined, () => 'daemon-a').inventory()
+ expect(inventory.state).toBe('available')
+ if (inventory.state !== 'available') return
+ // Its own (%1), one a build before the tag created (%3), and its own moved into a session the person
+ // named (%4). Not the other daemon's anywhere (%2, %6), and not the person's own shell (%5).
+ expect(inventory.roots.map((root) => root.runtime.paneId)).toEqual(['%1', '%3', '%4'])
+ })
+
it('rejects broad tmux targets before executing a command', async () => {
const backend = new TmuxBackend()
expect(await backend.kill({ backend: 'tmux', paneId: '*' })).toMatchObject({ state: 'failed', dispatch: 'not_started' })
@@ -99,7 +120,7 @@ esac
process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
process.env.TMUX_BACKEND_CALLS = calls
let theme = { background: '#171b29', foreground: '#f5f5f5' }
- const backend = new TmuxBackend(() => theme)
+ const backend = new TmuxBackend(() => theme, () => 'daemon-a')
await backend.create({ cwd: '/tmp/work', label: 'harness-codex-1' })
await backend.inventory()
@@ -109,7 +130,7 @@ esac
await backend.inventory()
const styleCalls = () => readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line.includes('window-style'))
await vi.waitFor(() => expect(styleCalls()).toEqual([
- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#171b29,fg=#f5f5f5',
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#171b29,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',
// The pane this daemon did not create is styled on the first scan; %7 already was.
'set-option -w -t %9 window-style bg=#171b29,fg=#f5f5f5',
// The app changed its palette: every live pane, once.
@@ -302,7 +323,7 @@ printf '%%42\\n'
process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
process.env.TMUX_BACKEND_CALLS = calls
- const created = await new TmuxBackend().create({
+ const created = await new TmuxBackend(undefined, () => 'daemon-a').create({
cwd: '/tmp/work',
label: 'harness-test',
// A grid relay key. It goes here rather than into `command` precisely so it stays out of the
@@ -318,7 +339,7 @@ printf '%%42\\n'
'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'
+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'
+ ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on'
- + ' ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5',
+ + ' ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',
)
})
it('respawns a pane in place with a new environment, keeping the pane id', async () => {
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 286cae342..56f069c95 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -32,6 +32,8 @@ import {
setPaneMouseOn,
setPaneWindowStyle,
} from './tmux.js'
+import { env } from '../config/env.js'
+import { HARNESS_OWNER_OPTION, harnessPaneOwner } from './harnessSessionLabel.js'
import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
import { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'
import { terminalRouteKey } from './terminalRuntime.js'
@@ -101,8 +103,13 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
/**
* [hostTheme] answers with the desktop's current pane colours (see `hostTheme.ts`); read at every
* use rather than captured, so a theme the app sends later reaches sessions created after it.
+ * [owner] is the tag this daemon's panes carry (`HARNESS_OWNER_OPTION`), read at every create for
+ * the same reason as the theme: the data folder is the daemon's to move.
*/
- constructor(private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME) {}
+ constructor(
+ private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME,
+ private readonly owner: () => string = () => harnessPaneOwner(env.ADAPTER_DATA_DIR),
+ ) {}
async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {
const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
@@ -131,6 +138,10 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
// first milliseconds and never again, so the style has to be there before the engine is.
const style = windowStyleOf(this.hostTheme())
args.push(';', 'set-option', '-w', 'window-style', style)
+ // Whose pane it is, from its first instant: another daemon on this tmux server scanning a moment
+ // later must already see it is not its own. On the pane, which keeps it wherever the person moves
+ // it (see HARNESS_OWNER_OPTION).
+ args.push(';', 'set-option', '-p', HARNESS_OWNER_OPTION, this.owner())
// `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.
type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }
const result = await new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {
@@ -270,7 +281,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
}
async inventory(): Promise<TerminalInventoryResult> {
- const result = await listTmuxPanes()
+ const result = await listTmuxPanes(this.owner())
if (!result.ok) return { state: 'unavailable', reason: result.error }
this.restyle(result.panes.map((pane) => pane.tmuxPane))
return {
diff --git a/cli/src/lib/tmuxLegacySessions.spec.ts b/cli/src/lib/tmuxLegacySessions.spec.ts
index aee9df7a4..fc8e533df 100644
--- a/cli/src/lib/tmuxLegacySessions.spec.ts
+++ b/cli/src/lib/tmuxLegacySessions.spec.ts
@@ -64,7 +64,7 @@ describe('adoptLegacyHarnessSessions', () => {
{ from: 'codex-1787549944131', to: 'harness-codex-1800000000001', paneId: '%1' },
])
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([
- 'list-panes -a -F #{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}',
+ 'list-panes -a -F #{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}|#{@harness_daemon}',
'rename-session -t =claude-1787912296587 harness-claude-1800000000000',
'rename-session -t =codex-1787549944131 harness-codex-1800000000001',
])