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
feat: resolve tmux via user login shell to fix daemon PATH issues and update error codes
0xken15743032aaf6cb
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d7333f01d..3206c4824 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -35,6 +35,7 @@ import { DeviceFleet } from './device/deviceFleet.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, daemonPort, isAlive, readPid } from './lib/daemonState.js'+import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { renderLoginSuccessHtml } from './lib/loginPage.js'@@ -711,6 +712,17 @@ async function runForeground(session: AuthSession): Promise<void> {? resolveConfiguredHerdrSessions(terminalConfig.herdrSessions, () => listInstalledHerdrSessions(env.HERDR_BIN)): discoverRunningHerdrSessions(env.HERDR_BIN)}+ // Before ANY tmux call: a daemon that came up outside a terminal (the usual shape after a reboot)+ // has a minimal PATH, and every `execFile('tmux', …)` below would ENOENT. Ask the user's own login+ // shell where tmux is and adopt that directory, the same way the engine launch already consults it.+ if (terminalConfig.backends.includes('tmux')) {+ const tmuxPath = await ensureTmuxOnPath()+ if (tmuxPath.state === 'adopted') {+ console.log(`[tmux] not on the daemon PATH · adopted ${tmuxPath.from} from the user's login shell`)+ } else if (tmuxPath.state === 'absent') {+ console.warn(`[tmux] unavailable · ${tmuxPath.reason} · new agents cannot be created`)+ }+ }const tmuxBackend = terminalConfig.backends.includes('tmux') ? new TmuxBackend() : nullconst herdrTargets = await resolveHerdrTargets()activeHerdrSessions = herdrTargets.map((target) => target.sessionName)@@ -2647,7 +2659,16 @@ async function runForeground(session: AuthSession): Promise<void> {const spawned = await tmuxBackend.create({ cwd, label, command: argv })if (spawned.state !== 'succeeded') {console.warn(`[agent] create ${engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)- return { ok: false, error: 'SPAWN_FAILED', detail: spawned.reason }+ // `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary. So a+ // daemon that cannot resolve `tmux` at all (a login context whose PATH lacks Homebrew's bin,+ // the usual shape after a reboot) reported the same SPAWN_FAILED as a tmux that answered and+ // refused. They need different fixes, so they get different codes.+ const missing = spawned.reason === 'tmux is unavailable'+ return {+ ok: false,+ error: missing ? 'TMUX_UNAVAILABLE' : 'SPAWN_FAILED',+ detail: spawned.reason,+ }}for (const delayMs of [150, 400, 800]) {await new Promise((resolve) => setTimeout(resolve, delayMs))diff --git a/cli/src/lib/tmuxOnPath.spec.ts b/cli/src/lib/tmuxOnPath.spec.tsnew file mode 100644index 000000000..8d4754f05--- /dev/null+++ b/cli/src/lib/tmuxOnPath.spec.ts@@ -0,0 +1,111 @@+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { TmuxBackend } from './tmuxBackend.js'+import { ensureTmuxOnPath, resolveViaLoginShell } from './tmuxOnPath.js'++const dirs: string[] = []+const originalPath = process.env.PATH+afterEach(() => {+ process.env.PATH = originalPath+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++function scratch(prefix: string): string {+ const dir = mkdtempSync(join(tmpdir(), prefix))+ dirs.push(dir)+ return dir+}++/** A stand-in for the user's shell: it knows about `binDir`, the daemon's own PATH does not. */+function fakeShell(binDir: string): string {+ const dir = scratch('tmux-onpath-shell-')+ const shell = join(dir, 'sh')+ writeFileSync(shell, `#!/bin/sh+# Mimics "zsh -lic <script> $0 $1": drop the flag, run the script with the remaining positionals.+shift+# Hermetic: ONLY this dir, or the real tmux on the test machine leaks in and the+# "cannot find it either" case silently passes for the wrong reason.+PATH="${binDir}" exec /bin/sh -c "$@"+`)+ chmodSync(shell, 0o700)+ return shell+}++function fakeTmux(): string {+ const dir = scratch('tmux-onpath-bin-')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, '#!/bin/sh\nexit 0\n')+ chmodSync(tmux, 0o700)+ return dir+}++describe('ensureTmuxOnPath', () => {+ it('adopts the directory the user\'s shell finds tmux in', async () => {+ const binDir = fakeTmux()+ const env: NodeJS.ProcessEnv = { PATH: '/nonexistent-for-this-test' }++ const outcome = await ensureTmuxOnPath(env, fakeShell(binDir))++ expect(outcome.state).toBe('adopted')+ if (outcome.state !== 'adopted') return+ expect(outcome.from).toBe(binDir)+ // The point of the whole exercise: every later execFile('tmux', …) now resolves.+ expect(env.PATH?.split(delimiter)[0]).toBe(binDir)+ expect(env.PATH).toContain('/nonexistent-for-this-test')+ })++ it('leaves an already-working PATH untouched', async () => {+ const binDir = fakeTmux()+ const env: NodeJS.ProcessEnv = { PATH: binDir }++ const outcome = await ensureTmuxOnPath(env, fakeShell(binDir))++ expect(outcome.state).toBe('present')+ // No duplicate entry: this runs on every start, so it has to be idempotent.+ expect(env.PATH).toBe(binDir)+ })++ it('reports absent when neither the daemon nor the shell can find tmux', async () => {+ const emptyBin = scratch('tmux-onpath-empty-')+ const env: NodeJS.ProcessEnv = { PATH: '/nonexistent-for-this-test' }++ const outcome = await ensureTmuxOnPath(env, fakeShell(emptyBin))++ expect(outcome.state).toBe('absent')+ expect(env.PATH).toBe('/nonexistent-for-this-test')+ })++ it('does not consult a shell it cannot trust', async () => {+ // A relative SHELL is not something to hand a command to.+ expect(await resolveViaLoginShell('tmux', 'sh')).toBeNull()+ })+ it('turns the reported failure into a working create', async () => {+ // A tmux that answers like the real one, in a directory the daemon's PATH does not list.+ const binDir = scratch('tmux-onpath-real-')+ const tmux = join(binDir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+case "$1" in+ new-session) printf '%%7\\n' ;;+esac+exit 0+`)+ chmodSync(tmux, 0o700)+ const shell = fakeShell(binDir)++ // Before: exactly what the machine reported after its reboot.+ process.env.PATH = '/nonexistent-for-this-test'+ const before = await new TmuxBackend().create({ cwd: '/tmp', label: 'harness-test' })+ expect(before.state).not.toBe('succeeded')+ if (before.state !== 'succeeded') expect(before.reason).toBe('tmux is unavailable')++ // After: the same call, once the daemon has been told where the user's shell finds tmux.+ expect((await ensureTmuxOnPath(process.env, shell)).state).toBe('adopted')+ const after = await new TmuxBackend().create({ cwd: '/tmp', label: 'harness-test' })++ expect(after).toEqual({+ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%7' },+ })+ })+})diff --git a/cli/src/lib/tmuxOnPath.ts b/cli/src/lib/tmuxOnPath.tsnew file mode 100644index 000000000..04b1de681--- /dev/null+++ b/cli/src/lib/tmuxOnPath.ts@@ -0,0 +1,76 @@+/**+ * Make `tmux` runnable from the daemon, not just from the user's terminal.+ *+ * Every tmux call in this CLI is `execFile('tmux', …)`, which resolves against the DAEMON's PATH.+ * That is fine while the daemon was started from a terminal and inherits the user's environment,+ * and it breaks the moment it is not: a login/launch-agent context gets a minimal PATH, Homebrew's+ * `/opt/homebrew/bin` is not on it, and every tmux call fails with ENOENT. The visible symptom is+ * agent creation failing for EVERY engine right after a reboot, since nothing else changed.+ *+ * The engine launch was already hardened against exactly this hazard — `buildEngineLaunchArgv`+ * wraps the engine in the user's interactive login shell — but the tmux calls underneath it never+ * were. This closes that asymmetry by asking the same shell where tmux is and putting its directory+ * on the daemon's PATH, once, at startup. Every existing `execFile('tmux', …)` then works unchanged.+ */+import { execFile } from 'node:child_process'+import { delimiter, dirname, isAbsolute } from 'node:path'+import { binaryOnPath } from './binaryOnPath.js'+import { interactiveEngineShell } from './engineLaunch.js'++// `$0` is a label, `$1` the command being resolved — the same positional shape the engine+// availability probe uses, so a command name can never be interpolated into shell source.+const RESOLVE_SCRIPT = 'command -v "$1" 2>/dev/null'++export type TmuxPathOutcome =+ /** Already resolvable; the daemon's PATH was left alone. */+ | { state: 'present'; path?: string }+ /** Found via the user's shell and its directory prepended to PATH. */+ | { state: 'adopted'; path: string; from: string }+ /** Not resolvable either way — tmux is genuinely absent, or there is no usable login shell. */+ | { state: 'absent'; reason: string }++/** Where the user's own interactive shell finds a command, which is not where the daemon looks. */+export async function resolveViaLoginShell(+ command: string,+ shell: string | undefined = undefined,+): Promise<string | null> {+ const interactive = interactiveEngineShell(shell)+ if (!interactive) return null+ return await new Promise<string | null>((resolve) => {+ execFile(+ interactive.path,+ [...interactive.args, RESOLVE_SCRIPT, 'harness-tmux-probe', command],+ { timeout: 5_000 },+ (error, stdout) => {+ const first = String(stdout ?? '').trim().split('\n')[0]?.trim() ?? ''+ resolve(!error && isAbsolute(first) ? first : null)+ },+ )+ })+}++/**+ * Idempotent: safe to call on every start, and a no-op when the daemon can already run tmux.+ *+ * The directory is PREPENDED rather than the binary path being threaded through call sites: the+ * tmux client and the tmux server have to agree on their socket, and a daemon that found tmux one+ * way while a helper found it another is how a machine ends up talking to two servers.+ */+export async function ensureTmuxOnPath(+ env: NodeJS.ProcessEnv = process.env,+ shell: string | undefined = undefined,+): Promise<TmuxPathOutcome> {+ if (binaryOnPath('tmux', env)) return { state: 'present' }+ const resolved = await resolveViaLoginShell('tmux', shell)+ if (!resolved) {+ return {+ state: 'absent',+ reason: interactiveEngineShell(shell)+ ? 'the user\'s login shell does not resolve tmux either'+ : 'no usable login shell to ask, and tmux is not on the daemon PATH',+ }+ }+ const dir = dirname(resolved)+ env.PATH = env.PATH ? `${dir}${delimiter}${env.PATH}` : dir+ return { state: 'adopted', path: resolved, from: dir }+}