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.

feat: implement RFC 8628-based device authorization flow with machine identity support

0xken15f06febd6ea18
diff --git a/README.md b/README.md
index 4bc6f258a..7bc69ad54 100644
--- a/README.md
+++ b/README.md
@@ -61,10 +61,15 @@ Two ways to integrate. We support both **CLI** and **API**.
To get started, run this:
```bash
-curl -fsSL https://harness.autonomous.ai/install.sh | bash -s -- <token>
-harness join
+curl -fsSL https://harness.autonomous.ai/install.sh | bash
+harness auth device
```
+`harness auth device` prints a six-character code and a link. Approve it in a browser where you are
+signed in and this computer is connected — there is no token to copy, and re-running it on the same
+computer reconnects it to the same machine rather than making a new one. If you already have a
+machine's token, `harness join <token>` still works.
+
Runs on **macOS and Linux** (Ubuntu 22.04+ verified). Node ≥ 20 and tmux and/or Herdr are the
prerequisites — see [`cli/README.md`](cli/README.md#supported-platforms).
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index ffe5467a4..1fc5bba84 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -378,7 +378,19 @@ function execFileText(cmd, args, timeout, env) {
* comm and args, which kills both halves of the Command Code marker in processMatchScore. macOS never
* substitutes, so this is Linux-only and cannot regress it.
*/
-const PS_ENV = process.platform === 'linux' ? { ...process.env, LC_ALL: 'C.UTF-8' } : undefined
+/**
+ * Mirrors lib/childLocale.ts. This process is spawned by the ENGINE, not by the daemon, so it inherits
+ * the engine's environment and has to set its own — it shells out to both `tmux` and `ps`, and Linux
+ * mangles both without a UTF-8 locale (tmux turns the -F TAB separator into `_`; ps turns `⌘` into
+ * `???`). Only when nothing usable is configured.
+ */
+function ensureUtf8Locale(env = process.env) {
+ if (process.platform !== 'linux') return
+ const configured = env.LC_ALL || env.LC_CTYPE || env.LANG
+ if (configured && /utf-?8/i.test(configured)) return
+ env.LC_ALL = 'C.UTF-8'
+}
+ensureUtf8Locale()
/** Second line of defence: /proc is raw bytes, so a glibc without C.UTF-8 still resolves correctly. */
function repairMangledRows(rows) {
@@ -548,7 +560,7 @@ function processMatchScore(row, engine, ownership, allowAgentHint = false) {
}
async function processRows() {
- const stdout = await execFileText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3000, PS_ENV)
+ const stdout = await execFileText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3000)
if (stdout === null) return null
const rows = []
for (const line of stdout.split('\n')) {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index abfadf09a..32ebab82e 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -19,15 +19,18 @@ import { readFileSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, s
import { join, resolve } from 'path'
import { fileURLToPath } from 'url'
import { spawn } from 'child_process'
-import { createHash, randomUUID } from 'crypto'
-import { homedir } from 'os'
+import { createHash } from 'crypto'
+import { homedir, hostname } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'
+import { ensureUtf8Locale } from './lib/childLocale.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { flashCommand } from './lib/flash.js'
+import { readOrMintComputerId } from './lib/computerIdentity.js'
+import { startDeviceAuth, awaitApproval, type DeviceAuthStart } from './lib/deviceAuth.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
import { buildEngineLaunchArgv } from './lib/engineLaunch.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
@@ -110,6 +113,10 @@ import { RuntimeProfileManager } from './lib/runtimeProfile.js'
import { RuntimeProfileController } from './lib/runtimeProfileController.js'
import { deviceErrorText } from './lib/deviceErrors.js'
import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'
+
+// Before ANY child is spawned: on Linux an absent locale makes tmux and ps mangle their output,
+// which silently costs the daemon every pane it would have discovered. See lib/childLocale.ts.
+ensureUtf8Locale()
import {
installTimestampedConsole, sid, preview,
prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS,
@@ -130,7 +137,9 @@ const LOG_FILE = join(env.ADAPTER_DATA_DIR, 'harness.log')
// earlier and elsewhere — by the table in config/env.ts, which runs at module load, before any daemon
// opens this file. Two mechanisms, one ancestor each, in the right order.
const LEGACY_LOG_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.log')
-const COMPUTER_ID_FILE = join(env.ADAPTER_DATA_DIR, 'computer-id')
+// NOT under ADAPTER_DATA_DIR — see config/env.ts. `reset` wipes that dir, so an id kept there
+// regenerates and the next `harness auth device` mints a SECOND machine for a box that already has one.
+const COMPUTER_ID_FILE = env.ADAPTER_COMPUTER_ID_FILE
// The machine's display name, mirrored from the backend (`machine_meta` on connect + web renames) by the
// daemon so the separate `harness status` process can print it. Absent = unnamed machine.
const MACHINE_NAME_FILE = join(env.ADAPTER_DATA_DIR, 'machine-name')
@@ -165,6 +174,7 @@ ${ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}
A launcher that hands the pane to one of these works the same — "ori claude" is a Claude Code agent.
Machine:
+ harness auth device connect this computer by approving a code in your browser (no token to copy)
harness join <token> connect this computer to an existing machine using the token from its machine page
harness join reconnect with the saved credential
harness join -f run in the FOREGROUND (for a supervisor; logs to stdout)
@@ -186,7 +196,13 @@ Browser end-to-end encryption:
harness --help
-Env: BACKEND_WS_URL (${env.BACKEND_WS_URL}), WEB_URL (${env.WEB_URL}), ADAPTER_DATA_DIR, CLAUDE_PROJECTS_DIR, PORT`)
+This computer's id lives at ${tildify(env.ADAPTER_COMPUTER_ID_FILE)} and is created once. Nothing here
+regenerates it — that is what keeps "harness auth device" reconnecting to the same machine instead of
+making a new one. Deleting it (or ~/.harness) makes this look like a brand-new computer. On a box with
+no durable home, a container or CI job, pin ADAPTER_COMPUTER_ID instead.
+
+Env: BACKEND_WS_URL (${env.BACKEND_WS_URL}), WEB_URL (${env.WEB_URL}), ADAPTER_DATA_DIR,
+ ADAPTER_COMPUTER_ID, CLAUDE_PROJECTS_DIR, PORT`)
process.exit(0)
}
@@ -223,18 +239,11 @@ function saveToken(token: string): void {
writeFileSync(TOKEN_FILE, token + '\n', { mode: 0o600 })
}
-/** Stable per-computer id (persisted in ${ADAPTER_DATA_DIR}/computer-id, created once). Sent on connect
- * so the backend can enforce one machine per machine — and tell a same-machine reconnect (its 30s
- * presence may still be alive) apart from a genuine second machine. Survives `unjoin`. */
+/** This computer's identity — see lib/computerIdentity.ts. Sent on connect so the backend can enforce
+ * one machine per computer, and used by `harness auth device` to reconnect to the machine already
+ * bound to this box instead of minting a second one. */
function computerId(): string {
- try {
- const saved = readFileSync(COMPUTER_ID_FILE, 'utf-8').trim()
- if (saved) return saved
- } catch { /* create below */ }
- const id = randomUUID()
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
- writeFileSync(COMPUTER_ID_FILE, id + '\n', { mode: 0o600 })
- return id
+ return readOrMintComputerId(COMPUTER_ID_FILE, env.ADAPTER_COMPUTER_ID)
}
// ── join ───────────────────────────────────────────────────────────────────────────────────────
@@ -270,11 +279,75 @@ async function postJson<T>(path: string, body: unknown, headers: Record<string,
return json.data as T
}
-function printJoinTokenRequired(): never {
- console.error('\n✗ This computer is not connected to a machine yet.')
- console.error(' Create or open a remote machine in the web UI, copy its connect token, then run:')
- console.error('\n harness join <token>\n')
- process.exit(1)
+/**
+ * `harness auth device` — connect this computer without ever handling a token.
+ *
+ * Prints a six-character code, the user approves it in a browser where they are already signed in, and
+ * we poll until a machine key comes back. The server answers with the machine already bound to THIS
+ * computer, or makes one if it has none — so re-running this on the same box reconnects it rather than
+ * collecting machines. Nothing is purchased; connecting a computer is free.
+ */
+async function authDeviceCommand(foreground: boolean, force: boolean): Promise<void> {
+ const existing = readSavedToken()
+ if (existing && !force) {
+ console.log('\n This computer is already connected.')
+ console.log(` machine ${webBase()}/machine/${agentIdFromToken(existing)}`)
+ console.log('\n Run `harness join` to reconnect, or `harness auth device --force` to connect it')
+ console.log(' to a different account.\n')
+ process.exit(0)
+ }
+
+ let start: DeviceAuthStart
+ try {
+ start = await startDeviceAuth(backendHttpBase(), computerId(), hostname())
+ } catch (e) {
+ console.error(`\n ✗ Could not reach the backend: ${e instanceof Error ? e.message : e}\n`)
+ process.exit(1)
+ }
+
+ const url = `${webBase()}/connect?code=${encodeURIComponent(start.userCode)}`
+ console.log('\n Approve this computer in your browser:\n')
+ console.log(` ${url}`)
+ console.log(`\n code ${start.userCode}\n`)
+ openInBrowser(url)
+
+ // A heartbeat, because ten minutes of nothing reads as a hang.
+ let waited = 0
+ const outcome = await awaitApproval(backendHttpBase(), start.deviceCode, {
+ intervalSec: start.interval,
+ expiresInSec: start.expiresIn,
+ onTick: () => {
+ waited += Math.max(2, start.interval)
+ if (waited % 30 === 0) console.log(` …waiting for approval (${waited}s)`)
+ },
+ })
+
+ if (outcome.status === 'denied') {
+ console.error(`\n ✗ That request was declined${outcome.error ? ` (${outcome.error})` : ''}.\n`)
+ process.exit(1)
+ }
+ if (outcome.status === 'expired') {
+ console.error('\n ✗ The code expired before it was approved. Run `harness auth device` again.\n')
+ process.exit(1)
+ }
+
+ saveToken(outcome.apiKey)
+ console.log('\n ✓ Connected.\n')
+ // Same tail as `join <token>`: one command gets you a running daemon.
+ if ((await launch(outcome.apiKey, foreground)) === 'deauth') {
+ console.error('\n✗ The machine rejected that key straight away — try `harness auth device` again.\n')
+ process.exit(1)
+ }
+}
+
+/** Best-effort: a failed open is not a failed connect, the URL is printed above either way. */
+function openInBrowser(url: string): void {
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'
+ try {
+ const child = spawn(cmd, [url], { stdio: 'ignore', detached: true, shell: process.platform === 'win32' })
+ child.on('error', () => { /* no browser here (headless/ssh) — the printed URL is the fallback */ })
+ child.unref()
+ } catch { /* ignore */ }
}
/**
@@ -306,12 +379,15 @@ async function joinCommand(foreground: boolean, argToken?: string): Promise<void
return
}
const token = readSavedToken()
- if (!token) printJoinTokenRequired()
+ // Nothing saved: rather than telling the user to go find a token, run the grant that gets one. This
+ // is the first-run path, so it is the one that should cost the fewest steps.
+ if (!token) { await authDeviceCommand(foreground, false); return }
// If the saved token was rejected (machine deleted/revoked → 401/403), launch wipes it and returns
// 'deauth'; do not create a new machine from the CLI.
if ((await launch(token, foreground)) === 'deauth') {
console.error('\n✗ This computer is no longer connected to a valid machine.')
- console.error(' Open the machine page, copy a fresh connect token, then run: harness join <token>')
+ console.error(' Reconnect with: harness auth device')
+ console.error(' (or copy a fresh token from the machine page and run: harness join <token>)')
process.exit(1)
}
}
@@ -2831,7 +2907,10 @@ function clearAdapterState(): void {
'harness.log',
'machine.log', // pre-rename names — still cleared so a reset leaves nothing behind
'adapter.log',
- 'computer-id',
+ // NOT 'computer-id' — it no longer lives here (config/env.ts keeps it at the product root,
+ // above everything this function reaches) and it must not be cleared anyway. A reset that
+ // changed this computer's identity would orphan its machine and mint a fresh one on the next
+ // `harness auth device`, which is the opposite of "start over on the same box".
'machine-name',
'registry.json',
'registry-boot',
@@ -3001,6 +3080,15 @@ const onError = (err: unknown): never => {
}
switch (cmd) {
+ case 'auth':
+ // `device` is the only grant there is; accepting a bare `harness auth` keeps the common case short
+ // without closing the door on a second one later.
+ if (args[0] && args[0] !== 'device') {
+ console.error(`Unknown auth subcommand: ${args[0]}\nUsage: harness auth device`)
+ process.exit(1)
+ }
+ authDeviceCommand(foreground, flags.includes('--force')).catch(onError)
+ break
case 'join':
joinCommand(foreground, args[0]).catch(onError)
break
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 85dc945a6..865f4f665 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -4,11 +4,19 @@ import { homedir } from 'os'
import { join } from 'path'
import { z } from 'zod'
import { parseHerdrSessions, parseTerminalBackends } from './terminalConfig.js'
+import { adoptComputerId } from '../lib/computerIdentity.js'
// Packaged files (cli.js/notify.mjs) live in ~/.harness/cli; mutable state in ~/.harness/cli/data.
// `~/.harness` is the PRODUCT data root and does not move — see the naming discipline in CLAUDE.md.
-const adapterCliDir = join(homedir(), '.harness', 'cli')
+const adapterRootDir = join(homedir(), '.harness')
+const adapterCliDir = join(adapterRootDir, 'cli')
const adapterDataDir = join(adapterCliDir, 'data')
+// The computer id lives at the PRODUCT root, one level ABOVE `cli/`, and deliberately not in the data
+// dir: `harness reset` wipes that dir, the ~/.machine adoption below force-replaces entries in it, and
+// a custom ADAPTER_DATA_DIR moves it. A computer's identity must outlive all three — the backend binds
+// a machine to it, so a regenerated id silently mints a SECOND machine for a box that already had one.
+// Nothing in the CLI writes above `~/.harness/cli`, which is exactly why it sits here.
+const computerIdFile = join(adapterRootDir, 'computer-id')
// ── One-time adoption of adapter state written under an older name ────────────────────────────────
//
@@ -50,11 +58,27 @@ function forceMove(current: string, legacy: string): boolean {
}
function migrateLegacyAdapterState(): void {
- // Only for the default location. An explicit ADAPTER_DATA_DIR (tests, custom installs) is the
- // caller's business and must not be reshaped underneath them.
+ // The computer id is lifted UNCONDITIONALLY, before the custom-dir bail-out below. It is the one
+ // piece of state whose location is not the caller's to choose: it is this box's identity, the
+ // backend binds a machine to it, and an install that kept it in a custom data dir must have it
+ // carried across rather than silently re-minted at the root. Point ADAPTER_COMPUTER_ID_FILE (or
+ // ADAPTER_COMPUTER_ID) somewhere else if you genuinely want a separate identity.
+ // Runs BEFORE the ~/.machine force-move below so that tree can no longer REPLACE an id we already
+ // adopted — see lib/computerIdentity.ts for why replacing one is a data-loss bug, not a refresh.
+ const adopted = adoptComputerId(computerIdFile, [
+ join(process.env.ADAPTER_DATA_DIR || adapterDataDir, 'computer-id'),
+ join(process.env.ADAPTER_DATA_DIR || adapterDataDir, 'machine-id'),
+ join(adapterDataDir, 'computer-id'),
+ join(adapterDataDir, 'machine-id'),
+ join(homedir(), '.machine', 'cli', 'data', 'computer-id'),
+ join(homedir(), '.machine', 'cli', 'data', 'machine-id'),
+ ])
+
+ // Everything past here only applies to the default location. An explicit ADAPTER_DATA_DIR (tests,
+ // custom installs) is the caller's business and must not be reshaped underneath them.
if (process.env.ADAPTER_DATA_DIR) return
- let moved = 0
+ let moved = adopted
// In-tree renames first, so a machine that never saw the ~/.machine build still lands on the new
// names. The force-move below overrides these where both exist.
@@ -192,6 +216,13 @@ const envSchema = z.object({
.default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'devin', 'config.json')),
// Where the tmux-session registry + connect token are persisted.
ADAPTER_DATA_DIR: z.string().default(adapterDataDir),
+ // This computer's stable id, minted once and never regenerated (see computerIdFile above). Pin it
+ // explicitly on a box with no durable home — a container or CI job that gets a fresh ~/.harness on
+ // every boot would otherwise look like a NEW computer each time and collect a machine per start.
+ // Setting this is a pin, not a regeneration: it is never written to disk, so unsetting it returns
+ // you to the file's id. Any 16-64 hex (dashes allowed, the backend de-dashes).
+ ADAPTER_COMPUTER_ID: z.string().optional(),
+ ADAPTER_COMPUTER_ID_FILE: z.string().default(computerIdFile),
// ---- Harness Analytics (see autonomous-code docs/design/harness-analytics.md) ----
// Collection is ON by default, but this computer uploads NOTHING until the account owner has
// acknowledged the field list — the backend answers `consent: "unacknowledged"` until then. This
diff --git a/cli/src/lib/childLocale.spec.ts b/cli/src/lib/childLocale.spec.ts
new file mode 100644
index 000000000..f2495edeb
--- /dev/null
+++ b/cli/src/lib/childLocale.spec.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest'
+import { ensureUtf8Locale } from './childLocale.js'
+
+const linux = process.platform === 'linux'
+
+describe('ensureUtf8Locale', () => {
+ /**
+ * The measured failure it prevents (Ubuntu 24.04, tmux 3.4, procps-ng 4.0.4, LANG unset):
+ * tmux list-panes -a -F '#{pane_id}\t#{pane_pid}\t#{pane_current_path}' → "%0_510_/home/app/proj"
+ * The TAB separator comes back as `_` (0x5F, checked with od -c), parsePanes splits on \t and yields
+ * ZERO panes, so discovery has nowhere to attach the engine process it did find and no agent is ever
+ * created. Under LC_ALL=C.UTF-8 the same call returns real tabs.
+ */
+ it.skipIf(!linux)('supplies a UTF-8 locale when the environment has none', () => {
+ const env: NodeJS.ProcessEnv = {}
+ ensureUtf8Locale(env)
+ expect(env.LC_ALL).toBe('C.UTF-8')
+ })
+
+ it.skipIf(!linux)('overrides a non-UTF-8 locale', () => {
+ const env: NodeJS.ProcessEnv = { LANG: 'POSIX' }
+ ensureUtf8Locale(env)
+ expect(env.LC_ALL).toBe('C.UTF-8')
+ })
+
+ it.skipIf(!linux)('leaves a UTF-8 locale the user configured alone', () => {
+ for (const key of ['LC_ALL', 'LC_CTYPE', 'LANG'] as const) {
+ const env: NodeJS.ProcessEnv = { [key]: 'en_US.UTF-8' }
+ ensureUtf8Locale(env)
+ expect(env.LC_ALL).toBe(key === 'LC_ALL' ? 'en_US.UTF-8' : undefined)
+ }
+ const lowercase: NodeJS.ProcessEnv = { LANG: 'C.utf8' }
+ ensureUtf8Locale(lowercase)
+ expect(lowercase.LC_ALL).toBeUndefined()
+ })
+
+ // macOS passes every byte through regardless of locale (verified: default, C.UTF-8 and POSIX all
+ // return `⌘` intact from ps), so there is nothing to fix and nothing to risk changing.
+ it.skipIf(linux)('does nothing off Linux', () => {
+ const env: NodeJS.ProcessEnv = {}
+ ensureUtf8Locale(env)
+ expect(env.LC_ALL).toBeUndefined()
+ })
+})
diff --git a/cli/src/lib/childLocale.ts b/cli/src/lib/childLocale.ts
new file mode 100644
index 000000000..fb8714ce4
--- /dev/null
+++ b/cli/src/lib/childLocale.ts
@@ -0,0 +1,28 @@
+/**
+ * Give this process (and therefore every child it spawns) a UTF-8 locale on Linux.
+ *
+ * Linux tools sanitize bytes they cannot represent in the current locale, and a daemon usually has NO
+ * locale at all: `LANG` is unset under systemd, under `docker run`, and in an ssh session that forwards
+ * nothing, which leaves `LC_CTYPE` at POSIX. Two measured consequences on Ubuntu 24.04, both silent:
+ *
+ * - `tmux list-panes -a -F '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'` returns the TAB separators
+ * as `_` (0x5F, verified with od -c). `parsePanes` splits on \t, so it parses ZERO panes, discovery
+ * has nothing to attach an engine process to, and no agent is ever created. This is exactly the
+ * "tmux + claude makes no agent" report: the engine process was found, the pane was not.
+ * - `ps -axo comm=,args=` returns `⌘ <title>` as `??? <title>`, which kills both halves of the Command
+ * Code marker in engineProcessMatchScore and lets the reaper evict a live pane.
+ *
+ * Why the whole process rather than per-spawn: the daemon shells out to tmux from several modules
+ * (discovery, the backend adapter, pane capture, input injection) and to `ps` from two, and each one
+ * would have to remember. Setting it once at entry covers every current and future child.
+ *
+ * Only when nothing usable is configured — a user with `LANG=en_US.UTF-8` keeps it. `C.UTF-8` is the
+ * portable choice (glibc ≥ 2.35, and Ubuntu's own /etc/default/locale ships exactly it); where it does
+ * not exist glibc falls back to C, i.e. no worse than doing nothing.
+ */
+export function ensureUtf8Locale(env: NodeJS.ProcessEnv = process.env): void {
+ if (process.platform !== 'linux') return
+ const configured = env.LC_ALL || env.LC_CTYPE || env.LANG
+ if (configured && /utf-?8/i.test(configured)) return
+ env.LC_ALL = 'C.UTF-8'
+}
diff --git a/cli/src/lib/computerIdentity.spec.ts b/cli/src/lib/computerIdentity.spec.ts
new file mode 100644
index 000000000..79feec650
--- /dev/null
+++ b/cli/src/lib/computerIdentity.spec.ts
@@ -0,0 +1,164 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { adoptComputerId, readOrMintComputerId } from './computerIdentity.js'
+
+// The invariant under test is one sentence: a computer that already has an id must never get a new one.
+// Every case below is a path that used to be able to break it — see the file's docstring for why that
+// is a data-loss bug (the old machine is orphaned and a replacement is created) rather than a refresh.
+
+let home = ''
+const root = () => join(home, '.harness')
+const canonical = () => join(root(), 'computer-id')
+const dataDir = () => join(root(), 'cli', 'data')
+const strayDataDir = () => join(home, '.machine', 'cli', 'data')
+
+/** The adoption order env.ts uses, newest tree first. */
+const legacyPaths = () => [
+ join(dataDir(), 'computer-id'),
+ join(dataDir(), 'machine-id'),
+ join(strayDataDir(), 'computer-id'),
+ join(strayDataDir(), 'machine-id'),
+]
+
+function seed(path: string, value: string): void {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, value + '\n')
+}
+
+beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'computer-identity-')) })
+afterEach(() => { rmSync(home, { recursive: true, force: true }) })
+
+describe('readOrMintComputerId', () => {
+ it('mints once, then returns the same value forever', () => {
+ const first = readOrMintComputerId(canonical())
+ expect(first).toMatch(/^[0-9a-f-]{36}$/)
+ expect(readOrMintComputerId(canonical())).toBe(first)
+ expect(readOrMintComputerId(canonical())).toBe(first)
+ })
+
+ it('writes the file 0600 — it identifies this box to the backend', () => {
+ readOrMintComputerId(canonical())
+ expect(statSync(canonical()).mode & 0o777).toBe(0o600)
+ })
+
+ it('never overwrites an id already on disk', () => {
+ seed(canonical(), 'an-existing-id')
+ expect(readOrMintComputerId(canonical())).toBe('an-existing-id')
+ expect(readFileSync(canonical(), 'utf-8').trim()).toBe('an-existing-id')
+ })
+
+ it('treats an empty or whitespace-only file as absent and mints into it', () => {
+ seed(canonical(), ' ')
+ const id = readOrMintComputerId(canonical())
+ expect(id).toMatch(/^[0-9a-f-]{36}$/)
+ })
+
+ it('the pin wins but is never written, so unsetting it returns the file id', () => {
+ seed(canonical(), 'file-id')
+ expect(readOrMintComputerId(canonical(), 'pinned-id')).toBe('pinned-id')
+ expect(readFileSync(canonical(), 'utf-8').trim()).toBe('file-id')
+ expect(readOrMintComputerId(canonical())).toBe('file-id')
+ })
+
+ it('ignores a blank pin rather than treating it as an identity', () => {
+ seed(canonical(), 'file-id')
+ expect(readOrMintComputerId(canonical(), ' ')).toBe('file-id')
+ })
+
+ it('recovers from a blank file instead of bricking every command', () => {
+ // A crashed or truncated write leaves the file present but empty, which fails the `wx` create AND
+ // the re-read. Throwing there would take down `harness status` too; a blank file was never sent to
+ // the backend, so there is no identity to protect.
+ seed(canonical(), '')
+ const id = readOrMintComputerId(canonical())
+ expect(id).toMatch(/^[0-9a-f-]{36}$/)
+ expect(readFileSync(canonical(), 'utf-8').trim()).toBe(id)
+ expect(readOrMintComputerId(canonical())).toBe(id)
+ })
+})
+
+describe('adoptComputerId', () => {
+ it('lifts an id out of the data dir instead of leaving it to be wiped', () => {
+ seed(join(dataDir(), 'computer-id'), 'legacy-id')
+ expect(adoptComputerId(canonical(), legacyPaths())).toBe(1)
+ expect(readOrMintComputerId(canonical())).toBe('legacy-id')
+ })
+
+ it('adopts the pre-rename machine-id name', () => {
+ seed(join(dataDir(), 'machine-id'), 'older-id')
+ adoptComputerId(canonical(), legacyPaths())
+ expect(readOrMintComputerId(canonical())).toBe('older-id')
+ })
+
+ it('adopts from the stray ~/.machine tree', () => {
+ seed(join(strayDataDir(), 'computer-id'), 'stray-id')
+ adoptComputerId(canonical(), legacyPaths())
+ expect(readOrMintComputerId(canonical())).toBe('stray-id')
+ })
+
+ it('the newest tree wins and the stray one cannot replace it', () => {
+ // This is the ~/.machine force-move bug: it used to rmSync the target and rename over it.
+ seed(join(dataDir(), 'computer-id'), 'current-id')
+ seed(join(strayDataDir(), 'computer-id'), 'stray-id')
+ adoptComputerId(canonical(), legacyPaths())
+ expect(readOrMintComputerId(canonical())).toBe('current-id')
+ })
+
+ it('never replaces an id already at the canonical path', () => {
+ seed(canonical(), 'settled-id')
+ seed(join(dataDir(), 'computer-id'), 'legacy-id')
+ expect(adoptComputerId(canonical(), legacyPaths())).toBe(0)
+ expect(readOrMintComputerId(canonical())).toBe('settled-id')
+ })
+
+ it('is a no-op on a fresh install and does not mint anything', () => {
+ expect(adoptComputerId(canonical(), legacyPaths())).toBe(0)
+ expect(() => readFileSync(canonical(), 'utf-8')).toThrow()
+ })
+
+ it('leaves no directory behind when there is nothing to adopt', () => {
+ // Runs at import time on EVERY command, so a run with nothing to move must not create the tree.
+ adoptComputerId(canonical(), legacyPaths())
+ expect(existsSync(root())).toBe(false)
+ })
+
+ it('adopts from a custom data dir, which is how a non-default install keeps its identity', () => {
+ // `migrateLegacyAdapterState` bails out early for a custom ADAPTER_DATA_DIR — the computer id is
+ // deliberately lifted BEFORE that bail-out, because re-minting it is not a layout choice.
+ const custom = join(home, 'custom-data')
+ seed(join(custom, 'computer-id'), 'custom-dir-id')
+ adoptComputerId(canonical(), [join(custom, 'computer-id'), ...legacyPaths()])
+ expect(readOrMintComputerId(canonical())).toBe('custom-dir-id')
+ })
+
+ it('is idempotent — running it again after adopting changes nothing', () => {
+ seed(join(dataDir(), 'computer-id'), 'legacy-id')
+ adoptComputerId(canonical(), legacyPaths())
+ adoptComputerId(canonical(), legacyPaths())
+ expect(readOrMintComputerId(canonical())).toBe('legacy-id')
+ })
+})
+
+describe('survives the commands that clear local state', () => {
+ // `harness reset` clears the data dir; in the dataDir !== cliDir case it rmSyncs the whole tree.
+ // The id sits ABOVE both, which is the entire reason it was moved out of there.
+ it.each([
+ ['data dir wiped', () => rmSync(dataDir(), { recursive: true, force: true })],
+ ['cli tree wiped', () => rmSync(join(root(), 'cli'), { recursive: true, force: true })],
+ ['stray tree wiped', () => rmSync(join(home, '.machine'), { recursive: true, force: true })],
+ ])('%s', (_label, wipe) => {
+ mkdirSync(dataDir(), { recursive: true })
+ mkdirSync(strayDataDir(), { recursive: true })
+ const id = readOrMintComputerId(canonical())
+ wipe()
+ expect(readOrMintComputerId(canonical())).toBe(id)
+ })
+
+ it('only deleting the product root itself makes this a new computer', () => {
+ const id = readOrMintComputerId(canonical())
+ rmSync(root(), { recursive: true, force: true })
+ expect(readOrMintComputerId(canonical())).not.toBe(id)
+ })
+})
diff --git a/cli/src/lib/computerIdentity.ts b/cli/src/lib/computerIdentity.ts
new file mode 100644
index 000000000..9a4870ea0
--- /dev/null
+++ b/cli/src/lib/computerIdentity.ts
@@ -0,0 +1,87 @@
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs'
+import { dirname } from 'path'
+import { randomUUID } from 'crypto'
+
+/**
+ * This computer's identity: minted ONCE, then never regenerated.
+ *
+ * The backend BINDS a machine to this value — `harness auth device` reuses the machine already bound
+ * to it, and creates one only when there is none. So regenerating it is not a cosmetic reset: it
+ * orphans the machine this box was using and mints a replacement. Every path here is therefore
+ * write-once, and the file itself lives at the product root (`~/.harness/computer-id`), above
+ * everything `reset`, `unjoin`, the self-updater and the legacy migrations touch.
+ *
+ * Deliberately parameterised and free of any `env` import: paths in, string out, so the invariants
+ * below can be tested against a temp dir instead of the user's real home.
+ */
+
+/**
+ * Move an id written by an older build up to the canonical path.
+ *
+ * Only ever moves onto a FREE target, so the first location that lands wins and the rest are no-ops —
+ * this can relocate an identity but never replace or mint one. Order `legacyPaths` newest-tree-first.
+ * Returns the number of files moved (0 or 1 in practice; the loop stops mattering once one lands).
+ */
+export function adoptComputerId(canonicalFile: string, legacyPaths: string[]): number {
+ let moved = 0
+ for (const legacy of legacyPaths) {
+ try {
+ if (existsSync(canonicalFile) || !existsSync(legacy)) continue
+ // Created lazily, only once there is something to move: this runs at import time on every
+ // command, and a run with nothing to adopt must not leave a directory behind. The parent has to
+ // exist or the rename fails with ENOENT, stranding the id in a tree a later migration is about
+ // to rewrite — which is exactly how an identity gets lost.
+ mkdirSync(dirname(canonicalFile), { recursive: true, mode: 0o700 })
+ renameSync(legacy, canonicalFile)
+ moved++
+ } catch { /* best-effort: a failed adoption must never stop the CLI from starting */ }
+ }
+ return moved
+}
+
+/**
+ * Read this computer's id, minting one only if the file does not exist yet.
+ *
+ * `pinned` (ADAPTER_COMPUTER_ID) is a pin, not a regeneration: it is never written to disk, so
+ * unsetting it returns you to the file's id. It exists for boxes with no durable home — a container or
+ * CI job that gets a fresh `~/.harness` every boot would otherwise look like a new computer each time
+ * and collect a machine per start.
+ */
+export function readOrMintComputerId(file: string, pinned?: string): string {
+ const pin = pinned?.trim()
+ if (pin) return pin
+ const existing = readIfPresent(file)
+ if (existing) return existing
+
+ const id = randomUUID()
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ try {
+ // Exclusive create: two CLI processes starting together must not end up disagreeing about who
+ // this computer is. The loser reads the winner's value instead of clobbering it.
+ writeFileSync(file, id + '\n', { flag: 'wx', mode: 0o600 })
+ return id
+ } catch {
+ const raced = readIfPresent(file)
+ if (raced) return raced
+ // The file exists but holds nothing — a crashed or truncated write, or a full disk. A blank file
+ // was never sent to the backend, so there is no identity to protect and replacing it cannot orphan
+ // a machine. Refusing here would instead brick every command, `harness status` included.
+ try {
+ writeFileSync(file, id + '\n', { mode: 0o600 })
+ return id
+ } catch (err) {
+ throw new Error(
+ `could not establish a computer id at ${file}: ${err instanceof Error ? err.message : String(err)}`,
+ )
+ }
+ }
+}
+
+function readIfPresent(file: string): string | null {
+ try {
+ const saved = readFileSync(file, 'utf-8').trim()
+ return saved || null
+ } catch {
+ return null
+ }
+}
diff --git a/cli/src/lib/deviceAuth.spec.ts b/cli/src/lib/deviceAuth.spec.ts
new file mode 100644
index 000000000..136ac1958
--- /dev/null
+++ b/cli/src/lib/deviceAuth.spec.ts
@@ -0,0 +1,138 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { startDeviceAuth, awaitApproval } from './deviceAuth.js'
+
+const BASE = 'http://backend.test'
+
+/** A fetch stub that answers the backend's `{ success, data }` envelope from a queue of payloads. */
+function stubFetch(...payloads: Array<unknown | Error>): ReturnType<typeof vi.fn> {
+ const queue = [...payloads]
+ const fn = vi.fn(async () => {
+ const next = queue.length > 1 ? queue.shift() : queue[0]
+ if (next instanceof Error) throw next
+ return { ok: true, status: 200, json: async () => ({ success: true, data: next }) } as Response
+ })
+ vi.stubGlobal('fetch', fn)
+ return fn
+}
+
+/** Time is injected, so a ten-minute deadline costs no wall-clock. */
+function fakeClock(stepMs = 0) {
+ let t = 0
+ return {
+ now: () => t,
+ sleep: async (ms: number) => { t += stepMs || ms },
+ }
+}
+
+afterEach(() => { vi.unstubAllGlobals() })
+
+describe('startDeviceAuth', () => {
+ it('returns the code pair and posts the computer id', async () => {
+ const fetchMock = stubFetch({ userCode: 'ABC123', deviceCode: 'f'.repeat(64), expiresIn: 600, interval: 2 })
+ const out = await startDeviceAuth(BASE, 'my-computer-id', 'MacBook-Pro')
+
+ expect(out).toEqual({ userCode: 'ABC123', deviceCode: 'f'.repeat(64), expiresIn: 600, interval: 2 })
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(`${BASE}/api/device-auth/start`)
+ expect(JSON.parse(String(init.body))).toEqual({ computerId: 'my-computer-id', label: 'MacBook-Pro' })
+ })
+
+ it('falls back to safe floors when the backend omits the timings', async () => {
+ // A zero interval would otherwise become a tight spin loop against the backend.
+ stubFetch({ userCode: 'ABC123', deviceCode: 'a'.repeat(64) })
+ const out = await startDeviceAuth(BASE, 'id', 'box')
+ expect(out.expiresIn).toBe(600)
+ expect(out.interval).toBe(2)
+ })
+
+ it('rejects a response with no code rather than polling for something that cannot arrive', async () => {
+ stubFetch({ expiresIn: 600 })
+ await expect(startDeviceAuth(BASE, 'id', 'box')).rejects.toThrow(/pairing code/)
+ })
+
+ it('surfaces the backend error message', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: false,
+ status: 400,
+ json: async () => ({ success: false, error: { message: 'computerId must be a hex computer fingerprint' } }),
+ } as Response)))
+ await expect(startDeviceAuth(BASE, 'nope', 'box')).rejects.toThrow(/hex computer fingerprint/)
+ })
+})
+
+describe('awaitApproval', () => {
+ it('polls through pending and returns the machine key on approval', async () => {
+ const fetchMock = stubFetch(
+ { status: 'pending' },
+ { status: 'pending' },
+ { status: 'approved', apiKey: 'k'.repeat(64), machineId: 'm'.repeat(32) },
+ )
+ const clock = fakeClock()
+
+ const out = await awaitApproval(BASE, 'd'.repeat(64), {
+ intervalSec: 2, expiresInSec: 600, ...clock,
+ })
+
+ expect(out).toEqual({ status: 'approved', apiKey: 'k'.repeat(64), machineId: 'm'.repeat(32) })
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ })
+
+ it('returns denied with the reason', async () => {
+ stubFetch({ status: 'denied', error: 'declined on the web' })
+ const out = await awaitApproval(BASE, 'd'.repeat(64), { intervalSec: 2, expiresInSec: 600, ...fakeClock() })
+ expect(out).toEqual({ status: 'denied', error: 'declined on the web' })
+ })
+
+ it('treats expired as terminal — it is also how an already-consumed code answers', async () => {
+ const fetchMock = stubFetch({ status: 'expired' })
+ const out = await awaitApproval(BASE, 'd'.repeat(64), { intervalSec: 2, expiresInSec: 600, ...fakeClock() })
+ expect(out).toEqual({ status: 'expired' })
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps polling through a network blip', async () => {
+ // A laptop that sleeps or changes wifi mid-approval must not lose the grant.
+ const fetchMock = stubFetch(
+ new Error('ECONNREFUSED'),
+ new Error('ENOTFOUND'),
+ { status: 'approved', apiKey: 'k'.repeat(64), machineId: 'm'.repeat(32) },
+ )
+ const out = await awaitApproval(BASE, 'd'.repeat(64), { intervalSec: 2, expiresInSec: 600, ...fakeClock() })
+ expect(out.status).toBe('approved')
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ })
+
+ it('gives up at the deadline instead of polling forever', async () => {
+ const fetchMock = stubFetch({ status: 'pending' })
+ // 10s of budget at a 2s interval = 5 polls, then the deadline ends it.
+ const out = await awaitApproval(BASE, 'd'.repeat(64), { intervalSec: 2, expiresInSec: 10, ...fakeClock() })
+ expect(out).toEqual({ status: 'expired' })
+ expect(fetchMock).toHaveBeenCalledTimes(5)
+ })
+
+ it('never polls faster than the 2s floor, whatever the backend advertises', async () => {
+ const slept: number[] = []
+ stubFetch({ status: 'pending' })
+ let t = 0
+ await awaitApproval(BASE, 'd'.repeat(64), {
+ intervalSec: 0,
+ expiresInSec: 10,
+ now: () => t,
+ sleep: async (ms) => { slept.push(ms); t += ms },
+ })
+ expect(slept.every((ms) => ms === 2000)).toBe(true)
+ })
+
+ it('honours an interval longer than the floor', async () => {
+ const slept: number[] = []
+ stubFetch({ status: 'pending' })
+ let t = 0
+ await awaitApproval(BASE, 'd'.repeat(64), {
+ intervalSec: 5,
+ expiresInSec: 10,
+ now: () => t,
+ sleep: async (ms) => { slept.push(ms); t += ms },
+ })
+ expect(slept).toEqual([5000, 5000])
+ })
+})
diff --git a/cli/src/lib/deviceAuth.ts b/cli/src/lib/deviceAuth.ts
new file mode 100644
index 000000000..ae90d87b2
--- /dev/null
+++ b/cli/src/lib/deviceAuth.ts
@@ -0,0 +1,113 @@
+/**
+ * The device-authorization grant (RFC 8628-shaped), client half.
+ *
+ * The CLI cannot do a browser OAuth redirect — the backend pins `redirect_uri` to the WEB callback
+ * page — so it never handles a credential of the user's at all. It shows a six-character code, the
+ * user approves it in a browser where they are already signed in, and this polls until a MACHINE key
+ * comes back. That key is the only credential a machine ever needs; nothing user-scoped is minted.
+ *
+ * Deliberately free of any cli.ts import: the base URL and the clock are parameters, so the polling
+ * loop is unit-testable without a daemon, a filesystem or a real two-second wait.
+ */
+
+export interface DeviceAuthStart {
+ /** The six characters the human retypes. Display as-is. */
+ userCode: string
+ /** 32-byte hex bearer secret. Never printed — it is what redeems the machine key. */
+ deviceCode: string
+ expiresIn: number
+ interval: number
+}
+
+export type ApprovalOutcome =
+ | { status: 'approved'; apiKey: string; machineId: string }
+ | { status: 'denied'; error?: string }
+ | { status: 'expired' }
+
+/** The backend's `{ success, data }` envelope, unwrapped. */
+async function postJson<T>(baseUrl: string, path: string, body: unknown): Promise<T> {
+ const res = await fetch(`${baseUrl.replace(/\/$/, '')}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ const json = (await res.json().catch(() => ({}))) as {
+ success?: boolean
+ data?: T
+ error?: { message?: string }
+ }
+ if (!res.ok || json.success === false) throw new Error(json.error?.message || `HTTP ${res.status}`)
+ return json.data as T
+}
+
+/** Mint a pending request. Unauthenticated by design — the CLI has no credential yet, which is the point. */
+export async function startDeviceAuth(
+ baseUrl: string,
+ computerId: string,
+ label: string,
+): Promise<DeviceAuthStart> {
+ const out = await postJson<Partial<DeviceAuthStart>>(baseUrl, '/api/device-auth/start', {
+ computerId,
+ label,
+ })
+ if (!out?.userCode || !out?.deviceCode) throw new Error('backend did not return a pairing code')
+ return {
+ userCode: out.userCode,
+ deviceCode: out.deviceCode,
+ // Floors, not defaults: a backend that omits these must not turn into a tight spin loop.
+ expiresIn: Number(out.expiresIn) > 0 ? Number(out.expiresIn) : 600,
+ interval: Number(out.interval) > 0 ? Number(out.interval) : 2,
+ }
+}
+
+export interface AwaitApprovalOptions {
+ intervalSec: number
+ expiresInSec: number
+ /** Called before each sleep, for a progress heartbeat. */
+ onTick?: () => void
+ /** Injected in tests; real callers get the wall clock and a real timer. */
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+}
+
+/** The floor the backend advertises (POLL_MIN_INTERVAL_SEC). Never poll faster, whatever it sends. */
+const MIN_INTERVAL_SEC = 2
+
+/**
+ * Poll until the code is approved, denied, or its ten minutes run out.
+ *
+ * Network failures are swallowed and the loop continues: a laptop that sleeps or changes wifi between
+ * printing the code and the user approving it must not lose the grant — the deadline is what ends this,
+ * not one failed request.
+ */
+export async function awaitApproval(
+ baseUrl: string,
+ deviceCode: string,
+ opts: AwaitApprovalOptions,
+): Promise<ApprovalOutcome> {
+ const now = opts.now ?? (() => Date.now())
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const intervalMs = Math.max(MIN_INTERVAL_SEC, opts.intervalSec) * 1000
+ const deadline = now() + opts.expiresInSec * 1000
+
+ while (now() < deadline) {
+ try {
+ const out = await postJson<{
+ status?: string
+ apiKey?: string
+ machineId?: string
+ error?: string
+ }>(baseUrl, '/api/device-auth/poll', { deviceCode })
+ if (out?.status === 'approved' && out.apiKey && out.machineId) {
+ return { status: 'approved', apiKey: out.apiKey, machineId: out.machineId }
+ }
+ if (out?.status === 'denied') return { status: 'denied', error: out.error }
+ // 'expired' is also how the backend answers an ALREADY-CONSUMED code — the poll that returns the
+ // key deletes it — so it is terminal either way.
+ if (out?.status === 'expired') return { status: 'expired' }
+ } catch { /* transient: keep polling until the deadline */ }
+ opts.onTick?.()
+ await sleep(intervalMs)
+ }
+ return { status: 'expired' }
+}
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index f950c3be7..4062e2ea6 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -144,11 +144,12 @@ export function parseProcessRow(line: string): ProcessRow | null {
}
/**
- * Second line of defence for the locale substitution described on PS_ENV: a glibc build with no
- * `C.UTF-8` locale falls back to POSIX and `ps` mangles again. `/proc` is raw bytes and cannot be
- * mangled by anything, so re-read the two fields from there — but only for the rows that actually show
- * a `?`, which under a working locale is none. Measured cost of reading every `/proc/<pid>/cmdline` on
- * a 63-process container: 0.48ms, so even the degenerate "every row" case is free.
+ * Second line of defence for the locale substitution `ensureUtf8Locale` (lib/childLocale.ts) prevents:
+ * a glibc build with no `C.UTF-8` locale falls back to POSIX and `ps` replaces every byte it cannot
+ * print with `?` — which erases the `⌘` that is Command Code's only pane marker. `/proc` is raw bytes
+ * and cannot be mangled by anything, so re-read the two fields from there, but only for the rows that
+ * actually show a `?`, which under a working locale is none. Measured cost of reading every
+ * `/proc/<pid>/cmdline` on a 63-process container: 0.48ms, so even the degenerate case is free.
*
* No-op off Linux: macOS has no /proc and does not substitute in the first place.
*/
@@ -167,27 +168,10 @@ function readProcField(pid: number, field: 'cmdline' | 'comm'): string | null {
try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }
}
-/**
- * The environment `ps` is read under.
- *
- * Linux procps replaces every byte it cannot print in the current locale with `?`, and a daemon
- * frequently has NO locale at all — `LANG` is unset under systemd, under `docker run`, and in an ssh
- * session that forwards nothing, which makes `LC_CTYPE` fall back to POSIX. Measured on Ubuntu 24.04
- * (procps-ng 4.0.4): a process whose argv is `⌘ <session title>` prints as `??? <session title>` in
- * BOTH `comm` and `args`, so both halves of the Command Code marker below fail and every live cmd pane
- * is evicted by the reaper. Under `LC_ALL=C.UTF-8` the same read returns the real bytes.
- *
- * macOS never substitutes (verified: default, C.UTF-8 and POSIX all pass ⌘ through), so this is applied
- * only where it is needed and cannot regress the platform that already works.
- */
-const PS_ENV = process.platform === 'linux'
- ? { ...process.env, LC_ALL: 'C.UTF-8' }
- : process.env
-
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
export async function processRows(): Promise<ProcessRow[] | null> {
const rows = await new Promise<ProcessRow[] | null>((resolve) => {
- execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000, env: PS_ENV }, (err, stdout) => {
+ execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000 }, (err, stdout) => {
if (err) { resolve(null); return }
const rows: ProcessRow[] = []
for (const line of stdout.split('\n')) {