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 branch 'main' into feat/server-canvas-control

enesba8dec1ba44d
diff --cc src/core/canvas-control-core.ts
index 9d53d6172,f66e934ce..f9adab6a2
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@@ -292,11 -304,8 +309,13 @@@ export function buildCanvasControlInstr
'starts with `--` (`--cmd=--version`); written as two tokens, a leading `--` is read as the next',
'flag. A flag with no value is allowed anywhere on the line.',
'',
+ ...dryRunDocLines(),
+ '',
+ 'Server Edition ownership is fail-closed: every request requires verified node identity, and',
+ 'a caller may mutate or message only nodes it opened during the current server run.',
+ 'Restarting the server clears that creator proof; persisted nodes and queued launches are never',
+ 'auto-adopted, relaunched, or controlled at boot. An unowned target receives a named refusal.',
+ '',
'Verbs:',
'- `list` — current nodes (id, kind, title). Start here when you need a node id.',
'- `help` — print the verb list. Answered by the shim itself, so it works even if the app is down.',
@@@ -349,9 -370,8 +382,10 @@@
' arrange across frames in one call); arranging a frame\'s children also shrinks the frame to fit.',
'- `link --to <id,id> [--from <id>]` — context-link nodes so each can READ the other\'s transcript',
' on demand (nodeterm linked-context CLI). `--from` defaults to you; nothing is pushed into the',
- ' linked sessions. Agent sessions you open are linked to you automatically — use `link` for nodes',
- ' you did not open, or to link two OTHER nodes together. On Server Edition the ownership rule',
- ' is stricter: every endpoint must be a node you opened during this server run.',
+ ' linked sessions. Agent sessions you open, and the stations you name in `--after`, are already',
+ ' linked — nothing to `link`. Use `link` only for nodes you did not open, or to link two OTHER nodes.',
++ ' On Server Edition the ownership rule is stricter: every endpoint must be a node you opened',
++ ' during this server run.',
'- `verify --node <id> [--lenses correctness,security,tests] [--focus "..."] [--synthesis off]` — open a',
' review panel over that node\'s work: one reviewer per lens, each armed behind the target and linked',
' to it, plus a judge armed behind the panel that merges the findings into one verdict. Reviewers are',
@@@ -366,15 -392,14 +406,17 @@@
' the user to confirm deletion.',
'- `branch --node <id>` — branch a Claude node\'s conversation (Claude nodes only).',
'- `rename --node <id> --title "New Name"` — rename any node (terminals, groups, stickies…).',
+ ' Renaming to the title the node ALREADY has is a no-op: nothing is typed into its agent',
+ ' session, and the reply says `already named`. Re-assert your own name as often as you like.',
+ `- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.`,
'- `write --node <id> --text "..."` / `close --node <id>` — type into / close a node.',
- ' Both ask the user to confirm a dialog and may be denied. Read WHICH answer came back:',
- ' `denied by user` is a decision and is FINAL — never re-ask — while `no answer within 120s`',
- ' means nobody reached the dialog, which is worth one retry when the user is back.',
+ ' Desktop asks the user to confirm both. `denied by user` is FINAL; `no answer within 120s`',
+ ' means nobody reached the dialog and is worth one retry when the user is back. Server Edition',
+ ' is narrower: close requires a node this caller opened during the current server run, and all',
+ ' node-mutating verbs accept only current-run creations. Every other target receives a named',
+ ' ownership refusal before any partial mutation.',
'- `send --node <id> --text "..."` / `reply --node <id> --text "..."` — deliver a message into',
- ' another AGENT node in this project (no confirm dialog: verified-only, gated by the project\'s',
+ ' an AGENT node the caller opened this run (no confirm dialog: verified-only, gated by the project\'s',
' agent-messaging switch — off by default — and rate-limited). A busy target is not interrupted',
' and does not lose the message: it is queued (bounded, TTL\'d) and delivered when the target',
' next goes idle. An incoming message is framed `--- NODETERM MESSAGE <nonce> ---` with a `reply-to:`',
@@@ -688,13 -713,14 +730,19 @@@ starts with \`--\` (\`--cmd=--version\`
next flag, so \`--text --oops\` sends an empty \`--text\` plus a stray \`--oops\`. A flag with no
value is allowed anywhere on the line, not only at the end.
+ ${dryRunDocLines().join('\n')}
+
+Server Edition ownership is fail-closed: every request requires verified node identity, and a
+caller may mutate or message only nodes it opened during the current server run. Restarting
+the server clears that creator proof; persisted nodes and queued launches are never auto-adopted,
+relaunched, or controlled at boot. An unowned target receives a named refusal.
+
Verbs:
- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
+ A row ending **LAST TURN ERRORED** is a station whose last turn died on an API/model error:
+ it is idle, but it produced nothing, so do not read its output or build on it. The marker
+ is on the row on purpose — a fan-out of seven stations should cost one call to learn this,
+ not seven. It clears itself the moment that station completes another turn.
- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so it
is also what to run when you are unsure whether the control endpoint is alive.
- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>]\` — open N plain terminals (default 1).
@@@ -775,10 -814,9 +839,11 @@@
- \`link --to <id,id> [--from <id>]\` — context-link nodes, so each can READ the other's
transcript on demand with the get-linked-context skill. \`--from\` defaults to you. Nothing is
pushed into the linked sessions — reading is on demand, so linking never interrupts anyone.
- Agent sessions you open (\`open-claude\`/\`open-agent\`/\`spawn-team\`) are linked to you
- automatically; use \`link\` for nodes you did not open, or to link two OTHER nodes together.
+ Agent sessions you open (\`open-claude\`/\`open-agent\`/\`spawn-team\`) and the stations you name in
+ \`--after\` are already linked — nothing to \`link\`. Use \`link\` only for nodes you did not open,
+ or to link two OTHER nodes together.
+ On Server Edition the ownership rule is stricter: every endpoint must be a node you opened
+ during this server run.
- \`verify --node <id> [--lenses correctness,security,tests] [--focus "..."] [--agent <id>] [--synthesis off] [--label L]\` —
open a review PANEL over that node's work: one reviewer per lens, each armed behind the target
(they start when it goes idle) and linked to it so they can read what it actually did, plus a
@@@ -802,14 -852,12 +879,16 @@@
- \`branch --node <id>\` — branch a Claude node's conversation: the node stays on the new
branch and a new node opens resuming the original. Target must be a Claude agent node.
- \`rename --node <id> --title "New Name"\` — rename any node (terminals, groups, stickies…).
+ Renaming to the title the node ALREADY has is a no-op: nothing is typed into its agent
+ session, and the reply says \`already named\`. Re-assert your own name as often as you like.
+- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.
- \`write --node <id> --text "..."\` — type text into a terminal node. (Asks the user to confirm.)
-- \`close --node <id>\` — close a node. (Asks the user to confirm.)
-- \`send --node <id> --text "..."\` — deliver a message INTO another agent node's session, in this
- project only. No confirm dialog; instead it is verified-only, gated by the project's
+- \`close --node <id>\` — close a node. Desktop asks the user to confirm. Server Edition closes
+ only nodes this caller opened during the current server run, without a dialog. Its other
+ node-mutating verbs (link/group/rename/color/sticky update) likewise accept only current-run
+ creations, and refuse the whole request before any partial mutation.
+- \`send --node <id> --text "..."\` — deliver a message INTO an agent node the caller opened during
+ this server run, in this project only. No confirm dialog; instead it is verified-only, gated by the project's
agent-messaging switch (Settings → Agents, OFF by default), and rate-limited. Delivery lands when
the target is idle at its prompt; a BUSY target is never interrupted and does not lose the
message — it is held in a bounded, TTL'd per-target queue and delivered when the target next goes
diff --cc src/core/pty-single-user.test.ts
index 042ce9278,2ea5a4523..b742685f5
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@@ -355,6 -355,6 +355,15 @@@ describe('SINGLE-USER REGRESSION: co-at
it('never exposes gateway credentials to a plain terminal', async () => {
const inherited = process.env.ANTHROPIC_AUTH_TOKEN
process.env.ANTHROPIC_AUTH_TOKEN = 'preexisting-shell-token'
++ // A pty inherits this process's environment, so the two assertions below are about what
++ // `buildPtyEnv` ADDS — and they can only say that if the ambient value is absent. nodeterm is
++ // developed inside nodeterm: a suite run from an agent pane inherits that pane's own
++ // NODETERM_AGENT_ID=claude / NODETERM_CANVAS_CONTROL=1, and the test then failed for the
++ // developer while passing in CI, which is the worst way round.
++ const inheritedAgent = process.env.NODETERM_AGENT_ID
++ const inheritedControl = process.env.NODETERM_CANVAS_CONTROL
++ delete process.env.NODETERM_AGENT_ID
++ delete process.env.NODETERM_CANVAS_CONTROL
try {
const { PtyManager } = await import('./pty-manager')
const m = new PtyManager()
@@@ -376,6 -374,6 +385,10 @@@
} finally {
if (inherited === undefined) delete process.env.ANTHROPIC_AUTH_TOKEN
else process.env.ANTHROPIC_AUTH_TOKEN = inherited
++ if (inheritedAgent === undefined) delete process.env.NODETERM_AGENT_ID
++ else process.env.NODETERM_AGENT_ID = inheritedAgent
++ if (inheritedControl === undefined) delete process.env.NODETERM_CANVAS_CONTROL
++ else process.env.NODETERM_CANVAS_CONTROL = inheritedControl
}
})
diff --cc src/core/tmux-socket-isolation.guard.test.ts
index 000000000,7f048f93e..ec709ac54
mode 000000,100644..100644
--- a/src/core/tmux-socket-isolation.guard.test.ts
+++ b/src/core/tmux-socket-isolation.guard.test.ts
@@@ -1,0 -1,176 +1,182 @@@
+ // Issue #629 — the invariant: **a test never touches the machine's live nodeterm tmux server.**
+ //
+ // This repo is developed from inside nodeterm, so `tmux -L node-terminal` and `-L nodeterm-rmt` are
+ // not names in a fixture — on a contributor's machine they are the servers holding every terminal
+ // they have open. A test that binds one shares a process with the user's entire canvas, and the
+ // failure mode is not a red test: it is every pane printing `[server exited unexpectedly]`.
+ //
+ // It is enforced three ways, deliberately, because each covers what the others cannot:
+ //
+ // 1. STRUCTURAL — `test/setup/tmux-sandbox.ts` gives the run a private `TMUX_TMPDIR`, which
+ // re-points every socket name, the real ones included. This is the only leg that covers a test
+ // nobody thought about.
+ // 2. BEHAVIOURAL — the third test below actually starts a server on the real socket NAME and
+ // proves the socket file landed inside the sandbox. Asserting the environment variable would
+ // only prove we set a variable; the resolution rule is a property of tmux.
+ // 3. BY REVIEW — the scan at the bottom lists the files that hand a real socket name to a real
+ // tmux binary. It cannot stop a new one being written; it makes writing one a decision
+ // somebody signs for, the way `fs-atomic.guard.test.ts` does for a bare rename.
+ //
+ // The scan is the weakest of the three ON PURPOSE. A test can still escape the sandbox by handing a
+ // real tmux an `env` object it built from scratch (with no `TMUX_TMPDIR` in it), and no regex sees
+ // that reliably; the allowlist is what keeps such a file rare and reviewed.
+ import { describe, expect, it } from 'vitest'
+ import { execFileSync } from 'child_process'
+ import { existsSync, readdirSync, readFileSync, statSync } from 'fs'
+ import { join, relative } from 'path'
+ import { TMUX_SOCKET } from './tmux-naming'
+ import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
+ import { SANDBOX_ENV, tmuxSocketPath } from './tmux-test-socket'
+
+ const REPO_ROOT = join(__dirname, '..', '..')
+ const TEST_ROOTS = [join(REPO_ROOT, 'src'), join(REPO_ROOT, 'test')]
+ const UID = process.getuid?.() ?? 0
+ const HAS_TMUX = (() => {
+ try {
+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })
+ return true
+ } catch {
+ return false
+ }
+ })()
+
+ describe('the run cannot reach a live nodeterm tmux server', () => {
+ it('runs inside a private TMUX_TMPDIR', () => {
+ const sandbox = process.env[SANDBOX_ENV]
+ expect(sandbox, 'globalSetup did not create the tmux sandbox').toBeTruthy()
+ expect(process.env.TMUX_TMPDIR).toBe(sandbox)
+ expect(existsSync(sandbox!)).toBe(true)
+ // `/tmp` is what an unset `TMUX_TMPDIR` resolves to, and it is where the live servers are.
+ expect(tmuxSocketPath(sandbox!, UID, TMUX_SOCKET)).not.toBe(
+ tmuxSocketPath('/tmp', UID, TMUX_SOCKET)
+ )
+ })
+
+ it('inherits no ambient tmux client', () => {
+ // Both are set for every process inside a nodeterm terminal — i.e. for the suite as it is
+ // normally run in this repo.
+ expect(process.env.TMUX).toBeUndefined()
+ expect(process.env.TMUX_PANE).toBeUndefined()
+ })
+
+ it.skipIf(!HAS_TMUX || process.platform === 'win32')(
+ 'binds the REAL socket name inside the sandbox — measured, not inferred from the env',
+ () => {
+ const sandbox = process.env[SANDBOX_ENV]!
+ // Its OWN session, killed by exact target. NOT `kill-server`: inside the sandbox this socket
+ // name is shared with `main/remote/host-destroy-tmux.test.ts`, which binds it too (it has no
+ // choice — `PtyManager` hardcodes the name), and killing the server took that suite's session
+ // out from under it on CI. The sandbox moves the shared server somewhere harmless; it does
+ // not stop a `kill-server` from being a SHARED-server kill once you are in there.
+ const session = `nt-isolation-guard-${process.pid}`
+ const tmux = (args: string[]): void => {
+ execFileSync('tmux', ['-L', TMUX_SOCKET, ...args], { stdio: 'ignore' })
+ }
+ try {
+ tmux(['new-session', '-d', '-s', session, 'sleep', '30'])
+ expect(existsSync(tmuxSocketPath(sandbox, UID, TMUX_SOCKET))).toBe(true)
+ } finally {
+ try {
+ // `=` is an exact match: without it tmux falls back to fnmatch and then to PREFIX
+ // matching, so a miss could kill somebody else's session.
+ tmux(['kill-session', '-t', `=${session}`])
+ } catch {
+ /* never started */
+ }
+ }
+ }
+ )
+ })
+
+ /**
+ * Files allowed to name a real nodeterm socket to a real tmux, each with the reason.
+ *
+ * Both are here because the NAME is part of what they measure, not because nobody got round to
+ * changing them. Each must also carry `TMUX_TMPDIR` in its own text — the sandbox is the floor, and
+ * a file that deliberately names a live socket owes an explicit statement of where it binds.
+ */
+ const REAL_SOCKET_ALLOWED = new Map<string, string>([
+ [
+ 'src/core/agents/pane-owner.test.ts',
+ 'the production bytes hardcode `-L nodeterm-rmt`; re-spelling it would judge different bytes'
+ ],
+ [
+ 'src/main/remote/host-destroy-tmux.test.ts',
+ 'PtyManager binds TMUX_SOCKET itself, so the verb can only be measured on that name'
++ ],
++ [
++ 'test/server/canvas-control-boot-e2e.test.ts',
++ 'boots a real Server Edition, whose PtyManager binds TMUX_SOCKET itself: the assertion is that ' +
++ 'boot spawns NOTHING, and only that socket can answer it. Reads with has-session and kills ' +
++ 'one per-run unique nt-<uuid> target — never a broad target and never the server itself.'
+ ]
+ ])
+
+ /**
+ * An exec of a real tmux whose argv begins `-L <a real nodeterm socket>`.
+ *
+ * Deliberately narrow: `['-L', 'node-terminal', …]` appears all over the suite as an EXPECTATION
+ * against a faked `execFile`, and a scan that flagged those would be switched off within a week.
+ * What it matches is the program-plus-argv adjacency, which only a real spawn has.
+ */
+ const REAL_SOCKET_EXEC =
+ /(?:execFile|execFileSync|spawn|spawnSync|run|runAsync)\s*\(\s*[^,()]*,\s*\[\s*'-L',\s*(?:TMUX_SOCKET|RMT_TMUX_SOCKET|'node-terminal'|'nodeterm-rmt')/
+
+ function testFiles(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry)
+ if (statSync(p).isDirectory()) {
+ if (entry !== 'node_modules') testFiles(p, out)
+ } else if (/\.test\.tsx?$/.test(entry)) {
+ out.push(p)
+ }
+ }
+ return out
+ }
+
+ describe('no unreviewed test hands a real socket name to a real tmux', () => {
+ const files = TEST_ROOTS.filter((r) => existsSync(r)).flatMap((r) => testFiles(r))
+
+ it('finds the test tree (a zero-file scan would pass silently)', () => {
+ expect(files.length).toBeGreaterThan(100)
+ })
+
+ it('matches the construction it is meant to catch, and not the expectations beside it', () => {
+ // The lesson from fs-atomic.guard.test.ts: a scan nobody proved can match anything reads
+ // exactly like a scan with nothing to find.
+ expect(REAL_SOCKET_EXEC.test("await run(TMUX!, ['-L', TMUX_SOCKET, 'has-session'])")).toBe(true)
+ expect(REAL_SOCKET_EXEC.test("execFileSync(bin, ['-L', 'nodeterm-rmt', 'ls'])")).toBe(true)
+ expect(
+ REAL_SOCKET_EXEC.test("expect(kills).toEqual([['-L', 'node-terminal', 'kill-session']])")
+ ).toBe(false)
+ })
+
+ it('flags every offender that is not allowlisted', () => {
+ // This file is skipped rather than allowlisted: it matches only because it spells the pattern
+ // out in the positive control above, and an allowlist entry would read as permission to run a
+ // real tmux from here.
+ const self = relative(REPO_ROOT, __filename).replace(/\\/g, '/')
+ const offenders = files
+ .filter((f) => REAL_SOCKET_EXEC.test(readFileSync(f, 'utf8')))
+ .map((f) => relative(REPO_ROOT, f).replace(/\\/g, '/'))
+ .filter((rel) => rel !== self && !REAL_SOCKET_ALLOWED.has(rel))
+ expect(offenders).toEqual([])
+ })
+
+ it('every allowlisted file still exists and says where it binds', () => {
+ for (const [rel] of REAL_SOCKET_ALLOWED) {
+ const p = join(REPO_ROOT, rel)
+ expect(existsSync(p), `${rel} is allowlisted but gone — drop the entry`).toBe(true)
+ expect(readFileSync(p, 'utf8'), `${rel} must say which TMUX_TMPDIR it binds in`).toContain(
+ 'TMUX_TMPDIR'
+ )
+ }
+ })
+
+ it('the socket names the scan spells are still the production ones', () => {
+ // The regex carries the two names as literals so it can read a test that hardcodes them. If a
+ // constant is ever renamed, this is what says the scan went blind.
+ expect(TMUX_SOCKET).toBe('node-terminal')
+ expect(RMT_TMUX_SOCKET).toBe('nodeterm-rmt')
+ })
+ })
diff --cc src/main/canvas-control-core.test.ts
index f7266e99a,b5614af7d..b7841133b
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@@ -13,7 -13,8 +13,8 @@@ import
CODEX_SANDBOX_RETRY_LINE
} from '../core/agents/hook-sandbox-hint-sh'
import { RETRYABLE } from '../core/agents/agent-message-decide'
-import { PROJECT_TARGETABLE_VERBS } from './project-grants'
+import { PROJECT_TARGETABLE_VERBS } from '../core/project-grants'
+ import { DRY_RUN_VERBS } from '../shared/control-verbs'
import { STRICT_CONTROL_VERBS } from '../core/agents/node-identity-policy'
import { BROWSER_ACTION_KEYS } from '../core/browser-verb'
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from '../core/browser-outcomes'
diff --cc src/main/codex-shim-identity.integration.test.ts
index 000000000,a985bbe90..6fd8cd06b
mode 000000,100644..100644
--- a/src/main/codex-shim-identity.integration.test.ts
+++ b/src/main/codex-shim-identity.integration.test.ts
@@@ -1,0 -1,82 +1,82 @@@
+ // A shared Codex app-server forks tool shells without the pane's NODETERM_* environment. These
+ // tests run both generated local shims under real /bin/sh with only CODEX_THREAD_ID, proving that
+ // the signed ownership-record prelude executes before either shim's "not a nodeterm node" gate.
+ import { afterEach, describe, expect, it } from 'vitest'
+ import { execFile } from 'node:child_process'
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+ import { tmpdir } from 'node:os'
+ import { join } from 'node:path'
+ import { promisify } from 'node:util'
+
+ import { buildContextShimScript } from '../core/context-link-core'
-import { buildControlShimScript } from './canvas-control-core'
++import { buildControlShimScript } from '../core/canvas-control-core'
+
+ const run = promisify(execFile)
+ const cleanup: string[] = []
+
+ afterEach(() => {
+ for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true })
+ })
+
+ describe('local Codex tool-shell identity recovery', () => {
+ for (const [name, build] of [
+ ['canvas control', buildControlShimScript],
+ ['linked context', buildContextShimScript]
+ ] as const) {
+ it(`${name} resolves CODEX_THREAD_ID before its NODETERM_* gate`, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'nodeterm-codex-local-shim-'))
+ cleanup.push(dir)
+ const root = join(dir, 'codex-thread-nodes')
+ const built = build(root)
+
+ const bin = join(dir, 'bin')
+ const endpoint = join(dir, 'hook-endpoint.env')
+ const tokens = join(dir, 'node-tokens')
+ const capture = join(dir, 'curl-args')
+ const script = join(dir, 'shim.sh')
+ mkdirSync(root)
+ mkdirSync(bin)
+ mkdirSync(tokens)
+ writeFileSync(
+ join(root, 'thread-1'),
+ `accountId=\nnodeId=node-1\nendpoint=${endpoint}\nsignature=test-fixture\n`,
+ { mode: 0o600 }
+ )
+ writeFileSync(
+ endpoint,
+ `NODETERM_HOOK_PORT=54321\nNODETERM_HOOK_TOKEN=test-hook\n` +
+ `NODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokens}\n`,
+ { mode: 0o600 }
+ )
+ writeFileSync(join(tokens, 'node-1'), 'test-node-token\n', { mode: 0o600 })
+ writeFileSync(script, built, { mode: 0o755 })
+ writeFileSync(
+ join(bin, 'curl'),
+ `#!/bin/sh
+ nt_out=''
+ while [ "$#" -gt 0 ]; do
+ case "$1" in
+ -o) shift; nt_out="$1" ;;
+ --data-urlencode) shift; printf '%s\n' "$1" >> "$NT_CAPTURE" ;;
+ esac
+ shift
+ done
+ [ -n "$nt_out" ] && printf 'ok\n' > "$nt_out"
+ printf '200'
+ `,
+ { mode: 0o755 }
+ )
+
+ const result = await run('/bin/sh', [script, 'list'], {
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}`,
+ CODEX_THREAD_ID: 'thread-1',
+ NT_CAPTURE: capture
+ }
+ })
+
+ expect(result.stdout.trim()).toBe('ok')
+ expect(readFileSync(capture, 'utf8').split('\n')).toContain('nodeId=node-1')
+ })
+ }
+ })
diff --cc src/main/remote-ssh/remote-shim-neutrality.guard.test.ts
index 000000000,2761b8036..268075925
mode 000000,100644..100644
--- a/src/main/remote-ssh/remote-shim-neutrality.guard.test.ts
+++ b/src/main/remote-ssh/remote-shim-neutrality.guard.test.ts
@@@ -1,0 -1,107 +1,107 @@@
+ // The shim scripts copied onto an SSH host must stay MACHINE-NEUTRAL: no path that only means
+ // something on the desktop/server that generated them.
+ //
+ // Since the local shims gained the shared-Codex identity prelude, the two builders take an
+ // `identityRoot` — this machine's `<userDataDir>/codex-thread-nodes`. The LOCAL installers pass it;
+ // the SSH installer must not, because a record root under one machine's user-data dir is not a
+ // path on somebody else's server. The rule is stated in three places (CLAUDE.md, CONTRIBUTING.md,
+ // docs/shared-codex-node-identity.md) and was enforced by none of them.
+ //
+ // WHY IT NEEDS A GUARD RATHER THAN A REVIEWER: the failure is SILENT AND ONE-SIDED. A remote shim
+ // carrying the prelude still works — the outer `[ -n "$CODEX_THREAD_ID" ]` guard is false in a
+ // remote pane, and even if it were true the baked root does not exist there, so every candidate
+ // read fails and the block changes nothing. Nothing breaks, no test goes red, no user reports a
+ // bug. The only symptom is that this machine's user-data layout is now sitting in a file on
+ // someone else's server, written there by us, and refreshed on every connect.
+ //
+ // Two legs, because they catch the mistake at different moments:
+ // 1. the VALUE — the neutral exports the SSH installer writes carry nothing machine-specific;
+ // 2. the IMPORT — `remote-hooks.ts` cannot even reach a builder that would produce one.
+ // Leg 2 is the one that survives a refactor: a future author who reaches for the parameterised
+ // builder "so the remote shim gets the fix too" is stopped at the import, before there is a value
+ // to assert about.
+ //
+ // Every assertion has a POSITIVE CONTROL beside it. A guard whose subject has been renamed or
+ // removed matches nothing and reports clean — the same failure mode `fs-atomic.guard.test.ts`
+ // opens with — and a silent pass here would restore exactly the blindness this file exists to end.
+ import { describe, expect, it } from 'vitest'
+ import { readFileSync } from 'fs'
+ import { join } from 'path'
+
-import { CONTROL_SHIM_SCRIPT, buildControlShimScript } from '../canvas-control-core'
++import { CONTROL_SHIM_SCRIPT, buildControlShimScript } from '../../core/canvas-control-core'
+ import { CONTEXT_SHIM_SCRIPT, buildContextShimScript } from '../../core/context-link-core'
+
+ /** A root no real machine would produce, so a hit is unambiguously the one we baked in. */
+ const SENTINEL_ROOT = '/nodeterm-guard-sentinel/codex-thread-nodes'
+
+ const REMOTE_HOOKS = join(__dirname, 'remote-hooks.ts')
+
+ /**
+ * Identifiers `remote-hooks.ts` must never name. Each one is a way to obtain a shim body carrying
+ * a local path, or the local path itself.
+ */
+ const BANNED_IN_REMOTE_HOOKS = [
+ 'buildControlShimScript',
+ 'buildContextShimScript',
+ 'codexThreadIdentityResolverSh',
+ 'codexThreadIdentityRoot'
+ ] as const
+
+ /**
+ * Identifiers `remote-hooks.ts` must still name — the neutral exports it writes to the host. If
+ * these disappear the file has been restructured and leg 2's scan is no longer looking at the
+ * thing it was written to look at, so it must go red rather than pass over an empty subject.
+ */
+ const REQUIRED_IN_REMOTE_HOOKS = ['CONTROL_SHIM_SCRIPT', 'CONTEXT_SHIM_SCRIPT'] as const
+
+ /**
+ * Strip comments before scanning, so this file's own rule can be EXPLAINED at the call site in
+ * `remote-hooks.ts` without the explanation tripping the scan. Only comments are removed; a string
+ * literal naming a banned identifier is still a hit, which is the conservative direction.
+ */
+ function code(source: string): string {
+ return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/[^\n]*/g, '$1')
+ }
+
+ describe('SSH-installed shims stay machine-neutral', () => {
+ describe('leg 1 — the exported neutral bodies carry no local path', () => {
+ for (const [name, neutral, build] of [
+ ['canvas control', CONTROL_SHIM_SCRIPT, buildControlShimScript],
+ ['linked context', CONTEXT_SHIM_SCRIPT, buildContextShimScript]
+ ] as const) {
+ it(`${name}: the builder DOES bake a root when given one (positive control)`, () => {
+ // Without this, the two assertions below would also pass if the prelude had been dropped
+ // from the local shims altogether — a regression, reported as compliance.
+ const local = build(SENTINEL_ROOT)
+ expect(local).toContain(SENTINEL_ROOT)
+ expect(local).toContain('CODEX_THREAD_ID')
+ })
+
+ it(`${name}: the neutral export names no record root`, () => {
+ expect(neutral).not.toContain('codex-thread-nodes')
+ })
+
+ it(`${name}: the neutral export carries no identity prelude at all`, () => {
+ // Broader than the path check on purpose. The path is what leaks today; the prelude is the
+ // only thing that can carry one, so refusing the whole block refuses the next spelling of
+ // the leak too (a root read from an env var, a relative path, a default argument).
+ expect(neutral).not.toContain('CODEX_THREAD_ID')
+ expect(build()).toBe(neutral)
+ })
+ }
+ })
+
+ describe('leg 2 — remote-hooks.ts cannot reach a parameterised builder', () => {
+ const source = code(readFileSync(REMOTE_HOOKS, 'utf8'))
+
+ it('is reading the real remote installer (positive control)', () => {
+ for (const required of REQUIRED_IN_REMOTE_HOOKS) expect(source).toContain(required)
+ })
+
+ for (const banned of BANNED_IN_REMOTE_HOOKS) {
+ it(`never names ${banned}`, () => {
+ expect(source).not.toContain(banned)
+ })
+ }
+ })
+ })
diff --cc src/renderer/canvas/Canvas.tsx
index 32a673e80,6521a4e31..9934b9b8d
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@@ -384,14 -411,27 +411,28 @@@ import
type RelayTab,
} from '../session/relay-tab'
import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'
- import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode } from '../lib/pendingLaunch'
+ import {
+ launchesToFire,
+ launchRetryDelay,
+ unmetDeps,
+ LAUNCH_STALL_MS,
+ type ArmedNode
+ } from '../lib/pendingLaunch'
+ import { WAIT_LABEL, dropAfterDep, edgeHidden, hiddenEdgeNodeIds, missingDepRopes, ropeInfoOf, ropeVisual } from '../lib/edgeModel'
+ import { triggerEdges } from '../lib/triggerCard'
import { freeSpot } from '../lib/placement'
- import { pushSessionRename } from '../lib/sessionRename'
- import { useReopenHistory } from '../state/reopenHistory'
+ import { pushSessionRename, sessionNameUnchanged } from '../lib/sessionRename'
+ import { useReopenHistory, type ReopenEntry } from '../state/reopenHistory'
import { snapshotNode, recreateNodeFromSnapshot } from '../lib/reopenNode'
- import { planReopen } from '../lib/reopenPlan'
+ import {
+ buildClosedSessionEntries,
+ recentlyClosedProjects,
+ stateToReopenSnapshot
+ } from '../lib/closedHistory'
+ import { uuid } from '../lib/uuid'
+ import { planReopen, type ReopenPlan } from '../lib/reopenPlan'
import { oneLine } from '@shared/one-line'
+import { invalidNodeColorMessage, isNodeColor } from '@shared/node-colors'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
import { activePermissionMode, projectPermissionMode } from '../state/permissionMode'
@@@ -9340,45 -10497,20 +10511,52 @@@ export function Canvas()
markDirty()
const agentId = target.data.agentId as AgentId | undefined
if (agentId && canRename(agentId) && title) {
- // Gated: an agent that opens a node and renames it in the same breath would
- // otherwise splice this line into the launch command still being typed.
- void pushSessionRename(api.pty, id, title)
+ // Gated twice: on the pane's owner (an agent that opens a node and renames it in the
+ // same breath would otherwise splice this line into the launch command still being
+ // typed) and, inside, on the name actually changing.
+ void pushSessionRename(api.pty, id, title, prevTitle)
}
- reply({ ok: true, message: `renamed ${id} to "${title}"` })
+ reply(
+ // Say which of the two happened: the caller cannot see the pane, and "already named"
+ // is the answer that lets an orchestrator stop re-asserting a name it already set.
+ title && sessionNameUnchanged(title, prevTitle)
+ ? { ok: true, message: `${id} is already named "${title}"` }
+ : { ok: true, message: `renamed ${id} to "${title}"` }
+ )
return
}
+ case 'color': {
+ if (!isNodeColor(args.color)) {
+ reply({ ok: false, error: invalidNodeColorMessage() })
+ return
+ }
+ const ids = [
+ ...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))
+ ]
+ const live = nodesRef.current
+ const colored = ids.filter((id) => live.some((node) => node.id === id))
+ if (!colored.length) {
+ reply({ ok: false, error: 'color: none of the given node ids exist' })
+ return
+ }
+ const selected = new Set(colored)
+ setNodes((nodes) =>
+ nodes.map((node) =>
+ selected.has(node.id)
+ ? { ...node, data: { ...node.data, color: args.color } }
+ : node
+ )
+ )
+ markDirty()
+ const skipped = ids.length - colored.length
+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
+ reply({
+ ok: true,
+ message: `colored ${colored.length} node(s) ${args.color}${note}`,
+ result: { colored, skipped, color: args.color }
+ })
+ return
+ }
case 'sticky': {
// Write INTO a note (issue #144): the door for "sync Linear/Jira/GitHub onto the
// canvas" — a scheduled agent turn rewrites one titled note; nodeterm ships no
diff --cc src/renderer/state/workspace.ts
index ed0b47bfd,66dd376f4..4c940c4e3
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@@ -24,12 -32,19 +32,13 @@@ import { useSettings } from './settings
// single implementation lives in src/shared and is shared with the relay host + the canvas-sync
// reflector.
export { applyCanvasMutation } from '@shared/canvas-mutations'
+ export { accountNodeColor, agentAccountColor } from '@shared/agents/account-color'
import { sanitizeInboundNode } from '@shared/node-exec'
+import { NODE_COLORS } from '@shared/node-colors'
-/** Preset color palette — macOS system colors (dark mode). */
-export const NODE_COLORS = [
- '#0a84ff', // systemBlue
- '#32d74b', // systemGreen
- '#ffd60a', // systemYellow
- '#ff453a', // systemRed
- '#bf5af2', // systemPurple
- '#6ac4dc', // systemTeal
- '#ff9f0a' // systemOrange
-]
+// Preserve the renderer's long-standing import surface; validation and the palette now live in
+// shared so Server Edition and canvas-control accept exactly what these pickers display.
+export { NODE_COLORS } from '@shared/node-colors'
const TERMINAL_SIZE = { width: 640, height: 440 }
const STICKY_SIZE = { width: 240, height: 200 }
diff --cc src/server/canvas-control.ts
index d905a6313,000000000..8efe12347
mode 100644,000000..100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@@ -1,229 -1,0 +1,235 @@@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import {
+ createDeliveryQueue,
+ deliverFromControl,
+ messagingEnabledVia,
+ onMessagingAgentEvent,
+ type AgentMessagingDeps
+} from '../core/agents/agent-messaging'
+import { paneOwnerProject } from '../core/agents/pane-ownership'
+import {
+ mirrorEntry,
+ nodeState
+} from '../core/agent-status-mirror'
+import type { BoardLogHandlers } from '../core/board-log-handlers'
+import {
+ buildControlShimScript,
+ buildCanvasControlInstructions,
+ buildCanvasSkillBody,
+ mergeCanvasControlBlock
+} from '../core/canvas-control-core'
+import { codexIdentityCaps } from '../core/codex-identity-caps'
+import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'
+import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
++import { grokCliCaps } from '../core/grok-cli'
++import type { GrokCliCaps } from '../shared/types'
+import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'
+import { platform } from '../core/platform'
+import type { PtyManager } from '../core/pty-manager'
+import type { WorkspaceStore } from '../core/workspace-store'
+import type { NormalizedAgentEvent } from '../shared/agents/normalize'
+import { IPC } from '../shared/ipc'
+import type { Project, Settings } from '../shared/types'
+import {
+ createServerEditionControlHandler,
+ type ServerEditionControlActions
+} from './control-unsupported'
+import { HeadlessNodeFactory } from './headless-node-factory'
+import { sendSettledEnvelope } from './settled-envelope'
+
+export interface ServerCanvasControlDeps {
+ workspaceStore: WorkspaceStore
+ ptyManager: PtyManager
+ settings(): Settings
+ boardLog: BoardLogHandlers
+ cliCaps?: () => Promise<ClaudeCliCaps>
++ /** grok's own `--session-id` probe; defaults to the real one. See HeadlessNodeFactoryDeps. */
++ grokCaps?: () => Promise<GrokCliCaps>
+ /** Test seam for the boot-populated shared Codex capability answer. */
+ codexSharedIdentity?: () => Promise<boolean>
+ /**
+ * Whether to write this server's discovery surface into the machine's REAL agent configuration
+ * directories: `~/.claude/skills/manage-nodeterm-canvas/SKILL.md`, the marker block in
+ * `~/.codex/AGENTS.md` and `~/.gemini/GEMINI.md`, and the same skill in every managed Claude
+ * account dir. `true` = the server's `installHooks` gate said yes; `false` = leave them alone.
+ *
+ * REQUIRED, and deliberately not defaulted. A service process editing files inside a user's
+ * `$HOME` is a documented hazard in this repo — those instruction files are loaded by EVERY
+ * agent session on the machine, nodeterm's or not, so a stray write follows the user into work
+ * that has nothing to do with this server (issue #490). The previous shape was an OPTIONAL flag
+ * read as `!== false`, which meant OMITTING the decision installed: the dangerous direction was
+ * the one you got by saying nothing, and a new call site or a test that simply forgot the field
+ * would rewrite the developer's own agent configuration with no diagnostic. Making it required
+ * turns "I did not think about this" into a compile error — the same asymmetry
+ * `session-memory-service.ts` uses for its `remote.isRemoteProject` dep, where
+ * reading-without-knowing is likewise refused at the type level.
+ *
+ * Production passes `config.installHooks !== false`; every test must pass `false` unless it is
+ * specifically exercising the install and has redirected `HOME` to a scratch directory first.
+ */
+ installAgentIntegrations: boolean
+}
+
+export interface ServerCanvasControl {
+ handler: ReturnType<typeof createServerEditionControlHandler>
+ onAgentEvent(event: NormalizedAgentEvent): void
+ installSkillInto(configDir: string): void
+ stop(): void
+}
+
+function canvasControlDir(): string {
+ return path.join(platform().userDataDir, 'canvas-control')
+}
+
+function shimPath(): string {
+ return path.join(canvasControlDir(), 'nodeterm.sh')
+}
+
+function skillPathIn(configDir: string): string {
+ return path.join(configDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md')
+}
+
+function writeShim(): void {
+ const dir = canvasControlDir()
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(shimPath(), buildControlShimScript(codexThreadIdentityRoot()), 'utf8')
+ try {
+ fs.chmodSync(shimPath(), 0o755)
+ } catch {
+ /* best effort on filesystems without POSIX modes */
+ }
+ // Same upgrade sweep as desktop: the POSIX shim replaced this Electron-as-Node script.
+ try {
+ fs.rmSync(path.join(dir, 'canvas-control-cli.mjs'), { force: true })
+ } catch {
+ /* best effort */
+ }
+}
+
+function installInstructions(file: string, body: string): void {
+ try {
+ let existing = ''
+ try {
+ existing = fs.readFileSync(file, 'utf8')
+ } catch {
+ /* first install */
+ }
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, mergeCanvasControlBlock(existing, body), 'utf8')
+ } catch (error) {
+ console.warn('[server-canvas-control] instruction install failed', file, error)
+ }
+}
+
+/**
+ * Boot the Server Edition canvas runtime and install its discovery surface.
+ *
+ * The shim itself always lives under the configured server dataDir, never under a hard-coded
+ * `~/.nodeterm-server`. Writes to real Claude/Codex/Gemini homes are separately controlled by the
+ * existing `installHooks` gate, exactly like `initServerContextLink`.
+ */
+export async function initServerCanvasControl(
+ deps: ServerCanvasControlDeps
+): Promise<ServerCanvasControl> {
+ try {
+ writeShim()
+ } catch (error) {
+ // The HTTP runtime remains useful even if discovery files cannot be written; fail open and loud.
+ console.warn('[server-canvas-control] shim install failed', error)
+ }
+
+ const skillBody = buildCanvasSkillBody(shimPath())
+ const instructions = buildCanvasControlInstructions(shimPath())
+ const installSkillInto = (configDir: string): void => {
+ const file = skillPathIn(configDir)
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, skillBody, 'utf8')
+ } catch (error) {
+ console.warn('[server-canvas-control] skill install failed', file, error)
+ }
+ }
+
+ // Required field, so this is a plain read of a decision the caller had to make — never a
+ // default. See ServerCanvasControlDeps.installAgentIntegrations for why omission must not
+ // be spellable here.
+ if (deps.installAgentIntegrations) {
+ installSkillInto(path.join(os.homedir(), '.claude'))
+ installInstructions(path.join(os.homedir(), '.codex', 'AGENTS.md'), instructions)
+ installInstructions(path.join(os.homedir(), '.gemini', 'GEMINI.md'), instructions)
+ // Managed accounts resolve skills relative to their own CLAUDE_CONFIG_DIR.
+ installHooksIntoLocalAccounts(deps.settings().claudeAccounts ?? [], installSkillInto)
+ }
+
+ const factory = new HeadlessNodeFactory({
+ workspaceStore: deps.workspaceStore,
+ ptyManager: deps.ptyManager,
+ settings: deps.settings,
+ cliCaps: deps.cliCaps ?? claudeCliCaps,
++ // grok answers with its own probe — see HeadlessNodeFactoryDeps.grokCaps.
++ grokCaps: deps.grokCaps ?? grokCliCaps,
+ codexSharedIdentity:
+ deps.codexSharedIdentity ?? (() => codexIdentityCaps().then((caps) => caps.shared)),
+ stateOf: nodeState,
+ agentIdOf: (nodeId) => mirrorEntry(nodeId)?.agentId,
+ publishProject: (project: Project) => platform().broadcast(IPC.workspaceExternalChange, project)
+ })
+
+ const messaging: AgentMessagingDeps = {
+ paneOwner: (nodeId) => deps.ptyManager.paneOwner(nodeId),
+ // Server delivery has no renderer/xterm echo stream. Capture the headless pane instead and
+ // separate paste from Enter so a fresh TUI cannot swallow the first submit keystroke.
+ sendEnvelope: (nodeId, envelope) =>
+ sendSettledEnvelope(deps.ptyManager, nodeId, envelope),
+ hasLiveSession: (nodeId) => deps.ptyManager.hasLiveSession(nodeId),
+ mirrorEntry,
+ projects: () => deps.workspaceStore.persistedCanvases(),
+ isRemoteNode: () => false,
+ messagingEnabled: messagingEnabledVia((projectId) =>
+ deps.workspaceStore.capabilityProjectFor(projectId)),
+ paneOwnerProject,
+ callerOwnsTarget: (sourceNodeId, targetNodeId) =>
+ factory.ownsSpawn(sourceNodeId, targetNodeId),
+ customAgents: () => deps.settings().customAgents,
+ appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry)
+ }
+ const queue = createDeliveryQueue(messaging)
+ messaging.queue = queue
+
+ const actions: ServerEditionControlActions = {
+ openProject: (sourceNodeId, args, verified) =>
+ factory.openProject(sourceNodeId, args, verified),
+ openTerminal: (sourceNodeId, args, verified) =>
+ factory.openTerminal(sourceNodeId, args, verified),
+ openAgent: (sourceNodeId, args, verified) => factory.openAgent(sourceNodeId, args, verified),
+ close: (sourceNodeId, args, verified) => factory.close(sourceNodeId, args, verified),
+ link: (sourceNodeId, args, verified) => factory.link(sourceNodeId, args, verified),
+ group: (sourceNodeId, args) => factory.group(sourceNodeId, args),
+ rename: (sourceNodeId, args) => factory.rename(sourceNodeId, args),
+ color: (sourceNodeId, args) => factory.color(sourceNodeId, args),
+ sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),
+ // `runDelivery` applies caller→target creator proof before any pane probe or write, and
+ // re-applies it when a queued delivery flushes.
+ deliver: async (input) => (await deliverFromControl(input, messaging)).reply
+ }
+
+ // Boot deliberately performs no canvas/session adoption. Creator proof is process-local and a
+ // restart clears it, so an owner request or browser view is the only cold-spawn authority.
+ await factory.start()
+
+ return {
+ handler: createServerEditionControlHandler(actions),
+ onAgentEvent: (event) => {
+ onMessagingAgentEvent(event, queue)
+ factory.onAgentEvent(event)
+ },
+ installSkillInto,
+ stop: () => {
+ factory.stop()
+ queue.resetForTests()
+ }
+ }
+}
diff --cc src/server/headless-node-factory.test.ts
index 2a4f49a54,000000000..c8b3f8a0d
mode 100644,000000..100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@@ -1,1110 -1,0 +1,1112 @@@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { fakePlatform } from '../core/platform-fake'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { WorkspaceStore } from '../core/workspace-store'
+import type { AgentState } from '../shared/agents/normalize'
+import {
+ DEFAULT_SETTINGS,
+ type CanvasNodeState,
+ type PtyCreateOptions,
+ type PtyCreateResult,
+ type Settings,
+ type Workspace
+} from '../shared/types'
+import {
+ createHeadlessNodeOwnership,
+ HeadlessNodeFactory,
+ type HeadlessNodeOwnership,
+ type HeadlessPty
+} from './headless-node-factory'
+
+class FakePty implements HeadlessPty {
+ readonly creates: PtyCreateOptions[] = []
+ readonly sends: Array<{ nodeId: string; text: string }> = []
+ readonly destroys: Array<{
+ clientId: number | null
+ nodeId: string
+ everySocket: boolean | undefined
+ wasLive: boolean
+ }> = []
+ readonly live = new Set<string>()
+ readonly alreadyDead = new Set<string>()
+
+ async createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {
+ this.creates.push(options)
+ if (options.persistKey) this.live.add(options.persistKey)
+ return { sessionId: `pty-${options.persistKey}`, fresh: true, persistent: true }
+ }
+
+ async sessionExists(persistKey: string): Promise<boolean> {
+ return this.live.has(persistKey)
+ }
+
+ async sendText(nodeId: string, text: string): Promise<boolean> {
+ this.sends.push({ nodeId, text })
+ return true
+ }
+
+ async destroySession(
+ clientId: number | null,
+ nodeId: string,
+ opts?: { everySocket?: boolean }
+ ): Promise<void> {
+ const wasLive = this.live.delete(nodeId)
+ this.destroys.push({ clientId, nodeId, everySocket: opts?.everySocket, wasLive })
+ this.alreadyDead.add(nodeId)
+ }
+
+ killOutOfBand(nodeId: string): void {
+ this.live.delete(nodeId)
+ this.alreadyDead.add(nodeId)
+ }
+}
+
+const terminal = (
+ id: string,
+ title: string,
+ agentId: 'claude' | 'codex' | 'gemini' = 'claude',
+ x = 20
+): CanvasNodeState => ({
+ id,
+ kind: 'terminal',
+ position: { x, y: 30 },
+ size: { width: 640, height: 440 },
+ title,
+ color: '#d97757',
+ group: null,
+ tags: [],
+ agentId
+})
+
+describe('HeadlessNodeFactory', () => {
+ let dataDir = ''
+ let projectDir = ''
+ let store: WorkspaceStore
+ let pty: FakePty
+ let states: Record<string, AgentState | undefined>
+ let published: CanvasNodeState[]
+ let removed: string[]
+ let publishedProjects: Workspace['projects']
+ let factory: HeadlessNodeFactory
+ let ownership: HeadlessNodeOwnership
+ let codexSharedIdentity: boolean
+
+ const settings = (): Settings => ({
+ ...DEFAULT_SETTINGS,
+ // Makes command expectations independent of the local Claude version probe.
+ claudePermissionMode: 'manual'
+ })
+
+ beforeEach(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-headless-factory-'))
+ projectDir = path.join(dataDir, 'project')
+ fs.mkdirSync(projectDir, { recursive: true })
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dataDir }))
+ store = new WorkspaceStore()
+ pty = new FakePty()
+ states = {}
+ published = []
+ removed = []
+ publishedProjects = []
+ codexSharedIdentity = false
+ ownership = createHeadlessNodeOwnership()
+ ownership.record('term-upstream', {
+ sourceNodeId: 'term-source',
+ projectId: 'project-1'
+ })
+ ownership.record('term-owned', {
+ sourceNodeId: 'term-source',
+ projectId: 'project-1'
+ })
+ const initial: Workspace = {
+ version: 2,
+ activeProjectId: 'project-1',
+ projects: [
+ {
+ id: 'project-1',
+ name: 'Test',
+ color: '#0a84ff',
+ cwd: projectDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ terminal('term-source', 'Director'),
+ terminal('term-upstream', 'Upstream', 'codex', 80),
+ terminal('term-owned', 'Owned', 'gemini', 900)
+ ],
+ bridges: [],
+ ropes: []
+ }
+ ]
+ }
+ await store.save(initial)
+ factory = new HeadlessNodeFactory({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings,
+ cliCaps: async () => ({
+ version: null,
+ autoPermissionMode: false,
+ fullscreenTui: false,
+ sessionIdFlag: false
+ }),
++ // Stated, not defaulted — the required field is what stops a probe being forgotten.
++ grokCaps: async () => ({ sessionIdFlag: false }),
+ codexSharedIdentity: async () => codexSharedIdentity,
+ ownership,
+ stateOf: (id) => states[id],
+ publishNode: (_projectId, node) => published.push(node),
+ publishRemoval: (_projectId, nodeId) => removed.push(nodeId),
+ publishProject: (project) => publishedProjects.push(structuredClone(project))
+ })
+ })
+
+ afterEach(() => {
+ factory.stop()
+ resetPlatformForTests()
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ it('creates a terminal PTY, persists both workspace index and project file, and publishes it', async () => {
+ const reply = await factory.openTerminal(
+ 'term-source',
+ { cwd: projectDir, cmd: 'printf hello' },
+ true
+ )
+ expect(reply).toMatchObject({ ok: true, result: { id: expect.stringMatching(/^term-/) } })
+ const id = (reply.result as { id: string }).id
+
+ expect(pty.creates).toEqual([
+ expect.objectContaining({
+ cwd: projectDir,
+ cols: 120,
+ rows: 36,
+ persistKey: id,
+ ownerProjectId: 'project-1'
+ })
+ ])
+ expect(pty.sends).toEqual([{ nodeId: id, text: 'printf hello' }])
+ expect(published.map((node) => node.id)).toEqual([id])
+
+ expect(fs.existsSync(path.join(dataDir, 'workspace.json'))).toBe(true)
+ const projectFile = path.join(projectDir, '.nodeterm', 'project.json')
+ expect(fs.existsSync(projectFile)).toBe(true)
+ const raw = JSON.parse(fs.readFileSync(projectFile, 'utf8')) as { nodes: CanvasNodeState[] }
+ const created = raw.nodes.find((node) => node.id === id)
+ // Local project files store cwd portably; WorkspaceStore resolves it back to absolute on load.
+ expect(created).toMatchObject({ kind: 'terminal', cwd: '.' })
+ expect(created!.position.x).toBeGreaterThan(terminal('x', 'x').position.x)
+
+ const reloaded = await new WorkspaceStore().load({ sideline: false })
+ expect(reloaded.projects[0].nodes.find((node) => node.id === id)).toMatchObject({
+ cwd: projectDir
+ })
+ })
+
+ it('re-grants an exact saved local project after a Server restart before cross-project open', async () => {
+ const targetDir = path.join(dataDir, 'loop-project')
+ fs.mkdirSync(targetDir, { recursive: true })
+ const workspace = await store.load({ sideline: false })
+ workspace.projects.push({
+ id: 'project-loop',
+ name: 'Loop',
+ color: '#6ac4dc',
+ cwd: targetDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [],
+ bridges: [],
+ ropes: []
+ })
+ await store.save(workspace)
+
+ await expect(
+ factory.openAgent(
+ 'term-source',
+ { agent: 'claude', project: 'project-loop', prompt: 'resume loop' },
+ true
+ )
+ ).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('project-target-refused')
+ })
+
+ await expect(
+ factory.openProject('term-source', { cwd: targetDir }, true)
+ ).resolves.toMatchObject({
+ ok: true,
+ result: {
+ projectId: 'project-loop',
+ cwd: targetDir,
+ created: false,
+ serverExistingOnly: true
+ }
+ })
+
+ // A grant belongs to the exact verified caller. Another agent in the same source project may
+ // not consume it merely because it learned the returned project id.
+ await expect(
+ factory.openAgent(
+ 'term-upstream',
+ { agent: 'claude', project: 'project-loop', prompt: 'steal grant' },
+ true
+ )
+ ).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('project-target-refused')
+ })
+
+ const opened = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', project: 'project-loop', prompt: 'resume loop' },
+ true
+ )
+ expect(opened.ok).toBe(true)
+ const id = (opened.result as { id: string }).id
+ expect(pty.creates.at(-1)).toMatchObject({
+ persistKey: id,
+ ownerProjectId: 'project-loop',
+ cwd: targetDir
+ })
+ expect((await store.load({ sideline: false })).projects
+ .find((project) => project.id === 'project-loop')?.nodes
+ .some((node) => node.id === id)).toBe(true)
+ })
+
+ it('never creates or enumerates a project through Server open-project', async () => {
+ const missing = path.join(dataDir, 'not-registered')
+ fs.mkdirSync(missing, { recursive: true })
+
+ await expect(
+ factory.openProject('term-source', { cwd: missing }, true)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('server-existing-only')
+ })
+ await expect(
+ factory.openProject('term-source', { cwd: projectDir }, false)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('identity-refused')
+ })
+
+ const reloaded = await store.load({ sideline: false })
+ expect(reloaded.projects).toHaveLength(1)
+ })
+
+ it('lets a verified caller close its own spawn, killing the pane before persisted edge removal and fanout', async () => {
+ const opened = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'owned work' },
+ true
+ )
+ const id = (opened.result as { id: string }).id
+ const closed = await factory.close('term-source', { node: id }, true)
+
+ expect(closed).toMatchObject({ ok: true, result: { ids: [id] } })
+ expect(pty.destroys).toEqual([
+ { clientId: null, nodeId: id, everySocket: true, wasLive: true }
+ ])
+ expect(removed).toEqual([id])
+
+ const workspace = await new WorkspaceStore().load({ sideline: false })
+ const project = workspace.projects[0]
+ expect(project.nodes.some((node) => node.id === id)).toBe(false)
+ expect(project.ropes?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(project.bridges?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(publishedProjects.at(-1)?.nodes.some((node) => node.id === id)).toBe(false)
+
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as {
+ nodes: CanvasNodeState[]
+ ropes?: Array<{ source: string; target: string }>
+ bridges?: Array<{ source: string; target: string }>
+ }
+ expect(projectFile.nodes.some((node) => node.id === id)).toBe(false)
+ expect(projectFile.ropes?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(projectFile.bridges?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ })
+
+ it('refuses a different caller without killing or removing the owned spawn', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+
+ await expect(factory.close('term-upstream', { node: id }, true)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-not-owner')
+ })
+ expect(pty.destroys).toEqual([])
+ expect((await store.load({ sideline: false })).projects[0].nodes.some((node) => node.id === id))
+ .toBe(true)
+ expect(removed).toEqual([])
+ })
+
+ it('closes a persisted owned node cleanly when its pane was already killed out of band', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+ pty.killOutOfBand(id)
+
+ await expect(factory.close('term-source', { node: id }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [id] }
+ })
+ expect(pty.destroys.at(-1)).toEqual({
+ clientId: null,
+ nodeId: id,
+ everySocket: true,
+ wasLive: false
+ })
+ expect((await store.load({ sideline: false })).projects[0].nodes.some((node) => node.id === id))
+ .toBe(false)
+ })
+
+ it('requires verified node identity before applying the process-local ownership ledger', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+
+ await expect(factory.close('term-source', { node: id }, false)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-identity-refused')
+ })
+ expect(pty.destroys).toEqual([])
+ })
+
+ it('refuses every node mutation against an unowned target without a partial write or spawn', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push(
+ terminal('term-foreign', 'Foreign', 'claude', 900),
+ {
+ id: 'sticky-foreign',
+ kind: 'sticky',
+ position: { x: 1200, y: 30 },
+ size: { width: 240, height: 200 },
+ title: 'Foreign note',
+ color: '#ffd60a',
+ group: null,
+ text: 'do not touch'
+ }
+ )
+ await store.save(workspace)
+ const before = structuredClone((await store.load({ sideline: false })).projects[0])
+
+ const replies = [
+ await factory.link('term-source', { to: 'term-foreign' }, true),
+ await factory.group('term-source', { nodes: 'term-source,term-foreign' }),
+ await factory.rename('term-source', { node: 'term-foreign', title: 'Stolen' }),
+ await factory.color('term-source', { node: 'term-foreign', color: '#32d74b' }),
+ await factory.sticky('term-source', { node: 'sticky-foreign', append: 'stolen' }),
+ await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', after: 'term-foreign', prompt: 'wait on foreign work' },
+ true
+ )
+ ]
+
+ expect(replies.map((reply) => reply.ok)).toEqual([false, false, false, false, false, false])
+ expect(replies.map((reply) => reply.error)).toEqual([
+ expect.stringContaining('link-not-owner'),
+ expect.stringContaining('group-not-owner'),
+ expect.stringContaining('rename-not-owner'),
+ expect.stringContaining('color-not-owner'),
+ expect.stringContaining('sticky-not-owner'),
+ expect.stringContaining('open-agent-not-owner')
+ ])
+ expect((await store.load({ sideline: false })).projects[0]).toEqual(before)
+ expect(pty.creates).toEqual([])
+ expect(pty.sends).toEqual([])
+ expect(published).toEqual([])
+ expect(publishedProjects).toEqual([])
+ })
+
+ it('refuses to close an owned frame if doing so would reparent an unowned child', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const ownedId = (opened.result as { id: string }).id
+ const grouped = await factory.group('term-source', { nodes: ownedId })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ const workspace = await store.load({ sideline: false })
+ const foreign = terminal('term-foreign-child', 'Foreign child')
+ foreign.parentId = groupId
+ workspace.projects[0].nodes.push(foreign)
+ await store.save(workspace)
+ pty.destroys.length = 0
+
+ await expect(factory.close('term-source', { node: groupId }, true)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-not-owner')
+ })
+ expect(pty.destroys).toEqual([])
+ const after = (await store.load({ sideline: false })).projects[0]
+ expect(after.nodes.find((node) => node.id === groupId)).toBeDefined()
+ expect(after.nodes.find((node) => node.id === 'term-foreign-child')?.parentId).toBe(groupId)
+ })
+
+ it('refuses a default link endpoint because the caller did not spawn its own node', async () => {
+ const reply = await factory.link('term-source', { to: 'term-upstream' }, true)
+
+ expect(reply).toMatchObject({
+ ok: false,
+ error: expect.stringContaining('link-not-owner')
+ })
+ expect(pty.sends).toEqual([])
+ const workspace = await new WorkspaceStore().load({ sideline: false })
+ expect(workspace.projects[0].bridges).toEqual([])
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as { bridges?: Array<{ source: string; target: string }> }
+ expect(projectFile.bridges).toEqual([])
+ expect(published).toEqual([])
+ expect(publishedProjects).toEqual([])
+ })
+
+ it('links two arbitrary existing nodes in the caller project', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push(terminal('term-third', 'Third', 'gemini', 900))
+ await store.save(workspace)
+ ownership.record('term-third', { sourceNodeId: 'term-source', projectId: 'project-1' })
+
+ await expect(
+ factory.link('term-source', { from: 'term-upstream', to: 'term-third' }, true)
+ ).resolves.toMatchObject({
+ ok: true,
+ result: { from: 'term-upstream', linked: ['term-third'] }
+ })
+ expect((await store.load({ sideline: false })).projects[0].bridges).toEqual([
+ expect.objectContaining({ source: 'term-upstream', target: 'term-third' })
+ ])
+ expect(pty.sends).toEqual([])
+ })
+
+ it('refuses unverified and cross-project link endpoints without a partial graph edit', async () => {
+ await expect(factory.link('term-source', { to: 'term-upstream' }, false)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('link-identity-refused')
+ })
+
+ const workspace = await store.load({ sideline: false })
+ const otherDir = path.join(dataDir, 'other-project')
+ fs.mkdirSync(otherDir, { recursive: true })
+ workspace.projects.push({
+ id: 'project-2',
+ name: 'Other',
+ color: '#32d74b',
+ cwd: otherDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [terminal('term-other-project', 'Elsewhere', 'claude')],
+ bridges: [],
+ ropes: []
+ })
+ await store.save(workspace)
+
+ await expect(
+ factory.link('term-source', { to: 'term-upstream,term-other-project' }, true)
+ ).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('link-project-refused')
+ })
+ expect((await store.load({ sideline: false })).projects[0].bridges).toEqual([])
+ expect(publishedProjects).toEqual([])
+ expect(pty.sends).toEqual([])
+ })
+
+ it('wraps loose nodes in a labeled persisted group and fans out every structural mutation', async () => {
+ const before = (await store.load({ sideline: false })).projects[0]
+ const beforePositions = new Map(before.nodes.map((node) => [node.id, node.position]))
+ const reply = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Director team'
+ })
+ expect(reply).toMatchObject({
+ ok: true,
+ result: {
+ groupId: expect.stringMatching(/^group-/),
+ grouped: ['term-upstream', 'term-owned'],
+ skipped: 0
+ }
+ })
+ const groupId = (reply.result as { groupId: string }).groupId
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ const group = project.nodes.find((node) => node.id === groupId)!
+ expect(project.nodes[0]).toMatchObject({ id: groupId, kind: 'group' })
+ expect(group.title).toBe('Director team')
+ for (const id of ['term-upstream', 'term-owned']) {
+ const child = project.nodes.find((node) => node.id === id)!
+ expect(child.parentId).toBe(groupId)
+ expect({
+ x: group.position.x + child.position.x,
+ y: group.position.y + child.position.y
+ }).toEqual(beforePositions.get(id))
+ }
+ expect(published.map((node) => node.id)).toEqual(
+ expect.arrayContaining([groupId, 'term-upstream', 'term-owned'])
+ )
+ expect(publishedProjects.at(-1)?.nodes.find((node) => node.id === groupId)?.title).toBe(
+ 'Director team'
+ )
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as { nodes: CanvasNodeState[] }
+ expect(projectFile.nodes.find((node) => node.id === groupId)).toMatchObject({
+ kind: 'group',
+ title: 'Director team'
+ })
+ })
+
+ it('lets the creator close a nested frame only, promoting surviving members to its parent', async () => {
+ const outerReply = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Outer'
+ })
+ const outerId = (outerReply.result as { groupId: string }).groupId
+ const innerReply = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Inner'
+ })
+ const innerId = (innerReply.result as { groupId: string }).groupId
+ const before = (await store.load({ sideline: false })).projects[0]
+ const root = (project: (typeof before), id: string): { x: number; y: number } => {
+ const node = project.nodes.find((candidate) => candidate.id === id)!
+ let x = node.position.x
+ let y = node.position.y
+ let parentId = node.parentId
+ const seen = new Set<string>()
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = project.nodes.find((candidate) => candidate.id === parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+ }
+ const rootsBefore = new Map(
+ ['term-upstream', 'term-owned'].map((id) => [id, root(before, id)])
+ )
+ published.length = 0
+ publishedProjects.length = 0
+ removed.length = 0
+
+ await expect(factory.close('term-source', { node: innerId }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [innerId] }
+ })
+
+ const after = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ expect(after.nodes.some((node) => node.id === innerId)).toBe(false)
+ expect(after.nodes.some((node) => node.id === outerId)).toBe(true)
+ for (const id of ['term-upstream', 'term-owned']) {
+ expect(after.nodes.find((node) => node.id === id)?.parentId).toBe(outerId)
+ expect(root(after, id)).toEqual(rootsBefore.get(id))
+ }
+ expect(pty.destroys).toEqual([])
+ expect(removed).toEqual([innerId])
+ expect(published.map((node) => node.id)).toEqual(
+ expect.arrayContaining(['term-upstream', 'term-owned'])
+ )
+ expect(publishedProjects.at(-1)?.nodes.some((node) => node.id === innerId)).toBe(false)
+ })
+
+ it('refuses a non-creator that tries to close a headless-created frame', async () => {
+ const grouped = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned'
+ })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ publishedProjects.length = 0
+
+ await expect(factory.close('term-upstream', { node: groupId }, true)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-not-owner')
+ })
+ expect((await store.load({ sideline: false })).projects[0].nodes.some(
+ (node) => node.id === groupId
+ )).toBe(true)
+ expect(pty.destroys).toEqual([])
+ expect(removed).toEqual([])
+ expect(publishedProjects).toEqual([])
+ })
+
+ it('closes an owned empty frame after its members were separately closed', async () => {
+ const first = await factory.openTerminal('term-source', {}, true)
+ const second = await factory.openTerminal('term-source', {}, true)
+ const memberIds = [
+ (first.result as { id: string }).id,
+ (second.result as { id: string }).id
+ ]
+ const grouped = await factory.group('term-source', { nodes: memberIds.join(',') })
+ const groupId = (grouped.result as { groupId: string }).groupId
+
+ for (const id of memberIds) {
+ await expect(factory.close('term-source', { node: id }, true)).resolves.toMatchObject({
+ ok: true
+ })
+ }
+ expect((await store.load({ sideline: false })).projects[0].nodes.find(
+ (node) => node.id === groupId
+ )).toMatchObject({ kind: 'group' })
+
+ await expect(factory.close('term-source', { node: groupId }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [groupId] }
+ })
+ const after = await store.load({ sideline: false })
+ expect(after.projects[0].nodes.some((node) => node.id === groupId)).toBe(false)
+ expect(pty.destroys.map((entry) => entry.nodeId)).toEqual(memberIds)
+ expect(removed).toEqual([...memberIds, groupId])
+ })
+
+ it('applies a validated palette color when creating a group', async () => {
+ const reply = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Purple team',
+ color: '#bf5af2'
+ })
+ const groupId = (reply.result as { groupId: string }).groupId
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ expect(project.nodes.find((node) => node.id === groupId)).toMatchObject({
+ title: 'Purple team',
+ color: '#bf5af2'
+ })
+ expect(publishedProjects.at(-1)?.nodes.find((node) => node.id === groupId)?.color).toBe(
+ '#bf5af2'
+ )
+ expect(pty.sends).toEqual([])
+ })
+
+ it('recolors a node, frame, and sticky with persistence and fanout but no PTY write', async () => {
+ const grouped = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Color targets'
+ })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ id: 'sticky-color',
+ kind: 'sticky',
+ position: { x: 1200, y: 30 },
+ size: { width: 240, height: 200 },
+ title: 'Color note',
+ color: '#ffd60a',
+ group: null,
+ text: 'ready'
+ })
+ await store.save(workspace)
+ ownership.record('sticky-color', { sourceNodeId: 'term-source', projectId: 'project-1' })
+ published.length = 0
+ publishedProjects.length = 0
+
+ await expect(factory.color('term-source', {
+ node: `term-upstream,${groupId},sticky-color`,
+ color: '#32d74b'
+ })).resolves.toMatchObject({
+ ok: true,
+ result: {
+ colored: ['term-upstream', groupId, 'sticky-color'],
+ skipped: 0,
+ color: '#32d74b'
+ }
+ })
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ for (const id of ['term-upstream', groupId, 'sticky-color']) {
+ expect(project.nodes.find((node) => node.id === id)?.color, id).toBe('#32d74b')
+ }
+ expect(published.map((node) => node.id)).toEqual([
+ 'term-upstream',
+ groupId,
+ 'sticky-color'
+ ])
+ expect(publishedProjects).toHaveLength(1)
+ expect(pty.sends).toEqual([])
+ expect(pty.destroys).toEqual([])
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as { nodes: CanvasNodeState[] }
+ expect(projectFile.nodes.find((node) => node.id === 'sticky-color')?.color).toBe('#32d74b')
+ })
+
+ it('refuses invalid group and recolor values by name without persistence or fanout', async () => {
+ await expect(factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ color: 'var(--danger)'
+ })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('node-color-invalid')
+ })
+ await expect(factory.color('term-source', {
+ node: 'term-source',
+ color: '#ffffff'
+ })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('node-color-invalid')
+ })
+ const project = (await store.load({ sideline: false })).projects[0]
+ expect(project.nodes.filter((node) => node.kind === 'group')).toEqual([])
+ expect(project.nodes.find((node) => node.id === 'term-source')?.color).toBe('#d97757')
+ expect(published).toEqual([])
+ expect(publishedProjects).toEqual([])
+ expect(pty.sends).toEqual([])
+ })
+
+ it('refuses grouping across containers or across an ancestor boundary', async () => {
+ const workspace = await store.load({ sideline: false })
+ const frame: CanvasNodeState = {
+ id: 'group-existing',
+ kind: 'group',
+ position: { x: 700, y: 20 },
+ size: { width: 760, height: 560 },
+ title: 'Existing frame',
+ color: '#32d74b',
+ group: null
+ }
+ const child = terminal('term-inside', 'Inside', 'gemini', 40)
+ child.parentId = frame.id
+ workspace.projects[0].nodes.unshift(frame)
+ workspace.projects[0].nodes.push(child)
+ await store.save(workspace)
+ ownership.record('group-existing', { sourceNodeId: 'term-source', projectId: 'project-1' })
+ ownership.record('term-inside', { sourceNodeId: 'term-source', projectId: 'project-1' })
+
+ for (const nodes of ['term-inside,term-upstream', 'group-existing,term-inside']) {
+ await expect(factory.group('term-source', { nodes })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('siblings in one container')
+ })
+ }
+ const after = await store.load({ sideline: false })
+ expect(after.projects[0].nodes.filter((node) => node.kind === 'group')).toHaveLength(1)
+ expect(after.projects[0].nodes.find((node) => node.id === 'term-inside')?.parentId).toBe(
+ 'group-existing'
+ )
+ expect(publishedProjects).toEqual([])
+ })
+
+ it('renames a node, group, and sticky durably without ever writing into their panes', async () => {
+ const grouped = await factory.group('term-source', {
+ nodes: 'term-upstream,term-owned',
+ label: 'Old group'
+ })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ id: 'sticky-status',
+ kind: 'sticky',
+ position: { x: 1200, y: 30 },
+ size: { width: 240, height: 200 },
+ title: 'Old note',
+ color: '#ffd60a',
+ group: null,
+ text: 'ready'
+ })
+ await store.save(workspace)
+ ownership.record('sticky-status', { sourceNodeId: 'term-source', projectId: 'project-1' })
+ published.length = 0
+ publishedProjects.length = 0
+
+ await expect(
+ factory.rename('term-source', { node: 'term-upstream', title: 'Reviewed\nUpstream' })
+ ).resolves.toMatchObject({ ok: true })
+ await expect(
+ factory.rename('term-source', { node: groupId, title: 'Director group' })
+ ).resolves.toMatchObject({ ok: true })
+ await expect(
+ factory.rename('term-source', { node: 'sticky-status', title: 'Round status' })
+ ).resolves.toMatchObject({ ok: true })
+
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ expect(project.nodes.find((node) => node.id === 'term-upstream')).toMatchObject({
+ title: 'Reviewed Upstream',
+ titleAuto: false
+ })
+ expect(project.nodes.find((node) => node.id === groupId)).toMatchObject({
+ title: 'Director group',
+ titleAuto: false
+ })
+ expect(project.nodes.find((node) => node.id === 'sticky-status')).toMatchObject({
+ title: 'Round status',
+ titleAuto: false
+ })
+ expect(published.map((node) => node.id)).toEqual([
+ 'term-upstream',
+ groupId,
+ 'sticky-status'
+ ])
+ expect(publishedProjects).toHaveLength(3)
+ expect(pty.sends).toEqual([])
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as { nodes: CanvasNodeState[] }
+ expect(projectFile.nodes.find((node) => node.id === 'sticky-status')?.title).toBe(
+ 'Round status'
+ )
+ })
+
+ it('places repeated spawns in the first free deterministic slots without overlapping busy nodes', async () => {
+ const workspace = await store.load({ sideline: false })
+ // Slot zero to the right of the source is already busy before any control request arrives.
+ workspace.projects[0].nodes.push(terminal('term-busy-slot', 'Busy slot', 'gemini', 740))
+ await store.save(workspace)
+
+ const spawnedIds: string[] = []
+ for (let i = 0; i < 5; i++) {
+ const reply = await factory.openTerminal('term-source', {}, true)
+ spawnedIds.push((reply.result as { id: string }).id)
+ }
+
+ const nodes = (await store.load({ sideline: false })).projects[0].nodes
+ const overlap = (a: CanvasNodeState, b: CanvasNodeState): boolean =>
+ a.position.x < b.position.x + b.size.width &&
+ a.position.x + a.size.width > b.position.x &&
+ a.position.y < b.position.y + b.size.height &&
+ a.position.y + a.size.height > b.position.y
+ for (const id of spawnedIds) {
+ const node = nodes.find((candidate) => candidate.id === id)!
+ expect(nodes.filter((candidate) => candidate.id !== id).some((candidate) => overlap(node, candidate)), id)
+ .toBe(false)
+ }
+ expect(new Set(spawnedIds.map((id) => {
+ const node = nodes.find((candidate) => candidate.id === id)!
+ return `${node.position.x},${node.position.y}`
+ })).size).toBe(spawnedIds.length)
+ })
+
+ it.each([
+ ['claude', "claude 'do work'"],
+ ['codex', "codex 'do work' --ask-for-approval untrusted"],
+ ['gemini', "gemini 'do work'"]
+ ] as const)('assembles the %s launch through the shared command builder', async (agent, command) => {
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent, prompt: 'do work' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.creates.at(-1)).toMatchObject({
+ persistKey: id,
+ ownerProjectId: 'project-1',
+ agentId: agent
+ })
+ expect(pty.sends.at(-1)).toEqual({ nodeId: id, text: command })
+ })
+
+ it('never cold-spawns a persisted arm during boot reconciliation', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ ...terminal('term-dormant', 'Dormant'),
+ pendingLaunch: {
+ after: [],
+ command: "claude 'must stay dormant'",
+ executor: 'server'
+ }
+ })
+ await store.save(workspace)
+
+ const load = vi.spyOn(store, 'load')
+ await factory.start()
+
+ expect(load).not.toHaveBeenCalled()
+ expect(pty.creates).toEqual([])
+ expect(pty.sends).toEqual([])
+ load.mockRestore()
+ expect((await store.load({ sideline: false })).projects[0].nodes
+ .find((node) => node.id === 'term-dormant')?.pendingLaunch).toBeDefined()
+ })
+
+ it('does not adopt or control a persisted arm even when its backend survived', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ ...terminal('term-survivor', 'Survivor'),
+ pendingLaunch: {
+ after: [],
+ command: "claude 'resume owned work'",
+ executor: 'server'
+ }
+ })
+ await store.save(workspace)
+ pty.live.add('term-survivor')
+
+ await factory.start()
+
+ expect(pty.creates).toEqual([])
+ expect(pty.sends).toEqual([])
+ expect((await store.load({ sideline: false })).projects[0].nodes
+ .find((node) => node.id === 'term-survivor')?.pendingLaunch).toBeDefined()
+ })
+
+ it('does not grant a plain shell Claude control authority by default', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ ...terminal('term-plain', 'Plain shell'),
+ agentId: undefined
+ })
+ await store.save(workspace)
+
+ await expect(factory.openTerminal('term-plain', {}, true)).resolves.toEqual({
+ ok: false,
+ error: 'source node is not a control-capable agent'
+ })
+ expect(pty.creates).toEqual([])
+ })
+
+ it('routes a Codex launch through the managed launcher when Server shared identity is ready', async () => {
+ codexSharedIdentity = true
+
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'codex', prompt: 'do work' },
+ true
+ )
+
+ expect(reply.ok).toBe(true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.sends.at(-1)).toEqual({
+ nodeId: id,
+ text: "nodeterm-codex 'do work' --ask-for-approval untrusted"
+ })
+ })
+
+ it('persists --after without launching, then flushes exactly once on the idle state', async () => {
+ states['term-upstream'] = 'working'
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: 'term-upstream' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.sends).toEqual([])
+
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toEqual({
+ after: ['term-upstream'],
+ command: "claude 'consume result'",
+ executor: 'server'
+ })
+ expect(workspace.projects[0].bridges).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ source: 'term-source', target: id }),
+ expect.objectContaining({ source: id, target: 'term-upstream' })
+ ])
+ )
+
+ states['term-upstream'] = 'done'
+ await factory.refreshArmed()
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()
+ })
+
+ it('holds a fresh dependency through its boot done blip, then releases after working -> done', async () => {
+ const upstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'produce result' },
+ true
+ )
+ const upstreamId = (upstreamReply.result as { id: string }).id
+ pty.sends.length = 0
+
+ const downstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: upstreamId },
+ true
+ )
+ const downstreamId = (downstreamReply.result as { id: string }).id
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toMatchObject({ after: [upstreamId], awaitWorking: [upstreamId] })
+
+ // Fresh Claude briefly idles at its composer before its argv prompt begins. This done is not
+ // terminal evidence because no working turn has been observed since the downstream was armed.
+ states[upstreamId] = 'done'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'done' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+
+ states[upstreamId] = 'working'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'working' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .not.toHaveProperty('awaitWorking')
+
+ states[upstreamId] = 'done'
+ factory.onAgentEvent({ nodeId: upstreamId, state: 'done' })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: downstreamId, text: "claude 'consume result'" }])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toBeUndefined()
+ })
+
+ it('launches immediately when a fresh dependency is already done at arm time', async () => {
+ const upstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'produce result' },
+ true
+ )
+ const upstreamId = (upstreamReply.result as { id: string }).id
+ states[upstreamId] = 'done'
+ pty.sends.length = 0
+
+ const downstreamReply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: upstreamId },
+ true
+ )
+ const downstreamId = (downstreamReply.result as { id: string }).id
+ expect(pty.sends).toEqual([{ nodeId: downstreamId, text: "claude 'consume result'" }])
+ const workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === downstreamId)?.pendingLaunch)
+ .toBeUndefined()
+ })
+
+ it('creates and updates a persisted sticky with lineage and an accountable byline', async () => {
+ const createdReply = await factory.sticky('term-source', {
+ node: 'Round status',
+ create: 'yes',
+ text: 'Round 1 complete'
+ })
+ expect(createdReply).toMatchObject({
+ ok: true,
+ result: { id: expect.stringMatching(/^sticky-/), created: true, mode: 'replace' }
+ })
+ const id = (createdReply.result as { id: string }).id
+
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)).toMatchObject({
+ kind: 'sticky',
+ title: 'Round status',
+ text: 'Round 1 complete',
+ textUpdatedBy: 'Director'
+ })
+ expect(workspace.projects[0].ropes).toEqual(
+ expect.arrayContaining([expect.objectContaining({ source: 'term-source', target: id })])
+ )
+
+ const updatedReply = await factory.sticky('term-source', {
+ node: id,
+ append: 'Round 2 ready'
+ })
+ expect(updatedReply).toMatchObject({
+ ok: true,
+ result: { id, created: false, mode: 'append' }
+ })
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.text).toBe(
+ 'Round 1 complete\nRound 2 ready'
+ )
+ expect(published.filter((node) => node.id === id)).toHaveLength(2)
+ })
+
+ it('refuses a non-v1 agent before a node or PTY is created', async () => {
+ const reply = await factory.openAgent('term-source', { agent: 'grok' }, true)
+ expect(reply).toMatchObject({ ok: false, error: expect.stringContaining('claude|codex|gemini') })
+ expect(pty.creates).toEqual([])
+ })
+})
diff --cc src/server/headless-node-factory.ts
index 131660d55,000000000..810ea733b
mode 100644,000000..100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@@ -1,1411 -1,0 +1,1423 @@@
+import { randomBytes, randomUUID } from 'node:crypto'
+import path from 'node:path'
+
+import { publishCanvasMutation } from '../core/canvas-sync'
+import { gateProjectTarget, GRANT_CAP } from '../core/project-grants'
+import { planBridges, type LinkEndpoint } from '../shared/canvas-link'
+import {
+ invalidNodeColorMessage,
+ isNodeColor,
+ NODE_COLORS,
+ type NodeColor
+} from '../shared/node-colors'
+import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../shared/sticky-write'
+import type { WorkspaceStore } from '../core/workspace-store'
+import {
+ AGENT_CONFIG,
+ canContextLink,
+ canControlCanvas,
+ gatePermissionMode,
+ hasHooks,
+ resolvePermissionMode,
+ supportsSessionIdFlag,
+ type AgentId,
+ type BuiltinAgentId
+} from '../shared/agents/config'
+import { assembleLaunchCommand } from '../shared/agents/launch'
+import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
+import { oneLine } from '../shared/one-line'
+import type {
+ BridgeLink,
+ CanvasNodeState,
+ ClaudeCliCaps,
++ GrokCliCaps,
+ Project,
+ PtyCreateOptions,
+ PtyCreateResult,
+ Settings,
+ Workspace
+} from '../shared/types'
+
+export interface ServerControlReply {
+ ok: boolean
+ message?: string
+ result?: unknown
+ error?: string
+}
+
+/** The PtyManager surface the headless factory uses, kept narrow for deterministic tests. */
+export interface HeadlessPty {
+ createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult>
+ /** Probe only. Boot reconciliation must never turn absence into a fresh session. */
+ sessionExists(persistKey: string): Promise<boolean>
+ sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+ destroySession(
+ clientId: number | null,
+ persistKey: string,
+ opts?: { everySocket?: boolean }
+ ): Promise<void>
+}
+
+/** WorkspaceStore's mutation surface, also narrow so tests can use the real store or a fake. */
+export type HeadlessWorkspace = Pick<WorkspaceStore, 'load' | 'save'>
+
+export interface HeadlessNodeFactoryDeps {
+ workspaceStore: HeadlessWorkspace
+ ptyManager: HeadlessPty
+ settings(): Settings
+ cliCaps(): Promise<ClaudeCliCaps>
++ /**
++ * grok's OWN `--session-id` probe. Separate from `cliCaps` because the two CLIs are installed and
++ * upgraded independently, so claude's answer is not evidence about grok (CLAUDE.md rule 9: a gate
++ * fed by a version probe belongs to the agent it probes). Wired even though `SERVER_AGENTS` does
++ * not yet include grok: `supportsSessionIdFlag`'s third argument is required precisely so a caller
++ * cannot forget the probe and silently get "grok never mints", and a hard-coded `false` here would
++ * be that forgotten probe, waiting for the day grok joins the set.
++ */
++ grokCaps(): Promise<GrokCliCaps>
+ /** Whether this host's Codex launcher + shared app-server identity spine are ready. */
+ codexSharedIdentity(): Promise<boolean>
+ /** Hook-mirror lookups. A stored agentId wins; these cover a plain terminal running an agent. */
+ stateOf(nodeId: string): AgentState | undefined
+ agentIdOf?(nodeId: string): string | undefined
+ env?: Record<string, string | undefined>
+ now?: () => number
+ publishNode?: (projectId: string, node: CanvasNodeState) => void
+ publishRemoval?: (projectId: string, nodeId: string) => void
+ publishProject?: (project: Project) => void
+ schedule?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>
+ clearSchedule?: (timer: ReturnType<typeof setTimeout>) => void
+ /** Injectable only so tests can seed creator facts; production uses a fresh process-local ledger. */
+ ownership?: HeadlessNodeOwnership
+}
+
+export interface HeadlessNodeOwner {
+ sourceNodeId: string
+ projectId: string
+}
+
+export interface HeadlessNodeOwnership {
+ ownerOf(nodeId: string): HeadlessNodeOwner | undefined
+ record(nodeId: string, owner: HeadlessNodeOwner): void
+ forget(nodeId: string): void
+ clear(): void
+}
+
+/**
+ * Creator proof for Server Edition canvas mutations. Deliberately process-local: after a service
+ * restart, a git-shared/hand-editable project file cannot reassert who created a node. Unknown
+ * ownership therefore fails closed until this server run records a fresh agent-requested spawn.
+ */
+export function createHeadlessNodeOwnership(): HeadlessNodeOwnership {
+ const owners = new Map<string, HeadlessNodeOwner>()
+ return {
+ ownerOf: (nodeId) => owners.get(nodeId),
+ record: (nodeId, owner) => owners.set(nodeId, owner),
+ forget: (nodeId) => owners.delete(nodeId),
+ clear: () => owners.clear()
+ }
+}
+
+const TERMINAL_LIMIT = 8
+const AGENT_LIMIT = 5
+const TERMINAL_COLS = 120
+const TERMINAL_ROWS = 36
+const TERMINAL_SIZE = { width: 640, height: 440 }
+const STICKY_SIZE = { width: 240, height: 200 }
+const H_GAP = 80
+const V_GAP = 36
+const GROUP_PAD = 28
+const GROUP_HEADER = 34
+const AFTER_RETRY_MS = 500
+const AFTER_RETRY_LIMIT = 5
+const SERVER_AGENTS: ReadonlySet<string> = new Set(['claude', 'codex', 'gemini'])
+
+function token(): string {
+ return randomBytes(4).toString('hex')
+}
+
+function nextId(prefix: 'term' | 'sticky' | 'group'): string {
+ return `${prefix}-${Date.now().toString(36)}-${token()}`
+}
+
+function edgeId(prefix: string, source: string, target: string): string {
+ return `${prefix}-${source}-${target}-${token()}`
+}
+
+function parseCount(raw: string | undefined, max: number): number {
+ return Math.max(1, Math.min(max, Number.parseInt(raw || '1', 10) || 1))
+}
+
+function terminalSize(settings: Settings): { width: number; height: number } {
+ const clamp = (value: unknown, min: number, max: number, fallback: number): number => {
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : fallback
+ return Math.min(max, Math.max(min, n))
+ }
+ return {
+ width: clamp(settings.defaultNodeWidth, 280, 2400, TERMINAL_SIZE.width),
+ height: clamp(settings.defaultNodeHeight, 160, 1600, TERMINAL_SIZE.height)
+ }
+}
+
+function unsupportedFlags(
+ args: Record<string, string>,
+ allowed: ReadonlySet<string>
+): string | undefined {
+ const unknown = Object.keys(args).find((key) => !allowed.has(key))
+ return unknown ? `--${unknown} is not supported by Server Edition canvas control` : undefined
+}
+
+function sourceProject(workspace: Workspace, nodeId: string): { project: Project; node: CanvasNodeState } | null {
+ const matches: Array<{ project: Project; node: CanvasNodeState }> = []
+ for (const project of workspace.projects) {
+ const node = project.nodes.find((candidate) => candidate.id === nodeId)
+ if (node) matches.push({ project, node })
+ }
+ return matches.length === 1 ? matches[0] : null
+}
+
+function effectiveAgentId(
+ node: CanvasNodeState,
+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined
+): AgentId | undefined {
+ const id = node.agentId || runtimeAgentId?.(node.id)
+ return id ? (id as AgentId) : undefined
+}
+
+function sourceCanControl(
+ node: CanvasNodeState,
+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined
+): boolean {
+ const agentId = effectiveAgentId(node, runtimeAgentId)
+ return !!agentId && canControlCanvas(agentId)
+}
+
+function absolutePosition(project: Project, node: CanvasNodeState): { x: number; y: number } {
+ let x = node.position.x
+ let y = node.position.y
+ let parent = node.parentId
+ const seen = new Set<string>()
+ while (parent && !seen.has(parent)) {
+ seen.add(parent)
+ const p = project.nodes.find((candidate) => candidate.id === parent)
+ if (!p) break
+ x += p.position.x
+ y += p.position.y
+ parent = p.parentId
+ }
+ return { x, y }
+}
+
+function placeRight(
+ project: Project,
+ source: CanvasNodeState,
+ size: { width: number; height: number },
+ reserved: readonly CanvasNodeState[] = []
+): { x: number; y: number } {
+ const origin = absolutePosition(project, source)
+ const sourceWidth = source.size?.width || TERMINAL_SIZE.width
+ const occupied = [...project.nodes, ...reserved].map((node) => {
+ const position = absolutePosition(project, node)
+ return {
+ x: position.x,
+ y: position.y,
+ width: Math.max(1, node.size?.width || TERMINAL_SIZE.width),
+ height: Math.max(1, node.size?.height || TERMINAL_SIZE.height)
+ }
+ })
+
+ // Keep the existing compact three-row grid, but scan it rather than assuming this request's
+ // local index is globally free. Repeated requests therefore continue into the first available
+ // row/column instead of returning to slot zero and stacking nodes on top of one another.
+ for (let slot = 0; ; slot++) {
+ const column = Math.floor(slot / 3)
+ const row = slot % 3
+ const candidate = {
+ x: origin.x + sourceWidth + H_GAP + column * (size.width + H_GAP),
+ y: origin.y + row * (size.height + V_GAP),
+ width: size.width,
+ height: size.height
+ }
+ const collides = occupied.some((rect) =>
+ candidate.x < rect.x + rect.width &&
+ candidate.x + candidate.width > rect.x &&
+ candidate.y < rect.y + rect.height &&
+ candidate.y + candidate.height > rect.y
+ )
+ if (!collides) return { x: candidate.x, y: candidate.y }
+ }
+}
+
+function addEdge(list: BridgeLink[], source: string, target: string, prefix: string): void {
+ if (source === target) return
+ if (list.some((edge) =>
+ (edge.source === source && edge.target === target) ||
+ (edge.source === target && edge.target === source))) return
+ list.push({ id: edgeId(prefix, source, target), source, target })
+}
+
+function nodeProjects(workspace: Workspace, nodeId: string): Project[] {
+ return workspace.projects.filter((project) => project.nodes.some((node) => node.id === nodeId))
+}
+
+function headlessLinkEndpoint(
+ node: CanvasNodeState,
+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined
+): LinkEndpoint {
+ const agentId = node.kind === 'terminal' ? node.agentId ?? runtimeAgentId?.(node.id) : undefined
+ return {
+ kind: node.kind,
+ contextCapable: !!agentId && canContextLink(agentId as AgentId)
+ }
+}
+
+function isDescendant(
+ nodes: readonly CanvasNodeState[],
+ candidateId: string,
+ ancestorId: string
+): boolean {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const seen = new Set<string>()
+ let current = byId.get(candidateId)
+ while (current?.parentId && !seen.has(current.parentId)) {
+ if (current.parentId === ancestorId) return true
+ seen.add(current.parentId)
+ current = byId.get(current.parentId)
+ }
+ return false
+}
+
+/** Persist frames before their descendants, matching React Flow's hydration requirement. */
+function groupsFirst(nodes: CanvasNodeState[]): CanvasNodeState[] {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const emitted = new Set<string>()
+ const visiting = new Set<string>()
+ const groups: CanvasNodeState[] = []
+ const emit = (node: CanvasNodeState): void => {
+ if (emitted.has(node.id) || node.kind !== 'group') return
+ if (visiting.has(node.id)) return
+ visiting.add(node.id)
+ const parent = node.parentId ? byId.get(node.parentId) : undefined
+ if (parent?.kind === 'group') emit(parent)
+ visiting.delete(node.id)
+ if (!emitted.has(node.id)) {
+ emitted.add(node.id)
+ groups.push(node)
+ }
+ }
+ nodes.forEach(emit)
+ return [...groups, ...nodes.filter((node) => node.kind !== 'group')]
+}
+
+/** Re-fit one persisted group around its direct children without moving them in parent space. */
+function fitGroupToChildren(
+ nodes: CanvasNodeState[],
+ groupId: string
+): CanvasNodeState[] {
+ const group = nodes.find((node) => node.id === groupId)
+ if (!group || group.kind !== 'group') return nodes
+ const children = nodes.filter((node) => node.parentId === groupId)
+ if (!children.length) return nodes
+ const absoluteX = (child: CanvasNodeState): number => group.position.x + child.position.x
+ const absoluteY = (child: CanvasNodeState): number => group.position.y + child.position.y
+ const minX = Math.min(...children.map(absoluteX))
+ const minY = Math.min(...children.map(absoluteY))
+ const maxX = Math.max(...children.map((child) => absoluteX(child) + child.size.width))
+ const maxY = Math.max(...children.map((child) => absoluteY(child) + child.size.height))
+ const x = minX - GROUP_PAD
+ const y = minY - GROUP_PAD - GROUP_HEADER
+ const size = {
+ width: maxX - minX + GROUP_PAD * 2,
+ height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER
+ }
+ return nodes.map((node) => {
+ if (node.id === groupId) return { ...node, position: { x, y }, size }
+ if (node.parentId === groupId) {
+ return {
+ ...node,
+ position: { x: absoluteX(node) - x, y: absoluteY(node) - y }
+ }
+ }
+ return node
+ })
+}
+
+function fitAncestorChain(
+ nodes: CanvasNodeState[],
+ groupId: string | undefined
+): CanvasNodeState[] {
+ let next = nodes
+ let currentId = groupId
+ const seen = new Set<string>()
+ while (currentId && !seen.has(currentId)) {
+ seen.add(currentId)
+ next = fitGroupToChildren(next, currentId)
+ currentId = next.find((node) => node.id === currentId)?.parentId
+ }
+ return next
+}
+
+function groupPersistedNodes(
+ nodes: CanvasNodeState[],
+ ids: string[],
+ groupIndex: number,
+ label: string | undefined,
+ color: NodeColor | undefined
+): { nodes: CanvasNodeState[]; groupId: string; changed: CanvasNodeState[] } | null {
+ const selected = new Set(ids)
+ const members = nodes.filter((node) => selected.has(node.id))
+ if (!members.length || new Set(members.map((node) => node.parentId ?? null)).size !== 1) {
+ return null
+ }
+ if (
+ members.some((member) =>
+ members.some(
+ (other) => other.id !== member.id && isDescendant(nodes, other.id, member.id)
+ )
+ )
+ ) {
+ return null
+ }
+
+ const minX = Math.min(...members.map((node) => node.position.x))
+ const minY = Math.min(...members.map((node) => node.position.y))
+ const maxX = Math.max(...members.map((node) => node.position.x + node.size.width))
+ const maxY = Math.max(...members.map((node) => node.position.y + node.size.height))
+ const x = minX - GROUP_PAD
+ const y = minY - GROUP_PAD - GROUP_HEADER
+ const parentId = members[0].parentId
+ const group: CanvasNodeState = {
+ id: nextId('group'),
+ kind: 'group',
+ position: { x, y },
+ size: {
+ width: maxX - minX + GROUP_PAD * 2,
+ height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER
+ },
+ title: label || `Group ${groupIndex + 1}`,
+ color: color ?? NODE_COLORS[groupIndex % NODE_COLORS.length],
+ group: null,
+ ...(parentId ? { parentId } : {})
+ }
+ const before = new Map(nodes.map((node) => [node.id, node]))
+ const updated = nodes.map((node) =>
+ selected.has(node.id)
+ ? {
+ ...node,
+ parentId: group.id,
+ position: { x: node.position.x - x, y: node.position.y - y }
+ }
+ : node
+ )
+ const next = groupsFirst(fitAncestorChain(groupsFirst([group, ...updated]), parentId))
+ return {
+ nodes: next,
+ groupId: group.id,
+ changed: next.filter((node) => !before.has(node.id) || before.get(node.id) !== node)
+ }
+}
+
+function rootPosition(
+ nodes: readonly CanvasNodeState[],
+ node: CanvasNodeState
+): { x: number; y: number } {
+ const byId = new Map(nodes.map((candidate) => [candidate.id, candidate]))
+ const seen = new Set<string>([node.id])
+ let x = node.position.x
+ let y = node.position.y
+ let parentId = node.parentId
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = byId.get(parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+}
+
+/** Desktop `ungroupNodes` semantics over persisted nodes: direct children move up one level. */
+function ungroupPersistedNodes(
+ nodes: CanvasNodeState[],
+ groupId: string
+): { nodes: CanvasNodeState[]; promoted: CanvasNodeState[] } {
+ const frame = nodes.find((node) => node.id === groupId)
+ if (!frame || frame.kind !== 'group') return { nodes, promoted: [] }
+ const parentId = frame.parentId
+ const parent = parentId ? nodes.find((node) => node.id === parentId && node.kind === 'group') : undefined
+ const parentRoot = parent ? rootPosition(nodes, parent) : { x: 0, y: 0 }
+ const promoted: CanvasNodeState[] = []
+ const moved = nodes.map((node) => {
+ if (node.parentId !== groupId) return node
+ const root = rootPosition(nodes, node)
+ const next: CanvasNodeState = {
+ ...node,
+ position: { x: root.x - parentRoot.x, y: root.y - parentRoot.y }
+ }
+ if (parent) next.parentId = parent.id
+ else delete next.parentId
+ promoted.push(next)
+ return next
+ })
+ return {
+ nodes: groupsFirst(moved.filter((node) => node.id !== groupId)),
+ promoted
+ }
+}
+
+function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {
+ return {
+ cwd: node.cwd || project.cwd,
+ cols: TERMINAL_COLS,
+ rows: TERMINAL_ROWS,
+ persistKey: node.id,
+ ownerProjectId: project.id,
+ ...(node.agentId ? { agentId: node.agentId } : {}),
+ ...(node.agentModel ? { agentModel: node.agentModel } : {}),
+ ...(node.accountId ? { accountId: node.accountId } : {})
+ }
+}
+
+/**
+ * Server-side canvas authoring and launch scheduler.
+ *
+ * Every workspace read/modify/save transaction is serialized. That is important even on one
+ * Node event loop: WorkspaceStore.load/save both await filesystem operations, so two simultaneous
+ * `/control/open-agent` calls would otherwise read the same snapshot and the later save would
+ * erase the earlier node. PTY creation happens after the node is durable, matching the renderer's
+ * recoverable failure direction: a spawn error leaves a visible, reopenable node instead of an
+ * invisible tmux session.
+ */
+export class HeadlessNodeFactory {
+ private serial: Promise<unknown> = Promise.resolve()
+ private attached = new Set<string>()
+ /** Process-local proof that a caller created a node during THIS Server Edition run. */
+ private ownership: HeadlessNodeOwnership
+ /** Fresh server-spawned agents that have not emitted their first real working turn yet. */
+ private awaitingFirstWorking = new Set<string>()
+ /**
+ * Server-local `open-project` grants. The browser shell's grant ledger is process-local too,
+ * but Server Edition has its own process and handler. A service restart deliberately clears
+ * this map; `openProject()` can re-establish a grant only for an exact, already-saved local
+ * project path, so a surviving agent session is never stranded after that restart.
+ */
+ private projectGrants = new Map<string, Set<string>>()
+ private retryCount = new Map<string, number>()
+ private retryTimers = new Map<string, ReturnType<typeof setTimeout>>()
+ private stopped = false
+
+ constructor(private readonly deps: HeadlessNodeFactoryDeps) {
+ this.ownership = deps.ownership ?? createHeadlessNodeOwnership()
+ }
+
+ private runExclusive<T>(work: () => Promise<T>): Promise<T> {
+ const run = this.serial.then(work, work)
+ this.serial = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ private publishChangeSet(
+ project: Project,
+ nodes: readonly CanvasNodeState[],
+ removedIds: readonly string[]
+ ): void {
+ this.deps.publishProject?.(project)
+ const publishNode = this.deps.publishNode ?? ((projectId: string, node: CanvasNodeState) => {
+ publishCanvasMutation(projectId, { op: 'upsert', node })
+ })
+ const publishRemoval = this.deps.publishRemoval ?? ((projectId: string, nodeId: string) => {
+ publishCanvasMutation(projectId, { op: 'remove', id: nodeId })
+ })
+ for (const node of nodes) publishNode(project.id, node)
+ for (const nodeId of removedIds) publishRemoval(project.id, nodeId)
+ }
+
+ private publish(project: Project, nodes: readonly CanvasNodeState[]): void {
+ this.publishChangeSet(project, nodes, [])
+ }
+
+ /** Literal creator ownership: a caller may act only on nodes it freshly spawned this run. */
+ ownsSpawn(sourceNodeId: string, nodeId: string): boolean {
+ return this.ownership.ownerOf(nodeId)?.sourceNodeId === sourceNodeId
+ }
+
+ /** A verified caller may mutate only a node it freshly created during this server run. */
+ private ownsMutation(sourceNodeId: string, nodeId: string): boolean {
+ return this.ownsSpawn(sourceNodeId, nodeId)
+ }
+
+ /** All-or-nothing ownership gate: validate every id before any canvas or session mutation. */
+ private unownedMutation(sourceNodeId: string, nodeIds: readonly string[]): string | undefined {
+ return nodeIds.find((nodeId) => !this.ownsMutation(sourceNodeId, nodeId))
+ }
+
+ private ownershipRefusal(verb: string, sourceNodeId: string, nodeId: string): ServerControlReply {
+ return {
+ ok: false,
+ error:
+ `${verb}-not-owner: ${sourceNodeId} may modify only nodes it spawned during this server ` +
+ `run; ${nodeId} was not spawned by this caller`
+ }
+ }
+
+ private projectGranted(sourceNodeId: string, projectId: string): boolean {
+ return this.projectGrants.get(sourceNodeId)?.has(projectId) ?? false
+ }
+
+ private grantProject(sourceNodeId: string, projectId: string): boolean {
+ const grants = this.projectGrants.get(sourceNodeId) ?? new Set<string>()
+ if (!grants.has(projectId) && grants.size >= GRANT_CAP) return false
+ grants.add(projectId)
+ this.projectGrants.set(sourceNodeId, grants)
+ return true
+ }
+
+ private async attach(project: Project, node: CanvasNodeState): Promise<PtyCreateResult> {
+ if (this.attached.has(node.id)) {
+ return { sessionId: node.id, fresh: false }
+ }
+ const result = await this.deps.ptyManager.createHeadless(ptyOptions(project, node))
+ if (result.sessionId) this.attached.add(node.id)
+ return result
+ }
+
+ private resolveTarget(
+ workspace: Workspace,
+ source: { project: Project; node: CanvasNodeState },
+ verb: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Project | ServerControlReply {
+ const targetId = args.project || source.project.id
+ const target = workspace.projects.find((project) => project.id === targetId)
+ const gate = gateProjectTarget({
+ verified,
+ verb,
+ targetProjectId: args.project || undefined,
+ callerProjectId: source.project.id,
+ targetIsSsh: target ? !!target.ssh : undefined,
+ granted: this.projectGranted(source.node.id, targetId)
+ })
+ if (gate !== 'allow') return { ok: false, error: gate.refuse }
+ if (!target) return { ok: false, error: 'project-target-refused: target project is unavailable' }
+ if (target.ssh) {
+ return {
+ ok: false,
+ error: 'project-target-ssh-unsupported: Server Edition v1 only creates local sessions'
+ }
+ }
+ return target
+ }
+
+ private resolveAfter(
+ project: Project,
+ raw: string | undefined,
+ verb: string
+ ): string[] | ServerControlReply {
+ if (!raw) return []
+ const ids = [...new Set(raw.split(',').map((id) => id.trim()).filter(Boolean))]
+ for (const id of ids) {
+ const node = project.nodes.find((candidate) => candidate.id === id)
+ if (!node) return { ok: false, error: `${verb}: --after names no existing node (${id})` }
+ const agentId = effectiveAgentId(node, this.deps.agentIdOf)
+ if (!agentId || !hasHooks(agentId)) {
+ return {
+ ok: false,
+ error: `${verb}: --after ${id} is not an agent session that reports when it is done`
+ }
+ }
+ }
+ return ids
+ }
+
+ async openTerminal(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.open(sourceNodeId, 'open-terminal', args, verified)
+ }
+
+ /**
+ * Re-open one exact local project that is already present in the Server workspace and mint a
+ * process-local targeting grant for this verified caller. Server Edition still cannot create,
+ * add, rename, recolor, or focus projects: those operations require the browser UI's explicit
+ * confirmation. This narrow existing-only form is the restart recovery path for long-lived
+ * agent nodes whose tmux sessions survive the Server process.
+ */
+ openProject(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['cwd']))
+ if (flagError) return { ok: false, error: `open-project: ${flagError}` }
+ if (!verified) {
+ return {
+ ok: false,
+ error: 'open-project-identity-refused: Server Edition open-project requires verified node identity'
+ }
+ }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+ if (source.project.ssh) {
+ return {
+ ok: false,
+ error: 'open-project-local-only: open-project is not available from an SSH project — do not retry'
+ }
+ }
+
+ const rawCwd = args.cwd ?? ''
+ if (!path.isAbsolute(rawCwd)) {
+ return {
+ ok: false,
+ error: 'open-project-cwd-invalid: --cwd must be an absolute path to an existing saved local project'
+ }
+ }
+ const cwd = path.resolve(rawCwd)
+ const target = workspace.projects.find(
+ (project) => !project.ssh && !!project.cwd && path.resolve(project.cwd) === cwd
+ )
+ if (!target) {
+ return {
+ ok: false,
+ error:
+ 'open-project-server-existing-only: Server Edition can only re-open an exact saved ' +
+ 'local project path; add the project in the UI first — do not retry this path'
+ }
+ }
+ if (!this.grantProject(sourceNodeId, target.id)) {
+ return {
+ ok: false,
+ error: 'open-project-grant-cap: this session already holds the maximum number of project grants'
+ }
+ }
+
+ return {
+ ok: true,
+ message: `re-opened saved local project ${target.id}; cross-project grant restored`,
+ result: {
+ projectId: target.id,
+ name: target.name,
+ cwd,
+ created: false,
+ serverExistingOnly: true
+ }
+ }
+ })
+ }
+
+ async openAgent(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.open(sourceNodeId, 'open-agent', args, verified)
+ }
+
+ close(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['node']))
+ if (flagError) return { ok: false, error: `close: ${flagError}` }
+ if (!verified) {
+ return {
+ ok: false,
+ error: 'close-identity-refused: Server Edition close requires verified node identity'
+ }
+ }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const ids = [...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))]
+ if (!ids.length) return { ok: false, error: 'close requires --node <id>' }
+
+ // Validate the WHOLE list before killing anything. A mixed owned/unowned request is one
+ // refusal, never a partial destructive success whose surviving ids the caller must guess.
+ const frameIds = new Set<string>()
+ for (const id of ids) {
+ const ownership = this.ownership.ownerOf(id)
+ if (!ownership || ownership.sourceNodeId !== sourceNodeId) {
+ return {
+ ok: false,
+ error: `close-not-owner: ${sourceNodeId} did not spawn ${id} during this server run`
+ }
+ }
+ const project = workspace.projects.find((candidate) => candidate.id === ownership.projectId)
+ const target = project?.nodes.find((node) => node.id === id)
+ if (target?.kind === 'group') {
+ const unownedChild = this.unownedMutation(
+ sourceNodeId,
+ project!.nodes.filter((node) => node.parentId === id).map((node) => node.id)
+ )
+ if (unownedChild) return this.ownershipRefusal('close', sourceNodeId, unownedChild)
+ frameIds.add(id)
+ }
+ }
+
+ // Kill terminal panes first: the durable canvas must never lose a session whose outcome is
+ // unknown. Frames have no PTY; closing one is the desktop `ungroup` transform followed by
+ // removal of the frame alone, regardless of who owns its members.
+ await Promise.all(
+ ids
+ .filter((id) => !frameIds.has(id))
+ .map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true }))
+ )
+
+ const removedByProject = new Map<Project, string[]>()
+ const changedByProject = new Map<Project, Map<string, CanvasNodeState>>()
+ for (const id of ids) {
+ const projectId = this.ownership.ownerOf(id)!.projectId
+ const project = workspace.projects.find((candidate) => candidate.id === projectId)
+ const target = project?.nodes.find((node) => node.id === id)
+ if (!project || !target) continue
+ if (target.kind === 'group') {
+ const ungrouped = ungroupPersistedNodes(project.nodes, id)
+ project.nodes = ungrouped.nodes
+ const changed = changedByProject.get(project) ?? new Map<string, CanvasNodeState>()
+ for (const node of ungrouped.promoted) changed.set(node.id, node)
+ changedByProject.set(project, changed)
+ } else {
+ project.nodes = project.nodes.filter((node) => node.id !== id)
+ }
+ if (project.ropes) {
+ project.ropes = project.ropes.filter((edge) => edge.source !== id && edge.target !== id)
+ }
+ if (project.bridges) {
+ project.bridges = project.bridges.filter((edge) => edge.source !== id && edge.target !== id)
+ }
+ const removed = removedByProject.get(project) ?? []
+ removed.push(id)
+ removedByProject.set(project, removed)
+ }
+
+ if (removedByProject.size) {
+ await this.deps.workspaceStore.save(workspace)
+ for (const [project, removed] of removedByProject) {
+ const surviving = project.nodes.map((node) => node.id)
+ const changed = [...(changedByProject.get(project)?.values() ?? [])].filter((node) =>
+ surviving.includes(node.id)
+ )
+ this.publishChangeSet(project, changed, removed)
+ }
+ }
+
+ for (const id of ids) {
+ this.ownership.forget(id)
+ this.attached.delete(id)
+ this.awaitingFirstWorking.delete(id)
+ this.retryCount.delete(id)
+ const timer = this.retryTimers.get(id)
+ if (timer) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.delete(id)
+ }
+ return {
+ ok: true,
+ message: `closed ${ids.length} owned node(s): ${ids.join(', ')}`,
+ result: { ids, id: ids[0] }
+ }
+ })
+ }
+
+ link(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['from', 'to']))
+ if (flagError) return { ok: false, error: `link: ${flagError}` }
+ if (!verified) {
+ return {
+ ok: false,
+ error: 'link-identity-refused: Server Edition link requires verified node identity'
+ }
+ }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const from = (args.from ?? sourceNodeId).trim()
+ const targets = (args.to ?? '').split(',').map((id) => id.trim()).filter(Boolean)
+ if (!targets.length) return { ok: false, error: 'link requires --to <id,id>' }
+
+ // An arbitrary `--from` is allowed, but every endpoint still belongs to the caller's one
+ // project. Refuse the whole request before appending anything if a named id resolves across
+ // that boundary (or ambiguously in more than one saved project).
+ for (const id of [from, ...targets]) {
+ const projects = nodeProjects(workspace, id)
+ if (projects.length && (projects.length !== 1 || projects[0].id !== source.project.id)) {
+ return {
+ ok: false,
+ error: `link-project-refused: ${id} is not exclusively in the caller's project`
+ }
+ }
+ }
+ const unowned = this.unownedMutation(sourceNodeId, [from, ...targets])
+ if (unowned) return this.ownershipRefusal('link', sourceNodeId, unowned)
+
+ const byId = new Map(source.project.nodes.map((node) => [node.id, node]))
+ if (!byId.has(from)) {
+ return { ok: false, error: `link: --from names no existing node (${from})` }
+ }
+ const existing = [...(source.project.bridges ?? [])]
+ const plan = planBridges(
+ from,
+ targets,
+ (id) => {
+ const node = byId.get(id)
+ return node ? headlessLinkEndpoint(node, this.deps.agentIdOf) : null
+ },
+ existing
+ )
+ if (!plan.edges.length) {
+ return {
+ ok: false,
+ error: `link: nothing linked — ${plan.skipped
+ .map((skipped) => `${skipped.id}: ${skipped.why}`)
+ .join('; ')}`
+ }
+ }
+
+ source.project.bridges = [...existing, ...plan.edges]
+ await this.deps.workspaceStore.save(workspace)
+ // An edge-only change has no node mutation to publish; the full-project event is the fanout.
+ this.publish(source.project, [])
+ const note = plan.skipped.length
+ ? ` (skipped ${plan.skipped.map((skipped) => `${skipped.id}: ${skipped.why}`).join('; ')})`
+ : ''
+ return {
+ ok: true,
+ message: `linked ${from} ↔ ${plan.linked.join(', ')}${note}`,
+ result: { from, linked: plan.linked, skipped: plan.skipped }
+ }
+ })
+ }
+
+ group(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['nodes', 'label', 'color']))
+ if (flagError) return { ok: false, error: `group: ${flagError}` }
+ let color: NodeColor | undefined
+ if (args.color !== undefined) {
+ if (!isNodeColor(args.color)) return { ok: false, error: invalidNodeColorMessage() }
+ color = args.color
+ }
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const ids = (args.nodes ?? '').split(',').map((id) => id.trim()).filter(Boolean)
+ const unowned = this.unownedMutation(sourceNodeId, ids)
+ if (unowned) return this.ownershipRefusal('group', sourceNodeId, unowned)
+ const resolvable = ids.filter((id) => source.project.nodes.some((node) => node.id === id))
+ if (!resolvable.length) {
+ return { ok: false, error: 'group: none of the given node ids exist' }
+ }
+ const grouped = groupPersistedNodes(
+ source.project.nodes,
+ resolvable,
+ source.project.nodes.filter((node) => node.kind === 'group').length,
+ args.label ? oneLine(args.label) : undefined,
+ color
+ )
+ if (!grouped) {
+ return {
+ ok: false,
+ error:
+ 'group: nodes must be siblings in one container and may not include an ancestor with its descendant'
+ }
+ }
+
+ source.project.nodes = grouped.nodes
+ await this.deps.workspaceStore.save(workspace)
+ this.ownership.record(grouped.groupId, {
+ sourceNodeId,
+ projectId: source.project.id
+ })
+ this.publish(source.project, grouped.changed)
+ const skipped = ids.length - resolvable.length
+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
+ return {
+ ok: true,
+ message: `grouped ${resolvable.length} node(s) into ${grouped.groupId}${note}`,
+ result: { groupId: grouped.groupId, grouped: resolvable, skipped }
+ }
+ })
+ }
+
+ rename(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['node', 'title']))
+ if (flagError) return { ok: false, error: `rename: ${flagError}` }
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const id = (args.node ?? '').trim()
+ const projects = nodeProjects(workspace, id)
+ if (projects.length && (projects.length !== 1 || projects[0].id !== source.project.id)) {
+ return {
+ ok: false,
+ error: `rename-project-refused: ${id} is not exclusively in the caller's project`
+ }
+ }
+ const target = source.project.nodes.find((node) => node.id === id)
+ if (!target) return { ok: false, error: `rename: no node with id ${id}` }
+ if (!this.ownsMutation(sourceNodeId, id)) {
+ return this.ownershipRefusal('rename', sourceNodeId, id)
+ }
+
+ const title = oneLine(args.title ?? '')
+ const renamed = { ...target, title, titleAuto: false }
+ source.project.nodes = source.project.nodes.map((node) =>
+ node.id === id ? renamed : node
+ )
+ await this.deps.workspaceStore.save(workspace)
+ // Metadata only. In particular, Server Edition never mirrors `/rename` into the pane.
+ this.publish(source.project, [renamed])
+ return { ok: true, message: `renamed ${id} to "${title}"` }
+ })
+ }
+
+ color(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['node', 'color']))
+ if (flagError) return { ok: false, error: `color: ${flagError}` }
+ if (!isNodeColor(args.color)) return { ok: false, error: invalidNodeColorMessage() }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const ids = [...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))]
+ const unowned = this.unownedMutation(sourceNodeId, ids)
+ if (unowned) return this.ownershipRefusal('color', sourceNodeId, unowned)
+ const changed = ids
+ .map((id) => source.project.nodes.find((node) => node.id === id))
+ .filter((node): node is CanvasNodeState => !!node)
+ .map((node) => ({ ...node, color: args.color }))
+ if (!changed.length) {
+ return { ok: false, error: 'color: none of the given node ids exist in the caller project' }
+ }
+ const byId = new Map(changed.map((node) => [node.id, node]))
+ source.project.nodes = source.project.nodes.map((node) => byId.get(node.id) ?? node)
+ await this.deps.workspaceStore.save(workspace)
+ this.publish(source.project, changed)
+ const skipped = ids.length - changed.length
+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
+ return {
+ ok: true,
+ message: `colored ${changed.length} node(s) ${args.color}${note}`,
+ result: { colored: changed.map((node) => node.id), skipped, color: args.color }
+ }
+ })
+ }
+
+ private open(
+ sourceNodeId: string,
+ verb: 'open-terminal' | 'open-agent',
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(
+ args,
+ verb === 'open-terminal'
+ ? new Set(['count', 'cwd', 'cmd', 'after', 'project'])
+ : new Set(['agent', 'count', 'cwd', 'prompt', 'after', 'project', 'model'])
+ )
+ if (flagError) return { ok: false, error: `${verb}: ${flagError}` }
+ if (!verified) {
+ return {
+ ok: false,
+ error: `${verb}-identity-refused: Server Edition ${verb} requires verified node identity`
+ }
+ }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+ const target = this.resolveTarget(workspace, source, verb, args, verified)
+ if ('ok' in target) return target
+ const after = this.resolveAfter(target, args.after, verb)
+ if (!Array.isArray(after)) return after
+ const unownedAfter = this.unownedMutation(sourceNodeId, after)
+ if (unownedAfter) return this.ownershipRefusal(verb, sourceNodeId, unownedAfter)
+
+ const settings = this.deps.settings()
+ const nodeSize = terminalSize(settings)
+ const caps = verb === 'open-agent' ? await this.deps.cliCaps() : null
++ const grokCaps = verb === 'open-agent' ? await this.deps.grokCaps() : null
+ const agentId = args.agent as BuiltinAgentId | undefined
+ if (verb === 'open-agent' && (!agentId || !SERVER_AGENTS.has(agentId))) {
+ return {
+ ok: false,
+ error: 'open-agent: Server Edition v1 supports --agent claude|codex|gemini'
+ }
+ }
+ // The Server shell owns the same shared Codex app-server spine as desktop. Ask its boot-time
+ // capability probe at the launch boundary: true routes through `nodeterm-codex`; every
+ // unavailable/failed case stays on the safe bare command supplied by the shared assembler.
+ const codexSharedIdentity =
+ verb === 'open-agent' && agentId === 'codex'
+ ? await this.deps.codexSharedIdentity().catch(() => false)
+ : false
+
+ const count = parseCount(args.count, verb === 'open-terminal' ? TERMINAL_LIMIT : AGENT_LIMIT)
+ const created: CanvasNodeState[] = []
+ const commands = new Map<string, string>()
+ const ropes = [...(target.ropes ?? [])]
+ const bridges = [...(target.bridges ?? [])]
+ const startIndex = target.nodes.length
+ const cwd = args.cwd || (target.id === source.project.id ? source.node.cwd : undefined) || target.cwd
+ // Snapshot dependency state at the arm boundary. A `working` state is already positive
+ // evidence that this fresh process made it through its boot composer; a later `done` may
+ // release it. An unknown/waiting fresh spawn needs a working event after this snapshot.
+ const afterStates = new Map(after.map((depId) => [depId, this.deps.stateOf(depId)]))
+ for (const [depId, state] of afterStates) {
+ if (state === 'working') this.awaitingFirstWorking.delete(depId)
+ }
+ const mustWait = after.some((depId) => afterStates.get(depId) !== 'done')
+ const awaitWorking = after.filter((depId) =>
+ afterStates.get(depId) !== 'done' &&
+ afterStates.get(depId) !== 'working' &&
+ this.awaitingFirstWorking.has(depId)
+ )
+
+ for (let i = 0; i < count; i++) {
+ let command = args.cmd
+ let title = `Terminal ${startIndex + i + 1}`
+ let color: string = NODE_COLORS[(startIndex + i) % NODE_COLORS.length]
+ let mintedSessionId: string | undefined
+ let permissionMode
+ if (verb === 'open-agent') {
+ const config = AGENT_CONFIG[agentId as BuiltinAgentId]
+ title = config.label
+ color = config.color
+ const resolvedMode = resolvePermissionMode(target, settings)
+ permissionMode = agentId === 'claude'
+ ? gatePermissionMode(resolvedMode, caps?.autoPermissionMode === true)
+ : resolvedMode
+ const sessionIdFlagSupported = supportsSessionIdFlag(
+ agentId as AgentId,
- caps?.sessionIdFlag === true
++ caps?.sessionIdFlag === true,
++ grokCaps?.sessionIdFlag === true
+ )
+ mintedSessionId = sessionIdFlagSupported ? randomUUID() : undefined
+ command = assembleLaunchCommand(
+ {
+ agentId: agentId as AgentId,
+ initialPrompt: args.prompt,
+ permissionMode,
+ sessionId: mintedSessionId,
+ sessionIdFlagSupported,
+ launchCmdOverride: settings.agentLaunchCommands?.[agentId as BuiltinAgentId],
+ sharedIdentity: codexSharedIdentity,
+ model: args.model
+ },
+ this.deps.env ?? process.env
+ ).command
+ }
+
+ const id = nextId('term')
+ // Match the desktop's `armAfter`: if every dependency is already done, launch now rather
+ // than persisting a wait that has no future edge left to wake it.
+ const pendingLaunch = command && mustWait
+ ? {
+ after,
+ command,
+ executor: 'server' as const,
+ ...(awaitWorking.length ? { awaitWorking: [...awaitWorking] } : {})
+ }
+ : undefined
+ const node: CanvasNodeState = {
+ id,
+ kind: 'terminal',
+ position: placeRight(target, source.node, nodeSize, created),
+ size: { ...nodeSize },
+ title,
+ ...(verb === 'open-agent' ? { titleAuto: true } : {}),
+ color,
+ group: null,
+ tags: [],
+ cwd,
+ ...(verb === 'open-agent' ? { agentId: agentId as AgentId } : {}),
+ ...(args.model && verb === 'open-agent' ? { agentModel: args.model } : {}),
+ ...(mintedSessionId ? { agentSessionId: mintedSessionId } : {}),
+ ...(source.node.accountId && verb === 'open-agent' &&
+ (agentId === 'claude' || agentId === 'codex')
+ ? { accountId: source.node.accountId }
+ : {}),
+ ...(pendingLaunch ? { pendingLaunch } : {})
+ }
+ created.push(node)
+ if (command && !pendingLaunch) commands.set(id, command)
+ addEdge(ropes, source.node.id, id, 'ctrl')
+
+ if (verb === 'open-agent') {
+ const sourceAgent = effectiveAgentId(source.node, this.deps.agentIdOf)
+ if (sourceAgent && canContextLink(sourceAgent) && canContextLink(agentId as AgentId)) {
+ addEdge(bridges, source.node.id, id, 'link')
+ }
+ for (const depId of after) {
+ const dep = target.nodes.find((candidate) => candidate.id === depId)
+ const depAgent = dep ? effectiveAgentId(dep, this.deps.agentIdOf) : undefined
+ if (depAgent && canContextLink(depAgent) && canContextLink(agentId as AgentId))
+ addEdge(bridges, id, depId, 'link')
+ }
+ }
+ }
+
+ target.nodes.push(...created)
+ target.ropes = ropes
+ target.bridges = bridges
+ await this.deps.workspaceStore.save(workspace)
+ for (const node of created) {
+ this.ownership.record(node.id, { sourceNodeId, projectId: target.id })
+ }
+ this.publish(target, created)
+
+ const failed: string[] = []
+ for (const node of created) {
+ try {
+ const result = await this.attach(target, node)
+ if (!result.sessionId) {
+ failed.push(node.id)
+ continue
+ }
+ if (verb === 'open-agent' && result.fresh) this.awaitingFirstWorking.add(node.id)
+ const command = commands.get(node.id)
+ if (command && !(await this.deps.ptyManager.sendText(node.id, command))) failed.push(node.id)
+ } catch {
+ failed.push(node.id)
+ }
+ }
+
+ const ids = created.map((node) => node.id)
+ if (failed.length) {
+ return {
+ ok: false,
+ error:
+ `launch-failed: node(s) ${failed.join(', ')} were persisted but their PTY or initial ` +
+ 'command could not be started; do not repeat the open request',
+ result: { ids, id: ids[0], after, failed }
+ }
+ }
+ return {
+ ok: true,
+ message:
+ `opened ${count} ${verb === 'open-agent' ? `${agentId} session` : 'terminal'}(s): ` +
+ ids.join(', ') +
+ (after.length ? `; waiting for ${after.join(', ')} before running` : ''),
+ result: { ids, id: ids[0], after }
+ }
+ })
+ }
+
+ sticky(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const parsed = parseStickyArgs(args)
+ if ('error' in parsed) return { ok: false, error: `sticky: ${parsed.error}` }
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const candidates = source.project.nodes.map((node) => ({
+ id: node.id,
+ sticky: node.kind === 'sticky',
+ title: node.title
+ }))
+ const resolved = resolveStickyRef(candidates, parsed.ref)
+ if ('error' in resolved) return { ok: false, error: `sticky: ${resolved.error}` }
+
+ let node: CanvasNodeState | undefined
+ let created = false
+ if ('id' in resolved) node = source.project.nodes.find((candidate) => candidate.id === resolved.id)
+ else if (parsed.create) {
+ created = true
+ node = {
+ id: nextId('sticky'),
+ kind: 'sticky',
+ position: placeRight(source.project, source.node, STICKY_SIZE),
+ size: { ...STICKY_SIZE },
+ title: oneLine(parsed.ref) || 'Note',
+ color: '#ffd60a',
+ group: null,
+ text: ''
+ }
+ source.project.nodes.push(node)
+ const ropes = [...(source.project.ropes ?? [])]
+ addEdge(ropes, source.node.id, node.id, 'ctrl')
+ source.project.ropes = ropes
+ } else {
+ return {
+ ok: false,
+ error: `sticky: no note named "${parsed.ref}"; pass --create yes to create it`
+ }
+ }
+ if (!node) return { ok: false, error: 'sticky: note disappeared while resolving it' }
+ if (!created && !this.ownsMutation(sourceNodeId, node.id)) {
+ return this.ownershipRefusal('sticky', sourceNodeId, node.id)
+ }
+
+ const write = applyStickyWrite(node.text ?? '', parsed.write)
+ if ('error' in write) return { ok: false, error: `sticky: ${write.error}` }
+ node.text = write.text
+ node.textUpdatedAt = (this.deps.now ?? Date.now)()
+ node.textUpdatedBy = source.node.title || source.node.id
+ await this.deps.workspaceStore.save(workspace)
+ if (created) {
+ this.ownership.record(node.id, { sourceNodeId, projectId: source.project.id })
+ }
+ this.publish(source.project, [node])
+ return {
+ ok: true,
+ message: `${created ? 'created' : 'updated'} sticky ${node.id} (${write.mode})`,
+ result: { id: node.id, created, mode: write.mode }
+ }
+ })
+ }
+
+ /**
+ * Boot is intentionally inert. Creator proof is process-local and empty after restart, so even
+ * sending a persisted command would control a session this process cannot attribute. Owner opens
+ * and browser views are the only cold-spawn authority; current-run agent events drive arms below.
+ */
+ start(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {
+ if (this.stopped || !event?.nodeId) return
+ if (event.state === 'working') this.awaitingFirstWorking.delete(event.nodeId)
+ if (event.state === 'working' || event.state === 'done') void this.refreshArmed(event)
+ }
+
+ refreshArmed(observed?: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): Promise<void> {
+ return this.runExclusive(async () => {
+ if (this.stopped) return
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const changedByProject = new Map<Project, CanvasNodeState[]>()
+
+ for (const project of workspace.projects) {
+ for (const node of project.nodes) {
+ const pending = node.pendingLaunch
+ if (!pending || pending.executor !== 'server' || !pending.command) continue
+ // A persisted arm surviving a restart is data, not creator proof. Only a node freshly
+ // spawned for this caller during the current run may receive automatic input.
+ if (!this.ownership.ownerOf(node.id)) continue
+ const markChanged = (): void => {
+ const list = changedByProject.get(project) ?? []
+ if (!list.includes(node)) list.push(node)
+ changedByProject.set(project, list)
+ }
+ if (observed?.state === 'working' && pending.awaitWorking?.includes(observed.nodeId)) {
+ const remaining = pending.awaitWorking.filter((depId) => depId !== observed.nodeId)
+ pending.awaitWorking = remaining.length ? remaining : undefined
+ // Persist the evidence even if the dependent PTY is temporarily unavailable. Losing
+ // this mutation would strand the arm when the next event is the legitimate `done`.
+ markChanged()
+ }
+ for (const depId of pending.awaitWorking ?? []) {
+ if (!(observed?.state === 'working' && observed.nodeId === depId))
+ this.awaitingFirstWorking.add(depId)
+ }
+ const ready = pending.after.every((depId) => {
+ const stillExists = project.nodes.some((candidate) => candidate.id === depId)
+ if (!stillExists) return true
+ if (pending.awaitWorking?.includes(depId)) return false
+ return observed?.nodeId === depId
+ ? observed.state === 'done'
+ : this.deps.stateOf(depId) === 'done'
+ })
+ if (!ready) continue
+ // `sessionExists` is a probe, whereas `createHeadless` is attach-or-create. Never call
+ // the latter from boot/event reconciliation: a dead node stays dormant until its owner
+ // explicitly opens it or a user views it. A probe failure also stays dormant because an
+ // unreadable backend is not proof that delivery is safe.
+ const live = this.attached.has(node.id) ||
+ await this.deps.ptyManager.sessionExists(node.id).catch(() => false)
+ if (!live) continue
+ if (!(await this.deps.ptyManager.sendText(node.id, pending.command))) {
+ this.scheduleRetry(node.id)
+ continue
+ }
+ node.pendingLaunch = undefined
+ this.retryCount.delete(node.id)
+ const timer = this.retryTimers.get(node.id)
+ if (timer) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.delete(node.id)
+ markChanged()
+ }
+ }
+
+ // A working event is definitive for every pending launch in this transaction. Keep the
+ // process-local fresh-spawn index aligned even when several arms named the same dependency.
+ if (observed?.state === 'working') this.awaitingFirstWorking.delete(observed.nodeId)
+
+ if (changedByProject.size) {
+ await this.deps.workspaceStore.save(workspace)
+ for (const [project, nodes] of changedByProject) this.publish(project, nodes)
+ }
+ })
+ }
+
+ private scheduleRetry(nodeId: string): void {
+ if (this.stopped || this.retryTimers.has(nodeId)) return
+ const count = (this.retryCount.get(nodeId) ?? 0) + 1
+ this.retryCount.set(nodeId, count)
+ if (count > AFTER_RETRY_LIMIT) return
+ const schedule = this.deps.schedule ?? ((cb: () => void, ms: number) => setTimeout(cb, ms))
+ const timer = schedule(() => {
+ this.retryTimers.delete(nodeId)
+ void this.refreshArmed()
+ }, AFTER_RETRY_MS)
+ this.retryTimers.set(nodeId, timer)
+ }
+
+ stop(): void {
+ this.stopped = true
+ for (const timer of this.retryTimers.values()) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.clear()
+ this.ownership.clear()
+ this.projectGrants.clear()
+ }
+}
diff --cc src/shared/canvas-link.ts
index 2652fd8c9,000000000..1c8546235
mode 100644,000000..100644
--- a/src/shared/canvas-link.ts
+++ b/src/shared/canvas-link.ts
@@@ -1,88 -1,0 +1,92 @@@
+// Pure planning for persisted canvas links. Both the desktop renderer and the headless server
+// use this exact refusal/deduplication matrix; neither shell may grow its own approximation.
+import type { BridgeLink } from './types'
+
+export interface LinkEndpoint {
+ /** Canvas node kind: 'terminal' | 'sticky' | 'editor' | … */
+ kind: string
- /** Terminal node whose agent is CONTEXT_LINK_CAPABLE (claude/codex/gemini). */
++ /**
++ * Terminal node whose agent is `CONTEXT_LINK_CAPABLE`. Deliberately not spelled out here: the
++ * list has gained two members since this comment was written (opencode, then grok) and named
++ * them wrong in between. Ask `canContextLink`; the list lives in `shared/agents/config.ts`.
++ */
+ contextCapable: boolean
+}
+
+export type LinkKind = 'context' | 'note'
+
+/** Decide what kind of link (if any) a new edge between two nodes forms. */
+export function classifyLink(a: LinkEndpoint, b: LinkEndpoint): LinkKind | null {
+ const stickies = (a.kind === 'sticky' ? 1 : 0) + (b.kind === 'sticky' ? 1 : 0)
+ if (stickies === 0) return a.contextCapable && b.contextCapable ? 'context' : null
+ if (stickies === 2) return null
+ const other = a.kind === 'sticky' ? b : a
+ return other.kind === 'terminal' ? 'note' : null
+}
+
+/** One node the plan refused to link, with the reason to report back to the caller. */
+export interface SkippedBridge {
+ id: string
+ why: string
+}
+
+export interface BridgePlan {
+ /** Edges to append (already deduped against `existing` AND within the batch). */
+ edges: BridgeLink[]
+ linked: string[]
+ skipped: SkippedBridge[]
+}
+
+/**
+ * Plan the link edges connecting `fromId` to each of `targetIds`.
+ *
+ * The caller supplies node lookup and the already-persisted edges, so this stays independent of
+ * React/store/server state. Note edges normalize to sticky→terminal; every pair dedupes in either
+ * direction. Creating the edges has no delivery side effect: context is always read on demand.
+ */
+export function planBridges(
+ fromId: string,
+ targetIds: string[],
+ lookup: (id: string) => LinkEndpoint | null,
+ existing: readonly { source: string; target: string }[]
+): BridgePlan {
+ const edges: BridgeLink[] = []
+ const linked: string[] = []
+ const skipped: SkippedBridge[] = []
+ const se = lookup(fromId)
+ const linkedAlready = (a: string, b: string) =>
+ [...existing, ...edges].some(
+ (edge) =>
+ (edge.source === a && edge.target === b) ||
+ (edge.source === b && edge.target === a)
+ )
+
+ for (const targetId of targetIds) {
+ if (targetId === fromId) {
+ skipped.push({ id: targetId, why: 'same node' })
+ continue
+ }
+ const te = lookup(targetId)
+ if (!se || !te) {
+ skipped.push({ id: targetId, why: 'no such node' })
+ continue
+ }
+ const kind = classifyLink(se, te)
+ if (!kind) {
+ skipped.push({
+ id: targetId,
+ why: 'not linkable (needs two context-capable agents, or a sticky + terminal)'
+ })
+ continue
+ }
+ const source = kind === 'note' && te.kind === 'sticky' ? targetId : fromId
+ const target = source === fromId ? targetId : fromId
+ if (linkedAlready(source, target)) {
+ skipped.push({ id: targetId, why: 'already linked' })
+ continue
+ }
+ edges.push({ id: `bridge-${source}-${target}`, source, target })
+ linked.push(targetId)
+ }
+ return { edges, linked, skipped }
+}
diff --cc test/server/canvas-control-boot-e2e.test.ts
index c4988fd02,000000000..43f45a919
mode 100644,000000..100644
--- a/test/server/canvas-control-boot-e2e.test.ts
+++ b/test/server/canvas-control-boot-e2e.test.ts
@@@ -1,137 -1,0 +1,154 @@@
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+import { sessionName, TMUX_SOCKET } from '../../src/core/tmux-naming'
++import { SANDBOX_ENV, tmuxSocketPath } from '../../src/core/tmux-test-socket'
+import { startServer } from '../../src/server/index'
+import type { Workspace } from '../../src/shared/types'
+
+const hasTmux = (() => {
+ try {
+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })
+ return true
+ } catch {
+ return false
+ }
+})()
+
+const PERSIST_KEY = `boot-rescue-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
+const TMUX_TARGET = sessionName(PERSIST_KEY)
+
+function backendExists(): boolean {
+ try {
+ execFileSync('tmux', ['-L', TMUX_SOCKET, 'has-session', '-t', TMUX_TARGET], {
+ stdio: 'ignore'
+ })
+ return true
+ } catch {
+ return false
+ }
+}
+
+describe.skipIf(!hasTmux)('disposable Server boot rescue', () => {
+ let dataDir = ''
+ let projectDir = ''
+ let close: (() => Promise<void>) | undefined
+ // Everything startServer printed while booting with canvasControl on. Captured rather than
+ // asserted through a spy call count because the boot logs several unrelated lines.
+ const bootLogs: string[] = []
+
++ // This suite reads and (on cleanup only) kills on the LIVE socket name, because the server it
++ // boots binds `TMUX_SOCKET` itself — the whole assertion is that boot spawns nothing, and only
++ // that socket can answer it. `TMUX_TMPDIR` is what keeps the name off the developer's live tmux
++ // SERVER (this repo is developed from inside nodeterm), so refuse to run at all when the run-wide
++ // sandbox is not in effect rather than fall back to it silently. See issue #629 and
++ // `src/core/tmux-socket-isolation.guard.test.ts`, where this file is allowlisted.
++ beforeAll(() => {
++ const sandbox = process.env[SANDBOX_ENV]
++ expect(sandbox, 'tmux sandbox not in effect — see test/setup/tmux-sandbox.ts').toBeTruthy()
++ expect(process.env.TMUX_TMPDIR).toBe(sandbox)
++ const uid = process.getuid?.() ?? 0
++ expect(tmuxSocketPath(sandbox!, uid, TMUX_SOCKET)).not.toBe(
++ tmuxSocketPath('/tmp', uid, TMUX_SOCKET)
++ )
++ })
++
+ beforeAll(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-server-boot-rescue-'))
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-server-boot-project-'))
+ const workspace: Workspace = {
+ version: 2,
+ activeProjectId: 'boot-project',
+ projects: [
+ {
+ id: 'boot-project',
+ name: 'Disposable boot rescue',
+ color: '#0a84ff',
+ cwd: projectDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ {
+ id: PERSIST_KEY,
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 640, height: 440 },
+ title: 'Persisted missing backend',
+ color: '#d97757',
+ group: null,
+ agentId: 'claude',
+ pendingLaunch: {
+ after: [],
+ command: "claude 'must remain dormant'",
+ executor: 'server'
+ }
+ }
+ ],
+ bridges: [],
+ ropes: []
+ }
+ ]
+ }
+ fs.writeFileSync(path.join(dataDir, 'workspace.json'), JSON.stringify(workspace), 'utf8')
+ expect(backendExists()).toBe(false)
+
+ const log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
+ bootLogs.push(args.map((a) => String(a)).join(' '))
+ })
+ const server = await startServer({
+ port: 0,
+ host: '127.0.0.1',
+ dataDir,
+ rendererDir: path.join(dataDir, 'no-renderer'),
+ insecureHttp: false,
+ passwordSeed: 'disposable-boot-rescue-password',
+ installHooks: false,
+ canvasControl: true,
+ headless: false
+ })
+ log.mockRestore()
+ close = server.close
+ }, 30_000)
+
+ afterAll(async () => {
+ await close?.()
+ // This exact session can exist only if this disposable server regressed and spawned it. Never
+ // touch the tmux server or any broad target; cleanup is scoped to the test-owned unique id.
+ if (backendExists()) {
+ try {
+ execFileSync('tmux', ['-L', TMUX_SOCKET, 'kill-session', '-t', TMUX_TARGET], {
+ stdio: 'ignore'
+ })
+ } catch {
+ // Already gone.
+ }
+ }
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ })
+
+ // The flag reads as "canvas control", but what it grants is command execution as the server's
+ // own user. An operator who never opens docs/SERVER.md still has to be told, so boot says it —
+ // and this pins that it is actually said, on a real boot with the flag on.
+ it('announces at boot that the flag grants command execution on this host', () => {
+ const notice = bootLogs.find((line) => line.includes('Server canvas control ENABLED'))
+ expect(notice).toBeDefined()
+ expect(notice).toContain('arbitrary commands on this host')
+ expect(notice).toContain('open-terminal --cmd')
+ expect(notice).toContain('NODETERM_SERVER_CANVAS_CONTROL')
+ })
+
+ it('leaves a persisted queued node dormant when no backend exists', () => {
+ expect(backendExists()).toBe(false)
+ const persisted = JSON.parse(
+ fs.readFileSync(path.join(dataDir, 'workspace.json'), 'utf8')
+ ) as Workspace
+ expect(persisted.projects[0].nodes[0].pendingLaunch).toMatchObject({
+ command: "claude 'must remain dormant'",
+ executor: 'server'
+ })
+ })
+})