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
fix(cli): keep hn current through automatic updates (#483)
Dee0f6fd3dd49b4
diff --git a/cli/RELEASE.md b/cli/RELEASE.mdindex 10b9624a8..03986287e 100644--- a/cli/RELEASE.md+++ b/cli/RELEASE.md@@ -127,6 +127,21 @@ The bucket must be public-read — that is bucket policy, not something the scriolder code — never by deleting the new one, which just leaves every daemon pointed at a 404. Disableself-update on one machine with `ADAPTER_UPDATE_DISABLE=true`.+## hn updates++The installed daemon checks the separate `harness/tui/metadata.json` manifest on startup and+on the same update schedule. An installed hn moves only to a newer published version, after+checksum, size and executable-version checks. Replacing the binary is atomic; open clients+keep running and the next launch uses the update. Failures retry without blocking CLI updates.+`harness update` also checks hn even if the CLI is already current.++An hn release still uses `release-tui.yml`; publishing a CLI does not rebuild or republish hn.+The CLI updater discovers whichever hn release is latest, so an hn-only release reaches+existing installations too. `ADAPTER_UPDATE_DISABLE=true` covers both automatic updaters.+Checkout/local CLI builds, `HARNESS_TUI_BIN` overrides, symlinked hn binaries and hn development+version labels are left alone. A missing hn is installed on first use or by the installer.+`harness tui --install` remains the explicit reinstall command.+## Rolling out safelyPublish to a scratch manifest before touching the real one, then point a local build at it:diff --git a/cli/scripts/test-hn-upgrade.mjs b/cli/scripts/test-hn-upgrade.mjsindex fd0a20269..95e19d516 100644--- a/cli/scripts/test-hn-upgrade.mjs+++ b/cli/scripts/test-hn-upgrade.mjs@@ -43,6 +43,9 @@ const env = {const options = { env, cwd: root, timeout: 20_000, encoding: 'utf8' }const server = createServer()let version+let hnVersion = '0.1.2'+let hnBadChecksum = false+const hnBytes = () => Buffer.from(`#!/bin/sh\nprintf 'hn ${hnVersion} (tmux 3.5a)\\n'\n`)const requests = []server.on('request', (request, response) => {requests.push(request.url)@@ -52,7 +55,13 @@ server.on('request', (request, response) => {cli: { url: `${base}/cli.js`, sha256: sha(bytes), size: bytes.length },notify: { url: `${base}/notify.mjs`, sha256: sha(notify), size: notify.length },} }))- } else if (request.url === '/cli.js') response.end(bytes)+ } else if (request.url === '/hn-metadata.json') {+ const nativeBytes = hnBytes()+ response.end(JSON.stringify({ version: hnVersion, builds: {+ [`${process.platform}-${process.arch}`]: { url: `${base}/harness-tui`, sha256: hnBadChecksum ? 'a'.repeat(64) : sha(nativeBytes), size: nativeBytes.length },+ } }))+ } else if (request.url === '/harness-tui') response.end(hnBytes())+ else if (request.url === '/cli.js') response.end(bytes)else if (request.url === '/notify.mjs') response.end(notify)else { response.statusCode = 404; response.end() }})@@ -119,7 +128,46 @@ try {assert.match(output, /^hn \d+\.\d+\.\d+ \(tmux /)console.log(`PASS repaired hn launcher runs the frozen native release: ${output}`)}- assert(requests.every(url => ['/metadata.json', '/cli.js', '/notify.mjs'].includes(url)), JSON.stringify(requests))+ rmSync(hn)+ await run(harness, ['version'], options)++ // An existing hn used to stay old forever when the CLI said it was already current.+ const managed = join(home, '.harness', 'bin', 'harness-tui')+ mkdirSync(dirname(managed), { recursive: true })+ const managedEnv = { ...env, HARNESS_TUI_MANIFEST_URL: `${base}/hn-metadata.json` }+ delete managedEnv.HARNESS_TUI_BIN+ const managedOptions = { ...options, env: managedEnv }+ const oldHn = Buffer.from("#!/bin/sh\nprintf 'hn 0.1.1 (tmux 3.5a)\\n'\n")+ writeFileSync(managed, oldHn, { mode: 0o755 })+ const hnUpdate = await run(harness, ['update'], managedOptions)+ assert(hnUpdate.stdout.includes(`Already on the latest version (v${version})`), hnUpdate.stdout)+ assert(hnUpdate.stdout.includes('Installed hn 0.1.2'), hnUpdate.stdout)+ assert.equal(sha(readFileSync(managed)), sha(hnBytes()))+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)+ const downloaded = requests.filter(url => url === '/harness-tui').length+ await run(harness, ['update'], managedOptions)+ assert.equal(requests.filter(url => url === '/harness-tui').length, downloaded)+ console.log('PASS an already-current CLI upgrades hn; the next hn launch uses it without repeated downloads')++ hnVersion = '0.1.3'+ hnBadChecksum = true+ const failedHn = await run(harness, ['update'], managedOptions)+ assert(failedHn.stderr.includes('hn update failed'), failedHn.stderr)+ assert(failedHn.stdout.includes('Already on the latest version'), failedHn.stdout)+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)+ hnBadChecksum = false+ await run(harness, ['update'], managedOptions)+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.3 /)+ console.log('PASS hn checksum failure preserves the installation and does not block CLI updates; retry succeeds')++ hnVersion = '0.1.2'+ await run(harness, ['update'], managedOptions)+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.3 /)+ rmSync(managed)+ await run(harness, ['tui', '--install'], managedOptions)+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)+ console.log('PASS no automatic downgrade; explicit first install still works')+ assert(requests.every(url => ['/metadata.json', '/cli.js', '/notify.mjs', '/hn-metadata.json', '/harness-tui'].includes(url)), JSON.stringify(requests))} finally {server.closeAllConnections()if (server.listening) await new Promise(done => server.close(done))diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 7c46fe513..32e52788f 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -234,6 +234,8 @@ import {type Poller, type UpdateEntry,} from './lib/selfUpdate.js'import { managedNodePath } from './lib/nodeRuntime.js'+import { updateTui } from './tui/install.js'+import { startTuiUpdater } from './tui/update.js'import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'import { readdir, stat } from 'fs/promises'import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'@@ -535,6 +537,7 @@ function spawnDaemonChild(extraEnv: Record<string, string>): ReturnType<typeof s*/const daemonBoot: {updater: Poller | null+ tuiUpdater: Poller | null/** The hook server, once bound — the only thing a mid-boot handoff has to release. */hookServer: Server | null/** Its Unix-socket twin (lib/localSocket.ts), when one could be opened. Read by `/api/status`. */@@ -545,7 +548,7 @@ const daemonBoot: {safeMode: string | nullhandingOff: booleanapplyStagedUpdate: (version: string) => void | Promise<void>-} = { updater: null, hookServer: null, localSocket: null, markNotReady: null, safeMode: null, handingOff: false, applyStagedUpdate: bootHandoff }+} = { updater: null, tuiUpdater: null, hookServer: null, localSocket: null, markNotReady: null, safeMode: null, handingOff: false, applyStagedUpdate: bootHandoff }/*** Hand the machine to a newer build without finishing start-up.@@ -563,6 +566,7 @@ const daemonBoot: {function bootHandoff(version: string): void {if (daemonBoot.handingOff) returndaemonBoot.handingOff = true+ daemonBoot.tuiUpdater?.stop()runBootHandoff(VERSION, version, {// The hook port has no fallback: a successor that cannot bind it is a daemon that does not come up.closeServer: () => {@@ -1244,6 +1248,16 @@ async function downloadCanaryStage(entry: UpdateEntry, dir: string, log: (m: strreturn true}+/** An explicit hn update manages only the installed bundle, never a checkout or a canary. */+function isInstalledCli(): boolean {+ const installedCli = join(env.ADAPTER_CLI_DIR, 'cli.js')+ try {+ const running = statSync(SCRIPT_PATH)+ const installed = statSync(installedCli)+ return running.dev === installed.dev && running.ino === installed.ino+ } catch { return SCRIPT_PATH === installedCli }+}+/** `harness update` — force the self-update NOW instead of waiting for the daemon's* background poll. Checks the manifest; if a newer build exists it stops any running daemon first (so* its poller can't race our staging), swaps in the new bytes, then relaunches on them. No-op on a@@ -1265,6 +1279,12 @@ async function updateCommand(force: boolean): Promise<void> {process.exit(0)}console.log(`▸ Checking for updates… (current v${VERSION})`)+ // hn has its own release cadence. An already-current CLI must still refresh an installed hn;+ // a failed optional download must not stop the CLI from updating.+ if (isInstalledCli()) {+ try { await updateTui((line) => console.log(line)) }+ catch (error) { console.warn(` hn update failed; continuing with the CLI update: ${error instanceof Error ? error.message : error}`) }+ }let entry: UpdateEntry | null = nulltry { entry = await fetchManifest(env.ADAPTER_UPDATE_URL, env.ADAPTER_UPDATE_KEY) }catch (e) { console.error(`✗ Could not reach the update manifest: ${e instanceof Error ? e.message : e}`); process.exit(1) }@@ -1493,6 +1513,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.log(`[update] self-update off · running a dev/repo build (v${VERSION}), not the installed copy`)}+ // Keep the CLI's recovery updater armed first. hn is an independent, optional download.+ daemonBoot.tuiUpdater = startTuiUpdater({+ currentVersion: VERSION,+ isInstalledCopy,+ disabled: env.ADAPTER_UPDATE_DISABLE,+ intervalMs: env.ADAPTER_UPDATE_CHECK_MS,+ slotSecond: env.ADAPTER_UPDATE_SLOT_SEC,+ })+const savedApis = new ApiConnections(env.ADAPTER_DATA_DIR)// Before any agent is probed: one already running on a saved API's model reports that model.rememberSavedApis(savedApis)@@ -6543,6 +6572,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.log(`[update] applying ${VERSION} → ${newVersion} — restarting daemon`)registry.flush()daemonBoot.updater?.stop()+ daemonBoot.tuiUpdater?.stop()agentReconciler.stop()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)@@ -6653,6 +6683,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {void cableRef?.stop()deviceLinkRef?.stop()daemonBoot.updater?.stop()+ daemonBoot.tuiUpdater?.stop()agentReconciler.stop()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex cf60a56b5..f16df55fb 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -68,7 +68,7 @@ function callArgument(source: string, call: string): { body: string; at: number}/** Every call whose dependencies run DURING start-up, before `runForeground` has finished its body. */-const STARTUP_CALLS = ['await repairClaudeCwd({', 'await restoreAgents({', 'startSelfUpdater({']+const STARTUP_CALLS = ['await repairClaudeCwd({', 'await restoreAgents({', 'startSelfUpdater({', 'startTuiUpdater({']/** What the prologue is allowed to do before the updater is running: nothing that can throw. */const PROLOGUE_CALLS = new Set([@@ -96,6 +96,7 @@ describe('cli.ts start-up order', () => {const updater = source.indexOf('startSelfUpdater({')expect(updater, 'cli.ts still starts the self-updater').toBeGreaterThan(-1)for (const risky of [+ 'startTuiUpdater(', // optional hn download must never precede CLI recovery'requireTmuxAvailable(', // throws outright when tmux is missing'await startHookServer(', // EADDRINUSE on a fixed port with no fallback'installSessionHooks(', // 13 vendor settings files, any of which can be unreadablediff --git a/cli/src/tui/index.spec.ts b/cli/src/tui/index.spec.tsindex cf6982713..a710b9c87 100644--- a/cli/src/tui/index.spec.ts+++ b/cli/src/tui/index.spec.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { findTuiBinary, opensClient, platformKey, tuiCommand } from './index.js'// No test may start a real binary, daemon or login flow, or make a network request.-vi.mock('node:child_process', () => ({ spawnSync: vi.fn() }))+vi.mock('node:child_process', async (original) => ({ ...await original<typeof import('node:child_process')>(), spawnSync: vi.fn() }))const ok = { status: 0, signal: null, pid: 0, stdout: '', stderr: '', output: [] }describe('harness tui launcher', () => {diff --git a/cli/src/tui/index.ts b/cli/src/tui/index.tsindex 0e48dcdbd..99252a98c 100644--- a/cli/src/tui/index.ts+++ b/cli/src/tui/index.ts@@ -11,28 +11,17 @@* 4. `harness-tui` on PATH*/import { spawnSync } from 'node:child_process'-import { createHash } from 'node:crypto'-import { chmodSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'-import { homedir } from 'node:os'-import { dirname, join, resolve } from 'node:path'+import { existsSync } from 'node:fs'+import { dirname, resolve } from 'node:path'import { fileURLToPath } from 'node:url'-export const TUI_MANIFEST_URL = process.env.HARNESS_TUI_MANIFEST_URL- || 'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/tui/metadata.json'--const installed = (): string => join(homedir(), '.harness', 'bin', 'harness-tui')--/** `darwin-arm64`, `linux-x64`, … — the key a release publishes each build under. */-export function platformKey(platform = process.platform, arch = process.arch): string | null {- const os = platform === 'darwin' ? 'darwin' : platform === 'linux' ? 'linux' : null- const cpu = arch === 'arm64' ? 'arm64' : arch === 'x64' ? 'x64' : null- return os && cpu ? `${os}-${cpu}` : null-}+import { installedTuiPath, installTui } from './install.js'+export { installTui, platformKey, TUI_MANIFEST_URL } from './install.js'export function findTuiBinary(): string | null {const fromEnv = process.env.HARNESS_TUI_BINif (fromEnv && existsSync(fromEnv)) return fromEnv- if (existsSync(installed())) return installed()+ if (existsSync(installedTuiPath())) return installedTuiPath()try {const here = dirname(fileURLToPath(import.meta.url))for (const up of ['../../../tui', '../../tui', '../tui']) {@@ -47,31 +36,6 @@ export function findTuiBinary(): string | null {return which.status === 0 && onPath ? onPath : null}-/** Download the published build for this platform, verify its sha256, install it. */-export async function installTui(log: (line: string) => void): Promise<string> {- const key = platformKey()- if (!key) throw new Error(`No harness tui build for ${process.platform}/${process.arch}.`)- const manifest = await fetch(TUI_MANIFEST_URL, { signal: AbortSignal.timeout(20_000) })- if (!manifest.ok) throw new Error(`The TUI is not published yet (${manifest.status}). Build it: cd tui && cargo build --release`)- const meta = await manifest.json() as { version?: string; builds?: Record<string, { url?: string; sha256?: string }> }- const build = meta.builds?.[key]- if (!build?.url || !build.sha256) throw new Error(`No harness tui build for ${key} in the manifest.`)- log(` Downloading harness-tui ${meta.version ?? ''} for ${key}…`)- const response = await fetch(build.url, { signal: AbortSignal.timeout(120_000) })- if (!response.ok) throw new Error(`Download failed: ${response.status}`)- const bytes = Buffer.from(await response.arrayBuffer())- const digest = createHash('sha256').update(bytes).digest('hex')- if (digest !== build.sha256.toLowerCase()) throw new Error('The download does not match its published checksum; nothing was installed.')- const target = installed()- mkdirSync(dirname(target), { recursive: true })- const temp = `${target}.${process.pid}.tmp`- writeFileSync(temp, bytes, { mode: 0o755 })- chmodSync(temp, 0o755)- renameSync(temp, target)- log(` ✓ Installed ${target}`)- return target-}-/** Read only the global flags needed for bootstrap; hn validates the full command line. */function clientPort(argv: string[], fallback: number): number | null {let port = fallbackdiff --git a/cli/src/tui/install.spec.ts b/cli/src/tui/install.spec.tsnew file mode 100644index 000000000..20ed33b36--- /dev/null+++ b/cli/src/tui/install.spec.ts@@ -0,0 +1,183 @@+import { createHash } from 'node:crypto'+import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { installedTuiPath, installTui, platformKey, updateTui } from './install.js'++// Only disposable executables are run, with --version. Downloads never reach the network.+const binary = (version: string): Buffer => Buffer.from(`#!/bin/sh\nprintf 'hn ${version} (tmux 3.5a)\\n'\n`)+const digest = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')+let home: string+let target: string+let downloads: string[]++function installed(version = '0.1.1'): Buffer {+ const bytes = binary(version)+ mkdirSync(dirname(target), { recursive: true })+ writeFileSync(target, bytes, { mode: 0o755 })+ return bytes+}++function published(version = '0.1.2', bytes = binary(version), overrides: Record<string, unknown> = {}): void {+ const meta = { version, builds: { [platformKey()!]: { url: 'https://example.test/hn', sha256: digest(bytes), size: bytes.length, ...overrides } } }+ vi.stubGlobal('fetch', vi.fn(async (url: string) => {+ downloads.push(url)+ return url === 'https://example.test/hn'+ ? new Response(new Uint8Array(bytes))+ : Response.json(meta)+ }))+}++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'hn-update-test-'))+ vi.stubEnv('HOME', home)+ vi.stubEnv('HARNESS_TUI_BIN', undefined)+ target = installedTuiPath()+ downloads = []+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('unexpected network request')))+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+ rmSync(home, { recursive: true, force: true })+})++describe('managed hn updates', () => {+ it('atomically upgrades an old installation while an open descriptor keeps the old bytes', async () => {+ const old = installed()+ const fd = openSync(target, 'r')+ const oldInode = fstatSync(fd).ino+ published()+ const log = vi.fn()+ try {+ expect(await updateTui(log)).toBe(true)+ expect(readFileSync(target)).toEqual(binary('0.1.2'))+ expect(readFileSync(fd)).toEqual(old)+ expect(lstatSync(target).ino).not.toBe(oldInode)+ expect(lstatSync(target).mode & 0o777).toBe(0o755)+ expect(readdirSync(dirname(target))).toEqual(['harness-tui'])+ expect(log).toHaveBeenLastCalledWith(expect.stringContaining('reopen hn'))+ } finally { closeSync(fd) }+ })++ it.each(['0.1.2', '0.1.3', '0.10.0'])('does not download or downgrade a current/newer hn %s', async (version) => {+ const old = installed(version)+ published()+ expect(await updateTui()).toBe(false)+ expect(downloads).toHaveLength(1)+ expect(readFileSync(target)).toEqual(old)+ })++ it('does not install an unused hn or replace an explicit override', async () => {+ expect(await updateTui()).toBe(false)+ installed()+ vi.stubEnv('HARNESS_TUI_BIN', join(home, 'custom-hn'))+ expect(await updateTui()).toBe(false)+ expect(fetch).not.toHaveBeenCalled()+ })++ it('leaves symlinked binaries and development versions alone', async () => {+ mkdirSync(dirname(target), { recursive: true })+ const custom = join(home, 'custom')+ writeFileSync(custom, binary('0.1.1'), { mode: 0o755 })+ symlinkSync(custom, target)+ expect(await updateTui()).toBe(false)+ expect(lstatSync(target).isSymbolicLink()).toBe(true)+ rmSync(target)+ installed('0.1.1-dev.local')+ expect(await updateTui()).toBe(false)+ expect(fetch).not.toHaveBeenCalled()+ })++ it.each([+ ['checksum', { sha256: 'a'.repeat(64) }],+ ['size', { size: 9999 }],+ ['invalid checksum', { sha256: 'broken' }],+ ['invalid URL', { url: 'file:///tmp/hn' }],+ ['plaintext URL', { url: 'http://example.test/hn' }],+ ])('keeps the old binary on a %s failure', async (_, overrides) => {+ const old = installed()+ published('0.1.2', binary('0.1.2'), overrides)+ await expect(updateTui()).rejects.toThrow()+ expect(readFileSync(target)).toEqual(old)+ expect(readdirSync(dirname(target))).toEqual(['harness-tui'])+ })++ it.each([+ binary('0.1.9'),+ Buffer.from('#!/bin/sh\nexit 1\n'),+ Buffer.from('#!/bin/sh\nprintf "not hn\\n"\n'),+ ])('rejects a checksum-valid executable that fails its version check', async (bytes) => {+ const old = installed()+ published('0.1.2', bytes)+ await expect(updateTui()).rejects.toThrow()+ expect(readFileSync(target)).toEqual(old)+ expect(readdirSync(dirname(target))).toEqual(['harness-tui'])+ })++ it('recovers on the next check after an offline manifest or failed download', async () => {+ const old = installed()+ await expect(updateTui()).rejects.toThrow('unexpected network')+ expect(readFileSync(target)).toEqual(old)+ published()+ vi.mocked(fetch).mockResolvedValueOnce(new Response('', { status: 503 }))+ await expect(updateTui()).rejects.toThrow('503')+ expect(await updateTui()).toBe(true)+ })++ it('does not replace a newer installation that arrives during the download', async () => {+ installed()+ published()+ const served = vi.mocked(fetch).getMockImplementation()!+ vi.mocked(fetch).mockImplementation(async (...args) => {+ if (args[0] === 'https://example.test/hn') installed('0.1.3')+ return served(...args)+ })+ expect(await updateTui()).toBe(false)+ expect(readFileSync(target)).toEqual(binary('0.1.3'))+ expect(readdirSync(dirname(target))).toEqual(['harness-tui'])+ })++ it('honors an override added while downloading', async () => {+ const old = installed()+ published()+ const served = vi.mocked(fetch).getMockImplementation()!+ vi.mocked(fetch).mockImplementation(async (...args) => {+ if (args[0] === 'https://example.test/hn') vi.stubEnv('HARNESS_TUI_BIN', '/custom/hn')+ return served(...args)+ })+ expect(await updateTui()).toBe(false)+ expect(readFileSync(target)).toEqual(old)+ })++ it('serializes overlapping checks without downloading the same build twice', async () => {+ installed()+ published()+ expect(await Promise.all([updateTui(), updateTui(), updateTui()])).toEqual([true, false, false])+ expect(downloads.filter(url => url === 'https://example.test/hn')).toHaveLength(1)+ })++ it('cancels an update before it can replace the binary', async () => {+ const old = installed()+ published()+ const controller = new AbortController()+ const served = vi.mocked(fetch).getMockImplementation()!+ vi.mocked(fetch).mockImplementation(async (...args) => {+ if (args[0] === 'https://example.test/hn') controller.abort()+ return served(...args)+ })+ await expect(updateTui(undefined, controller.signal)).rejects.toThrow()+ expect(readFileSync(target)).toEqual(old)+ })++ it('still installs on first use and explicitly repairs a broken binary', async () => {+ published()+ expect(await installTui(() => {})).toBe(target)+ writeFileSync(target, 'broken')+ expect(await installTui(() => {})).toBe(target)+ expect(readFileSync(target)).toEqual(binary('0.1.2'))+ expect(existsSync(target)).toBe(true)+ })+})diff --git a/cli/src/tui/install.ts b/cli/src/tui/install.tsnew file mode 100644index 000000000..da1fbdaf3--- /dev/null+++ b/cli/src/tui/install.ts@@ -0,0 +1,135 @@+/** The managed hn binary. Replace its pathname atomically; running clients keep their old inode. */+import { execFile } from 'node:child_process'+import { createHash } from 'node:crypto'+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { dirname, join } from 'node:path'+import { promisify } from 'node:util'+import { withSpawnLock } from '../lib/daemonSpawnLock.js'+import { semverGt } from '../lib/selfUpdate.js'++export const TUI_MANIFEST_URL = process.env.HARNESS_TUI_MANIFEST_URL+ || 'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/tui/metadata.json'+export const installedTuiPath = (): string => join(homedir(), '.harness', 'bin', 'harness-tui')+const run = promisify(execFile)+const releaseVersion = /^\d+\.\d+\.\d+$/+type Log = (line: string) => void+type Release = { version: string; url: string; sha256: string; size?: number }++/** `darwin-arm64`, `linux-x64`, … — the key a release publishes each build under. */+export function platformKey(platform = process.platform, arch = process.arch): string | null {+ const os = platform === 'darwin' ? 'darwin' : platform === 'linux' ? 'linux' : null+ const cpu = arch === 'arm64' ? 'arm64' : arch === 'x64' ? 'x64' : null+ return os && cpu ? `${os}-${cpu}` : null+}++async function binaryVersion(binary: string, signal?: AbortSignal): Promise<string | null> {+ const result = await run(binary, ['--version'], { timeout: 5_000, maxBuffer: 4096, signal, env: { ...process.env, HN_AS_TMUX: '0' } })+ // A prerelease, development label or unrelated program is not a managed release.+ return /^hn (\d+\.\d+\.\d+)(?: \(tmux [^\r\n]+\))?$/.exec(result.stdout.trim())?.[1] ?? null+}++async function managedVersion(signal?: AbortSignal): Promise<string | null> {+ if (process.env.HARNESS_TUI_BIN) return null+ try {+ // Never replace someone's symlink or install a binary they haven't used yet.+ if (!lstatSync(installedTuiPath()).isFile()) return null+ return await binaryVersion(installedTuiPath(), signal)+ } catch (error) {+ signal?.throwIfAborted()+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error+ }+}++function downloadUrl(value: unknown): value is string {+ if (typeof value !== 'string') return false+ try {+ const url = new URL(value)+ return url.protocol === 'https:' || (url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))+ } catch { return false }+}++async function publishedRelease(key: string, signal?: AbortSignal): Promise<Release> {+ const response = await fetch(TUI_MANIFEST_URL, { signal: timeoutSignal(20_000, signal) })+ if (!response.ok) throw new Error(`Could not fetch the hn release manifest (${response.status}).`)+ const meta = await response.json() as { version?: unknown; builds?: Record<string, Partial<Release>> } | null+ const build = meta?.builds?.[key]+ if (typeof meta?.version !== 'string' || !releaseVersion.test(meta.version)+ || !downloadUrl(build?.url) || typeof build?.sha256 !== 'string' || !/^[a-f\d]{64}$/i.test(build.sha256)+ || (build.size !== undefined && (!Number.isSafeInteger(build.size) || build.size <= 0))) {+ throw new Error(`No valid hn release for ${key} in the manifest.`)+ }+ return { version: meta.version, url: build.url, sha256: build.sha256, size: build.size }+}++function timeoutSignal(ms: number, signal?: AbortSignal): AbortSignal {+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms)+}++// Serialize this process too: the shared daemon spawn lock is intentionally re-entrant. Other CLI+// processes take that lock only for the final version check and rename, never for the download.+let pending: Promise<unknown> = Promise.resolve()+function serialized<T>(fn: () => Promise<T>): Promise<T> {+ const next = pending.then(fn, fn)+ pending = next.catch(() => {})+ return next+}++async function replaceTui(force: boolean, log: Log, signal?: AbortSignal): Promise<boolean> {+ signal?.throwIfAborted()+ const key = platformKey()+ if (!key) {+ if (force) throw new Error(`No harness tui build for ${process.platform}/${process.arch}.`)+ return false+ }+ const current = force ? null : await managedVersion(signal)+ if (!force && current === null) return false+ const release = await publishedRelease(key, signal)+ if (current && !semverGt(release.version, current)) return false+ log(` Downloading hn ${release.version} for ${key}…`)+ const response = await fetch(release.url, { signal: timeoutSignal(120_000, signal) })+ if (!response.ok) throw new Error(`hn download failed (${response.status}).`)+ const bytes = Buffer.from(await response.arrayBuffer())+ if (createHash('sha256').update(bytes).digest('hex') !== release.sha256.toLowerCase()+ || (release.size !== undefined && bytes.length !== release.size)) {+ throw new Error('The hn download does not match its published checksum or size; nothing was installed.')+ }+ signal?.throwIfAborted()+ const target = installedTuiPath()+ mkdirSync(dirname(target), { recursive: true })+ const staging = mkdtempSync(join(dirname(target), '.hn-update-'))+ const binary = join(staging, 'harness-tui')+ try {+ writeFileSync(binary, bytes, { mode: 0o755 })+ chmodSync(binary, 0o755)+ if (await binaryVersion(binary, signal) !== release.version) {+ throw new Error('The hn download failed its version check; nothing was installed.')+ }+ return await withSpawnLock('update', async () => {+ // A newer release or an explicit override may have landed while downloading. Check again+ // under the same lock used by `harness update` and `harness tui --install`.+ if (!force) {+ const latest = await managedVersion(signal)+ if (latest === null || !semverGt(release.version, latest)) return false+ }+ signal?.throwIfAborted()+ renameSync(binary, target)+ log(` ✓ Installed hn ${release.version}; reopen hn to use it.`)+ return true+ }, force ? {} : { waitMs: 0 })+ } finally {+ rmSync(staging, { recursive: true, force: true })+ }+}++/** Explicit install (also the first launch): allowed to replace an older, newer or broken binary. */+export async function installTui(log: Log): Promise<string> {+ await serialized(() => replaceTui(true, log))+ return installedTuiPath()+}++/** Upgrade an existing managed release only. No downgrades, overrides or process restarts. */+export function updateTui(log: Log = () => {}, signal?: AbortSignal): Promise<boolean> {+ return serialized(() => replaceTui(false, log, signal))+}diff --git a/cli/src/tui/update.integration.spec.ts b/cli/src/tui/update.integration.spec.tsnew file mode 100644index 000000000..a55a9d1db--- /dev/null+++ b/cli/src/tui/update.integration.spec.ts@@ -0,0 +1,63 @@+import { createHash } from 'node:crypto'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:http'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import type { Poller } from '../lib/selfUpdate.js'++let updater: Poller | undefined+const server = createServer()+let home = ''+afterEach(async () => {+ updater?.stop()+ server.closeAllConnections()+ if (server.listening) await new Promise<void>(done => server.close(() => done()))+ vi.unstubAllEnvs()+ if (home) rmSync(home, { recursive: true, force: true })+})++it('follows an hn-only release over HTTP, preserves the old binary on failure and retries', async () => {+ // Real HTTP, executable-version checks and disk replacement; no real daemon, tmux or user home.+ home = mkdtempSync(join(tmpdir(), 'hn-auto-http-'))+ const target = join(home, '.harness', 'bin', 'harness-tui')+ const binary = (version: string): Buffer => Buffer.from(`#!/bin/sh\nprintf 'hn ${version} (tmux 3.5a)\\n'\n`)+ mkdirSync(dirname(target), { recursive: true })+ writeFileSync(target, binary('0.1.1'), { mode: 0o755 })+ let version = '0.1.2'+ let corrupt = false+ let downloads = 0+ let base = ''+ server.on('request', (req, res) => {+ const bytes = binary(version)+ if (req.url === '/metadata.json') {+ res.end(JSON.stringify({ version, builds: {+ [`${process.platform}-${process.arch}`]: { url: `${base}/hn`, sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },+ } }))+ } else if (req.url === '/hn') {+ downloads+++ res.end(corrupt ? Buffer.from('incomplete') : bytes)+ } else { res.statusCode = 404; res.end() }+ })+ await new Promise<void>(done => server.listen(0, '127.0.0.1', done))+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('fixture did not listen')+ base = `http://127.0.0.1:${address.port}`+ vi.stubEnv('HOME', home)+ vi.stubEnv('HARNESS_TUI_BIN', undefined)+ vi.stubEnv('HARNESS_TUI_MANIFEST_URL', `${base}/metadata.json`)+ vi.resetModules()+ const { startTuiUpdater } = await import('./update.js')+ const log = vi.fn()+ updater = startTuiUpdater({ currentVersion: '0.3.28', isInstalledCopy: true, disabled: false, intervalMs: 100, log })+ await vi.waitFor(() => expect(readFileSync(target)).toEqual(binary('0.1.2')), { timeout: 5000 })+ expect(downloads).toBe(1)+ // Keep the CLI at exactly the same version and publish only hn.+ version = '0.1.3'+ corrupt = true+ await vi.waitFor(() => expect(log).toHaveBeenCalledWith(expect.stringContaining('will retry')), { timeout: 5000 })+ expect(readFileSync(target)).toEqual(binary('0.1.2'))+ corrupt = false+ await vi.waitFor(() => expect(readFileSync(target)).toEqual(binary('0.1.3')), { timeout: 5000 })+ updater.stop()+}, 15_000)diff --git a/cli/src/tui/update.spec.ts b/cli/src/tui/update.spec.tsnew file mode 100644index 000000000..bf13d98ca--- /dev/null+++ b/cli/src/tui/update.spec.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { updateTui } from './install.js'+import { startTuiUpdater } from './update.js'++vi.mock('./install.js', () => ({ updateTui: vi.fn() }))+const options = { currentVersion: '0.3.28', isInstalledCopy: true, disabled: false, intervalMs: 60_000, slotSecond: 45 }++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-09-30T01:00:00Z'))+ vi.mocked(updateTui).mockReset().mockResolvedValue(false)+})+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers() })++describe('hn automatic update schedule', () => {+ it('checks immediately and keeps checking when the CLI version has not changed', async () => {+ const updater = startTuiUpdater(options)+ expect(updateTui).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(44_999)+ expect(updateTui).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(1)+ expect(updateTui).toHaveBeenCalledTimes(2)+ await vi.advanceTimersByTimeAsync(60_000)+ expect(updateTui).toHaveBeenCalledTimes(3)+ updater.stop()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(updateTui).toHaveBeenCalledTimes(3)+ })++ it.each([+ { disabled: true },+ { isInstalledCopy: false },+ { currentVersion: '0.3.28-dev.local' },+ { currentVersion: '0.0.0-dev' },+ ])('does not start for a disabled or development installation: %j', async (override) => {+ const updater = startTuiUpdater({ ...options, ...override })+ await vi.advanceTimersByTimeAsync(120_000)+ expect(updateTui).not.toHaveBeenCalled()+ updater.stop()+ })++ it('retries after failure without overlapping a slow download', async () => {+ const log = vi.fn()+ let finish!: () => void+ vi.mocked(updateTui).mockRejectedValueOnce(new Error('offline')).mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve(true) }))+ const updater = startTuiUpdater({ ...options, log })+ await vi.advanceTimersByTimeAsync(45_000)+ expect(log).toHaveBeenCalledWith(expect.stringContaining('offline'))+ expect(updateTui).toHaveBeenCalledTimes(2)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(updateTui).toHaveBeenCalledTimes(2)+ finish()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(updateTui).toHaveBeenCalledTimes(3)+ updater.stop()+ })++ it('aborts a pending download during shutdown without logging a failure', async () => {+ const log = vi.fn()+ let signal!: AbortSignal+ vi.mocked(updateTui).mockImplementation((_log, pendingSignal) => new Promise((_resolve, reject) => {+ signal = pendingSignal!+ signal.addEventListener('abort', () => reject(new Error('aborted')))+ }))+ const updater = startTuiUpdater({ ...options, log })+ updater.stop()+ expect(signal.aborted).toBe(true)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(updateTui).toHaveBeenCalledTimes(1)+ expect(log).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/tui/update.ts b/cli/src/tui/update.tsnew file mode 100644index 000000000..23554e3c0--- /dev/null+++ b/cli/src/tui/update.ts@@ -0,0 +1,35 @@+import { isLocalDevBuild, msUntilSlot, type Poller } from '../lib/selfUpdate.js'+import { updateTui } from './install.js'++/** hn follows the installed CLI's automatic-update policy, including after an hn-only release. */+export function startTuiUpdater(opts: {+ currentVersion: string+ isInstalledCopy: boolean+ disabled: boolean+ intervalMs: number+ slotSecond?: number+ log?: (line: string) => void+}): Poller {+ if (!opts.isInstalledCopy || opts.disabled || isLocalDevBuild(opts.currentVersion)) return { stop() {} }+ const log = opts.log ?? ((line: string) => console.log(`[hn-update] ${line.trim()}`))+ const controller = new AbortController()+ let timer: NodeJS.Timeout | undefined+ let checking = false+ const tick = async (): Promise<void> => {+ if (controller.signal.aborted) return+ timer = setTimeout(() => void tick(), msUntilSlot(Date.now(), opts.slotSecond, opts.intervalMs))+ timer.unref?.()+ if (checking) return+ checking = true+ try {+ await updateTui(log, controller.signal)+ } catch (error) {+ if (!controller.signal.aborted) log(`Check failed; will retry: ${error instanceof Error ? error.message : error}`)+ } finally {+ checking = false+ }+ }+ // Independent of the CLI download/handoff: an hn failure must never hold up a CLI fix.+ void tick()+ return { stop() { clearTimeout(timer); controller.abort() } }+}diff --git a/tui/README.md b/tui/README.mdindex dfc810df2..754bfbc9b 100644--- a/tui/README.md+++ b/tui/README.md@@ -8,6 +8,13 @@ curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash # installs harhn # or: harness tui```+The installed CLI keeps hn up to date automatically: it checks at daemon startup and on the+same schedule as CLI updates, including when only hn has a new release. Reopen hn to use the+new version; running clients and panes keep working. `harness update` also checks hn when+the CLI is already current. `ADAPTER_UPDATE_DISABLE=true` disables automatic updates for both;+local CLI builds and `HARNESS_TUI_BIN` overrides stay untouched. The first hn launch downloads+it if missing; `harness tui --install` explicitly reinstalls the latest published build.+hn follows tmux 3.5a's keys, commands, formats and `~/.tmux.conf`, with your harnesses onevery machine behind them. What tmux users have asked for over the years, and what hn doesabout it: [docs/tmux-improved.md](docs/tmux-improved.md).