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.

Review fixes: update path under a v0.3.58 master, slow links, orphan exit codes, old tmux restarts (#832)

Dee1a408ead526b
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index c97340bf1..224be5ba9 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -1512,7 +1512,9 @@ async function main() {
...mutationFields,
})
if (ok === false) await fallbackSessionEnd(input.session_id || input.conversation_id, input.reason, engine, tmuxPane)
- if (engine === 'cursor' && ok) await clearCursorTasks(input.session_id || input.conversation_id)
+ // Only once the daemon has taken the end in: a reply that did not come in time ('late') is no answer,
+ // and the tasks it would have settled are still the daemon's to settle.
+ if (engine === 'cursor' && ok === true) await clearCursorTasks(input.session_id || input.conversation_id)
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 3b248ee0f..618e20dd5 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -51,7 +51,7 @@ import { registry, projectDisplayName, validTranscriptPath, type RegisteredSessi
import { engineSessionTitle } from './lib/sessionTitle.js'
import { machineNames } from './lib/machineNames.js'
import { installCodexHooks } from './lib/hooks.js'
-import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
+import { DAEMON_LOG_FILE, HARNESSD_REEXEC_FILE, HARNESSD_STATUS_FILE, PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
import { clearSafeModeMarker, readSafeModeMarker, runBootHandoff, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from './lib/daemonSafeMode.js'
import { awakeTimeout } from './lib/sleepAware.js'
import {
@@ -219,7 +219,7 @@ import { DeviceLogStore } from './lib/e2ee/deviceLogStore.js'
import { TrustGroupStore, type GroupMember } from './lib/e2ee/trustGroup.js'
import {
startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,
- fetchManifest, downloadVerified, canary, stage, semverGt, isLocalDevBuild,
+ fetchManifest, downloadVerified, canary, stage, semverGt, isLocalDevBuild, DOWNLOAD_LIMITS,
type Poller, type UpdateEntry,
} from './lib/selfUpdate.js'
import { managedNodePath } from './lib/nodeRuntime.js'
@@ -1687,7 +1687,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onWaiting: (owner) => console.log(`[update] waiting — the daemon is ${describeSpawnLockOwner(owner)}`),
}),
onStaged: (v) => daemonBoot.applyStagedUpdate(v),
- limits: { idleMs: env.ADAPTER_UPDATE_IDLE_MS, deadlineMs: env.ADAPTER_UPDATE_DEADLINE_MS },
+ limits: { idleMs: env.ADAPTER_UPDATE_IDLE_MS, deadlineMs: env.ADAPTER_UPDATE_DEADLINE_MS, floorBytesPerSecond: DOWNLOAD_LIMITS.floorBytesPerSecond },
+ stageWhileJudged: !coreLink.supervised || process.env.HARNESSD_JUDGES_SUPERSEDED === '1',
})
const slotted = env.ADAPTER_UPDATE_SLOT_SEC >= 0 && 60_000 % env.ADAPTER_UPDATE_CHECK_MS === 0
console.log(`[update] self-update on · v${VERSION} · every ${Math.round(env.ADAPTER_UPDATE_CHECK_MS / 1000)}s`
@@ -3844,9 +3845,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
await watcher.stop()
shareRelay.close()
sharedViewers.stop()
+ // The data folder's socket first: a successor waiting for this core to leave (lib/localSocket.ts) can
+ // start as soon as it is gone, whatever the clients below take to close.
+ await localSocket?.close()
await localWsServer.close()
hookServer.close()
- await localSocket?.close()
codexActivity.close()
shutdownVoiceRouter()
await ports.viewers?.stop()
@@ -5390,8 +5393,9 @@ const enterSafeMode = (err: unknown): void => {
if (!disposition.stay) {
console.error(`[safe-mode] not staying up — ${disposition.reason}`)
// 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)
+ // keeps from running was restarted for as long as its master lived (e2e/twodaemons.e2e.ts). Except
+ // what stands in the way is leaving too: then the master starts this core again.
+ onError(err, coreLink.supervised && !disposition.retry ? 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/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index 3d10a71db..cbde981ef 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -24,6 +24,7 @@ function setup(row: RegisteredSession | null = session()) {
const tmuxBackend = {
holdOpen: vi.fn(async () => ({ state: 'succeeded' })),
respawn: vi.fn(async () => ({ state: 'succeeded' })),
+ respawnRefusal: vi.fn(async (request: { env?: Record<string, string> }) => request.env ? 'too old' : null),
}
const deps: PaneSwapDeps = {
byAgent: vi.fn(() => row ?? undefined),
@@ -57,6 +58,9 @@ describe('the pane-process swap', () => {
expect(deps.prepareSessionResume).toHaveBeenCalledWith(session())
swapDeps.keepAbandoned?.()
expect(deps.keepAbandonedConversation).toHaveBeenCalledWith(session())
+ // Asked of tmux with the relaunch's own environment, before anything is stopped.
+ expect(await swapDeps.respawnRefusal?.()).toBe('too old')
+ expect(await swap.paneSwapDeps(session(), runtime).respawnRefusal?.()).toBeNull()
expect(await swapDeps.holdOpen()).toEqual({ ok: true })
tmuxBackend.holdOpen.mockResolvedValueOnce({ state: 'failed', reason: 'pane gone' } as never).mockResolvedValueOnce({ state: 'unknown' } as never)
expect(await swapDeps.holdOpen()).toEqual({ ok: false, reason: 'pane gone' })
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index f8541524b..aff2d47b6 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -52,6 +52,7 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
prepareResume: () => prepareSessionResume(session),
// The row as the swap found it: the conversation a fallback to a fresh start leaves behind.
keepAbandoned: () => keepAbandonedConversation(session),
+ respawnRefusal: () => tmuxBackend!.respawnRefusal(launch.env ? { env: launch.env } : {}),
holdOpen: async () => {
const result = await tmuxBackend!.holdOpen(runtime)
return result.state === 'succeeded'
diff --git a/cli/src/harnessd/supervisor.spec.ts b/cli/src/harnessd/supervisor.spec.ts
index 1f1c39ae7..5e9e21f8c 100644
--- a/cli/src/harnessd/supervisor.spec.ts
+++ b/cli/src/harnessd/supervisor.spec.ts
@@ -95,7 +95,7 @@ describe('Supervisor', () => {
supervisor.start()
supervisor.start()
expect(cores).toHaveLength(1)
- expect(core().env).toEqual({ HARNESSD_SUPERVISED: '1', HARNESSD_RESTARTS: '0', HARNESSD_WATCHDOG_MS: '6000' })
+ expect(core().env).toEqual({ HARNESSD_SUPERVISED: '1', HARNESSD_RESTARTS: '0', HARNESSD_WATCHDOG_MS: '6000', HARNESSD_JUDGES_SUPERSEDED: '1' })
expect(supervisor.status()).toMatchObject({ state: 'starting', corePid: 1000 })
core().bind()
expect(calls).toEqual(['claim'])
@@ -140,7 +140,7 @@ describe('Supervisor', () => {
expect(cores).toHaveLength(1)
vi.advanceTimersByTime(1)
expect(cores).toHaveLength(2)
- expect(core().env).toEqual({ HARNESSD_SUPERVISED: '1', HARNESSD_RESTARTS: '1', HARNESSD_WATCHDOG_MS: '6000', HARNESSD_LAST_EXIT: 'signal SIGKILL' })
+ expect(core().env).toEqual({ HARNESSD_SUPERVISED: '1', HARNESSD_RESTARTS: '1', HARNESSD_WATCHDOG_MS: '6000', HARNESSD_JUDGES_SUPERSEDED: '1', HARNESSD_LAST_EXIT: 'signal SIGKILL' })
expect(lines.at(-1)).toBe('[harnessd] core started (pid ?) · restart 1')
core().bind()
expect(lines.at(-1)).toBe(`[harnessd] core bound (pid ?, protocol ${HARNESSD_PROTOCOL})`)
@@ -565,6 +565,31 @@ describe('Supervisor', () => {
expect(supervisor.status()).toMatchObject({ state: 'running', restarts: 2, lastExitReason: 'update' })
})
+ it('does not keep an update whose core has staged a newer build while it tears down for it', () => {
+ // The probation ends in the seconds between v2's core staging v3 and its exit for it. Kept then,
+ // v3's pending note and the backup to roll it back to went with v2's, and v3 had nothing to restore.
+ let disk = 'v1'
+ const supervisor = make({}, { bundle: () => disk })
+ supervisor.start()
+ core().up()
+ disk = 'v2'
+ core().exit(CORE_EXIT_UPDATE)
+ vi.advanceTimersByTime(0)
+ core().up()
+ vi.advanceTimersByTime(options.updateProbationMs - 1)
+ disk = 'v3'
+ vi.advanceTimersByTime(1)
+ expect(calls).toEqual(['claim'])
+ expect(lines.at(-1)).toBe('[harnessd] the update stayed up, but has staged a newer build — leaving that one to be judged')
+ core().exit(CORE_EXIT_UPDATE)
+ vi.advanceTimersByTime(0)
+ // v3 on probation of its own: a failure rolls it back, as any update's.
+ core().up()
+ core().exit(1)
+ expect(calls).toEqual(['claim', 'restore'])
+ expect(supervisor.status().state).toBe('restarting')
+ })
+
it('judges the newer build a core still starting on an update staged, and rolls that one back if it fails', () => {
let disk = 'v1'
make({}, { bundle: () => disk }).start()
diff --git a/cli/src/harnessd/supervisor.ts b/cli/src/harnessd/supervisor.ts
index dc920b652..8210ffd5b 100644
--- a/cli/src/harnessd/supervisor.ts
+++ b/cli/src/harnessd/supervisor.ts
@@ -336,8 +336,12 @@ export class Supervisor {
this.killReason = null
// The core is told how long a silence the master allows, and beats well inside it (systemd passes
// WATCHDOG_USEC the same way): a timeout shorter than the core's own beat would kill a healthy core.
+ // HARNESSD_JUDGES_SUPERSEDED: this master judges a build its core on probation stages on its own
+ // (#807). A master from before rolls back on any exit during probation, the update's own included,
+ // and its core must not stage then: see `stageWhileJudged` in lib/selfUpdate.ts.
const env: Record<string, string> = {
HARNESSD_SUPERVISED: '1', HARNESSD_RESTARTS: String(this.restarts), HARNESSD_WATCHDOG_MS: String(this.options.heartbeatTimeoutMs),
+ HARNESSD_JUDGES_SUPERSEDED: '1',
}
if (this.lastExit) env.HARNESSD_LAST_EXIT = this.lastExit
if (this.safeMode) env.HARNESSD_SAFE_MODE = this.safeMode
@@ -427,6 +431,14 @@ export class Supervisor {
this.update = 'probation'
this.armTimer('probationTimer', () => {
this.probationTimer = null
+ // The core on probation has staged a newer build and is on its way out for it (a teardown can
+ // take seconds). Kept now, the newer build's pending note and the backup to roll it back to were
+ // deleted with this one's, and it ran on probation with nothing to restore. Left on probation, its
+ // exit for the update is the superseded one, and the newer build is judged on its own.
+ if (this.stagedSinceSpawn()) {
+ this.deps.log('[harnessd] the update stayed up, but has staged a newer build — leaving that one to be judged')
+ return
+ }
this.update = null
this.deps.confirmUpdate()
this.deps.log('[harnessd] the update stayed up — keeping it')
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 69c0cf2e5..94fc0d324 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -312,6 +312,30 @@ describe('hook notify terminal scope', () => {
expect(() => readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')).toThrow()
})
+ it('keeps a Cursor session\'s tasks when its end was not answered in time', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cursor-late-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const cursorHome = join(dir, 'cursor')
+ let slow = false
+ const server = createServer((req, res) => {
+ if (slow) { setTimeout(() => { try { res.end('{}') } catch { /* the hook has gone */ } }, 2_000).unref(); return }
+ req.resume()
+ req.on('end', () => res.end('{}'))
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+ const hook = (input: Record<string, unknown>) => runHook({ port: address.port, tmuxPane: '%21', engine: 'cursor', dataDir, cursorHome, input })
+ await hook({ hook_event_name: 'preToolUse', session_id: 'cursor-session', tool_name: 'Task', tool_use_id: 'call-1', tool_input: { description: 'Inspect', prompt: 'Read code' } })
+ const tasks = () => JSON.parse(readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')) as unknown[]
+ expect(tasks()).toHaveLength(1)
+ slow = true
+ await hook({ hook_event_name: 'sessionEnd', session_id: 'cursor-session', reason: 'logout' })
+ expect(tasks()).toHaveLength(1)
+ })
+
it('ignores Cursor background agents without leaking them into the registry', async () => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cursor-background-'))
tmpDirs.push(dir)
diff --git a/cli/src/lib/daemonSafeMode.spec.ts b/cli/src/lib/daemonSafeMode.spec.ts
index 4f079e723..665d34896 100644
--- a/cli/src/lib/daemonSafeMode.spec.ts
+++ b/cli/src/lib/daemonSafeMode.spec.ts
@@ -29,6 +29,9 @@ describe('safeModeDisposition', () => {
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)
+ // The core of a master that is gone, still leaving: this core leaves to be started again, not for good.
+ const leaving = Object.assign(new Error('The core (pid 8) of a master that is gone still serves /data/daemon-18473.sock'), { code: 'ORPHAN_STILL_SERVING' })
+ expect(safeModeDisposition(leaving, nobody)).toEqual({ stay: false, reason: leaving.message, retry: true })
expect(safeModeDisposition(null, nobody).stay).toBe(true)
})
diff --git a/cli/src/lib/daemonSafeMode.ts b/cli/src/lib/daemonSafeMode.ts
index c58491cad..cfaa65706 100644
--- a/cli/src/lib/daemonSafeMode.ts
+++ b/cli/src/lib/daemonSafeMode.ts
@@ -27,6 +27,8 @@ export interface SafeModeMarker {
export interface SafeModeDisposition {
stay: boolean
reason: string
+ /** Leave so as to be started again: what stands in the way is leaving too (lib/localSocket.ts). */
+ retry?: true
}
/** Thrown at the top of start-up when harnessd's master asks for safe mode: the core kept crashing. */
@@ -57,6 +59,10 @@ export function safeModeDisposition(
// 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 }
+ // The core of a master that is gone, still leaving once the wait for it was over: this core goes, and is
+ // started again by its master, which by then finds the folder free. Gone for good instead, its master
+ // went with it, cleanly, and launchd and systemd do not start a clean exit again.
+ if ((error as { code?: unknown } | null | undefined)?.code === 'ORPHAN_STILL_SERVING') return { stay: false, reason: message, retry: true }
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/daemonState.ts b/cli/src/lib/daemonState.ts
index d3d0373ed..336a62710 100644
--- a/cli/src/lib/daemonState.ts
+++ b/cli/src/lib/daemonState.ts
@@ -17,6 +17,8 @@ export const PID_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.pid')
export const DAEMON_LOG_FILE = join(env.ADAPTER_DATA_DIR, 'harness.log')
/** What harnessd's master last said about itself, for `harness status` when no core answers. */
export const HARNESSD_STATUS_FILE = join(env.ADAPTER_DATA_DIR, 'harnessd-status.json')
+/** Where a master re-executing on a new bundle leaves word of it, until that master's core is up (harnessd/reexec.ts). */
+export const HARNESSD_REEXEC_FILE = join(env.ADAPTER_DATA_DIR, 'harnessd-reexec.json')
/** This user's recorded TCP port; the configured port still names its private Unix socket. */
export function daemonPort(): number {
diff --git a/cli/src/lib/daemonStop.spec.ts b/cli/src/lib/daemonStop.spec.ts
index 75b70cd7e..93757c249 100644
--- a/cli/src/lib/daemonStop.spec.ts
+++ b/cli/src/lib/daemonStop.spec.ts
@@ -46,6 +46,29 @@ describe('stopDaemonProcess', () => {
expect(existsSync(PID_FILE)).toBe(false)
})
+ it('clears the re-execution marker of the master it stopped, and no other', async () => {
+ // Stopped in the moment after it re-executed, the master dies of the signal before it can clear its
+ // marker; the next start must not take that for an update that never came up.
+ const { stopDaemonProcess } = await load()
+ const { HARNESSD_REEXEC_FILE, PID_FILE } = await import('./daemonState.js')
+ const marker = (pid: number) => JSON.stringify({ pid, from: 'a'.repeat(64), to: 'b'.repeat(64), at: 1 })
+ writeFileSync(PID_FILE, '500\n')
+ writeFileSync(HARNESSD_REEXEC_FILE, marker(500))
+ await stopDaemonProcess(fakeDeps({ pid: 500, alive: new Set([500]), killed: [], locked: 0, released: 0 }))
+ expect(existsSync(HARNESSD_REEXEC_FILE)).toBe(false)
+ // Another master's marker (one stopped beside it, or a pid file gone stale) is not this stop's.
+ writeFileSync(PID_FILE, '501\n')
+ writeFileSync(HARNESSD_REEXEC_FILE, marker(777))
+ await stopDaemonProcess(fakeDeps({ pid: 501, alive: new Set([501]), killed: [], locked: 0, released: 0 }))
+ expect(existsSync(HARNESSD_REEXEC_FILE)).toBe(true)
+ // Stopped through launchd or systemd, likewise.
+ writeFileSync(HARNESSD_REEXEC_FILE, marker(600))
+ await stopDaemonProcess(fakeDeps({ pid: 600, alive: new Set(), killed: [], locked: 0, released: 0 }, {
+ stopPlatform: () => ({ ok: true, stopped: 600 }) as never,
+ }))
+ expect(existsSync(HARNESSD_REEXEC_FILE)).toBe(false)
+ })
+
it('does not delete a pid file that a different daemon wrote meanwhile', async () => {
const { stopDaemonProcess } = await load()
const { PID_FILE } = await import('./daemonState.js')
diff --git a/cli/src/lib/daemonStop.ts b/cli/src/lib/daemonStop.ts
index 95365a12d..2c9f17d44 100644
--- a/cli/src/lib/daemonStop.ts
+++ b/cli/src/lib/daemonStop.ts
@@ -8,7 +8,8 @@
*/
import { rmSync } from 'fs'
-import { PID_FILE, isAlive, readPid } from './daemonState.js'
+import { HARNESSD_REEXEC_FILE, PID_FILE, isAlive, readPid } from './daemonState.js'
+import { readMarker, removeMarker } from '../harnessd/reexec.js'
import { acquireSpawnLock, describeSpawnLockFailure, describeSpawnLockOwner, SPAWN_LOCK_WAIT_MS } from './daemonSpawnLock.js'
import { PLATFORM_STOP_WAIT_MS, stopUnderPlatform, type PlatformStop } from './platformDaemon.js'
@@ -56,12 +57,23 @@ export function defaultStopDeps(): StopDeps {
export const STOP_GRACE_MS = 3_000
+/**
+ * A re-execution marker that names the master just stopped. A master stopped in the moment after it
+ * re-executed on a new bundle, before its code has its signal handlers, dies of the signal and leaves
+ * the marker it would have cleared; the next start took that for a re-execution that never came up,
+ * rolled the update back and rejected its version (harnessd/reexec.ts recoverFailedReexec). A stop is
+ * not a failure.
+ */
+function clearReexecMarker(pid: number): void {
+ if (readMarker(HARNESSD_REEXEC_FILE)?.pid === pid) removeMarker(HARNESSD_REEXEC_FILE)
+}
+
/** SIGTERM the daemon named by the pid file, SIGKILL if it lingers. Returns what was stopped. */
export async function stopDaemonProcess(deps: StopDeps = defaultStopDeps()): Promise<{ pid: number | null; stopped: boolean }> {
const release = await deps.lock()
try {
const stopped = await stopThroughPlatform(deps)
- if (stopped !== null) return { pid: stopped, stopped: true }
+ if (stopped !== null) { clearReexecMarker(stopped); return { pid: stopped, stopped: true } }
const pid = deps.readPid()
if (!pid || !deps.isAlive(pid)) {
// A pid file naming nothing is debris from a crash; nobody else can be relying on it.
@@ -76,6 +88,7 @@ export async function stopDaemonProcess(deps: StopDeps = defaultStopDeps()): Pro
// (shutdown), and a daemon that came up meanwhile — impossible under the lock, but cheap to
// respect — must not lose its record to us.
if (deps.readPid() === pid) { try { rmSync(PID_FILE, { force: true }) } catch { /* ignore */ } }
+ if (!deps.isAlive(pid)) clearReexecMarker(pid)
return { pid, stopped: true }
} finally {
release()
diff --git a/cli/src/lib/harnessSessionLabel.spec.ts b/cli/src/lib/harnessSessionLabel.spec.ts
index 1fc0b0e78..a6a0230c3 100644
--- a/cli/src/lib/harnessSessionLabel.spec.ts
+++ b/cli/src/lib/harnessSessionLabel.spec.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { harnessPaneOwner, ownedHere, ownerCommand, paneOwnerFormat, paneOwnerOf } from './harnessSessionLabel.js'
+import { isolatedTmux } from '../testing/isolatedTmux.js'
const dirs: string[] = []
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
@@ -63,7 +64,26 @@ describe('the tag on a tmux before 3.0', () => {
// tmux 2.x cannot cut a substring out of a format: the start command comes back cut to the prefix
// and a tag's length, never whole (it can hold the `|` and newlines a listing is split on).
expect(paneOwnerFormat(false))
- .toBe('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{@harness_daemon}}')
+ .toBe('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{?#{m:harness-*,#{session_name}},#{@harness_daemon},}}')
+ })
+
+ it('reads the window\'s tag only in a session Harness named, on a real tmux', async () => {
+ // A pane the person split into an agent's window, once they had moved that window into their own
+ // session, carries no tag of its own: the window's was taken for it, and it was styled as an agent.
+ const tmux = await isolatedTmux()
+ try {
+ const tag = '0123456789abcdef'
+ await tmux.run('new-session', '-d', '-s', 'harness-claude-1', '-x', '80', '-y', '24')
+ await tmux.run('set-option', '-w', '-t', 'harness-claude-1', '@harness_daemon', tag)
+ await tmux.run('new-session', '-d', '-s', 'mine', '-x', '80', '-y', '24')
+ await tmux.run('move-window', '-s', 'harness-claude-1:0', '-t', 'mine:5')
+ await tmux.run('new-session', '-d', '-s', 'harness-codex-2', '-x', '80', '-y', '24')
+ await tmux.run('set-option', '-w', '-t', 'harness-codex-2', '@harness_daemon', tag)
+ const owners = (await tmux.run('list-panes', '-a', '-F', `#{session_name}|${paneOwnerFormat(false)}`)).split('\n')
+ expect(owners.sort()).toEqual(['harness-codex-2|0123456789abcdef', 'mine|', 'mine|'])
+ } finally {
+ await tmux.close()
+ }
})
it('takes the tag out of a start command, and any other field as the tag itself', () => {
diff --git a/cli/src/lib/harnessSessionLabel.ts b/cli/src/lib/harnessSessionLabel.ts
index df07671bd..151c3404e 100644
--- a/cli/src/lib/harnessSessionLabel.ts
+++ b/cli/src/lib/harnessSessionLabel.ts
@@ -63,7 +63,11 @@ export function ownerCommand(owner: string, command: readonly string[]): string[
export function paneOwnerFormat(paneOptions: boolean): string {
if (paneOptions) return `#{${HARNESS_OWNER_OPTION}}`
const width = OWNER_COMMAND_PREFIX.length + OWNER_TAG_LENGTH
- return `#{?#{m:${OWNER_COMMAND_PREFIX}*,#{pane_start_command}},#{=${width}:pane_start_command},#{${HARNESS_OWNER_OPTION}}}`
+ // The window's tag only in a session Harness named. Everywhere else it named a pane the person split
+ // into an agent's window, or joined into one they had moved into their own session: taken for the
+ // agent's, it was restyled, given mouse mode, and counted among Harness's terminals.
+ return `#{?#{m:${OWNER_COMMAND_PREFIX}*,#{pane_start_command}},#{=${width}:pane_start_command},`
+ + `#{?#{m:${HARNESS_SESSION_PREFIX}*,#{session_name}},#{${HARNESS_OWNER_OPTION}},}}`
}
/** The tag out of a `paneOwnerFormat` field: the field itself, unless it is a start command's prefix. */
diff --git a/cli/src/lib/localSocket.spec.ts b/cli/src/lib/localSocket.spec.ts
index 173e2e159..2936dcae8 100644
--- a/cli/src/lib/localSocket.spec.ts
+++ b/cli/src/lib/localSocket.spec.ts
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writ
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
- askDataFolderServer, isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, ORPHAN_WAIT_MS,
+ askDataFolderServer, isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketName, localSocketPath, ORPHAN_STILL_SERVING, ORPHAN_WAIT_MS,
refuseServedDataFolder, type DataFolderServer, type LocalSocketServer, type ServedFolderDeps,
} from './localSocket.js'
@@ -286,8 +286,9 @@ describe('refuseServedDataFolder', () => {
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.
+ // Refused as the orphan it is, which its master starts again, never as another daemon (an exit for good).
const lingering = await run([{ pid: 7, corePid: 8 }])
- expect(lingering).toMatchObject({ outcome: 'EADDRINUSE', waited: ORPHAN_WAIT_MS })
+ expect(lingering).toMatchObject({ outcome: ORPHAN_STILL_SERVING, waited: ORPHAN_WAIT_MS })
expect(lingering.lines).toHaveLength(1)
})
})
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index b2278f5a0..6512635d4 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -119,6 +119,16 @@ export async function listenLocalSocket(handler: http.RequestListener, path: str
const alreadyServing = (path: string): Error =>
Object.assign(new Error(`A Harness daemon is already serving ${path}`), { code: 'EADDRINUSE' })
+/**
+ * The core of a master that is gone still serves the data folder once the wait for it is over. Not another
+ * daemon: it is leaving, slowly (a client that will not answer its close). Its own code, so start-up ends
+ * in an exit its master starts again, and the next core finds it gone, where EADDRINUSE ends it for good,
+ * and launchd and systemd do not start a clean exit again (lib/daemonSafeMode.ts).
+ */
+export const ORPHAN_STILL_SERVING = 'ORPHAN_STILL_SERVING'
+const orphanStillServing = (path: string, corePid: number): Error =>
+ Object.assign(new Error(`The core (pid ${corePid}) of a master that is gone still serves ${path}`), { code: ORPHAN_STILL_SERVING })
+
/**
* 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
@@ -229,6 +239,7 @@ export async function refuseServedDataFolder(
if (!path) return
const deadline = deps.now() + waitMs
let orphanSeen = false
+ let orphanCore = 0
for (;;) {
const server = await deps.who(path, timeoutMs)
if (server === 'none') {
@@ -242,8 +253,9 @@ export async function refuseServedDataFolder(
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
+ orphanCore = server.corePid
}
- if (deps.now() >= deadline) throw alreadyServing(path)
+ if (deps.now() >= deadline) throw orphanSeen ? orphanStillServing(path, orphanCore) : alreadyServing(path)
await deps.sleep(ORPHAN_POLL_MS)
}
}
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index 32cd8536a..d44740bff 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -72,6 +72,17 @@ describe('restartAgent', () => {
expect(d.calls).toEqual(['holdOpen', 'terminate', 'buildArgv', 'respawn', 'waitForProcess'])
})
+ it('stops nothing when the respawn would be refused, as on a tmux too old for the relaunch\'s environment', async () => {
+ const d = { ...deps(), respawnRefusal: async () => 'this machine\'s tmux is older than 3.0, the first version that can give a respawned pane its own environment. Upgrade tmux.' }
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(outcome).toEqual({ ok: false, detail: 'this machine\'s tmux is older than 3.0, the first version that can give a respawned pane its own environment. Upgrade tmux. Nothing was stopped.' })
+ expect(d.calls).toEqual([])
+ // Asked, and not refused: the restart goes on as before.
+ const allowed = { ...deps(), respawnRefusal: async () => null }
+ expect(await restartAgent({ engine: 'codex', sessionId: 's1' }, false, allowed)).toMatchObject({ ok: true })
+ expect(allowed.calls).toEqual(['holdOpen', 'terminate', 'buildArgv', 'respawn', 'waitForProcess'])
+ })
+
it('never respawns when holdOpen fails to re-arm the pane', async () => {
const d = deps({ holdOpen: async () => ({ ok: false, reason: 'tmux unreachable' }) })
const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index beccb15eb..e03f3e305 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -83,6 +83,9 @@ export interface RestartAgentDeps {
terminate: (checkAfterMs?: number) => Promise<TerminateOutcome>
/** `tmux respawn-pane` (or equivalent) with a fully-built argv. */
respawn: (argv: string[]) => Promise<{ ok: boolean; reason?: string }>
+ /** Why `respawn` would be refused here (a tmux too old for what the relaunch needs), asked before
+ * anything is stopped; null when it would try. Left out, never refused. */
+ respawnRefusal?: () => Promise<string | null>
/** Poll the pane for a recognizable engine process, up to an internal budget. Null on timeout. */
waitForProcess: () => Promise<ProcessIdentity | null>
/** Prepare persisted history only once the old writer is confirmed stopped. A failure must
@@ -106,6 +109,10 @@ export async function restartAgent(
const changed = { ok: false, detail: 'the harness changed or stopped during restart' } as const
const current = () => deps.isCurrent?.() !== false
if (!current()) return changed
+ // Before anything is stopped: refused after the kill, the agent was left with no engine at all.
+ const refused = await deps.respawnRefusal?.()
+ if (refused) return { ok: false, detail: `${refused} Nothing was stopped.` }
+ if (!current()) return changed
const armed = await deps.holdOpen()
if (!current()) return changed
if (!armed.ok) {
diff --git a/cli/src/lib/runtimeInstall.spec.ts b/cli/src/lib/runtimeInstall.spec.ts
index e0968b61e..a594bc1c0 100644
--- a/cli/src/lib/runtimeInstall.spec.ts
+++ b/cli/src/lib/runtimeInstall.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { execFileSync } from 'node:child_process'
+import { execFileSync, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -391,6 +391,25 @@ describe('ensureManagedGrid', () => {
expect(existsSync(join(runtimeDir, 'current-grid'))).toBe(false)
})
+ it('clears the staging a process that is gone left behind, and leaves a running one\'s', async () => {
+ // A core that exited mid-unpack (an update's handoff) left its staging, archive and partial tree.
+ const gone = spawnSync('/usr/bin/true').pid!
+ const left = join(runtimeDir, `.grid-staging-${gone}-1790000000000`)
+ const running = join(runtimeDir, `.grid-staging-${process.pid}-1790000000001`)
+ const other = join(runtimeDir, `.node-staging-${gone}-1790000000002`)
+ for (const dir of [left, running, other]) {
+ mkdirSync(join(dir, 'grid-0.3.47', 'bin'), { recursive: true })
+ writeFileSync(join(dir, 'grid.tar.gz'), 'partial')
+ }
+ stubFetch(null)
+ const { ensureManagedGrid } = await load()
+ await ensureManagedGrid()
+ expect(existsSync(left)).toBe(false)
+ expect(existsSync(running)).toBe(true)
+ // Each runtime sweeps its own.
+ expect(existsSync(other)).toBe(true)
+ })
+
it('keeps the grid it has when the manifest is unreachable, and has nothing when it has nothing', async () => {
vi.stubGlobal('fetch', async () => { throw new Error('ENOTFOUND') })
const { ensureManagedGrid } = await load()
diff --git a/cli/src/lib/runtimeInstall.ts b/cli/src/lib/runtimeInstall.ts
index 21d96f593..b65ebd86e 100644
--- a/cli/src/lib/runtimeInstall.ts
+++ b/cli/src/lib/runtimeInstall.ts
@@ -140,7 +140,29 @@ interface ManagedArchive {
* Everything here is best-effort and returns rather than throws: a daemon must not fail to start
* because a download failed.
*/
+/**
+ * The staging folders of processes that are gone: a core that exited in the middle of an unpack (an
+ * update's handoff, a master's restart) left its `.<name>-staging-<pid>-<time>`, the archive and a
+ * partial tree in it, and nothing else ever removes one. Another process's, still running, is its own.
+ */
+function sweepStaging(name: string): void {
+ const prefix = `.${name}-staging-`
+ let entries: string[]
+ try { entries = readdirSync(env.ADAPTER_RUNTIME_DIR) } catch { return }
+ for (const entry of entries) {
+ if (!entry.startsWith(prefix)) continue
+ const pid = Number(entry.slice(prefix.length).split('-')[0])
+ if (Number.isSafeInteger(pid) && pid > 0 && processAlive(pid)) continue
+ try { rmSync(join(env.ADAPTER_RUNTIME_DIR, entry), { recursive: true, force: true }) } catch { /* the next start tries again */ }
+ }
+}
+
+function processAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }
+}
+
async function ensureManagedArchive(spec: ManagedArchive): Promise<string | null> {
+ sweepStaging(spec.name)
const installed = spec.installed()
if (installed && !spec.followsPin) return installed
const key = platformKey()
diff --git a/cli/src/lib/selfUpdate.spec.ts b/cli/src/lib/selfUpdate.spec.ts
index bbb0c8603..4b5ba9cf3 100644
--- a/cli/src/lib/selfUpdate.spec.ts
+++ b/cli/src/lib/selfUpdate.spec.ts
@@ -149,6 +149,61 @@ describe('startSelfUpdater', () => {
expect(events).toEqual(['lock', 'staged:9.9.9', 'handoff-done', 'unlock'])
})
+ it('stopped while a check is under way, swaps nothing and hands nothing over', async () => {
+ // A daemon shutting down (`harness stop`, a sign-out) while the updater waits on a download or a
+ // canary. Here the canary: the build answers after a moment, and the stop lands before it does.
+ const slow = Buffer.from('setTimeout(() => console.log("9.9.9"), 400)\n')
+ vi.stubGlobal('fetch', async (url: string) => {
+ if (url === 'https://updates.test/metadata.json') {
+ return new Response(JSON.stringify({ adapter: { version: '9.9.9', cli: { url: 'https://updates.test/cli.js', sha256: sha(slow) }, notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notifySource) } } }))
+ }
+ if (url === 'https://updates.test/cli.js') return new Response(slow)
+ if (url === 'https://updates.test/notify.mjs') return new Response(notifySource)
+ return new Response('', { status: 404 })
+ })
+ const dir = tempDir()
+ const staged: string[] = []
+ const canarying = () => readdirSync(dir).some((name) => name.startsWith('.canary-'))
+ const poller = startSelfUpdater({
+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 20,
+ onStaged: (version) => { staged.push(version) },
+ })
+ await vi.waitFor(() => expect(canarying()).toBe(true), { timeout: 5_000 })
+ poller.stop()
+ await vi.waitFor(() => expect(canarying()).toBe(false), { timeout: 5_000 })
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ expect(staged).toEqual([])
+ expect(existsSync(join(dir, 'cli.js'))).toBe(false)
+ })
+
+ it('under a master that would roll both back, waits for the build on probation to be kept before staging a newer one', async () => {
+ // v0.3.58's master rolls back on any exit of a core on probation, the one for a newer build included.
+ serveUpdate()
+ const dir = tempDir()
+ const running = Buffer.from('console.log("1.5.0")\n')
+ writeFileSync(join(dir, 'cli.js'), running)
+ writeFileSync(join(dir, 'update-pending.json'), JSON.stringify({ version: '1.5.0', sha256: sha(running), at: 1 }))
+ const staged: string[] = []
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const poller = startSelfUpdater({
+ currentVersion: '1.5.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 20,
+ stageWhileJudged: false, onStaged: (version) => { staged.push(version) },
+ })
+ try {
+ await vi.waitFor(() => expect(log).toHaveBeenCalledWith('[update] 9.9.9 is ready — waiting for this build to be kept before staging it'), { timeout: 5_000 })
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ expect(staged).toEqual([])
+ expect(readFileSync(join(dir, 'cli.js'))).toEqual(running)
+ expect(log.mock.calls.filter(([line]) => String(line).includes('waiting for this build to be kept'))).toHaveLength(1)
+ // Its master keeps it (the pending note goes): the newer build is staged at the next check.
+ rmSync(join(dir, 'update-pending.json'))
+ await vi.waitFor(() => expect(staged).toEqual(['9.9.9']), { timeout: 5_000 })
+ } finally {
+ poller.stop()
+ log.mockRestore()
+ }
+ })
+
it('is already stopped when onStaged runs — a handler that defers loses the updater for good', async () => {
// `done = true` and `stop()` happen BEFORE `onStaged`, so a handler that returns without handing
// the machine over leaves no timer and no way back. This is why the daemon's boot-time handler
@@ -590,6 +645,14 @@ describe('the canary\'s verdicts', () => {
.toEqual({ ok: false, problem: 'failed', detail: 'no answer within 1 s' })
})
+ it('kills a build that ignores the SIGTERM at its deadline, so the next check can run', async () => {
+ const started = performance.now()
+ const stubborn = Buffer.from("process.on('SIGTERM', () => {})\nsetInterval(() => {}, 1000)\n")
+ expect(await runCanary(stubborn, tempDir(), '9.9.9', 300)).toEqual({ ok: false, problem: 'failed', detail: 'no answer within 300 ms' })
+ // SIGTERM at 300 ms, ignored; SIGKILL two seconds on.
+ expect(performance.now() - started).toBeLessThan(10_000)
+ }, 20_000)
+
it('says why a canary that never ran failed', async () => {
vi.resetModules()
vi.doMock('./nodeRuntime.js', () => ({ managedNodePath: () => '/nonexistent/node' }))
@@ -876,6 +939,34 @@ describe('a link that stalls without dropping (e2e/updateHostile.e2e.ts)', () =>
await expect(downloadVerified({ url: 'https://updates.test/empty.js', sha256: sha(Buffer.alloc(0)) }, limits)).resolves.toEqual(Buffer.alloc(0))
})
+ it('gives a transfer of a known size the time its floor rate needs, and no more', async () => {
+ // 40 bytes, four every 30 ms: about 300 ms, past a 100 ms deadline, within what 40 B/s needs (1 s).
+ const bytes = Buffer.from('console.log("9.9.9") // forty bytes ...\n')
+ expect(bytes.length).toBe(40)
+ const slowly = (headers: Record<string, string> = {}) => {
+ let sent = 0
+ return new Response(new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ await new Promise((resolve) => setTimeout(resolve, 30))
+ if (sent >= bytes.length) { controller.close(); return }
+ controller.enqueue(new Uint8Array(bytes.subarray(sent, sent + 4)))
+ sent += 4
+ },
+ }), { headers })
+ }
+ vi.stubGlobal('fetch', async (url: string) => slowly(url.endsWith('/sized.js') ? { 'content-length': '40' } : {}))
+ const floor = { idleMs: 200, deadlineMs: 100, floorBytesPerSecond: 40 }
+ // By its Content-Length, or by the size the manifest names.
+ await expect(downloadVerified({ url: 'https://updates.test/sized.js', sha256: sha(bytes) }, floor)).resolves.toEqual(bytes)
+ await expect(downloadVerified({ url: 'https://updates.test/unsized.js', sha256: sha(bytes), size: 40 }, floor)).resolves.toEqual(bytes)
+ // Of unknown size, or slower than the floor, the deadline stands.
+ await expect(downloadVerified({ url: 'https://updates.test/unsized.js', sha256: sha(bytes) }, floor)).rejects.toThrow('took longer than 100 ms in all')
+ await expect(downloadVerified({ url: 'https://updates.test/sized.js', sha256: sha(bytes) }, { ...floor, floorBytesPerSecond: 200 }))
+ .rejects.toThrow('took longer than 200 ms in all (40 bytes at 200 B/s)')
+ // The bundle's own: a slow but steady link finishes.
+ expect(DOWNLOAD_LIMITS).toEqual({ idleMs: 60_000, deadlineMs: 15 * 60_000, floorBytesPerSecond: 1_024 })
+ })
+
it('reads a response with no stream whole, and sets no deadline for an infinite one', async () => {
const bytes = Buffer.from('console.log("9.9.9")\n')
vi.stubGlobal('fetch', async (url: string) => url.endsWith('/buffered.js')
diff --git a/cli/src/lib/selfUpdate.ts b/cli/src/lib/selfUpdate.ts
index 62dec6fff..5e0c4696f 100644
--- a/cli/src/lib/selfUpdate.ts
+++ b/cli/src/lib/selfUpdate.ts
@@ -19,6 +19,7 @@ import { execFile } from 'child_process'
import { join } from 'path'
import { SpawnLockBusyError, describeSpawnLockFailure } from './daemonSpawnLock.js'
import { managedNodePath } from './nodeRuntime.js'
+import { patientDeadline } from './patientExec.js'
export interface FileRef {
url: string
@@ -141,9 +142,20 @@ export function shouldAutoUpdate(candidate: string, current: string): boolean {
* held it for as long as the trickle lasted, every later check skipped meanwhile, with a fix waiting
* (e2e/updateHostile.e2e.ts). Each is now its own failure, retried at the next check.
*/
-export interface TransferLimits { idleMs: number; deadlineMs: number }
-/** A bundle: a minute without a byte, a quarter of an hour in all (4.4 MB at 5 KB/s). */
-export const DOWNLOAD_LIMITS: TransferLimits = { idleMs: 60_000, deadlineMs: 15 * 60_000 }
+export interface TransferLimits {
+ idleMs: number
+ deadlineMs: number
+ /**
+ * The slowest a transfer of a known size (Content-Length, or the size the manifest names) may average:
+ * its deadline grows to what that rate needs, when that is longer. A link that keeps sending, however
+ * slowly, finishes; one that trickles a byte a minute to stay under the idle limit still ends.
+ */
+ floorBytesPerSecond?: number
+}
+/** A bundle: a minute without a byte, and a quarter of an hour in all or whatever 1 KB/s needs, the longer
+ * (4.4 MB: about 75 minutes). The fixed quarter of an hour left a link under 5 KB/s never updating: each
+ * check started again from nothing and kept the link full. */
+export const DOWNLOAD_LIMITS: TransferLimits = { idleMs: 60_000, deadlineMs: 15 * 60_000, floorBytesPerSecond: 1_024 }
/** The manifest is a few hundred bytes. */
export const MANIFEST_LIMITS: TransferLimits = { idleMs: 30_000, deadlineMs: 60_000 }
/**
@@ -157,7 +169,7 @@ export const RUNTIME_DOWNLOAD_LIMITS: TransferLimits = { idleMs: 300_000, deadli
export class TransferStalledError extends Error {}
/** GET `url` whole within `limits`: the status, and the body once it has all arrived. */
-async function fetchWithin(url: string, limits: TransferLimits): Promise<{ ok: boolean; status: number; body: Buffer }> {
+async function fetchWithin(url: string, limits: TransferLimits, expectedBytes?: number): Promise<{ ok: boolean; status: number; body: Buffer }> {
const controller = new AbortController()
let stalled!: (error: TransferStalledError) => void
const gaveUp = new Promise<never>((_, reject) => { stalled = reject })
@@ -174,12 +186,23 @@ async function fetchWithin(url: string, limits: TransferLimits): Promise<{ ok: b
return handle
}
// No deadline at all for an infinite one: a timer given Infinity fires at once.
- const deadline = Number.isFinite(limits.deadlineMs) ? timer(limits.deadlineMs, `took longer than ${limits.deadlineMs} ms in all`) : undefined
+ const startedAt = performance.now()
+ let deadline = Number.isFinite(limits.deadlineMs) ? timer(limits.deadlineMs, `took longer than ${limits.deadlineMs} ms in all`) : undefined
+ /** Once the size is known: the deadline the floor rate needs, when that is the longer. */
+ const scaleDeadline = (bytes: number): void => {
+ if (!deadline || !limits.floorBytesPerSecond || !(bytes > 0)) return
+ const needed = Math.ceil(bytes / limits.floorBytesPerSecond * 1000)
+ if (needed <= limits.deadlineMs) return
+ clearTimeout(deadline)
+ deadline = timer(Math.max(0, needed - (performance.now() - startedAt)), `took longer than ${needed} ms in all (${bytes} bytes at ${limits.floorBytesPerSecond} B/s)`)
+ }
+ if (expectedBytes !== undefined) scaleDeadline(expectedBytes)
let idle = timer(limits.idleMs, `sent nothing for ${limits.idleMs} ms`)
const heard = (): void => { clearTimeout(idle); idle = timer(limits.idleMs, `sent nothing for ${limits.idleMs} ms`) }
try {
const res = await Promise.race([fetch(url, { signal: controller.signal }), gaveUp])
heard()
+ if (expectedBytes === undefined) scaleDeadline(Number(res.headers?.get?.('content-length')))
// Read as it arrives, so the idle timer hears every chunk. A response with no stream (a body-less
// status, or a Response-like object that only buffers) is read whole, within the same limits.
if (!res.body) {
@@ -220,7 +243,7 @@ export class DigestMismatchError extends Error {}
/** Download one file within `limits` and verify its sha256 in memory; throws on a non-2xx, a stall or a
* digest mismatch. */
export async function downloadVerified(ref: FileRef, limits: TransferLimits = DOWNLOAD_LIMITS): Promise<Buffer> {
- const res = await fetchWithin(ref.url, limits)
+ const res = await fetchWithin(ref.url, limits, ref.size)
if (!res.ok) throw new Error(`download ${ref.url} → HTTP ${res.status}`)
const got = sha256(res.body)
if (got.toLowerCase() !== ref.sha256.toLowerCase()) {
@@ -238,6 +261,8 @@ export type CanaryResult = { ok: true } | { ok: false; problem: 'unwritable' | '
/** How long the canary may take to answer. */
export const CANARY_TIMEOUT_MS = 15_000
+/** How long a canary that outlived its deadline has between SIGTERM and SIGKILL. */
+export const CANARY_KILL_GRACE_MS = 2_000
/** Cheap runnability check: write the new bundle into a temp install-shaped dir and run
* `node cli.js version`. This catches broken ESM/CJS packaging before the live install is touched.
@@ -263,18 +288,33 @@ export async function runCanary(cliBuf: Buffer, dir: string, version?: string, t
}
// The interpreter the NEXT daemon will run on — see managedNodePath(). Canarying on this
// process's interpreter would assert about a Node the new build may never be started with.
+ // The deadline counts only time this process's event loop ran (patientDeadline): Node's own timeout,
+ // fired late after a held loop, threw a build's answer away and took it for no answer. A build that
+ // outlives it is sent SIGTERM, and SIGKILL [CANARY_KILL_GRACE_MS] later: one that ignores SIGTERM held
+ // the check open for good, and with it every later check (`checking`), a fixed release's included.
const r = await new Promise<{ failure: string | null; stdout: string }>((resolve) => {
- execFile(managedNodePath(), [tmpCli, 'version'], { timeout: timeoutMs, encoding: 'utf8' }, (error, stdout) => {
+ let timedOut = false
+ let grace: ReturnType<typeof setTimeout> | undefined
+ let cancel = (): void => {}
+ const child = execFile(managedNodePath(), [tmpCli, 'version'], { encoding: 'utf8' }, (error, stdout) => {
+ cancel()
+ clearTimeout(grace)
+ // An answer is an answer, even one that raced the kill.
if (!error) { resolve({ failure: null, stdout }); return }
- const failed = error as NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null; code?: number | string }
+ const failed = error as NodeJS.ErrnoException & { signal?: NodeJS.Signals | null; code?: number | string }
resolve({
- failure: failed.killed && failed.signal === 'SIGTERM' ? `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`
+ failure: timedOut ? `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`
: typeof failed.code === 'number' ? `exit ${failed.code}`
: failed.signal ? `signal ${failed.signal}`
: failed.message,
stdout: '',
})
})
+ cancel = patientDeadline(timeoutMs, () => {
+ timedOut = true
+ child.kill('SIGTERM')
+ grace = setTimeout(() => child.kill('SIGKILL'), CANARY_KILL_GRACE_MS)
+ })
})
if (r.failure !== null) return { ok: false, problem: 'failed', detail: r.failure }
const lines = r.stdout.trim().split('\n')
@@ -471,6 +511,15 @@ export function startSelfUpdater(opts: {
withLock?: <T>(fn: () => Promise<T>) => Promise<T>
/** How long a download may go without a byte, and take in all; the manifest gets at most its own. */
limits?: TransferLimits
+ /**
+ * Whether a newer build may be staged while the bundle on disk is itself an update still being judged.
+ * A master from before #807 (v0.3.58) rolls back on ANY exit of a core on probation, the exit for the
+ * newer build included: it put back the backup, which #807's `stage` keeps as the last build kept (two
+ * builds back), and rejected the newer one for good. A core such a master runs waits for its own build
+ * to be kept, then stages. True when left out, and for every master that says it judges such an exit
+ * itself (HARNESSD_JUDGES_SUPERSEDED).
+ */
+ stageWhileJudged?: boolean
}): Poller {
let checking = false
let done = false
@@ -485,6 +534,7 @@ export function startSelfUpdater(opts: {
let refused: { entry: string; tries: number; until: number } | null = null
// Said once per version: the check repeats every interval.
let toldRejected: string | null = null
+ let toldWaiting: string | null = null
const now = opts.now ?? Date.now
const download = opts.limits ?? DOWNLOAD_LIMITS
@@ -492,6 +542,10 @@ export function startSelfUpdater(opts: {
idleMs: Math.min(download.idleMs, MANIFEST_LIMITS.idleMs), deadlineMs: Math.min(download.deadlineMs, MANIFEST_LIMITS.deadlineMs),
}
const stop = (): void => { if (timer) { clearTimeout(timer); timer = null } }
+ // Stopped from outside: a check under way goes no further than the step it is on. Before, only the
+ // next check was cancelled, and one waiting on a download or a canary went on to swap the bundle and
+ // hand the machine over (`onStaged`) on a daemon that was shutting down.
+ let halted = false
const schedule = (): void => {
stop()
timer = setTimeout(() => void tick(), msUntilSlot(now(), opts.slotSecond, opts.intervalMs))
@@ -509,7 +563,7 @@ export function startSelfUpdater(opts: {
checking = true
try {
const entry = await fetchManifest(opts.url, opts.key, manifest)
- if (!entry || !shouldAutoUpdate(entry.version, opts.currentVersion)) return
+ if (halted || !entry || !shouldAutoUpdate(entry.version, opts.currentVersion)) return
const unremembered = settleRolledBack(opts.dir)
if (unremembered === entry.version || rejectedVersions(opts.dir).includes(entry.version)) {
if (toldRejected !== entry.version) console.log(`[update] ${entry.version} was rolled back on this machine — waiting for a newer build (\`harness update\` installs it anyway)`)
@@ -540,8 +594,10 @@ export function startSelfUpdater(opts: {
}
verified = { entry: key, version: entry.version, cliBuf, notifyBuf, canaried: false }
}
+ if (halted) return
if (!verified.canaried) {
const result = await runCanary(verified.cliBuf, opts.dir, entry.version)
+ if (halted) return
if (!result.ok && result.problem === 'unwritable') {
console.error(`[update] could not write the canary for ${entry.version} (${result.detail}) — trying again next check`)
return
@@ -550,9 +606,15 @@ export function startSelfUpdater(opts: {
verified.canaried = true
}
const ready = verified
+ if (opts.stageWhileJudged === false && unjudgedUpdate(opts.dir, fileSha256(join(opts.dir, CLI)))) {
+ if (toldWaiting !== ready.version) console.log(`[update] ${ready.version} is ready — waiting for this build to be kept before staging it`)
+ toldWaiting = ready.version
+ return
+ }
// Downloaded and verified OUTSIDE the lock (that can take a while on a slow link and touches
// nothing shared); swapped and handed off INSIDE it.
await withLock(async () => {
+ if (halted) return
stage(opts.dir, ready.cliBuf, ready.notifyBuf, ready.version)
done = true
stop()
@@ -572,5 +634,5 @@ export function startSelfUpdater(opts: {
}
schedule()
- return { stop }
+ return { stop: () => { halted = true; stop() } }
}
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index c56f7253f..4df8d1c5e 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -552,7 +552,7 @@ describe('TmuxBackend on a tmux before 3.0', () => {
)
const inventory = await new TmuxBackend(undefined, () => 'daemon-a').inventory()
expect(inventory.state === 'available' && inventory.roots.map((root) => root.runtime.paneId)).toEqual(['%1', '%3'])
- expect(calls()[0]).toContain('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{@harness_daemon}}')
+ expect(calls()[0]).toContain('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{?#{m:harness-*,#{session_name}},#{@harness_daemon},}}')
})
})
@@ -589,6 +589,9 @@ describe('TmuxBackend with variables on a tmux that cannot take them', () => {
it('refuses a respawn below 3.0, saying why, and asks tmux nothing', async () => {
assumeTmuxVersion({ major: 2, minor: 9 })
const calls = recordingTmux()
+ // Asked before a restart stops anything, with the same answer.
+ expect(await new TmuxBackend().respawnRefusal({ env })).toContain('older than 3.0')
+ expect(await new TmuxBackend().respawnRefusal({})).toBeNull()
const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%9' }, { env, command: ['codex'] })
expect(moved).toMatchObject({ state: 'failed', dispatch: 'not_started' })
expect(moved.state !== 'succeeded' && moved.reason).toContain('older than 3.0')
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 4bb7496d1..5e8d1fc24 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -222,11 +222,21 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
* immediately (a rejected key, a model the grid does not serve) must leave its error on screen
* instead of taking the pane down with it. Whoever calls this owns turning it back off.
*/
+ /**
+ * Why [respawn] would refuse this request on this machine's tmux, or null when it would try. Asked by a
+ * restart BEFORE it stops the engine it replaces: a respawn refused after the kill left the agent with
+ * a dead pane and no engine.
+ */
+ async respawnRefusal(request: Pick<TerminalRespawnRequest, 'env'>): Promise<string | null> {
+ // `respawn-pane -e` is tmux 3.0; refused before, for the reason `create` gives.
+ return Object.keys(request.env ?? {}).length && !(await this.features()).respawnEnv ? tmuxTooOldForEnv('3.0', 'a respawned pane') : null
+ }
+
async respawn(runtime: TmuxRuntimeRef, request: TerminalRespawnRequest): Promise<TerminalActionResult> {
+ const refused = await this.respawnRefusal(request)
+ if (refused) return terminalActionNotStarted(refused)
const features = await this.features()
const variables = Object.entries(request.env ?? {})
- // `respawn-pane -e` is tmux 3.0; refused before, for the reason `create` gives.
- if (variables.length && !features.respawnEnv) return terminalActionNotStarted(tmuxTooOldForEnv('3.0', 'a respawned pane'))
const scope = paneOptionScope(features)
// The engine-exit marker is the pane's, and a respawned pane is a new launch: cleared here, in
// the same invocation, or the new engine would read as exited the moment it started. A `-p` here
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 9c002b715..3850e93b5 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -1,9 +1,9 @@
import http from 'node:http'
-import type { AddressInfo } from 'node:net'
+import net, { type AddressInfo } from 'node:net'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { WebSocket } from 'ws'
import type { Frame, LocalClientSink } from './backendSocket.js'
-import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer, type LocalWsServerOptions } from './localWsServer.js'
+import { attachLocalWsServer, LOCAL_WS_CLOSE_GRACE_MS, type LocalWsBackend, type LocalWsServer, type LocalWsServerOptions } from './localWsServer.js'
import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
import { listenLocalSocket } from './lib/localSocket.js'
import { mkdtempSync, rmSync } from 'node:fs'
@@ -83,6 +83,23 @@ describe('local CLI WebSocket', () => {
return `ws://127.0.0.1:${port}/api/local-ws`
}
+ it('closes within a moment, however long a client takes to answer the close', async () => {
+ // A client that never answers the close frame: a raw socket past the handshake that reads nothing.
+ const url = new URL(await start(new FakeBackend()))
+ const raw = net.connect(Number(url.port), '127.0.0.1')
+ await new Promise<void>((resolve) => raw.once('connect', () => resolve()))
+ raw.write(['GET /api/local-ws HTTP/1.1', `Host: 127.0.0.1:${url.port}`, 'Upgrade: websocket', 'Connection: Upgrade',
+ 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Version: 13', '', ''].join('\r\n'))
+ await new Promise<void>((resolve) => raw.once('data', () => resolve()))
+ raw.pause()
+ const started = performance.now()
+ await local!.close()
+ local = null
+ // ws alone waits 30 s for it.
+ expect(performance.now() - started).toBeLessThan(LOCAL_WS_CLOSE_GRACE_MS + 2_000)
+ raw.destroy()
+ })
+
it('keeps notification identities on the local read and snapshot paths', async () => {
const backend = new FakeBackend(), seen = vi.fn(), unread = vi.fn()
const ws = new WebSocket(await start(backend, { onAgentSeen: seen, onAppUnread: unread }))
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 8fb9960f6..f1dbf187e 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -279,6 +279,9 @@ function withLocalClient(frame: Frame, localClient: LocalWsServerOptions['localC
* no credential: loopback-only, no Origin header, and the desktop computer-id validation identify the
* local process without placing SSO credentials on this transport.
*/
+/** How long a closing server waits for its clients to answer the close before it drops them. */
+export const LOCAL_WS_CLOSE_GRACE_MS = 1_000
+
export function attachLocalWsServer(server: http.Server, options: LocalWsServerOptions): LocalWsServer {
const wss = new WebSocketServer({
noServer: true,
@@ -774,7 +777,12 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
close: async () => {
for (const each of servers) each.off('upgrade', onUpgrade)
for (const client of wss.clients) client.close(1001, 'server shutting down')
+ // A client that does not answer the close (a suspended `hn`, a window whose process is hung) held
+ // this for ws's own close timeout, 30 s, and with it every shutdown: an update's teardown, and the
+ // core of a master that is gone, whose successor waits for its socket only 20 s.
+ const grace = setTimeout(() => { for (const client of wss.clients) client.terminate() }, LOCAL_WS_CLOSE_GRACE_MS)
await new Promise<void>((resolve) => wss.close(() => resolve()))
+ clearTimeout(grace)
},
}
}