Skip to content

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.

Merge remote-tracking branch 'origin/main' into feat/windows-path-semantics

enesbdc7b4b51448
diff --cc src/main/remote-ssh/remote-hooks.test.ts
index 31fee9b13,0c0a93540..155d18e11
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@@ -54,17 -51,8 +54,17 @@@ describe('RemoteHooks.setup', () =>
const joined = calls.map((c) => c.args.join(' '))
// reverse forward binds the ABSOLUTE remote socket (no unexpanded ~).
expect(joined.some((j) => j.includes('-O forward') && j.includes('/home/u/.nodeterm/hook-p1.sock:127.0.0.1:51234'))).toBe(true)
- // endpoint file written to the absolute PER-PROJECT path, with the absolute sock + token.
- expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/hook-endpoint-p1.env'`))).toBe(true)
+ // Endpoint bearer goes to a private, invocation-owned temp and is then published atomically.
- const endpointWrite = calls.find((c) => (c.stdin ?? '').includes('NODETERM_HOOK_TOKEN=tok'))
++ const endpointWrite = calls.find((c) => (c.stdin ?? '').includes("NODETERM_HOOK_TOKEN='tok'"))
+ const endpointTemp = endpointWrite?.cmd.match(
+ /cat > ('\/home\/u\/\.nodeterm\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
+ )?.[1]
+ expect(endpointTemp).toBeTruthy()
+ expect(endpointWrite?.cmd).toContain(`chmod 600 -- ${endpointTemp}`)
+ expect(endpointWrite?.cmd).toContain(
+ `mv -f -- ${endpointTemp} '/home/u/.nodeterm/hook-endpoint-p1.env'`
+ )
+ expect(endpointWrite?.cmd).toContain(`rm -f -- ${endpointTemp}`)
expect(
calls.some(
(c) =>
diff --cc src/main/remote-ssh/ssh-project.ts
index 4b06f0c96,c448227e1..866ea706a
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@@ -43,7 -42,13 +43,14 @@@ import { setRemoteSessionEnvWriter } fr
import { askpassServer } from './ssh-askpass'
import { appSshAgent } from './ssh-agent'
import { sessionName } from '../../core/tmux-naming'
+import { remoteAtomicWrite } from '../remote-atomic-write'
+ import { buildCodexLauncherScript } from '../../core/codex-identity-proxy'
+ import {
+ ACCOUNT_ID_RE,
+ assertCodexAccountId,
+ remoteCodexHome,
+ remoteCodexSocket
+ } from '../../core/codex-accounts-core'
interface Runners {
userDataDir: string
@@@ -1400,6 -1418,344 +1546,344 @@@ 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` uses `ln` (hardlink), which
+ * fails ATOMICALLY with `EEXIST` when the target exists — the same never-overwrite primitive as
+ * PR 3's local `linkSync`, with no check-then-act race. `mv` is deliberately NOT used (it would
+ * silently clobber). 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 token = randomUUID()
+ 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 NEVER overwrites — the same discipline as PR 3's local `linkSync`
+ // (`commitCodexRolloutExposure`), now over SSH: `ln` (hardlink) is used, NOT `mv`, precisely
+ // because POSIX `mv` SILENTLY overwrites its destination. `link(2)` instead fails atomically
+ // with `EEXIST` (non-zero) when the target already exists — there is no check-then-act window a
+ // concurrent writer could race (a bare `[ -e ] && mv` would have one). Same-filesystem holds:
+ // staging (`$HOME/.nodeterm/codex-imports`) and target (`$HOME/.nodeterm/cx/<digest>/sessions`
+ // or `$HOME/.codex/sessions`) are both under the host `$HOME`; a cross-device `ln` (`EXDEV`)
+ // also fails closed here (exit 17), it is never silently copied. On success `chmod 600` the
+ // shared inode (credential-adjacent conversation) and drop the staging name, leaving the target.
+ const installed = await this.r.run(
+ childArgs(
+ c!.conn,
+ c!.controlPath,
+ `mkdir -p ${posixQuote(targetDir)} && chmod 700 ${posixQuote(targetDir)} || { rm -f ${posixQuote(staging)}; exit 70; }; ` +
+ `if ln ${posixQuote(staging)} ${posixQuote(target)} 2>/dev/null; then ` +
+ `chmod 600 ${posixQuote(target)}; rm -f ${posixQuote(staging)}; ` +
+ `else rm -f ${posixQuote(staging)}; exit 17; fi`
+ )
+ )
+ 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.
diff --cc src/renderer/nodes/TerminalNode.tsx
index 4ac9193a8,b7fcc6f3a..24563af1d
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@@ -169,7 -168,9 +171,9 @@@ import { agentEnvSnapshot } from '@rend
import { normalizedAgentModel } from '@shared/agents/model-gateway'
import { ensureActivePermissionMode } from '../state/permissionMode'
import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
- import { hintLabel, isWindowsPlatform } from '@shared/platform-utils'
+ import { chipFor, effectiveBindings, terminalShortcutPolicy } from '../lib/keybindingOverrides'
+ import { matchesShortcut } from '@shared/shortcut'
-import { isMacPlatform } from '@shared/platform-utils'
++import { hintLabel, isWindowsPlatform, isMacPlatform } from '@shared/platform-utils'
import { ColumnPill } from '../components/kanban/ColumnPill'
import { BoardLogPanel } from '../components/kanban/BoardLogPanel'
import { AgentMascot } from './AgentMascot'