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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep a live daemon out of harness start's way, survive a 401 refresh, and slot the update tick
0xken151ebb59d9d3d9
diff --git a/cli/README.md b/cli/README.mdindex 1f2b568ff..0765363d1 100644--- a/cli/README.md+++ b/cli/README.md@@ -82,10 +82,15 @@ It's one file, not a rotation — 10 MB is the total on disk. A log left under a(`machine.log`, or the older `adapter.log`) is adopted by rename on the first start, so existing historycarries over.-The daemon **auto-updates itself** — it polls the release manifest (default every 60 s) and, on a newer-build, downloads + verifies + swaps its own bundle and restarts when idle (with rollback on a bad-build). See [`RELEASE.md`](RELEASE.md) for publishing and the update internals. Disable with-`ADAPTER_UPDATE_DISABLE=true`.+The daemon **auto-updates itself** — it polls the release manifest once a minute, at second :45 of+each minute (`ADAPTER_UPDATE_SLOT_SEC`), and, on a newer build, downloads + verifies + swaps its own+bundle and restarts at once (with rollback on a bad build). The slot is deliberate: the desktop app+spawns `harness start` only around :15, so an update handoff and a spawn never contend for the daemon's+spawn lock. `harness start` itself stages the newest build only for a daemon it is about to spawn —+with one already running it says so and touches nothing, leaving the update to that daemon. A `401`+on the backend link refreshes the SSO token and reconnects; only a refresh token the backend rejects+signs the computer out. See [`RELEASE.md`](RELEASE.md) for publishing and the update internals.+Disable with `ADAPTER_UPDATE_DISABLE=true`.Custom Herdr-capable builds must keep self-update disabled or use a fork-owned signed`ADAPTER_UPDATE_URL` until that build is available in the configured upstream manifest. Otherwise the@@ -247,7 +252,8 @@ reported as such, not described as exercised.| `TMUX_REAP_INTERVAL_MS` | `5000` | process discovery interval (removal requires two confirmed misses) || `ADAPTER_UPDATE_URL` | `…/adapter/metadata.json` | GCS release manifest the daemon polls for a newer build || `ADAPTER_UPDATE_KEY` | `cli` | manifest key for this CLI |-| `ADAPTER_UPDATE_CHECK_MS` | `60000` | how often (ms) to poll for a newer build (check also runs on start) |+| `ADAPTER_UPDATE_CHECK_MS` | `60000` | how often (ms) to poll for a newer build (no check on start — `harness start` already staged the newest) |+| `ADAPTER_UPDATE_SLOT_SEC` | `45` | the wall-clock second each poll lands on; keeps clear of the desktop's `harness start` slot at :15. Negative = plain interval || `ADAPTER_UPDATE_DISABLE` | `false` | set `true` to turn self-update off || `ADAPTER_CLI_DIR` | `~/.harness/cli` | install dir holding the `cli.js`/`notify.mjs` the updater swaps || `LOG_FRAMES` | `false` | one log line per backend frame — type, audience and opaque ids, never a payload body. Every content-bearing frame is encrypted before it reaches the socket, so this is the only way to see what the daemon actually sent |diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 1a3904ef1..98cffe110 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { readFileSync } from 'fs'import { fileURLToPath } from 'url'import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, grokHistoryPage } from './backendSocket.js'+import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'import type { TerminalStreamManager } from './lib/terminalStreamManager.js'import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'@@ -80,6 +81,12 @@ const wsMock = vi.hoisted(() => {this.close()}+ /** What `ws` does when the upgrade is answered with an HTTP status: 'error', then 'close'. */+ refused(status: number): void {+ this.emit('error', new Error(`Unexpected server response: ${status}`))+ this.close()+ }+terminate(): void {this.close()}@@ -205,6 +212,84 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ describe('a 401 on the upgrade', () => {+ // A stub in the shape the socket needs: the first token is what the backend refuses, and the+ // refresh answers with whatever the case under test says.+ function authStub(refresh: () => Promise<string>): { auth: AuthSessionManager; calls: Array<{ force?: boolean; failedToken?: string }> } {+ const calls: Array<{ force?: boolean; failedToken?: string }> = []+ let current = 'stale-token'+ const auth = {+ accessToken: async (opts: { force?: boolean; failedToken?: string } = {}) => {+ if (opts.force) { calls.push(opts); current = await refresh() }+ return current+ },+ } as unknown as AuthSessionManager+ return { auth, calls }+ }++ it('refreshes the token, reports the link down meanwhile, and reconnects with the new token', async () => {+ vi.useFakeTimers()+ const statuses: boolean[] = []+ const { auth, calls } = authStub(async () => 'fresh-token')+ const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth, (connected) => statuses.push(connected))+ const revoked = vi.fn()+ socket.onRevoked = revoked+ socket.connect()+ await vi.advanceTimersByTimeAsync(0)+ const ws1 = wsMock.instances[0]+ expect(ws1.protocols).toEqual(['stale-token'])+ ws1.open()++ ws1.refused(401)+ await vi.advanceTimersByTimeAsync(0)+ // The socket is gone the ordinary way: status says so, no session was wiped.+ expect(statuses).toEqual([true, false])+ expect(calls).toEqual([{ force: true, failedToken: 'stale-token' }])+ expect(revoked).not.toHaveBeenCalled()+ // And the refresh, not a backoff timer, opened the next socket — with the new token.+ expect(wsMock.instances).toHaveLength(2)+ expect(wsMock.instances[1].protocols).toEqual(['fresh-token'])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(wsMock.instances).toHaveLength(2) // no second dial racing the first+ await socket.stop()+ })++ it('keeps the session and backs off when the refresh merely fails', async () => {+ vi.useFakeTimers()+ const { auth } = authStub(async () => { throw new AuthSessionError('service unavailable', 'UNAVAILABLE') })+ const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth)+ const revoked = vi.fn()+ socket.onRevoked = revoked+ socket.connect()+ await vi.advanceTimersByTimeAsync(0)+ wsMock.instances[0].open()+ wsMock.instances[0].refused(401)+ await vi.advanceTimersByTimeAsync(0)+ expect(revoked).not.toHaveBeenCalled()+ expect(wsMock.instances).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(wsMock.instances).toHaveLength(2) // the ordinary backoff, session intact+ await socket.stop()+ })++ it('signs out only when the refresh token itself is rejected', async () => {+ vi.useFakeTimers()+ const { auth } = authStub(async () => { throw new AuthSessionError('refresh token is invalid', 'INVALID_REFRESH') })+ const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth)+ const revoked = vi.fn()+ socket.onRevoked = revoked+ socket.connect()+ await vi.advanceTimersByTimeAsync(0)+ wsMock.instances[0].open()+ wsMock.instances[0].refused(401)+ await vi.advanceTimersByTimeAsync(0)+ expect(revoked).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(wsMock.instances).toHaveLength(1)+ await socket.stop()+ })+ })+it('keeps a frame queued when ws.send reports an error and retries after reconnect', async () => {vi.useFakeTimers()const socket = new BackendSocket('token')diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 92a5d5b22..f2d5653a7 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -284,6 +284,7 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strinexport class BackendSocket {private ws: WebSocket | null = nullprivate connecting = false+ /** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */private retryingAuth = falseprivate readonly auth: AuthSessionManager/** Constructor-without-auth is retained for isolated unit tests only. */@@ -627,6 +628,9 @@ export class BackendSocket {this.replayCommanderOnNextSnapshot = truethis.onStatus(false)if (this.closed) return+ // A 401 refresh owns the next connect (see the error handler below): no competing backoff timer,+ // or two sockets would race for the one machine claim.+ if (this.retryingAuth) { console.log(`[backend] disconnected (${why}) — refreshing the token before reconnecting`); return }const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))console.log(`[backend] disconnected (${why}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)setTimeout(() => this.connect(), delay)@@ -636,14 +640,36 @@ export class BackendSocket {const e = err as Error & { code?: string }const msg = e.message || e.code || String(err)console.error('[backend] socket error:', msg)- // 401/403 on the upgrade = this machine is gone/invalid (deleted while we were offline, or a bad- // token). Retrying cannot help → stop for good and let CLI clear the saved SSO session.+ // 401 on the upgrade = the access token was refused. Refresh it and come back; the socket is+ // torn down the ordinary way below (`ws.close()` → onGone: timers, status, streams), which is+ // what the previous shape skipped — it nulled `this.ws` first, so onGone returned at its first+ // line, status kept saying connected, and a refresh that failed for ANY reason (a network blip+ // included) wiped the SSO session. Only a refresh token the backend itself rejects means the+ // session is over; everything else is a transient and re-enters the backoff.if (/Unexpected server response: 401\b/.test(msg) && !this.retryingAuth) {this.retryingAuth = true- this.ws = nullvoid this.auth.accessToken({ force: true, failedToken: token })- .then(() => { this.retryingAuth = false; this.connect() })- .catch(() => { this.retryingAuth = false; this.closed = true; this.onRevoked?.() })+ .then(() => {+ this.retryingAuth = false+ // onGone has normally run by now (the close lands long before a network round trip+ // returns); if this socket is somehow still ours, let go of it before dialing again.+ if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }+ this.connect()+ })+ .catch((error: unknown) => {+ this.retryingAuth = false+ // No session to refresh, or a refresh token the backend rejects: the session is over.+ if (error instanceof AuthSessionError && (error.code === 'INVALID_REFRESH' || error.code === 'MISSING')) {+ this.closed = true+ this.onRevoked?.()+ return+ }+ if (this.closed) return+ if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }+ const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))+ console.log(`[backend] token refresh failed (${error instanceof Error ? error.message : String(error)}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)+ setTimeout(() => this.connect(), delay)+ })} else if (/Unexpected server response: 40[13]\b/.test(msg)) {this.closed = truethis.onRevoked?.()diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f71e049d2..685400e37 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -803,6 +803,19 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi// cli.js/.prev, and two writers there can leave `.prev` holding the NEW bytes — which is what a// later rollback would then "restore". The lock is re-entrant, so `launch` below just joins it.if (!foreground) {+ // A daemon that is already up is left ALONE — bundle included. Staging is for the daemon this+ // command is about to spawn; a live one updates itself (and hands off under the spawn lock). The+ // desktop app re-runs `harness start` whenever its 400ms probe misreads a busy daemon as down, and+ // staging on each of those swapped cli.js/notify.mjs under the running process and dropped its+ // `.prev` — so the daemon's own updater later wrote `.prev` from the NEW bytes, and a rollback+ // "restored" the very build that had just failed. `spawnDaemon` repeats this check under the+ // lock, for the daemon that comes up while we are waiting our turn.+ const running = readPid()+ if (running && isAlive(running)) {+ console.log(`machine already running (pid ${running}) — it auto-reconnects.`)+ console.log(' check: harness status · stop: harness stop · update now: harness update')+ process.exit(0)+ }await withSpawnLock('start', async () => {const [v] = await Promise.all([stageLatestBundle((m) => console.log(m)),@@ -4130,6 +4143,7 @@ async function runForeground(session: AuthSession): Promise<void> {key: env.ADAPTER_UPDATE_KEY,dir: env.ADAPTER_CLI_DIR,intervalMs: env.ADAPTER_UPDATE_CHECK_MS,+ slotSecond: env.ADAPTER_UPDATE_SLOT_SEC,// The lock spans the byte swap AND the handoff it triggers, as one critical section: a// `harness start` that lands between the two would otherwise stage over our .prev, and one// that lands during the handoff would spawn a second daemon.@@ -4144,7 +4158,9 @@ async function runForeground(session: AuthSession): Promise<void> {handoffChild = null}),})- console.log(`[update] self-update on · v${VERSION} · every ${Math.round(env.ADAPTER_UPDATE_CHECK_MS / 1000)}s`)+ 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`+ + (slotted ? ` at :${String(env.ADAPTER_UPDATE_SLOT_SEC % 60).padStart(2, '0')}` : ''))} else if (!env.ADAPTER_UPDATE_DISABLE) {console.log(`[update] self-update off · running a dev/repo build (v${VERSION}), not the installed copy`)}diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 7341124fd..c27605748 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -373,6 +373,11 @@ const envSchema = z.object({// How often the daemon checks for a newer build (ms). The poll is a tiny no-cache metadata fetch;// the artifact is downloaded only when the manifest version is strictly newer.ADAPTER_UPDATE_CHECK_MS: z.string().default('60000').transform(Number),+ // The wall-clock second each check lands on, when the interval divides a minute. The desktop app+ // spawns `harness start` only around :15 (see desktop/lib/ws/local_cli_discovery.dart `inSpawnSlot`);+ // keeping the update handoff 30s away from that is what stops the two from fighting over the spawn+ // lock. Set to a negative number to keep the plain interval.+ ADAPTER_UPDATE_SLOT_SEC: z.string().default('45').transform(Number),// Set 'true' to disable self-update entirely.ADAPTER_UPDATE_DISABLE: z.string().default('false').transform((v) => v === 'true'),// Install dir holding the packaged cli.js + notify.mjs that the self-updater swaps in place.diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex 9f8e47b70..f2de7cbda 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -97,6 +97,19 @@ describe('AuthSessionManager', () => {expect(readAuthSession()).toMatchObject({ refreshToken: 'refresh-1' })})+ it('gives up on a refresh that never answers, keeping the session', async () => {+ // The daemon's reconnect waits on this call, and the desktop never restarts a daemon that is+ // alive — an unbounded fetch here was a machine "connected" in status and disconnected in fact.+ writeAuthSession(baseSession())+ vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener('abort', () => reject(new Error('aborted')))+ })))+ const manager = new AuthSessionManager('https://api.example.test', { refreshTimeoutMs: 50 })++ await expect(manager.accessToken()).rejects.toMatchObject({ code: 'UNAVAILABLE' })+ expect(readAuthSession()).toMatchObject({ refreshToken: 'refresh-1' })+ })+it('still says `harness login` when the service gives no message of its own', async () => {writeAuthSession(baseSession())vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new Error('socket hang up')))diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex e2b1edcbd..82d0756e1 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -136,7 +136,12 @@ function unavailableMessage(said?: string): string {+ 'like here — if it keeps happening, run `harness login` to sign in again.'}-async function refreshRequest(baseUrl: string, current: AuthSession): Promise<RefreshResult> {+// A refresh that never answers must fail, not hang: the daemon's backend reconnect waits on it, and+// the desktop app never restarts a daemon that is alive — so an unbounded fetch here was a machine+// that stayed "connected" in status and disconnected in fact until someone ran `harness stop`.+const REFRESH_TIMEOUT_MS = 15_000++async function refreshRequest(baseUrl: string, current: AuthSession, timeoutMs = REFRESH_TIMEOUT_MS): Promise<RefreshResult> {if (!current.refreshToken) throw new AuthSessionError('No SSO refresh token. Run `harness login`.', 'MISSING')let response: Responsetry {@@ -144,6 +149,7 @@ async function refreshRequest(baseUrl: string, current: AuthSession): Promise<Remethod: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ refreshToken: current.refreshToken, autonomousEnv: current.autonomousEnv }),+ signal: AbortSignal.timeout(timeoutMs),})} catch {throw new AuthSessionError(unavailableMessage(), 'UNAVAILABLE')@@ -170,7 +176,10 @@ async function refreshRequest(baseUrl: string, current: AuthSession): Promise<Re/** One in-process refresh plus a file lock for daemon/command races. */export class AuthSessionManager {private refreshInFlight: Promise<string> | null = null- constructor(private readonly backendBaseUrl: string) {}+ constructor(+ private readonly backendBaseUrl: string,+ private readonly opts: { refreshTimeoutMs?: number } = {},+ ) {}session(): AuthSession | null { return readAuthSession() }@@ -188,7 +197,7 @@ export class AuthSessionManager {const stillNeedsRefresh = opts.force === true || (latest.expiresAt != null && latest.expiresAt <= Date.now() + REFRESH_SKEW_MS)if (!stillNeedsRefresh) return latest.accessTokentry {- const refreshed = await refreshRequest(this.backendBaseUrl, latest)+ const refreshed = await refreshRequest(this.backendBaseUrl, latest, this.opts.refreshTimeoutMs)const next: AuthSession = {...latest,accessToken: refreshed.token,diff --git a/cli/src/lib/selfUpdate.spec.ts b/cli/src/lib/selfUpdate.spec.tsindex 8fc1e7407..0b6cee948 100644--- a/cli/src/lib/selfUpdate.spec.ts+++ b/cli/src/lib/selfUpdate.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'os'import { join } from 'path'import { createHash } from 'crypto'import { afterEach, describe, expect, it, vi } from 'vitest'-import { canary, isLocalDevBuild, semverGt, shouldAutoUpdate, stage, startSelfUpdater } from './selfUpdate.js'+import { canary, isLocalDevBuild, msUntilSlot, semverGt, shouldAutoUpdate, stage, startSelfUpdater } from './selfUpdate.js'let dirs: string[] = []@@ -60,6 +60,33 @@ describe('shouldAutoUpdate', () => {})})+describe('msUntilSlot', () => {+ const MIN = 60_000+ const at = (second: number, ms = 0) => second * 1000 + ms // some minute boundary + offset++ it('lands on the slot second of the current minute when it is still ahead', () => {+ expect(msUntilSlot(at(10), 45, MIN)).toBe(35_000)+ expect(msUntilSlot(at(44, 999), 45, MIN)).toBe(1)+ })++ it('waits for the next minute once the slot has passed — including exactly on it', () => {+ expect(msUntilSlot(at(45), 45, MIN)).toBe(MIN)+ expect(msUntilSlot(at(50), 45, MIN)).toBe(55_000)+ })++ it('folds the slot into a shorter interval that still divides a minute', () => {+ // 30s interval: slot :45 is 15s past each boundary.+ expect(msUntilSlot(at(0), 45, 30_000)).toBe(15_000)+ expect(msUntilSlot(at(20), 45, 30_000)).toBe(25_000)+ })++ it('is the plain interval without a slot, or with one that cannot align to the clock', () => {+ expect(msUntilSlot(at(10), undefined, MIN)).toBe(MIN)+ expect(msUntilSlot(at(10), -1, MIN)).toBe(MIN)+ expect(msUntilSlot(at(10), 45, 7_000)).toBe(7_000) // 7s does not divide a minute+ })+})+describe('startSelfUpdater', () => {const cliSource = Buffer.from('#!/usr/bin/env node\nimport { createRequire } from "module";\nconsole.log(createRequire(import.meta.url) ? "9.9.9" : "nope")\n')const notifySource = Buffer.from('export {}\n')@@ -99,7 +126,7 @@ describe('startSelfUpdater', () => {url: 'https://updates.test/metadata.json',key: 'adapter',dir,- intervalMs: 60_000,+ intervalMs: 20, // no tick on start any more — the first one is a short interval awaywithLock: async (fn) => {events.push('lock')try { return await fn() } finally { events.push('unlock') }@@ -118,6 +145,65 @@ describe('startSelfUpdater', () => {expect(events).toEqual(['lock', 'staged:9.9.9', 'handoff-done', 'unlock'])})+ it('does not check on start; the first check lands on the slot, the next on the following one', async () => {+ vi.useFakeTimers()+ try {+ vi.setSystemTime(new Date('2026-09-15T10:00:10.000Z'))+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ adapter: { version: '1.0.0' } })))+ vi.stubGlobal('fetch', fetchMock)+ const poller = startSelfUpdater({+ currentVersion: '1.0.0',+ url: 'https://updates.test/metadata.json',+ key: 'adapter',+ dir: tempDir(),+ intervalMs: 60_000,+ slotSecond: 45,+ onStaged: () => {},+ })+ await vi.advanceTimersByTimeAsync(34_000)+ expect(fetchMock).not.toHaveBeenCalled() // :44 — not yet+ await vi.advanceTimersByTimeAsync(1_000)+ expect(fetchMock).toHaveBeenCalledTimes(1) // :45+ await vi.advanceTimersByTimeAsync(59_000)+ expect(fetchMock).toHaveBeenCalledTimes(1) // :44 of the next minute+ await vi.advanceTimersByTimeAsync(1_000)+ expect(fetchMock).toHaveBeenCalledTimes(2) // :45 again+ poller.stop()+ await vi.advanceTimersByTimeAsync(120_000)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ } finally {+ vi.useRealTimers()+ }+ })++ it('keeps the schedule alive when a check is still running as the next slot arrives', async () => {+ vi.useFakeTimers()+ try {+ vi.setSystemTime(new Date('2026-09-15T10:00:44.000Z'))+ // The first manifest fetch hangs for two minutes (a stalled link); later ones answer at once.+ let release: () => void = () => {}+ const stalled = new Promise<Response>((resolve) => { release = () => resolve(new Response(JSON.stringify({ adapter: { version: '1.0.0' } }))) })+ const fetchMock = vi.fn()+ .mockImplementationOnce(() => stalled)+ .mockImplementation(async () => new Response(JSON.stringify({ adapter: { version: '1.0.0' } })))+ vi.stubGlobal('fetch', fetchMock)+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(),+ intervalMs: 60_000, slotSecond: 45, onStaged: () => {},+ })+ await vi.advanceTimersByTimeAsync(1_000) // :45 — the stalled check starts+ expect(fetchMock).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(60_000) // next :45 — skipped, still checking+ expect(fetchMock).toHaveBeenCalledTimes(1)+ release()+ await vi.advanceTimersByTimeAsync(60_000) // the :45 after that — the chain is still booked+ expect(fetchMock).toHaveBeenCalledTimes(2)+ poller.stop()+ } finally {+ vi.useRealTimers()+ }+ })+it('releases the lock when onStaged throws', async () => {serveUpdate()const dir = tempDir()@@ -129,7 +215,7 @@ describe('startSelfUpdater', () => {url: 'https://updates.test/metadata.json',key: 'adapter',dir,- intervalMs: 60_000,+ intervalMs: 20, // no tick on start any more — the first one is a short interval awaywithLock: async (fn) => {events.push('lock')try { return await fn() } finally { events.push('unlock'); sawThrow() }diff --git a/cli/src/lib/selfUpdate.ts b/cli/src/lib/selfUpdate.tsindex 9419099ff..59d0318d3 100644--- a/cli/src/lib/selfUpdate.ts+++ b/cli/src/lib/selfUpdate.ts@@ -154,12 +154,32 @@ export function confirm(dir: string): void {export interface Poller { stop(): void }+/**+ * Milliseconds from `nowMs` to the next tick. With a slot, ticks land on the wall-clock instant+ * `slotSecond` seconds past each `intervalMs` boundary (`:45` of every minute for the defaults) —+ * strictly in the future, so a call made exactly on the slot waits a whole interval rather than+ * firing twice. Without a usable slot (negative, or an interval that does not divide a minute) it is+ * the plain interval.+ */+export function msUntilSlot(nowMs: number, slotSecond: number | undefined, intervalMs: number): number {+ if (slotSecond === undefined || slotSecond < 0 || intervalMs <= 0 || 60_000 % intervalMs !== 0) return intervalMs+ const slotMs = (slotSecond * 1000) % intervalMs+ const phase = ((nowMs % intervalMs) + intervalMs) % intervalMs+ const wait = slotMs - phase+ return wait > 0 ? wait : wait + intervalMs+}+/*** Poll on an interval; on the first build {@link shouldAutoUpdate} allows that also verifies and* passes its canary, STAGE it and call `onStaged(version)` exactly once, then stop polling (the* caller restarts immediately). Every failure* (fetch/parse/sha/canary/disk) is swallowed and simply retried next tick — the daemon never crashes* on a bad update.+ *+ * Ticks are SCHEDULED, not immediate: the first one lands on the next slot (see {@link msUntilSlot}),+ * and each tick books the next from the clock rather than from its own end, so a slow download does+ * not drift the slot. `harness start` already staged the newest build before spawning this daemon,+ * which is why nothing is lost by not checking at start.*/export function startSelfUpdater(opts: {currentVersion: string@@ -167,6 +187,10 @@ export function startSelfUpdater(opts: {key: stringdir: stringintervalMs: number+ /** Wall-clock second the ticks land on; omit or negative for a plain interval. */+ slotSecond?: number+ /** The clock (tests). */+ now?: () => number/** Awaited: the section from the byte swap through whatever `onStaged` does (the daemon's restart* handoff) is ONE critical section, and the lock `withLock` takes must outlive all of it. */onStaged: (version: string) => void | Promise<void>@@ -183,10 +207,23 @@ export function startSelfUpdater(opts: {// swap again, not the whole download.let verified: { version: string; cliBuf: Buffer; notifyBuf: Buffer } | null = null- const stop = (): void => { if (timer) { clearInterval(timer); timer = null } }+ const now = opts.now ?? Date.now+ const stop = (): void => { if (timer) { clearTimeout(timer); timer = null } }+ const schedule = (): void => {+ if (done) return+ stop()+ timer = setTimeout(() => void tick(), msUntilSlot(now(), opts.slotSecond, opts.intervalMs))+ timer.unref?.()+ }const tick = async (): Promise<void> => {- if (checking || done) return+ if (done) return+ // Booked before the work, from the clock: the next tick is on the next slot whatever this one+ // costs; a tick that stages calls `stop()` below and cancels it. Booked even when this slot is+ // skipped because the previous check is still running (a download on a slow link can outlast a+ // minute) — otherwise the chain would end there and the daemon would never look again.+ schedule()+ if (checking) returnchecking = truetry {const entry = await fetchManifest(opts.url, opts.key)@@ -221,7 +258,6 @@ export function startSelfUpdater(opts: {}}- timer = setInterval(() => void tick(), opts.intervalMs)- void tick() // also check immediately on start+ schedule()return { stop }}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex e87ad6f2d..84c85056e 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -2223,6 +2223,7 @@ class AppNotifier extends ChangeNotifier {/// a not-ready daemon is what lets a boot that landed mid-update recover without a click.void _startDaemonSupervision(LocalCliDiscovery discovery) {_daemonSupervisionTimer ??= discovery.startSupervising(+ spawnAllowedAt: inSpawnSlot,stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),onSnapshot: _updateLocalProjectSnapshot,diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex 988187963..30a0287a6 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -93,6 +93,14 @@ Future<void> runHarnessStart(HarnessCliRunner runner) async {Future<void> _defaultSpawnCommand() => runHarnessStart(HarnessCliRunner());+/// The wall-clock window in which the supervisor may spawn `harness start`: seconds :10–:20 of+/// every minute. The CLI's own updater ticks at :45 (`ADAPTER_UPDATE_SLOT_SEC` in the harness CLI's+/// `config/env.ts`), so a spawn and an update handoff — both of which take the daemon's spawn lock —+/// never land in the same second, and neither burns its lock wait on the other. The window is wide+/// enough that a 5s probe cadence always gets a tick inside it, and ends 25s before the update slot.+bool inSpawnSlot(DateTime now, {int second = 15, int window = 10}) =>+ now.second >= second - window ~/ 2 && now.second < second + window ~/ 2;+/// What one look at the daemon's control port found.////// THREE answers, not two, and the middle one is the point. A port that@@ -256,6 +264,10 @@ class LocalCliDiscovery {/// state a daemon sits in for the length of every self-update's backend handshake, and it is what/// this loop used to spawn into every few seconds.///+ /// [spawnAllowedAt] gates the spawn — not the probe — to a moment: production passes [inSpawnSlot]+ /// so the spawn keeps clear of the CLI's update slot. Outside the window a down daemon stays down+ /// for a few more ticks and is spawned on the first tick inside it.+ ////// Spawning waits for [spawnAfter] consecutive quiet ticks rather than one: a self-update leaves/// the port unowned for a second or two between the old daemon closing it and the new one binding,/// and a spawn into that gap is a wasted process (the CLI's own lock refuses it), not a fix.@@ -278,6 +290,7 @@ class LocalCliDiscovery {Duration initialBackoff = const Duration(seconds: 2),Duration maxBackoff = const Duration(seconds: 30),int spawnAfter = 2,+ bool Function(DateTime now)? spawnAllowedAt,Future<bool> Function()? stillSignedIn,void Function()? onSignedOut,void Function(LocalCliEndpoint endpoint)? onReady,@@ -329,6 +342,7 @@ class LocalCliDiscovery {quietTicks += 1;if (quietTicks < spawnAfter) return;if (DateTime.now().isBefore(nextSpawnAllowedAt)) return;+ if (!(spawnAllowedAt?.call(DateTime.now()) ?? true)) return;// A daemon that signed itself OUT — its machine was deleted from another machine, or its// session expired — deletes its session file and exits. Respawning it is the one failure// this loop cannot fix: every replacement starts without a session and exits again,diff --git a/desktop/test/daemon_readiness_test.dart b/desktop/test/daemon_readiness_test.dartindex 15bf92485..ff5e3348f 100644--- a/desktop/test/daemon_readiness_test.dart+++ b/desktop/test/daemon_readiness_test.dart@@ -37,6 +37,7 @@ class _ScriptedDiscovery extends LocalCliDiscovery {Duration initialBackoff = const Duration(seconds: 2),Duration maxBackoff = const Duration(seconds: 30),int spawnAfter = 2,+ bool Function(DateTime now)? spawnAllowedAt,Future<bool> Function()? stillSignedIn,void Function()? onSignedOut,void Function(LocalCliEndpoint endpoint)? onReady,diff --git a/desktop/test/local_cli_discovery_test.dart b/desktop/test/local_cli_discovery_test.dartindex 59824a4be..44ef43b6d 100644--- a/desktop/test/local_cli_discovery_test.dart+++ b/desktop/test/local_cli_discovery_test.dart@@ -478,6 +478,53 @@ void main() {await runHarnessStart(fine);});+ test('inSpawnSlot is :10–:20 of every minute, clear of the CLI update slot at :45', () {+ DateTime at(int second) => DateTime(2026, 9, 15, 10, 0, second);+ expect(inSpawnSlot(at(9)), isFalse);+ expect(inSpawnSlot(at(10)), isTrue);+ expect(inSpawnSlot(at(15)), isTrue);+ expect(inSpawnSlot(at(19)), isTrue);+ expect(inSpawnSlot(at(20)), isFalse);+ expect(inSpawnSlot(at(45)), isFalse);+ expect(inSpawnSlot(at(0), second: 5, window: 10), isTrue);+ });++ test('startSupervising holds a spawn outside the slot and takes it on the first tick inside', () async {+ const computerId = '0123456789abcdef0123456789abcdef';+ final identityFile = File('${scratch.path}/computer-id')+ ..writeAsStringSync(computerId);+ final port = await freePort();+ var spawnCount = 0;+ var slotOpen = false;+ final discovery = discoveryFor(+ port,+ identityFile,+ spawnCommand: () async {+ spawnCount++;+ server = await serveStatus(port, () => readyStatus(computerId));+ },+ );++ final timer = discovery.startSupervising(+ checkInterval: const Duration(milliseconds: 20),+ graceStep: const Duration(milliseconds: 10),+ graceWindow: const Duration(milliseconds: 100),+ initialBackoff: const Duration(milliseconds: 200),+ maxBackoff: const Duration(milliseconds: 200),+ spawnAllowedAt: (_) => slotOpen,+ );+ addTearDown(timer.cancel);++ // Down for many ticks, but the slot is shut: nothing is spawned, and nothing is backed off+ // either — the moment the slot opens the spawn is immediate.+ await Future.delayed(const Duration(milliseconds: 200));+ expect(spawnCount, 0);+ slotOpen = true;+ await Future.delayed(const Duration(milliseconds: 60));+ expect(spawnCount, 1);+ expect(server, isNotNull);+ });+test('startSupervising spawns harness start while down, and stops once discovery succeeds', () async {const computerId = '0123456789abcdef0123456789abcdef';final identityFile = File('${scratch.path}/computer-id')