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.

Repair legacy hn launchers through the managed updater (#500)

Dee5e2d026a935c
diff --git a/cli/RELEASE.md b/cli/RELEASE.md
index 03986287e..bbb99b46a 100644
--- a/cli/RELEASE.md
+++ b/cli/RELEASE.md
@@ -138,9 +138,17 @@ keep running and the next launch uses the update. Failures retry without blockin
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.
+Checkout/local CLI builds, `HARNESS_TUI_BIN` overrides, symlinked managed binaries and hn development
+version labels are left alone. A missing managed binary is repaired on the next update check when
+the managed `hn` launcher is present; otherwise first use or the installer downloads it.
+
+Older manual/development `hn` commands can bypass this managed binary. `harness update` diagnoses
+these installations, including a different `hn` earlier on PATH. `harness tui --install` or
+`harness update --force` verifies the latest download, backs up a recognized old Harness launcher
+under `~/.local/bin/.hn-backup-*/hn`, and replaces it with a launcher that follows `harness tui`.
+An unrelated command is preserved; use `harness tui` or correct PATH in that case. Explicit
+`HARNESS_TUI_BIN` overrides remain in effect until unset. The installer never writes through
+an existing `hn` symlink.
## Rolling out safely
diff --git a/cli/scripts/install.sh b/cli/scripts/install.sh
index adcaced06..2986b030c 100755
--- a/cli/scripts/install.sh
+++ b/cli/scripts/install.sh
@@ -695,13 +695,19 @@ const bin = path.join(os.homedir(), '.local', 'bin')
const shellQuote = value => "'" + value.replaceAll("'", "'\\''") + "'"
fs.writeFileSync(path.join(bin, 'harness'), '#!/bin/sh\nexec ' + shellQuote(NODE) + ' ' + shellQuote(path.join(dir, 'cli.js')) + ' "$@"\n', { mode: 0o755 })
console.log(' ✓ installed harness ' + entry.version + ' → ' + dir)
- // `hn` is `harness tui`: it signs in and starts the daemon the first time, then opens hn. An `hn`
- // that is someone else's (another program by that name) is left alone.
+ // Delegate through harness so runtime repairs and update pins apply to both commands.
+ // Preserve existing entries, including dangling development links. Never write through a link
+ // or infer ownership from `.harness` appearing somewhere in an executable's bytes.
const hn = path.join(bin, 'hn')
- let theirs = false
- try { theirs = !fs.readFileSync(hn, 'utf8').includes('.harness') } catch { /* none yet */ }
- if (theirs) console.log(' · ' + hn + ' is another program; run hn as: harness tui')
- else fs.writeFileSync(hn, '#!/bin/sh\nexec ' + shellQuote(NODE) + ' ' + shellQuote(path.join(dir, 'cli.js')) + ' tui "$@"\n', { mode: 0o755 })
+ const staged = fs.mkdtempSync(path.join(bin, '.hn-'))
+ try {
+ const launcher = path.join(staged, 'hn')
+ fs.writeFileSync(launcher, '#!/bin/sh\nexec ' + shellQuote(path.join(bin, 'harness')) + ' tui "$@"\n', { mode: 0o755 })
+ try { fs.linkSync(launcher, hn) } catch (error) {
+ if (error.code !== 'EEXIST') throw error
+ console.log(' · Kept existing ' + hn + '; use harness tui, or harness tui --install to migrate an old Harness build.')
+ }
+ } finally { fs.rmSync(staged, { recursive: true, force: true }) }
})().catch((err) => { console.error('✗ install failed: ' + err.message); process.exit(1) })
HARNESSJS
diff --git a/cli/scripts/test-hn-upgrade.mjs b/cli/scripts/test-hn-upgrade.mjs
index 95e19d516..2f3292b40 100644
--- a/cli/scripts/test-hn-upgrade.mjs
+++ b/cli/scripts/test-hn-upgrade.mjs
@@ -167,6 +167,67 @@ try {
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')
+
+ // A legacy development link bypassed the managed binary entirely. A normal update diagnoses it;
+ // explicit repair switches commands only after a verified download and keeps a usable backup.
+ const checkout = join(root, 'checkout', 'tui')
+ const legacy = join(checkout, 'target', 'hn-test', 'hn')
+ mkdirSync(dirname(legacy), { recursive: true })
+ writeFileSync(join(checkout, 'Cargo.toml'), '[package]\nname = "harness-tui"\n')
+ writeFileSync(legacy, oldHn, { mode: 0o755 })
+ for (const repair of [['tui', '--install'], ['update', '--force']]) {
+ rmSync(hn)
+ rmSync(managed)
+ symlinkSync(legacy, hn)
+ const bypass = await run(harness, ['update'], managedOptions)
+ assert(bypass.stdout.includes('does not receive automatic updates'), bypass.stdout)
+ assert(bypass.stdout.includes('harness tui --install'), bypass.stdout)
+ assert.equal(readlinkSync(hn), legacy)
+ assert(!existsSync(managed))
+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.1 /)
+ const override = await run(harness, ['update', '--force'], options)
+ assert(override.stdout.includes('HARNESS_TUI_BIN='), override.stdout)
+ assert.equal(readlinkSync(hn), legacy, 'an explicit development override prevents forced migration')
+ hnBadChecksum = true
+ await run(harness, repair, managedOptions).catch(error => assert.equal(error.code, 1))
+ assert.equal(readlinkSync(hn), legacy, 'failed downloads must not change the launcher')
+ hnBadChecksum = false
+ const repaired = await run(harness, repair, managedOptions)
+ assert(repaired.stdout.includes('hn now follows automatic updates'), repaired.stdout)
+ assert.equal(readFileSync(hn, 'utf8'), `#!/bin/sh\nexec ${quote(harness)} tui "$@"\n`)
+ assert.equal(sha(readFileSync(legacy)), sha(oldHn))
+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)
+ }
+ const backups = readdirSync(bin).filter(name => name.startsWith('.hn-backup-'))
+ assert.equal(backups.length, 2)
+ for (const backup of backups) assert.equal(readlinkSync(join(bin, backup, 'hn')), legacy)
+ console.log('PASS legacy development installs migrate through --install or update --force, with backups and verified downloads')
+
+ if (native) {
+ rmSync(hn)
+ copyFileSync(native, hn)
+ const original = sha(readFileSync(hn))
+ const repaired = await run(harness, ['tui', '--install'], managedOptions)
+ assert(repaired.stdout.includes('hn now follows automatic updates'), repaired.stdout)
+ const backup = readdirSync(bin).find(name => name.startsWith('.hn-backup-') && !backups.includes(name))
+ assert(backup)
+ assert.equal(sha(readFileSync(join(bin, backup, 'hn'))), original)
+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)
+ console.log('PASS a copied production-native hn migrates with an intact native backup')
+ }
+
+ rmSync(managed)
+ await run(harness, ['update'], managedOptions)
+ assert.match((await run(hn, ['--version'], managedOptions)).stdout, /^hn 0\.1\.2 /)
+ console.log('PASS updates restore a missing binary behind an existing managed launcher')
+
+ const shadowDir = join(root, 'earlier-bin')
+ mkdirSync(shadowDir)
+ writeFileSync(join(shadowDir, 'hn'), oldHn, { mode: 0o755 })
+ const shadow = await run(harness, ['update'], { ...managedOptions, env: { ...managedEnv, PATH: `${shadowDir}:${managedEnv.PATH}` } })
+ assert(shadow.stdout.includes(`Your PATH resolves hn to ${join(shadowDir, 'hn')}`), shadow.stdout)
+ assert.equal(sha(readFileSync(join(shadowDir, 'hn'))), sha(oldHn))
+ console.log('PASS PATH shadowing is reported without changing unrelated commands')
assert(requests.every(url => ['/metadata.json', '/cli.js', '/notify.mjs', '/hn-metadata.json', '/harness-tui'].includes(url)), JSON.stringify(requests))
} finally {
server.closeAllConnections()
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e7369b99e..acd71abba 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -236,7 +236,7 @@ import {
type Poller, type UpdateEntry,
} from './lib/selfUpdate.js'
import { managedNodePath } from './lib/nodeRuntime.js'
-import { updateTui } from './tui/install.js'
+import { updateManagedTui } from './tui/manage.js'
import { startTuiUpdater } from './tui/update.js'
import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'
import { readdir, stat } from 'fs/promises'
@@ -1219,7 +1219,7 @@ async function updateCommand(force: boolean): Promise<void> {
// 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)) }
+ try { await updateManagedTui(SCRIPT_PATH, force, (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 = null
diff --git a/cli/src/scripts/install.spec.ts b/cli/src/scripts/install.spec.ts
index bdd04ca65..8278bba5a 100644
--- a/cli/src/scripts/install.spec.ts
+++ b/cli/src/scripts/install.spec.ts
@@ -1,6 +1,6 @@
import { spawnSync } from "child_process";
import { join } from "path";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "fs";
+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { describe, expect, it } from "vitest";
@@ -1030,7 +1030,7 @@ describe("scripts/install.sh: hn", () => {
return { code, out };
};
- it("writes `hn` beside `harness` as `harness tui`, pinned to the same Node and cli.js", async () => {
+ it("writes `hn` beside `harness`, following its runtime and update policy", async () => {
const scratch = mkdtempSync(join(tmpdir(), "harness-hn-launcher-"));
try {
const home = join(scratch, "home");
@@ -1039,7 +1039,7 @@ describe("scripts/install.sh: hn", () => {
expect(code).toBe(0);
expect(out).toContain("installed harness 9.9.9");
const cli = join(home, ".harness", "cli", "cli.js");
- expect(readFileSync(join(home, ".local", "bin", "hn"), "utf8")).toBe(`#!/bin/sh\nexec '/opt/harness node/bin/node' '${cli}' tui "$@"\n`);
+ expect(readFileSync(join(home, ".local", "bin", "hn"), "utf8")).toBe(`#!/bin/sh\nexec '${join(home, ".local", "bin", "harness")}' tui "$@"\n`);
expect(readFileSync(join(home, ".local", "bin", "harness"), "utf8")).toBe(`#!/bin/sh\nexec '/opt/harness node/bin/node' '${cli}' "$@"\n`);
expect(statSync(join(home, ".local", "bin", "hn")).mode & 0o111).not.toBe(0);
} finally {
@@ -1056,9 +1056,38 @@ describe("scripts/install.sh: hn", () => {
const { code, out } = await runCliStep(home);
expect(code).toBe(0);
expect(readFileSync(join(home, ".local", "bin", "hn"), "utf8")).toBe("#!/bin/sh\necho hacker news\n");
- expect(out).toContain("is another program; run hn as: harness tui");
+ expect(out).toContain("Kept existing");
+ expect(out).toContain("use harness tui");
} finally {
rmSync(scratch, { recursive: true, force: true });
}
}, 20_000);
+
+ it.each(['native symlink', 'dangling symlink', 'unrelated wrapper'])("preserves an existing %s even when it contains .harness", async kind => {
+ const scratch = mkdtempSync(join(tmpdir(), "harness-hn-preserved-"));
+ try {
+ const home = join(scratch, "home");
+ const bin = join(home, ".local", "bin");
+ const hn = join(bin, "hn");
+ const target = join(scratch, "old-hn");
+ mkdirSync(bin, { recursive: true });
+ const bytes = kind === 'unrelated wrapper' ? Buffer.from('#!/bin/sh\necho "$HOME/.harness"\n') : Buffer.from('\x7fELF native .harness bytes');
+ if (kind === 'unrelated wrapper') writeFileSync(hn, bytes);
+ else {
+ if (kind === 'native symlink') writeFileSync(target, bytes, { mode: 0o755 });
+ symlinkSync(target, hn);
+ }
+ const { code, out } = await runCliStep(home);
+ expect(code).toBe(0);
+ expect(out).toContain('harness tui --install');
+ if (kind === 'unrelated wrapper') expect(readFileSync(hn)).toEqual(bytes);
+ else {
+ expect(lstatSync(hn).isSymbolicLink()).toBe(true);
+ expect(readlinkSync(hn)).toBe(target);
+ if (kind === 'native symlink') expect(readFileSync(target)).toEqual(bytes);
+ else expect(existsSync(target)).toBe(false);
+ }
+ expect(readdirSync(bin).sort()).toEqual(['harness', 'hn']);
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
+ }, 20_000);
});
diff --git a/cli/src/tui/index.ts b/cli/src/tui/index.ts
index 99252a98c..2c52d740e 100644
--- a/cli/src/tui/index.ts
+++ b/cli/src/tui/index.ts
@@ -16,6 +16,7 @@ import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { installedTuiPath, installTui } from './install.js'
+import { installManagedTui } from './manage.js'
export { installTui, platformKey, TUI_MANIFEST_URL } from './install.js'
export function findTuiBinary(): string | null {
@@ -102,7 +103,7 @@ async function ensureDaemon(port: number, signedIn: () => boolean): Promise<bool
export async function tuiCommand(argv: string[], opts: { port: number; signedIn?: () => boolean }): Promise<number> {
if (argv[0] === '--install' || argv[0] === 'install') {
- try { await installTui((line) => console.log(line)); return 0 } catch (error) { console.error(` ✗ ${(error as Error).message}`); return 1 }
+ try { await installManagedTui(process.argv[1] ?? '', (line) => console.log(line)); return 0 } catch (error) { console.error(` ✗ ${(error as Error).message}`); return 1 }
}
if (argv[0] === '--where') { console.log(findTuiBinary() ?? '(not installed)'); return 0 }
const port = clientPort(argv, opts.port)
diff --git a/cli/src/tui/install.spec.ts b/cli/src/tui/install.spec.ts
index 20ed33b36..5530134dc 100644
--- a/cli/src/tui/install.spec.ts
+++ b/cli/src/tui/install.spec.ts
@@ -3,7 +3,10 @@ import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, op
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'
+let installedTuiPath: typeof import('./install.js').installedTuiPath
+let installTui: typeof import('./install.js').installTui
+let platformKey: typeof import('./install.js').platformKey
+let updateTui: typeof import('./install.js').updateTui
// 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`)
@@ -29,10 +32,14 @@ function published(version = '0.1.2', bytes = binary(version), overrides: Record
}))
}
-beforeEach(() => {
+beforeEach(async () => {
home = mkdtempSync(join(tmpdir(), 'hn-update-test-'))
vi.stubEnv('HOME', home)
vi.stubEnv('HARNESS_TUI_BIN', undefined)
+ vi.stubEnv('HARNESS_BIN_DIR', join(home, '.local', 'bin'))
+ vi.stubEnv('ADAPTER_CLI_DIR', join(home, '.harness', 'cli'))
+ vi.resetModules()
+ ;({ installedTuiPath, installTui, platformKey, updateTui } = await import('./install.js'))
target = installedTuiPath()
downloads = []
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('unexpected network request')))
@@ -78,6 +85,17 @@ describe('managed hn updates', () => {
expect(fetch).not.toHaveBeenCalled()
})
+ it('repairs a missing managed binary when the managed command is already installed', async () => {
+ const bin = join(home, '.local', 'bin')
+ mkdirSync(bin, { recursive: true })
+ writeFileSync(join(bin, 'hn'), `#!/bin/sh\nexec '${join(bin, 'harness')}' tui "$@"\n`, { mode: 0o755 })
+ published()
+ expect(await updateTui()).toBe(true)
+ expect(readFileSync(target)).toEqual(binary('0.1.2'))
+ expect(await updateTui()).toBe(false)
+ expect(downloads.filter(url => url === 'https://example.test/hn')).toHaveLength(1)
+ })
+
it('leaves symlinked binaries and development versions alone', async () => {
mkdirSync(dirname(target), { recursive: true })
const custom = join(home, 'custom')
diff --git a/cli/src/tui/install.ts b/cli/src/tui/install.ts
index da1fbdaf3..6b20434b1 100644
--- a/cli/src/tui/install.ts
+++ b/cli/src/tui/install.ts
@@ -2,15 +2,16 @@
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'
+import { installedTuiPath } from './paths.js'
+import { isManagedHnLauncher } from './launcher.js'
+export { installedTuiPath } from './paths.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
@@ -32,12 +33,12 @@ async function binaryVersion(binary: string, signal?: AbortSignal): Promise<stri
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.
+ // Never replace a custom binary symlink. A managed launcher with a missing binary is repaired below.
if (!lstatSync(installedTuiPath()).isFile()) return null
return await binaryVersion(installedTuiPath(), signal)
} catch (error) {
signal?.throwIfAborted()
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return isManagedHnLauncher() ? '0.0.0' : null
throw error
}
}
diff --git a/cli/src/tui/launcher.spec.ts b/cli/src/tui/launcher.spec.ts
new file mode 100644
index 000000000..f6014e639
--- /dev/null
+++ b/cli/src/tui/launcher.spec.ts
@@ -0,0 +1,156 @@
+import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join, relative } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const probe = vi.hoisted(() => vi.fn())
+// Native version output is a fixture. Never execute a developer's real hn or an unknown command.
+vi.mock('node:child_process', async original => {
+ const actual = await original<typeof import('node:child_process')>()
+ const { promisify } = await import('node:util')
+ return { ...actual, execFile: Object.assign(() => {}, { [promisify.custom]: probe }) }
+})
+
+let home: string
+let bin: string
+let cli: string
+let hn: string
+let api: typeof import('./launcher.js')
+const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
+const managed = () => `#!/bin/sh\nexec ${quote(join(bin, 'harness'))} tui "$@"\n`
+
+function developmentLink(relativeLink = false, dangling = false): string {
+ const project = join(home, 'checkout', 'tui')
+ const target = join(project, 'target', 'hn-test', 'hn')
+ mkdirSync(dirname(target), { recursive: true })
+ writeFileSync(join(project, 'Cargo.toml'), '[package]\nname = "harness-tui"\n')
+ if (!dangling) writeFileSync(target, 'old development build', { mode: 0o755 })
+ symlinkSync(relativeLink ? relative(bin, target) : target, hn)
+ return target
+}
+
+beforeEach(async () => {
+ home = mkdtempSync(join(tmpdir(), "hn-launcher-'quoted-"))
+ bin = join(home, '.local', 'bin')
+ cli = join(home, '.harness', 'cli', 'cli.js')
+ hn = join(bin, 'hn')
+ mkdirSync(bin, { recursive: true })
+ mkdirSync(dirname(cli), { recursive: true })
+ writeFileSync(cli, '// installed bundle')
+ writeFileSync(join(bin, 'harness'), `#!/bin/sh\nexec node ${quote(cli)} "$@"\n`, { mode: 0o755 })
+ vi.stubEnv('HOME', home)
+ vi.stubEnv('HARNESS_BIN_DIR', bin)
+ vi.stubEnv('ADAPTER_CLI_DIR', dirname(cli))
+ vi.stubEnv('HARNESS_TUI_BIN', undefined)
+ vi.stubEnv('PATH', bin)
+ probe.mockReset().mockResolvedValue({ stdout: 'hn 0.1.0 (tmux 3.5a)\n', stderr: '' })
+ vi.resetModules()
+ api = await import('./launcher.js')
+})
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+})
+
+describe('hn launcher migration', () => {
+ it('creates a missing launcher only for the installed CLI', async () => {
+ const source = join(home, 'source.js')
+ writeFileSync(source, '// development bundle')
+ await api.repairHnLauncher(source, vi.fn())
+ expect((await api.inspectHnLauncher()).kind).toBe('missing')
+ await api.repairHnLauncher(cli, vi.fn())
+ expect(readFileSync(hn, 'utf8')).toBe(managed())
+ expect(lstatSync(hn).mode & 0o777).toBe(0o755)
+ })
+
+ it.each(['managed', 'old installer', 'unquoted repair', 'binary symlink'])('recognizes the %s launcher without probing it', async kind => {
+ if (kind === 'managed') writeFileSync(hn, managed())
+ if (kind === 'old installer') writeFileSync(hn, `#!/bin/sh\nexec '/old/node' ${quote(cli)} tui "$@"\n`)
+ if (kind === 'unquoted repair') writeFileSync(hn, `#!/bin/sh\nexec ${join(bin, 'harness')} tui "$@"\n`)
+ if (kind === 'binary symlink') symlinkSync(join(home, '.harness', 'bin', 'harness-tui'), hn)
+ expect((await api.inspectHnLauncher()).kind).toBe('managed')
+ await api.repairHnLauncher(cli, vi.fn())
+ expect(probe).not.toHaveBeenCalled()
+ expect(readdirSync(bin).sort()).toEqual(['harness', 'hn'])
+ })
+
+ it.each([[false, false], [true, false], [true, true]])('backs up development links (relative=%s, dangling=%s) without changing their target', async (relativeLink, dangling) => {
+ const target = developmentLink(relativeLink, dangling)
+ expect((await api.inspectHnLauncher()).kind).toBe('legacy')
+ const log = vi.fn()
+ await api.repairHnLauncher(cli, log)
+ expect(readFileSync(hn, 'utf8')).toBe(managed())
+ expect(lstatSync(hn).isSymbolicLink()).toBe(false)
+ const backups = readdirSync(bin).filter(s => s.startsWith('.hn-backup-'))
+ expect(backups).toHaveLength(1)
+ const backup = join(bin, backups[0], 'hn')
+ expect(readlinkSync(backup)).toBe(target)
+ if (!dangling) {
+ expect(readFileSync(backup, 'utf8')).toBe('old development build')
+ expect(readFileSync(target, 'utf8')).toBe('old development build')
+ }
+ expect(readdirSync(dirname(backup))).toEqual(['hn'])
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('hn now follows automatic updates'))
+ await api.repairHnLauncher(cli, log)
+ expect(readdirSync(bin).filter(s => s.startsWith('.hn-backup-'))).toEqual(backups)
+ })
+
+ it('migrates a copied native hn with a verified version response', async () => {
+ const bytes = Buffer.from('7f454c466c6567616379', 'hex')
+ writeFileSync(hn, bytes, { mode: 0o755 })
+ await api.repairHnLauncher(cli, vi.fn())
+ expect(probe).toHaveBeenCalledWith(hn, ['--version'], expect.objectContaining({ timeout: 3000 }))
+ expect(readFileSync(hn, 'utf8')).toBe(managed())
+ const backup = readdirSync(bin).find(s => s.startsWith('.hn-backup-'))!
+ expect(readFileSync(join(bin, backup, 'hn'))).toEqual(bytes)
+ expect(lstatSync(join(bin, backup, 'hn')).mode & 0o777).toBe(0o755)
+ })
+
+ it.each(['shell', 'dangling symlink', 'unrelated native', 'broken native'])('preserves an unrelated %s command', async kind => {
+ const bytes = kind.includes('native') ? Buffer.from('7f454c466f74686572', 'hex') : Buffer.from('#!/bin/sh\necho .harness\n')
+ if (kind === 'dangling symlink') symlinkSync(join(home, 'missing'), hn)
+ else writeFileSync(hn, bytes, { mode: 0o755 })
+ if (kind === 'unrelated native') probe.mockResolvedValue({ stdout: 'Hacker News 1.0\n' })
+ if (kind === 'broken native') probe.mockRejectedValue(new Error('broken'))
+ const log = vi.fn()
+ await api.repairHnLauncher(cli, log)
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('another or unrecognized command'))
+ if (kind === 'dangling symlink') expect(readlinkSync(hn)).toBe(join(home, 'missing'))
+ else expect(readFileSync(hn)).toEqual(bytes)
+ if (!kind.includes('native')) expect(probe).not.toHaveBeenCalled()
+ expect(readdirSync(bin).sort()).toEqual(['harness', 'hn'])
+ })
+
+ it('leaves a command changed during its version probe alone', async () => {
+ writeFileSync(hn, Buffer.from('7f454c46', 'hex'))
+ probe.mockImplementation(async () => {
+ writeFileSync(hn, 'replacement command')
+ return { stdout: 'hn 0.1.0 (tmux 3.5a)' }
+ })
+ await expect(api.repairHnLauncher(cli, vi.fn())).rejects.toThrow('changed during installation')
+ expect(readFileSync(hn, 'utf8')).toBe('replacement command')
+ })
+
+ it('does not redirect hn through an unmanaged harness command', async () => {
+ const target = developmentLink()
+ writeFileSync(join(bin, 'harness'), '#!/bin/sh\necho something else\n')
+ await expect(api.repairHnLauncher(cli, vi.fn())).rejects.toThrow('not managed')
+ expect(readlinkSync(hn)).toBe(target)
+ })
+
+ it('explains legacy installs, explicit overrides and PATH shadowing', async () => {
+ developmentLink()
+ const outside = join(home, 'other-bin')
+ mkdirSync(outside)
+ writeFileSync(join(outside, 'hn'), '#!/bin/sh\n', { mode: 0o755 })
+ vi.stubEnv('PATH', `${outside}:${bin}`)
+ vi.stubEnv('HARNESS_TUI_BIN', '/chosen/development/hn')
+ const lines: string[] = []
+ await api.reportHnLauncher(s => lines.push(s))
+ expect(lines.join('\n')).toContain('HARNESS_TUI_BIN=/chosen/development/hn')
+ expect(lines.join('\n')).toContain('does not receive automatic updates')
+ expect(lines.join('\n')).toContain('harness tui --install')
+ expect(lines.join('\n')).toContain(`Your PATH resolves hn to ${join(outside, 'hn')}`)
+ })
+})
diff --git a/cli/src/tui/launcher.ts b/cli/src/tui/launcher.ts
new file mode 100644
index 000000000..d44bb4aba
--- /dev/null
+++ b/cli/src/tui/launcher.ts
@@ -0,0 +1,138 @@
+/** Identify the command users actually run before reporting that hn is up to date. */
+import { execFile } from 'node:child_process'
+import { accessSync, closeSync, constants, copyFileSync, lstatSync, mkdtempSync, openSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { dirname, join, resolve } from 'node:path'
+import { promisify } from 'node:util'
+import { env } from '../config/env.js'
+import { resolveBinaryOnPath } from '../lib/binaryOnPath.js'
+import { ensureHnLauncher } from '../lib/runtimeInstall.js'
+import { installedTuiPath } from './paths.js'
+
+const run = promisify(execFile)
+const quote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
+export const hnLauncherPath = (): string => join(env.HARNESS_BIN_DIR, 'hn')
+const launcherSource = (): string => `#!/bin/sh\nexec ${quote(join(env.HARNESS_BIN_DIR, 'harness'))} tui "$@"\n`
+type Launcher = { path: string; kind: 'missing' | 'managed' | 'legacy' | 'other'; identity?: string }
+
+function identity(path: string): string | undefined {
+ try {
+ const s = lstatSync(path)
+ return `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
+ throw error
+ }
+}
+
+function prefix(path: string): Buffer {
+ if (!statSync(path).isFile()) throw new Error('Not a regular file')
+ const fd = openSync(path, 'r')
+ try {
+ const bytes = Buffer.alloc(8192)
+ return bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, 0))
+ } finally { closeSync(fd) }
+}
+
+function linkedTarget(path: string): string | null {
+ try { return lstatSync(path).isSymbolicLink() ? resolve(dirname(path), readlinkSync(path)) : null } catch { return null }
+}
+
+/** Recognize only the launchers we have shipped, including the older direct Node launcher. */
+export function isManagedHnLauncher(path = hnLauncherPath()): boolean {
+ const linked = linkedTarget(path)
+ if (linked === installedTuiPath() || linked === join(env.ADAPTER_CLI_DIR, 'cli.js')) return true
+ try {
+ const text = prefix(path).toString('utf8').trim()
+ const harness = join(env.HARNESS_BIN_DIR, 'harness')
+ if ([quote(harness), `"${harness}"`, harness].some(word => text === `#!/bin/sh\nexec ${word} tui "$@"`)) return true
+ const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')
+ // The old installer's two-line script pins Node and cli.js. No extra commands or fuzzy
+ // `.harness` substring: native binaries and unrelated programs can contain that string too.
+ const lines = text.split('\n')
+ return lines.length === 2 && lines[0] === '#!/bin/sh'
+ && lines[1].startsWith('exec ') && lines[1].endsWith(' tui "$@"')
+ && [quote(cli), `"${cli}"`, cli].some(word => lines[1].includes(` ${word} tui "$@"`))
+ } catch { return false }
+}
+
+function checkoutLink(path: string): boolean {
+ const linked = linkedTarget(path)
+ if (!linked) return false
+ const match = /^(.*)[/\\]target[/\\].+[/\\](?:hn|harness-tui)$/.exec(linked)
+ if (!match) return false
+ try { return /^name\s*=\s*"harness-tui"\s*$/m.test(readFileSync(join(match[1], 'Cargo.toml'), 'utf8')) } catch { return false }
+}
+
+export async function inspectHnLauncher(path = hnLauncherPath()): Promise<Launcher> {
+ const before = identity(path)
+ if (!before) return { path, kind: 'missing' }
+ if (isManagedHnLauncher(path)) return { path, kind: 'managed', identity: before }
+ if (checkoutLink(path)) return { path, kind: 'legacy', identity: before }
+ try {
+ // Only native executables get a version probe. Never run somebody else's shell wrapper.
+ const magic = prefix(path).subarray(0, 4).toString('hex')
+ if (['7f454c46', 'cffaedfe', 'feedfacf', 'cefaedfe', 'feedface', 'cafebabe', 'bebafeca'].includes(magic)) {
+ const result = await run(path, ['--version'], { timeout: 3000, maxBuffer: 4096, env: { ...process.env, HN_AS_TMUX: '0' } })
+ if (/^hn \d+\.\d+\.\d+(?:[-+][\w.-]+)? \(tmux [^\r\n]+\)$/.test(result.stdout.trim())) {
+ return { path, kind: 'legacy', identity: before }
+ }
+ }
+ } catch { /* unrelated or broken: preserve it */ }
+ return { path, kind: 'other', identity: before }
+}
+
+function installedCli(script: string): boolean {
+ try { return realpathSync(script) === realpathSync(join(env.ADAPTER_CLI_DIR, 'cli.js')) } catch { return false }
+}
+
+/** Explicit migration only, after the managed binary was verified. Preserve the old entry itself. */
+export async function repairHnLauncher(script: string, log: (line: string) => void): Promise<void> {
+ if (!installedCli(script)) return
+ const state = await inspectHnLauncher()
+ if (state.kind === 'managed') return
+ if (state.kind === 'missing') {
+ if (!ensureHnLauncher(script) && !isManagedHnLauncher()) {
+ throw new Error(`Could not create ${state.path}; use \`harness tui\` to run the installed version.`)
+ }
+ return
+ }
+ if (state.kind === 'other') {
+ log(` hn at ${state.path} is another or unrecognized command; use \`harness tui\` for the managed version.`)
+ return
+ }
+ const harness = join(env.HARNESS_BIN_DIR, 'harness')
+ const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')
+ accessSync(harness, constants.X_OK)
+ const exec = /^exec .*$/m.exec(readFileSync(harness, 'utf8'))?.[0]
+ if (!exec || !(exec.includes(cli) || exec.includes(quote(cli)))) throw new Error('The harness launcher is not managed; hn was left unchanged.')
+ if (identity(state.path) !== state.identity) throw new Error('The hn launcher changed during installation; run `harness tui --install` again.')
+ const backup = mkdtempSync(join(env.HARNESS_BIN_DIR, '.hn-backup-'))
+ const staged = join(backup, 'new-hn')
+ try {
+ const target = linkedTarget(state.path)
+ // The backup lives one directory deeper; resolve relative links so it still runs the old build.
+ if (target !== null) symlinkSync(target, join(backup, 'hn'))
+ else copyFileSync(state.path, join(backup, 'hn'), constants.COPYFILE_EXCL)
+ writeFileSync(staged, launcherSource(), { mode: 0o755 })
+ if (identity(state.path) !== state.identity) throw new Error('The hn launcher changed during installation; run `harness tui --install` again.')
+ renameSync(staged, state.path)
+ log(` ✓ hn now follows automatic updates. Previous launcher: ${join(backup, 'hn')}`)
+ } finally { rmSync(staged, { force: true }) }
+}
+
+export async function reportHnLauncher(log: (line: string) => void): Promise<void> {
+ if (process.env.HARNESS_TUI_BIN) {
+ log(` hn uses HARNESS_TUI_BIN=${process.env.HARNESS_TUI_BIN}; unset it to use automatic updates.`)
+ }
+ const standard = await inspectHnLauncher()
+ if (standard.kind === 'legacy') {
+ log(` hn at ${standard.path} is an unmanaged Harness build and does not receive automatic updates.`)
+ log(' Run `harness tui --install` (or `harness update --force`) to back it up and switch to the managed release.')
+ } else if (standard.kind === 'other') {
+ log(` hn at ${standard.path} is another or unrecognized command; use \`harness tui\` for the managed version.`)
+ }
+ const active = resolveBinaryOnPath('hn')
+ if (active && resolve(active) !== resolve(standard.path)) {
+ log(` Your PATH resolves hn to ${active}; put ${env.HARNESS_BIN_DIR} first or use \`harness tui\`.`)
+ }
+}
diff --git a/cli/src/tui/manage.ts b/cli/src/tui/manage.ts
new file mode 100644
index 000000000..b8d438fb2
--- /dev/null
+++ b/cli/src/tui/manage.ts
@@ -0,0 +1,19 @@
+import { installTui, updateTui } from './install.js'
+import { inspectHnLauncher, repairHnLauncher, reportHnLauncher } from './launcher.js'
+
+/** One explicit operation repairs both the downloaded binary and the command on PATH. */
+export async function installManagedTui(script: string, log: (line: string) => void): Promise<void> {
+ await installTui(log)
+ await repairHnLauncher(script, log)
+ await reportHnLauncher(log)
+}
+
+export async function updateManagedTui(script: string, force: boolean, log: (line: string) => void): Promise<void> {
+ const launcher = await inspectHnLauncher()
+ if (force && launcher.kind === 'legacy' && !process.env.HARNESS_TUI_BIN) {
+ await installManagedTui(script, log)
+ return
+ }
+ await updateTui(log)
+ await reportHnLauncher(log)
+}
diff --git a/cli/src/tui/paths.ts b/cli/src/tui/paths.ts
new file mode 100644
index 000000000..6b924008f
--- /dev/null
+++ b/cli/src/tui/paths.ts
@@ -0,0 +1,4 @@
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+export const installedTuiPath = (): string => join(homedir(), '.harness', 'bin', 'harness-tui')
diff --git a/tui/README.md b/tui/README.md
index b63b6e632..ec0c4bb61 100644
--- a/tui/README.md
+++ b/tui/README.md
@@ -15,6 +15,13 @@ the CLI is already current. `ADAPTER_UPDATE_DISABLE=true` disables automatic upd
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.
+If `hn --version` stays old after an update, run `harness update` to check the launcher too.
+Old manual or development installs can bypass automatic updates. `harness tui --install` or
+`harness update --force` backs up a recognized old Harness launcher and switches it to managed
+updates after verifying the download. Unrelated commands and explicit `HARNESS_TUI_BIN` overrides
+are preserved; the update output explains any PATH conflict. A missing binary behind a managed
+launcher is restored automatically.
+
hn follows tmux 3.5a's keys, commands, formats and `~/.tmux.conf`, with your harnesses on
every machine behind them. What tmux users have asked for over the years, and what hn does
about it: [docs/tmux-improved.md](docs/tmux-improved.md).