Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(codex): SSH remote runtime install, account lifecycle, and the atomic remote import (S6 PR 6, Tasks 6.0–6.2)
enes20aeabcfe9ce
diff --git a/package.json b/package.jsonindex 27a5092a5..1beefe9cb 100644--- a/package.json+++ b/package.json@@ -11,7 +11,8 @@"main": "./out/main/index.js","scripts": {"dev": "electron-vite dev",- "build": "electron-vite build",+ "build": "electron-vite build && npm run build:codex-relay",+ "build:codex-relay": "node scripts/build-codex-relay.mjs","preview": "electron-vite preview","start": "electron-vite preview","typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json",diff --git a/scripts/build-codex-relay.mjs b/scripts/build-codex-relay.mjsnew file mode 100644index 000000000..93d3056a8--- /dev/null+++ b/scripts/build-codex-relay.mjs@@ -0,0 +1,28 @@+// Bundle the Codex relay daemon into a STANDALONE `codex-relay.js` that runs under a bare `node` on+// an SSH host — ws inlined, no node_modules required on the far side. This is the artifact the+// desktop uploads to a Linux host (`installRemoteCodexRuntime`); it is executable code only, never+// a credential (S6 Property 1). Runs AFTER `electron-vite build`, writing into `out/main/` so+// `codexRelaySource()` can read it beside the main entry (`path.join(__dirname, 'codex-relay.js')`)+// in both dev and a packaged asar, and so electron-builder's `out/**/*` picks it up.+//+// Unlike `server:build` (which keeps `ws` external because the server runs from a node_modules+// tree), this bundle inlines `ws` — the remote host has node but not our dependencies. Verified+// runnable over real SSH against codex-cli 0.146.0 (docs/superpowers/probes/2026-08-codex-ssh-remote.md).+import { build } from 'esbuild'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')++await build({+ entryPoints: [resolve(root, 'src/main/codex-relay-daemon.ts')],+ outfile: resolve(root, 'out/main/codex-relay.js'),+ bundle: true,+ platform: 'node',+ target: 'node20',+ format: 'cjs',+ // node-pty is never reached by the relay; keep it external so its native require() is not bundled.+ external: ['node-pty'],+ tsconfig: resolve(root, 'tsconfig.node.json'),+ logLevel: 'info'+})diff --git a/src/main/index.ts b/src/main/index.tsindex 75326063f..e7a03ffd4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2,7 +2,7 @@ import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'-import { existsSync, statSync } from 'fs'+import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, Notification, powerMonitor, safeStorage, shell, systemPreferences, webContents } from 'electron'@@ -398,6 +398,28 @@ wirePeerRegistry({// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters and// (via the closures below) to resolve a live SSH project's ControlMaster for remote workspace IO.let sshProjectManager: ReturnType<typeof initSshProject> | undefined++// The standalone Codex relay bundle (`out/main/codex-relay.js`, built by scripts/build-codex-relay.mjs+// after electron-vite build), uploaded to a Linux host for managed Codex accounts. Read once, beside+// the main entry so the same `__dirname` resolves in dev and inside a packaged asar. Single-fd read+// (open→fstat→read the SAME descriptor) — no stat-then-read on the path. Empty string on any miss so+// the SSH manager degrades to "no managed Codex runtime" instead of throwing.+let codexRelayBundleCache: string | undefined+async function loadCodexRelayBundle(): Promise<string> {+ if (codexRelayBundleCache !== undefined) return codexRelayBundleCache+ try {+ const fd = openSync(join(__dirname, 'codex-relay.js'), 'r')+ try {+ fstatSync(fd) // touch the open descriptor; the bundle is a plain file we just built+ codexRelayBundleCache = readFileSync(fd, 'utf8')+ } finally {+ closeSync(fd)+ }+ } catch {+ codexRelayBundleCache = ''+ }+ return codexRelayBundleCache+}// Remote SSH IO for the workspace store: mirrors each SSH project's <remoteCwd>/.nodeterm/project.json// over that project's live master. Resolves the ref lazily — the manager is created after the window// is ready — and fails open (no-op) while the project is disconnected.@@ -3128,7 +3150,14 @@ app.whenReady().then(async () => {}).catch(() => {// best-effort: a failed resync leaves the stale sweep as the backstop, exactly as today})- }+ },+ // The standalone relay bundle uploaded to a Linux host for managed Codex accounts (S6 PR 6).+ // Only executable code is ever uploaded — never a credential (Property 1). Reading it is+ // single-fd (openSync→fstatSync→readFileSync(fd)) so there is no stat-then-read TOCTOU on the+ // path, and the result is cached (the artifact never changes within an app run). A missing+ // artifact resolves to '' — `installRemoteCodexRuntime` treats an empty bundle as "no runtime"+ // and never fails a plain SSH connect over it.+ loadCodexRelayBundle)// Wake-from-sleep: re-validate every SSH master NOW instead of letting ServerAlive discover the// dead TCP ~60s later — until it does, every remote terminal looks alive and is dead (no echo,diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 5c5fbe32b..ac1c4a8e7 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -2110,3 +2110,228 @@ describe('SshProjectManager — per-node tokens on the host', () => {expect(run.mock.calls).toHaveLength(0)})})++// ── Managed remote Codex accounts (S6 PR 6) ──────────────────────────────────────────────────+// Every remote Codex op runs over the project's live ControlMaster with only executable code ever+// uploaded (Property 1), fails closed when the account/connection cannot be proven (Property 4),+// and lands a cross-machine import atomically without ever overwriting (Property 2 + 11). The fake+// `run` records every command string so these can argv-spy the exact shell issued.+const RELAY_BYTES = 'RELAY_BUNDLE_BYTES'+const NODE = '/usr/bin/node'+const CODEX = '/usr/bin/codex'++/** A connected manager whose conn has a resolved remoteHome + installed Codex runtime paths, plus a+ * recorder of every `run`/`runScp` command. `handler` overrides specific commands per test. */+async function makeCodexMgr(opts?: {+ home?: string+ handler?: (cmd: string, stdin?: string) => { code: number; stdout?: string } | undefined+}) {+ const home = opts?.home ?? '/home/u'+ const runCalls: { cmd: string; stdin?: string }[] = []+ const scpCalls: string[][] = []+ const run = vi.fn(async (args: string[], stdin?: string) => {+ const cmd = args.join(' ')+ runCalls.push({ cmd, stdin })+ if (cmd.includes('printf %s')) return { code: 0, stdout: home }+ if (cmd.includes('readlink -f')) return { code: 0, stdout: `${NODE}\n${CODEX}\n/usr/bin/curl` }+ const over = opts?.handler?.(cmd, stdin)+ if (over) return { code: over.code, stdout: over.stdout ?? '' }+ return { code: 0, stdout: '' }+ })+ const runScp = vi.fn(async (args: string[]) => {+ scpCalls.push(args)+ return { code: 0 }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run,+ runScp,+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ codexRelaySource: async () => RELAY_BYTES,+ onStatus: vi.fn()+ })+ const res = await mgr.connect('p1', conn, '/srv/repo')+ return { mgr, run, runScp, runCalls, scpCalls, res, home }+}++describe('SshProjectManager — managed remote Codex runtime install (Task 6.1, Property 1)', () => {+ it('uploads ONLY executable code — the relay bundle body + the launcher script — never a credential', async () => {+ const { res, runCalls } = await makeCodexMgr()+ // connect surfaced the runtime paths (node/codex/curl resolved, bundle uploaded).+ expect(res.codexRelayRuntimePath).toBe(NODE)+ expect(res.codexCliPath).toBe(CODEX)+ expect(res.codexRelayScriptPath).toBe('/home/u/.nodeterm/bin/codex-relay.js')+ expect(res.codexLauncherPath).toBe('/home/u/.nodeterm/bin/nodeterm-codex')+ // The relay file is written with the injected bundle bytes on stdin, chmod 700, under bin/.+ const relayWrite = runCalls.find((c) => c.cmd.includes('codex-relay.js') && c.cmd.includes('cat >'))+ expect(relayWrite?.stdin).toBe(RELAY_BYTES)+ expect(relayWrite?.cmd).toContain('chmod 700')+ // The launcher body is the generated sh script (starts with a shebang), never a credential.+ const launcherWrite = runCalls.find((c) => c.cmd.includes('nodeterm-codex') && c.cmd.includes('cat >'))+ expect(launcherWrite?.stdin?.startsWith('#!')).toBe(true)+ expect(launcherWrite?.cmd).toContain('chmod 700')+ // No command line or stdin body carries a bearer/authorization secret (GC 6 — tokens go via the+ // relay's env/header, never argv). auth.json is never uploaded.+ for (const { cmd, stdin } of runCalls) {+ expect(cmd).not.toMatch(/Authorization|Bearer|auth\.json.*cat|-H /)+ if (stdin && stdin !== RELAY_BYTES && !stdin.startsWith('#!')) {+ expect(stdin).not.toContain('auth.json')+ }+ }+ })++ it('installs no runtime (all paths undefined) when node/codex/curl do not all resolve', async () => {+ // curl missing → probe returns 2 lines → runtime declines, but the connect still succeeds.+ const run = vi.fn(async (args: string[]) => {+ const cmd = args.join(' ')+ if (cmd.includes('printf %s')) return { code: 0, stdout: '/home/u' }+ if (cmd.includes('readlink -f')) return { code: 0, stdout: `${NODE}\n${CODEX}` } // no curl+ return { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ codexRelaySource: async () => RELAY_BYTES,+ onStatus: vi.fn()+ })+ const res = await mgr.connect('p1', conn, '/srv/repo')+ expect(res.controlPath).toBeTruthy() // connect still succeeded+ expect(res.codexRelayScriptPath).toBeUndefined()+ expect(res.codexLauncherPath).toBeUndefined()+ })++ it('refuses to build any remote path from an UNSAFE remote home (newline injection — GC 7)', async () => {+ // A $HOME carrying a newline would append a command; isSafeRemoteHome rejects it, so the runtime+ // never installs and every account op refuses rather than run against a poisoned path.+ const { mgr, res } = await makeCodexMgr({ home: '/home/u\nrm -rf /' })+ expect(res.codexRelayScriptPath).toBeUndefined()+ await expect(mgr.remoteCodexAccountAdd('p1', 'acc1')).rejects.toThrow(/safe SSH host home/)+ })+})++describe('SshProjectManager — remote Codex account lifecycle (Task 6.1, Property 4)', () => {+ it('a remote op on a DISCONNECTED project refuses and never runs against the local system account', async () => {+ const { mgr, run } = await makeCodexMgr()+ const before = run.mock.calls.length+ await expect(mgr.remoteCodexAccountAdd('nope', 'acc1')).rejects.toThrow(/not connected/)+ await expect(+ mgr.remoteCodexImportThread('nope', 'acc1', 'threadid', 'sessions/a/b.jsonl', '/l/r.jsonl')+ ).rejects.toThrow(/not connected/)+ expect(run.mock.calls.length).toBe(before) // neither refusal issued any ssh+ })++ it('remoteCodexAccountIdentity returns null unless a specific account has a REAL non-symlink auth.json', async () => {+ // auth gate FAILS (no real login) even though account-read WOULD return an email → still null.+ const authFail = await makeCodexMgr({+ handler: (cmd) => {+ if (cmd.includes('test ! -L')) return { code: 1 } // auth.json missing or a symlink+ if (cmd.includes('account-read')) return { code: 0, stdout: '{"email":"[email protected]"}' }+ return undefined+ }+ })+ expect(await authFail.mgr.remoteCodexAccountIdentity('p1', 'acc1')).toBeNull()+ // auth gate PASSES → the real email is read back.+ const authOk = await makeCodexMgr({+ handler: (cmd) => {+ if (cmd.includes('test ! -L')) return { code: 0 }+ if (cmd.includes('account-read')) return { code: 0, stdout: '{"email":"[email protected]"}' }+ return undefined+ }+ })+ expect(await authOk.mgr.remoteCodexAccountIdentity('p1', 'acc1')).toEqual({+ email: '[email protected]'+ })+ })++ it('remoteCodexExposeThread surfaces the relay refusal for an ambiguous thread (Property 3)', async () => {+ const cm = await makeCodexMgr({+ handler: (cmd) => (cmd.includes('expose-thread') ? { code: 69 } : undefined)+ })+ const controlPath = cm.res.controlPath+ await expect(+ cm.mgr.remoteCodexExposeThread(controlPath, undefined, 'thread1', ['acc1'])+ ).rejects.toThrow(/unavailable or ambiguous/)+ })+})++describe('SshProjectManager — atomic remote import (Task 6.2, Property 2 + 11)', () => {+ const REL = 'sessions/2026/08/19/rollout-x.jsonl'++ it('validates the thread id and confines the rollout path to sessions/… (no traversal), no ssh on refusal', async () => {+ const { mgr, run, runScp } = await makeCodexMgr()+ const before = run.mock.calls.length+ await expect(+ mgr.remoteCodexImportThread('p1', undefined, 'bad id!', REL, '/l/r.jsonl')+ ).rejects.toThrow(/Invalid Codex thread id/)+ for (const bad of ['etc/passwd', 'sessions/../etc/x', 'sessions//x', '/abs/sessions/x']) {+ await expect(+ mgr.remoteCodexImportThread('p1', undefined, 'thread1', bad, '/l/r.jsonl')+ ).rejects.toThrow(/Invalid Codex rollout path/)+ }+ expect(run.mock.calls.length).toBe(before)+ expect(runScp.mock.calls.length).toBe(0)+ })++ it('no-ops (imported:false) and uploads NOTHING when the thread already exists on the target', async () => {+ const { mgr, runScp } = await makeCodexMgr({+ handler: (cmd) => (cmd.includes('thread-check') ? { code: 0 } : undefined) // already present+ })+ expect(await mgr.remoteCodexImportThread('p1', undefined, 'thread1', REL, '/l/r.jsonl')).toEqual({+ imported: false+ })+ expect(runScp.mock.calls.length).toBe(0)+ })++ it('installs atomically and NEVER overwrites: exit-17 guard present, mv is not forced', async () => {+ let phase = 0+ const cm = await makeCodexMgr({+ handler: (cmd) => {+ if (cmd.includes('thread-check')) return { code: phase++ === 0 ? 69 : 0 } // absent, then found+ return undefined+ }+ })+ const out = await cm.mgr.remoteCodexImportThread('p1', 'acc1', 'thread1', REL, '/l/r.jsonl')+ expect(out).toEqual({ imported: true })+ const install = cm.runCalls.find((c) => c.cmd.includes('exit 17'))+ expect(install).toBeTruthy()+ // The never-overwrite guard: refuse if the target exists, drop the staged file, exit 17.+ expect(install!.cmd).toMatch(/if \[ -e '[^']*rollout-x\.jsonl' \]; then rm -f '[^']*\.part'; exit 17; fi/)+ // The land is a bare `mv` (atomic within one fs), NEVER `mv -f` (which would clobber).+ expect(install!.cmd).toMatch(/(^| )mv '[^']*\.part' '[^']*rollout-x\.jsonl'/)+ expect(install!.cmd).not.toMatch(/mv -f /)+ })++ it('refuses when the install hits an existing target (exit 17 surfaces as a refusal)', async () => {+ const { mgr } = await makeCodexMgr({+ handler: (cmd) => {+ if (cmd.includes('thread-check')) return { code: 69 } // absent everywhere+ if (cmd.includes('exit 17')) return { code: 17 } // target already exists on the host+ return undefined+ }+ })+ await expect(+ mgr.remoteCodexImportThread('p1', 'acc1', 'thread1', REL, '/l/r.jsonl')+ ).rejects.toThrow(/already exists or could not be installed/)+ })++ it('verify-before-recycle: rolls the staged file back and refuses when the far side cannot discover it', async () => {+ const seen: string[] = []+ const { mgr } = await makeCodexMgr({+ handler: (cmd) => {+ seen.push(cmd)+ if (cmd.includes('thread-check')) return { code: 69 } // never discovered — before OR after install+ if (cmd.includes('exit 17')) return { code: 0 } // install succeeds+ return undefined+ }+ })+ await expect(+ mgr.remoteCodexImportThread('p1', 'acc1', 'thread1', REL, '/l/r.jsonl')+ ).rejects.toThrow(/did not discover the imported conversation/)+ // The rollback removed the freshly installed target — no half-landed state.+ expect(seen.some((c) => /rm -f '[^']*rollout-x\.jsonl'/.test(c))).toBe(true)+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 5cf630b76..d557cb72d 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -41,6 +41,13 @@ import { setRemoteSessionEnvWriter } from '../../core/remote-ssh/session-env'import { askpassServer } from './ssh-askpass'import { appSshAgent } from './ssh-agent'import { sessionName } from '../../core/tmux-naming'+import { buildCodexLauncherScript } from '../../core/codex-identity-proxy'+import {+ ACCOUNT_ID_RE,+ assertCodexAccountId,+ remoteCodexHome,+ remoteCodexSocket+} from '../../core/codex-accounts-core'interface Runners {userDataDir: string@@ -69,6 +76,11 @@ interface Runners {runScp: (args: string[]) => Promise<{ code: number }>/** Live loopback hook-server coordinates (injected so the manager stays testable). */getHook: () => { port: number; token: string; version: string }+ /** The standalone relay bundle (ws inlined) uploaded to a Linux host as `codex-relay.js`. Only+ * EXECUTABLE code is ever uploaded — never a credential (Property 1 / GC 6). Injected so the+ * manager stays a pure unit and so a host without the built artifact simply gets no managed+ * Codex runtime rather than a crash. Undefined keeps every non-Codex SSH path unchanged. */+ codexRelaySource?: () => Promise<string>onStatus: (e: SshProjectStatusEvent) => void/** Delays between claude-probe retries after a FAILED attempt (claude not found). Injected so* tests don't wait on real backoff; production uses PROBE_RETRY_DELAYS_MS. */@@ -199,10 +211,80 @@ export interface ConnectResult {hookEndpointPath?: stringtmuxConfPath?: stringremoteHome?: string+ codexLauncherPath?: string+ codexRelayScriptPath?: string+ codexRelayRuntimePath?: string+ codexCliPath?: stringclaudeAutoPermissionMode?: booleanremoteClaudeVersion?: string | null}+/**+ * Shared runtime assets (installation, not credentials) symlinked from the system Codex home into+ * a managed account home so a managed login sees the same config/skills/plugins without sharing its+ * credential jar or thread SQLite DB. Mirrors `SHARED_ENTRIES` in `codex-accounts.ts`; kept in+ * lock-step by hand because that list lives in an Electron-only module this core-adjacent builder+ * must not import. `auth.json` is deliberately NOT here (each home owns its own — §2.1).+ */+const REMOTE_CODEX_SHARED_ENTRIES = [+ 'config.toml',+ 'AGENTS.md',+ 'skills',+ 'plugins',+ 'packages',+ 'rules',+ 'hooks.json'+] as const++/**+ * The `sh` that creates one isolated managed Codex home on the host: `umask 077` mkdir + `chmod+ * 700`, then symlink each shared runtime asset in from the system home (installation shared,+ * credentials never). Each failure prints a `NODETERM_CODEX_ACCOUNT_SETUP:<phase>` marker and exits+ * non-zero so the caller can name the phase. `remoteHome` MUST already be `isSafeRemoteHome`-checked+ * by the caller — a `$HOME` with a newline would append a command here (GC 7).+ * Based on @Corvin's `remoteCodexAccountSetupCommand` in PR #112.+ */+export function remoteCodexAccountSetupCommand(remoteHome: string, accountId: string): string {+ const home = remoteCodexHome(remoteHome, accountId)+ const system = remoteCodexHome(remoteHome)+ const shared = REMOTE_CODEX_SHARED_ENTRIES.map(+ (name) =>+ `if [ -e ${posixQuote(`${system}/${name}`)} ] && [ ! -e ${posixQuote(`${home}/${name}`)} ]; then ln -s ${posixQuote(`${system}/${name}`)} ${posixQuote(`${home}/${name}`)} || { printf '%s\\n' ${posixQuote(`NODETERM_CODEX_ACCOUNT_SETUP:link:${name}`)}; exit 71; }; fi;`+ ).join(' ')+ return `umask 077; mkdir -p ${posixQuote(home)} && chmod 700 ${posixQuote(home)} || { printf '%s\\n' 'NODETERM_CODEX_ACCOUNT_SETUP:home'; exit 70; }; ${shared}`+}++/**+ * The `sh` that guarantees exactly one persistent Codex `app-server` per remote `CODEX_HOME`.+ * Official standalone installs use the daemon manager (`app-server daemon start`); a plain npm/global+ * install cannot (it refuses without `<CODEX_HOME>/packages/standalone/current/codex`), so this+ * falls back to a single lock-guarded `nohup codex app-server --listen "unix://<sock>"` and reuses+ * its socket + pid across every node on the account. The fallback is LIVE-VERIFIED against+ * codex-cli 0.146.0 (see docs/superpowers/probes/2026-08-codex-ssh-remote.md — the `--listen` path+ * binds `<CODEX_HOME>/app-server-control/app-server-control.sock` on a plain npm install).+ * No credential is ever on this command line (GC 6). Based on @Corvin's PR #112.+ */+export function remoteCodexAppServerStartCommand(runtime: string, codexCli: string): string {+ if (!path.posix.isAbsolute(runtime) || !path.posix.isAbsolute(codexCli)) {+ throw new Error('Remote Codex runtime paths must be absolute')+ }+ const node = posixQuote(runtime)+ const codex = posixQuote(codexCli)+ return (+ `${node} ${codex} app-server daemon start >/dev/null 2>&1 || { ` ++ `nt_as_dir="$CODEX_HOME/app-server-control"; nt_as_sock="$nt_as_dir/app-server-control.sock"; nt_as_pid="$nt_as_dir/nodeterm-direct.pid"; nt_as_lock="$nt_as_dir/nodeterm-start.lock"; ` ++ `mkdir -p "$nt_as_dir" && chmod 700 "$nt_as_dir" || exit 70; ` ++ `nt_as_live=; if [ -S "$nt_as_sock" ] && [ -f "$nt_as_pid" ]; then nt_as_old_pid=$(cat "$nt_as_pid" 2>/dev/null || true); case "$nt_as_old_pid" in ''|*[!0-9]*) ;; *) kill -0 "$nt_as_old_pid" 2>/dev/null && nt_as_live=1 ;; esac; fi; ` ++ `if [ -z "$nt_as_live" ] && mkdir "$nt_as_lock" 2>/dev/null; then ` ++ `rm -f "$nt_as_sock" "$nt_as_pid"; ` ++ `CODEX_HOME="$CODEX_HOME" nohup ${node} ${codex} app-server --listen "unix://$nt_as_sock" </dev/null >"$nt_as_dir/nodeterm-direct.log" 2>&1 & echo $! >"$nt_as_pid"; ` ++ `rmdir "$nt_as_lock"; fi; ` ++ `nt_as_i=0; while [ ! -S "$nt_as_sock" ] && [ "$nt_as_i" -lt 50 ]; do sleep 0.1; nt_as_i=$((nt_as_i + 1)); done; ` ++ `[ -S "$nt_as_sock" ]; ` ++ `}`+ )+}+interface Conn {conn: SshConnectioncontrolPath: string@@ -215,6 +297,14 @@ interface Conn {/** The remote `$HOME`, resolved at connect. Used (Phase 2b) to jail remote transcript reads* under `<remoteHome>/.claude/projects`. Undefined if it couldn't be resolved (fail-open). */remoteHome?: string+ /** Managed-Codex runtime paths staged at connect by `installRemoteCodexRuntime`. All undefined+ * (the pre-Codex behavior) when node/codex/curl didn't resolve, no `codexRelaySource` was+ * injected, or the upload failed — a host that simply cannot host managed Codex accounts, never a+ * failed connect. `codexRelayRuntimePath` is the host's own Node; `codexCliPath` is `codex`. */+ codexLauncherPath?: string+ codexRelayScriptPath?: string+ codexRelayRuntimePath?: string+ codexCliPath?: string/** The project's remote repo cwd (Phase 4). Lets `refForRemoteCwd` route remote git ops to this* connection's master. Undefined when the project has no folder selected. */remoteCwd?: string@@ -409,6 +499,10 @@ export class SshProjectManager {hookEndpointPath: existing.hookEndpointPath,tmuxConfPath: existing.tmuxConfPath,remoteHome: existing.remoteHome,+ codexLauncherPath: existing.codexLauncherPath,+ codexRelayScriptPath: existing.codexRelayScriptPath,+ codexRelayRuntimePath: existing.codexRelayRuntimePath,+ codexCliPath: existing.codexCliPath,claudeAutoPermissionMode: existing.claudeAutoPermissionMode,remoteClaudeVersion: existing.remoteClaudeVersion}@@ -598,6 +692,18 @@ export class SshProjectManager {// Same not-awaited best-effort terms as the two installs.void this.materialiseNodeTokens(projectId, conn, controlPath, remoteHome)}+ // Managed-Codex runtime: upload the relay bundle + launcher and probe node/codex/curl.+ // Deliberately gated on `remoteHome` ALONE, not on `hookEndpointPath` — account isolation ++ // a shared app-server need only the launcher/relay, never the canvas hooks, and the reverse+ // hook tunnel can be legitimately unavailable on an otherwise healthy host (the Ubuntu/WSL+ // case). Gating this on the tunnel made "Add Codex account" fail even when node, codex, curl,+ // SSH and the account filesystem were all usable. AWAITED (unlike the hook installs above):+ // the paths must be on `entry` before this connect reports `connected`, so a Codex node that+ // launches immediately after resolves its runtime. Install-only-executable-code (Property 1):+ // `installRemoteCodexRuntime` uploads the relay JS + launcher and NOTHING else.+ const codexRuntime = remoteHome+ ? await this.installRemoteCodexRuntime(conn, controlPath, remoteHome)+ : null// Same ownership check the failure path makes below, and for the same reason: the setup// above is several remote round-trips, and a disconnect + reconnect inside that window// leaves a DIFFERENT attempt's master in the map. Writing this attempt's results onto it@@ -610,6 +716,10 @@ export class SshProjectManager {entry.hookEndpointPath = hookEndpointPathentry.remoteHome = remoteHomeentry.tmuxConfPath = tmuxConfPath+ entry.codexLauncherPath = codexRuntime?.launcher+ entry.codexRelayScriptPath = codexRuntime?.relay+ entry.codexRelayRuntimePath = codexRuntime?.runtime+ entry.codexCliPath = codexRuntime?.codexthis.r.onStatus({ projectId, status: 'connected' })// The tunnel is live again on a master we just established (the reuse branch returned long// before this line), so this is exactly the moment the hook events lost while it was down@@ -655,6 +765,10 @@ export class SshProjectManager {hookEndpointPath,tmuxConfPath,remoteHome,+ codexLauncherPath: entry?.codexLauncherPath,+ codexRelayScriptPath: entry?.codexRelayScriptPath,+ codexRelayRuntimePath: entry?.codexRelayRuntimePath,+ codexCliPath: entry?.codexCliPath,claudeAutoPermissionMode: entry?.claudeAutoPermissionMode,remoteClaudeVersion: entry?.remoteClaudeVersion}@@ -1271,6 +1385,336 @@ export class SshProjectManager {return undefined}+ // ── Managed REMOTE Codex accounts (S6 PR 6) ───────────────────────────────────────────────+ // The DESKTOP drives the whole remote leg over the project's live ControlMaster: it uploads only+ // executable code (the relay bundle + launcher) and runs `codex`/relay subcommands with+ // `childArgs`. The SSH host is a dumb target — it runs plain `codex` + `node` + the uploaded+ // relay JS, and needs NO nodeterm-side account handlers (I2 resolved: no Server-Edition bridge+ // handlers for the remote leg — see the PR body). A remote `$HOME` is DATA: every method that+ // builds an absolute remote path re-validates it with `isSafeRemoteHome` first (GC 7), because a+ // `$HOME` carrying a newline would otherwise append a command. Based on @Corvin's PR #112.++ /** Guard a connection's remote home before it becomes an absolute remote path. `isSafeRemoteHome`+ * rejects a `$HOME` that is relative, over-long, or carries a control char / newline (GC 7). */+ private codexRemoteHome(c: Conn | undefined): string {+ if (!c) throw new Error('SSH host is not connected')+ if (!isSafeRemoteHome(c.remoteHome)) {+ throw new Error('Could not resolve a safe SSH host home directory')+ }+ return c.remoteHome as string+ }++ private connByControlPath(controlPath: string): Conn | undefined {+ for (const c of this.conns.values()) if (c.controlPath === controlPath) return c+ return undefined+ }++ /** Create one isolated managed Codex home on the host (umask-077 mkdir + shared-asset symlinks).+ * Never uploads a credential — the account's `auth.json` is created ON the host by a later+ * device login. Returns the remote home, or throws with the named failure phase. */+ async remoteCodexAccountAdd(+ projectId: string,+ accountId: string+ ): Promise<{ home: string } | null> {+ assertCodexAccountId(accountId)+ const c = this.conns.get(projectId)+ const remoteHome = this.codexRemoteHome(c)+ const home = remoteCodexHome(remoteHome, accountId)+ const { code, stdout } = await this.r.run(+ childArgs(c!.conn, c!.controlPath, remoteCodexAccountSetupCommand(remoteHome, accountId))+ )+ if (code !== 0) {+ const marker = stdout+ .split(/\r?\n/)+ .find((line) => /^NODETERM_CODEX_ACCOUNT_SETUP:(?:home|link:[A-Za-z0-9._-]+)$/.test(line))+ const phase = marker?.slice('NODETERM_CODEX_ACCOUNT_SETUP:'.length) ?? 'remote command'+ throw new Error(+ `Could not create the isolated Codex account directory (${phase}; SSH exit ${code})`+ )+ }+ return { home }+ }++ /**+ * Read a managed remote account's ChatGPT identity by asking its own app-server `account/read`.+ * A managed account (has an id) must own a REAL `auth.json` — a file, not a symlink (the shared+ * assets are symlinked; the credential is not) — before this reports anything, so a home with no+ * device login yet returns null instead of leaking the system login's identity. The system+ * account (no id) reads its own `~/.codex`. Never uploads or downloads a credential.+ */+ async remoteCodexAccountIdentity(+ projectId: string,+ accountId?: string+ ): Promise<{ email: string | null } | null> {+ if (accountId) assertCodexAccountId(accountId)+ const c = this.conns.get(projectId)+ if (!c || !isSafeRemoteHome(c.remoteHome)) return null+ if (!c.codexRelayScriptPath || !c.codexRelayRuntimePath || !c.codexCliPath) return null+ const remoteHome = c.remoteHome as string+ const home = remoteCodexHome(remoteHome, accountId)+ if (accountId) {+ // A managed account's identity is gated on a REAL, non-symlink auth.json: the shared runtime+ // assets are symlinks, the credential jar is never — so `test -f && test ! -L` is what+ // distinguishes "this account has actually logged in" from "it inherited a shared config".+ const auth = await this.r.run(+ childArgs(+ c.conn,+ c.controlPath,+ `test -f ${posixQuote(`${home}/auth.json`)} && test ! -L ${posixQuote(`${home}/auth.json`)}`+ )+ )+ if (auth.code !== 0) return null+ }+ const socket = remoteCodexSocket(remoteHome, accountId)+ const start = remoteCodexAppServerStartCommand(c.codexRelayRuntimePath, c.codexCliPath)+ const command = `CODEX_HOME=${posixQuote(home)} ${start} && ${posixQuote(c.codexRelayRuntimePath)} ${posixQuote(c.codexRelayScriptPath)} account-read ${posixQuote(socket)}`+ const result = await this.r.run(childArgs(c.conn, c.controlPath, command))+ if (result.code !== 0) return null+ try {+ const parsed = JSON.parse(result.stdout) as { email?: unknown }+ return { email: typeof parsed.email === 'string' ? parsed.email : null }+ } catch {+ return null+ }+ }++ /** Stop the account's app-server and delete its home (credential jar included). Runs entirely on+ * the host — the credential never travels. No-op false when not connected. */+ async remoteCodexAccountRemove(projectId: string, accountId: string): Promise<boolean> {+ assertCodexAccountId(accountId)+ const c = this.conns.get(projectId)+ if (!c || !isSafeRemoteHome(c.remoteHome)) return false+ const home = remoteCodexHome(c.remoteHome as string, accountId)+ const stop = c.codexCliPath+ ? `CODEX_HOME=${posixQuote(home)} ${posixQuote(c.codexCliPath)} app-server daemon stop >/dev/null 2>&1 || true; `+ : ''+ const command = `${stop}rm -rf -- ${posixQuote(home)}`+ return (await this.r.run(childArgs(c.conn, c.controlPath, command))).code === 0+ }++ /**+ * Install ONLY executable code (Property 1 / GC 6): the standalone relay bundle + the launcher.+ * One relay process later serves every node on this host; account separation stays CODEX_HOME ++ * one app-server socket per account. Gated on node + codex + curl all resolving through+ * `readlink -f` (the launcher shells `curl`; the relay + app-server run under the host's node).+ * Returns null — never throws — when the host cannot host managed Codex accounts, so a plain SSH+ * connect is never failed by this.+ */+ private async installRemoteCodexRuntime(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string+ ): Promise<{ launcher: string; relay: string; runtime: string; codex: string } | null> {+ if (!this.r.codexRelaySource) return null+ if (!isSafeRemoteHome(remoteHome)) return null+ // Resolve node/codex/curl through the login shell, then `readlink -f` each to an absolute real+ // path (a shell alias / nvm shim would not survive into a non-interactive relay launch). All+ // three must resolve; curl backs the launcher's token POSTs.+ const probe = await this.r.run(+ childArgs(+ conn,+ controlPath,+ `$SHELL -lc ${posixQuote('nt_node=$(command -v node) && readlink -f "$nt_node"; nt_codex=$(command -v codex) && readlink -f "$nt_codex"; nt_curl=$(command -v curl) && readlink -f "$nt_curl"')}`+ )+ )+ const lines = probe.code === 0 ? probe.stdout.trim().split(/\r?\n/) : []+ const runtime = lines[0]+ const codex = lines[1]+ if (!runtime?.startsWith('/') || !codex?.startsWith('/') || lines.length < 3) return null+ const dir = `${remoteHome}/.nodeterm/bin`+ const launcher = `${dir}/nodeterm-codex`+ const relay = `${dir}/codex-relay.js`+ const source = await this.r.codexRelaySource()+ // The relay bundle is written to the host over the SSH ControlMaster (`childArgs` → the+ // multiplexed ssh child, body on stdin). CodeQL note: this file-data→network write is confined+ // to the authenticated SSH transport, and the payload is our OWN executable bundle, never a+ // credential (Property 1). `chmod 700` — owner-only, executable code.+ const writeRelay = await this.r.run(+ childArgs(+ conn,+ controlPath,+ `umask 077; mkdir -p ${posixQuote(dir)} && cat > ${posixQuote(relay)} && chmod 700 ${posixQuote(relay)}`+ ),+ source+ )+ if (writeRelay.code !== 0) return null+ // The launcher embeds the app-server start command (absolute node + codex only, no secret). Same+ // SSH-tunnel-confined write; still only executable code.+ const writeLauncher = await this.r.run(+ childArgs(+ conn,+ controlPath,+ `umask 077; cat > ${posixQuote(launcher)} && chmod 700 ${posixQuote(launcher)}`+ ),+ buildCodexLauncherScript(remoteCodexAppServerStartCommand(runtime, codex))+ )+ return writeLauncher.code === 0 ? { launcher, relay, runtime, codex } : null+ }++ /** Ensure one app-server is live for the system account plus each named managed account, and+ * return their control-socket paths. Every id is validated before it becomes a path; the runtime+ * must be installed or this throws (the remote leg is unavailable, never silently degraded). */+ async remoteCodexCatalog(+ controlPath: string,+ accountIds: string[]+ ): Promise<Array<{ accountId?: string; socketPath: string }>> {+ const c = this.connByControlPath(controlPath)+ if (!c || !isSafeRemoteHome(c.remoteHome)) throw new Error('SSH Codex host is unavailable')+ for (const id of accountIds) assertCodexAccountId(id)+ if (!c.codexCliPath || !c.codexRelayRuntimePath) throw new Error('SSH Codex CLI is unavailable')+ const remoteHome = c.remoteHome as string+ const ids: Array<string | undefined> = [undefined, ...accountIds]+ for (const id of ids) {+ const home = remoteCodexHome(remoteHome, id)+ const startCommand = remoteCodexAppServerStartCommand(c.codexRelayRuntimePath, c.codexCliPath)+ const start = await this.r.run(+ childArgs(c.conn, c.controlPath, `CODEX_HOME=${posixQuote(home)} ${startCommand}`)+ )+ if (start.code !== 0) throw new Error('SSH Codex app-server is unavailable')+ }+ return ids.map((accountId) => ({+ accountId,+ socketPath: remoteCodexSocket(remoteHome, accountId)+ }))+ }++ /** Does the account's app-server already know this thread? The relay's `thread-check` does a live+ * `thread/read` and exits 0 only when the far side reports the thread with an absolute path+cwd —+ * the verify-before-recycle primitive (§4.2 step 4). Fail-closed false on any bad input / miss. */+ async remoteCodexThreadExists(+ controlPath: string,+ accountId: string | undefined,+ threadId: string+ ): Promise<boolean> {+ if (accountId) assertCodexAccountId(accountId)+ if (!ACCOUNT_ID_RE.test(threadId)) return false+ const c = this.connByControlPath(controlPath)+ if (!c || !isSafeRemoteHome(c.remoteHome)) return false+ if (!c.codexRelayRuntimePath || !c.codexRelayScriptPath) return false+ const socket = remoteCodexSocket(c.remoteHome as string, accountId)+ const command = `${posixQuote(c.codexRelayRuntimePath)} ${posixQuote(c.codexRelayScriptPath)} thread-check ${posixQuote(socket)} ${posixQuote(threadId)}`+ return (await this.r.run(childArgs(c.conn, c.controlPath, command))).code === 0+ }++ /** Cross-account expose ON THE HOST: hardlink the one authoritative rollout for `threadId` into+ * the target account and verify the target app-server can discover it. The relay's `expose-thread`+ * fails closed (non-zero) when the thread is ambiguous (more than one distinct rollout inode+ * across catalogs) or unavailable — this surfaces that as a thrown refusal (Property 3). */+ async remoteCodexExposeThread(+ controlPath: string,+ accountId: string | undefined,+ threadId: string,+ accountIds: string[]+ ): Promise<void> {+ const c = this.connByControlPath(controlPath)+ if (!c || !isSafeRemoteHome(c.remoteHome) || !c.codexRelayRuntimePath || !c.codexRelayScriptPath) {+ throw new Error('SSH Codex runtime is unavailable')+ }+ const catalog = await this.remoteCodexCatalog(controlPath, accountIds)+ const target = remoteCodexSocket(c.remoteHome as string, accountId)+ const args = catalog.map((entry) => posixQuote(entry.socketPath)).join(' ')+ const command = `${posixQuote(c.codexRelayRuntimePath)} ${posixQuote(c.codexRelayScriptPath)} expose-thread ${posixQuote(target)} ${posixQuote(threadId)} ${args}`+ if ((await this.r.run(childArgs(c.conn, c.controlPath, command))).code !== 0) {+ throw new Error('SSH Codex session is unavailable or ambiguous')+ }+ }++ /**+ * Atomic remote import (Property 2 + 11): copy one authoritative LOCAL rollout into a remote+ * account home so its conversation id survives the machine hop. The source stays untouched; the+ * remote write is STAGED under `~/.nodeterm/codex-imports/<token>.part` and installed into+ * `CODEX_HOME/<sessionsRelativePath>` only after scp completes.+ *+ * The discipline PR 3 enforced locally, now over SSH:+ * - **No-op if the thread already exists** on the target (never re-import).+ * - **Never overwrite** an existing remote target: the install `sh` `exit 17`s if the path is+ * already present, and this surfaces `exit 17` as a refusal — a partial/racing import can never+ * corrupt a target account's rollout.+ * - **Verify-before-recycle:** after install, re-catalog and re-check discoverability; if the far+ * side cannot see the thread, ROLL THE STAGED FILE BACK and refuse — no half-landed state.+ *+ * Argument order + `{ imported }` return match the `CodexSshImporter` contract PR 5 typed against+ * (the source-leg planner hands off here). `imported: false` is the already-present no-op;+ * `imported: true` means a fresh, verified land.+ */+ async remoteCodexImportThread(+ projectId: string,+ accountId: string | undefined,+ threadId: string,+ sessionsRelativePath: string,+ localRolloutPath: string+ ): Promise<{ imported: boolean }> {+ if (accountId) assertCodexAccountId(accountId)+ if (!ACCOUNT_ID_RE.test(threadId)) throw new Error('Invalid Codex thread id')+ // The relative path is renderer/main-supplied but ends up as a remote absolute path, so it is+ // confined to `sessions/…` with no absolute segment and no `.`/`..`/empty component (traversal+ // guard — the host layout U7 proves `sessions/` is a sibling of the socket under CODEX_HOME).+ if (+ !sessionsRelativePath.startsWith('sessions/') ||+ path.posix.isAbsolute(sessionsRelativePath) ||+ sessionsRelativePath+ .split('/')+ .some((segment) => !segment || segment === '.' || segment === '..')+ ) {+ throw new Error('Invalid Codex rollout path')+ }+ const c = this.conns.get(projectId)+ const remoteHome = this.codexRemoteHome(c)+ if (await this.remoteCodexThreadExists(c!.controlPath, accountId, threadId)) {+ return { imported: false }+ }++ const target = `${remoteCodexHome(remoteHome, accountId)}/${sessionsRelativePath}`+ const targetDir = target.slice(0, target.lastIndexOf('/'))+ const token = `${Date.now().toString(36)}${(this.uploadSeq++).toString(36)}`+ const stagingDir = `${remoteHome}/.nodeterm/codex-imports`+ const staging = `${stagingDir}/${token}.part`+ const prepared = await this.r.run(+ childArgs(+ c!.conn,+ c!.controlPath,+ `mkdir -p ${posixQuote(stagingDir)} && chmod 700 ${posixQuote(stagingDir)}`+ )+ )+ if (prepared.code !== 0) throw new Error('Could not prepare remote Codex import')+ // Upload the LOCAL rollout to a private staging path over the SSH ControlMaster. CodeQL note:+ // this file-data→network transfer is confined to the authenticated SSH transport; the rollout is+ // conversation data the user is deliberately moving to a host they own, never a credential.+ const uploaded = await this.r.runScp(scpArgs(c!.conn, c!.controlPath, localRolloutPath, staging))+ if (uploaded.code !== 0) {+ await this.r+ .run(childArgs(c!.conn, c!.controlPath, `rm -f ${posixQuote(staging)}`))+ .catch(() => {})+ throw new Error('Could not upload Codex conversation')+ }+ // Atomic install that REFUSES to overwrite: if the target already exists, drop the staged file+ // and `exit 17` (never clobber a remote rollout — Property 2/11). Only on a clear target does the+ // `mv` (atomic within one filesystem) land it, `chmod 600` (credential-adjacent conversation).+ const installed = await this.r.run(+ childArgs(+ c!.conn,+ c!.controlPath,+ `if [ -e ${posixQuote(target)} ]; then rm -f ${posixQuote(staging)}; exit 17; fi; ` ++ `mkdir -p ${posixQuote(targetDir)} && chmod 700 ${posixQuote(targetDir)} && ` ++ `mv ${posixQuote(staging)} ${posixQuote(target)} && chmod 600 ${posixQuote(target)}`+ )+ )+ if (installed.code !== 0) {+ throw new Error('Remote Codex conversation already exists or could not be installed')+ }+ // Verify-before-recycle: re-catalog so a running app-server re-reads its index, then re-check+ // discoverability. If the far side still cannot see the thread, roll the staged file back and+ // refuse — the caller must never recycle a node onto a half-landed import (§4.2 step 4).+ await this.remoteCodexCatalog(c!.controlPath, accountId ? [accountId] : [])+ if (!(await this.remoteCodexThreadExists(c!.controlPath, accountId, threadId))) {+ await this.r+ .run(childArgs(c!.conn, c!.controlPath, `rm -f ${posixQuote(target)}`))+ .catch(() => {})+ throw new Error('Remote Codex app-server did not discover the imported conversation')+ }+ return { imported: true }+ }+// ── Managed REMOTE Claude accounts (Task 12) ──────────────────────────────────────────────// These run over the project's live master. Every op no-ops (null / silently) when the project// isn't connected, so the renderer's account list stays authoritative and fails open.@@ -1578,7 +2022,12 @@ export function initSshProject(/** Passed straight through to the manager's `onTunnelVerified` (see Runners). It lives on the* caller because the resync it drives needs main's agent-status funnel and transcript readers,* none of which this module knows about. */- onTunnelVerified?: (projectId: string, controlPath: string, conn: SshConnection) => void+ onTunnelVerified?: (projectId: string, controlPath: string, conn: SshConnection) => void,+ /** Resolves the standalone relay bundle (`out/main/codex-relay.js`, ws inlined) to upload to a+ * Linux host. Injected by the caller (main/index.ts) so this module reads no build artifact+ * itself. Undefined ⇒ no managed Codex runtime is installed, and every non-Codex path is+ * unchanged (Server Edition passes nothing today — see the PR's I2 decision). */+ codexRelaySource?: () => Promise<string>): SshProjectManager {const ssh = sshBin()const scp = scpBin()@@ -1675,6 +2124,7 @@ export function initSshProject()}),getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),+ codexRelaySource,// Per-node identity for REMOTE nodes. Both come from the same module the local materialiser// uses, so one canvas cannot be judged by two different rules depending on where it runs.nodeIdsForProject: (projectId) => nodeIdsForCanvas(projectId),