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.

feat(ssh): canvas-control skill works in SSH projects

enes94c04106fa28
diff --git a/docs/ssh-agent-skills.md b/docs/ssh-agent-skills.md
new file mode 100644
index 000000000..6d092e002
--- /dev/null
+++ b/docs/ssh-agent-skills.md
@@ -0,0 +1,117 @@
+# nodeterm skills in SSH projects
+
+How the agent-facing skills (`manage-nodeterm-canvas`, `get-linked-context`) reach an agent
+that is running on a **remote host** in an SSH project.
+
+## The problem
+
+Both skills were installed only into the desktop's own home:
+
+- `manage-nodeterm-canvas` → `~/.claude/skills/…` + `<userData>/canvas-control/`
+- `get-linked-context` → `~/.claude/skills/…` + `<userData>/context-links/`
+
+An SSH project's agent runs on the **host**, reads the **host's** `~/.claude/skills`, and finds
+nothing. Copying the files over would not have helped either: both shims were generated as
+
+```sh
+ELECTRON_RUN_AS_NODE=1 exec "<the desktop's Electron binary>" "<…>/cli.mjs" "$@"
+```
+
+— a path that exists on exactly one machine. And the Node CLI they exec'd talked to the hook
+server over `127.0.0.1:<port>`, which on the host is the host's own loopback, not the desktop's.
+
+## The transport (already there)
+
+Nothing new had to be invented: an SSH project already runs a **reverse unix-socket tunnel** from
+the host back to the desktop's loopback hook server, because that is how remote agents report
+status (`RemoteHooks.setup`, `docs/`-less but see `src/main/remote-ssh/remote-hooks.ts`):
+
+```
+remote agent → curl --unix-socket ~/.nodeterm/hook-<projectId>.sock
+ → ssh -R → desktop 127.0.0.1:<hook port>
+```
+
+The per-project endpoint file `~/.nodeterm/hook-endpoint-<projectId>.env` carries the live
+`NODETERM_HOOK_SOCK` / `_TOKEN` / `_VERSION`, and every remote session's tmux env already points
+at it (`NODETERM_HOOK_ENDPOINT`) along with `NODETERM_NODE_ID`. So the design rule is:
+
+> **The remote side is a thin client.** It ships no parsing, no state and no app knowledge — it
+> POSTs over the existing tunnel and prints what comes back.
+
+## What shipped: canvas control over SSH
+
+1. **The CLI is now POSIX sh + curl** (`CONTROL_SHIM_SCRIPT` in `canvas-control-core.ts`),
+ replacing the Electron-as-Node CLI. It carries **no machine-specific paths**, so the same
+ script is installed on the desktop and on the host. It picks its transport from the endpoint
+ it was given: `--unix-socket $NODETERM_HOOK_SOCK` when one is advertised (SSH), else
+ `127.0.0.1:$NODETERM_HOOK_PORT` (desktop). `curl` is not a new dependency — the managed hook
+ script already requires it.
+
+ The request is **form-urlencoded**, not JSON: `curl --data-urlencode` is the only escaping sh
+ can be trusted with. Values like `--prompt`, `--html` and `--team` routinely contain quotes,
+ newlines and `$`, and hand-built JSON in sh breaks on all three. `parseControlBody`
+ (`hook-server.ts`) reads both dialects; the desktop's in-process callers still send JSON.
+ A `text/plain` `Accept` makes the server render the reply, since sh has no JSON parser.
+
+2. **`RemoteHooks.installCanvasControl`** writes the shim + `SKILL.md` onto the host at connect,
+ and merges the same marker-delimited instruction block into the host's `~/.codex/AGENTS.md`,
+ `~/.gemini/GEMINI.md` and `${XDG_CONFIG_HOME:-~/.config}/opencode/AGENTS.md` (that last path
+ is expanded by the **remote** shell — the desktop's XDG value says nothing about the host).
+ `installCanvasSkillIntoAccountDir` covers managed Claude accounts, whose sessions resolve
+ skills relative to `CLAUDE_CONFIG_DIR` and never see `~/.claude/skills`.
+
+3. **The env gap** — `remoteHookEnvArgs` injected only endpoint/node-id/version, so a remote
+ session inherited neither `NODETERM_AGENT_ID` nor `NODETERM_CANVAS_CONTROL`. The CLI gates
+ itself on the latter, so the skill would have been inert on every SSH node even once
+ installed. It now mirrors the local `hookServer.buildPtyEnv` exactly, `canControlCanvas`
+ gate included.
+
+### Gating and failure behavior
+
+Install is gated on **both** a resolved remote `$HOME` (every remote path must be absolute — a
+literal `~` does not expand where these strings land) and a **verified** tunnel: `setup()` only
+returns an endpoint path after proving the reverse forward reaches *this* app run. A skill
+pointing at a dead socket is worse than no skill, because the agent retries instead of telling
+the user canvas control is unavailable.
+
+Everything else fails open, per step: an unwritable instruction file, a host without `curl`, a
+dropped connection — the session runs, just without canvas control. Outside a nodeterm-spawned
+session the shim exits immediately on its env gate, so it stays inert in the user's own
+terminals (same discipline as the managed hook script).
+
+## Testing
+
+`canvas-control-shim.test.ts` runs the **real shim** under `/bin/sh` against a **real** hook
+server, over both a TCP port and a **unix socket** — the shim is generated source no compiler
+checks, and it is now the only canvas-control client. It covers the nasty-value round trip
+(quotes / newlines / `$` / backticks / backslashes), the positional forms, error propagation,
+the env gate, a bad token, a dead socket, and reading coordinates from the endpoint file.
+
+## Still owed: context link over SSH (Phase 2)
+
+`get-linked-context` is **not** yet available on SSH nodes. It cannot use the same trick as-is,
+because its CLI is a ~230-line parser for three transcript formats (claude JSONL, codex rollout,
+gemini event-sourced) — too much to ship as sh, and the host may have no `node`.
+
+The plan is the same shape, one level deeper: put the parsing **on the desktop**.
+
+1. A `/context-link/<verb>` route on the hook server, with the parsing lifted out of
+ `CLI_SCRIPT` into ordinary (testable) TS — the string-embedded JS CLI retires with it, and
+ the local path collapses onto the same route.
+2. Remote reads are already reachable from the desktop: the hook-fed `transcriptPath` for a
+ remote node **is a remote path**, readable over the ControlMaster with `SshFs.readText`, and
+ `PtyManager.captureSession` is already remote-aware.
+3. `resolveLinkTranscript` needs a fix first: for an SSH node it must not fall back to the
+ **local** `locateCodex`/`locateGemini`, which would happily resolve some unrelated transcript
+ on the wrong machine.
+4. **Authorization moves to the route.** Today a node may only read the links in its own link
+ file, which the per-node file layout enforces implicitly. Once `nodeId` arrives in a request
+ body, the route must check it explicitly — the same class of guard as the board-log relay's
+ `sharedProjectId` scope check.
+
+## Out of scope
+
+- **Server Edition** — canvas control is not wired there at all (no `agent:control` handler),
+ which this change does not alter. The shim is now portable enough to be reused when it is.
+- **Mobile companion** — no canvas, so no canvas control to surface.
+- **Relay remote nodes** — a different transport with no client fs; unaffected.
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index d3508c076..e53e22de2 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -43,6 +43,32 @@ function parseForm(body: string): Record<string, string> {
return out
}
+/**
+ * Read a /control/ request body in either dialect. The desktop's own callers send JSON; the
+ * POSIX-sh shim sends form-urlencoded with `nodeId` plus one `arg.<name>` field per flag,
+ * because `curl --data-urlencode` is the only escaping sh can be trusted with (hand-built JSON
+ * would break on the first quote in a `--prompt` or `--html` value). Exported for tests.
+ */
+export function parseControlBody(
+ raw: string,
+ contentType: string
+): { nodeId: string; args: Record<string, string> } {
+ if (contentType.includes('application/x-www-form-urlencoded')) {
+ const form = parseForm(raw)
+ const args: Record<string, string> = {}
+ for (const [k, v] of Object.entries(form)) {
+ if (k.startsWith('arg.') && k.length > 4) args[k.slice(4)] = v
+ }
+ return { nodeId: form.nodeId ?? '', args }
+ }
+ try {
+ const parsed = JSON.parse(raw) as { nodeId?: string; args?: Record<string, string> }
+ return { nodeId: parsed.nodeId ?? '', args: parsed.args ?? {} }
+ } catch {
+ return { nodeId: '', args: {} }
+ }
+}
+
class HookServer {
private server: Server | null = null
private port = 0
@@ -108,19 +134,23 @@ class HookServer {
const reqUrl = new URL(req.url ?? '/', 'http://127.0.0.1')
if (reqUrl.pathname.startsWith('/control/')) {
const verb = decodeURIComponent(reqUrl.pathname.replace(/^\/control\//, ''))
- let parsed: { nodeId?: string; args?: Record<string, string> } = {}
- try {
- parsed = JSON.parse(await readBody(req))
- } catch {
- parsed = {}
- }
+ const { nodeId, args } = parseControlBody(
+ await readBody(req),
+ String(req.headers['content-type'] ?? '')
+ )
const result = this.controlHandler
- ? await this.controlHandler({
- verb,
- nodeId: parsed.nodeId ?? '',
- args: parsed.args ?? {}
- })
+ ? await this.controlHandler({ verb, nodeId, args })
: { ok: false, error: 'control unavailable' }
+ // The POSIX-sh shim asks for text/plain: it has no JSON parser, so the server does the
+ // rendering the Node CLI used to do client-side. Everything else keeps the JSON shape.
+ if (String(req.headers.accept ?? '').includes('text/plain')) {
+ const text = result.ok
+ ? result.message ?? JSON.stringify(result.result ?? {})
+ : result.error ?? 'control request failed'
+ res.writeHead(result.ok ? 200 : 400, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end(`${text}\n`)
+ return
+ }
res.writeHead(result.ok ? 200 : 400, { 'content-type': 'application/json' })
res.end(JSON.stringify(result))
return
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 62f5a9ece..e338c12e9 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1184,7 +1184,10 @@ export class PtyManager {
...remoteHookEnvArgs(
options.sshRemote.hookEndpointPath,
options.persistKey,
- hookServer.getVersion()
+ hookServer.getVersion(),
+ // Same default the local path applies (`hookServer.buildPtyEnv(persistKey, agentId ??
+ // 'claude', …)`) so a remote node's agent env matches its local twin exactly.
+ options.agentId ?? 'claude'
),
// Arm the remote permission hook's wait-branch too (deterministic approvals over SSH):
// the request/answer files live on the REMOTE host; the desktop answers over the
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 3e809de8f..de625e537 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -4,6 +4,7 @@ import os from 'os'
import path from 'path'
import { createHash } from 'crypto'
import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'
+import { canControlCanvas } from '../../shared/agents/config'
// Dependency-free (no node-pty): safe to import from these pure builders.
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
@@ -192,9 +193,33 @@ export function hookForwardArgs(conn: SshConnection, controlPath: string, remote
export function hookForwardCancelArgs(conn: SshConnection, controlPath: string, remoteSock: string, hookPort: number): string[] {
return ['-O', 'cancel', '-R', fwdSpec(remoteSock, hookPort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]
}
-/** tmux `-e KEY=VALUE` pairs injecting the remote hook endpoint file + node id + protocol version. */
-export function remoteHookEnvArgs(endpointPath: string, nodeId: string, version: string): string[] {
- return ['-e', `NODETERM_HOOK_ENDPOINT=${endpointPath}`, '-e', `NODETERM_NODE_ID=${nodeId}`, '-e', `NODETERM_HOOK_VERSION=${version}`]
+/**
+ * tmux `-e KEY=VALUE` pairs injecting the remote hook endpoint file + node id + protocol version,
+ * plus the agent identity. The identity pair matters: the local path's `hookServer.buildPtyEnv`
+ * sets NODETERM_AGENT_ID and gates NODETERM_CANVAS_CONTROL on `canControlCanvas`, and a remote
+ * session that inherited neither had the canvas-control CLI disable itself on its own env gate —
+ * so the skill was inert on every SSH node even once it was installed there.
+ * `agentId` is omitted for plain (non-agent) terminals, which get neither pair.
+ */
+export function remoteHookEnvArgs(
+ endpointPath: string,
+ nodeId: string,
+ version: string,
+ agentId?: string
+): string[] {
+ const env = [
+ '-e',
+ `NODETERM_HOOK_ENDPOINT=${endpointPath}`,
+ '-e',
+ `NODETERM_NODE_ID=${nodeId}`,
+ '-e',
+ `NODETERM_HOOK_VERSION=${version}`
+ ]
+ if (agentId) {
+ env.push('-e', `NODETERM_AGENT_ID=${agentId}`)
+ if (canControlCanvas(agentId)) env.push('-e', 'NODETERM_CANVAS_CONTROL=1')
+ }
+ return env
}
/** Contents of the remote endpoint env file the managed hook script sources (unix-socket transport). */
export function remoteEndpointFileContents(sock: string, token: string, version: string): string {
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index bc8e08b78..5f4eb0ddb 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -153,70 +153,177 @@ export function buildCanvasControlInstructions(shimPath: string): string {
].join('\n')
}
-// Standalone CLI written to disk by canvas-control.ts and run via Electron-as-Node.
-// Self-contained (no deps), no backticks / ${} so it survives this template literal.
-export const CONTROL_CLI_SCRIPT = `// nodeterm canvas-control CLI (auto-generated — do not edit).
-import fs from 'node:fs'
-import http from 'node:http'
+// The canvas-control CLI, as a POSIX sh script (written to disk by canvas-control.ts, and
+// installed on the remote host for SSH projects by RemoteHooks). It replaced a Node CLI run
+// via Electron-as-Node: that shim hardcoded the desktop's own `process.execPath`, so it could
+// never run anywhere but the machine the app is installed on — which is exactly what kept this
+// skill from working in SSH projects, where the agent runs on the remote host.
+//
+// sh + curl only, for two reasons: the remote host has neither node nor the app, and curl is
+// already a hard dependency of the managed hook script, so it buys no new failure mode. The
+// request is form-urlencoded rather than JSON because `curl --data-urlencode` does the escaping
+// for us — emitting valid JSON from sh for arbitrary values (`--prompt`, `--html`, `--team`)
+// could not be made safe.
+export const CONTROL_SHIM_SCRIPT = `#!/bin/sh
+# nodeterm canvas-control CLI (auto-generated — do not edit).
-function out(s) { process.stdout.write(s + '\\n') }
-function fail(s) { process.stderr.write(s + '\\n'); process.exit(1) }
+if [ -z "$NODETERM_CANVAS_CONTROL" ]; then
+ echo "Canvas control is not available in this session (not a nodeterm agent node)." >&2
+ exit 1
+fi
-if (!process.env.NODETERM_CANVAS_CONTROL) {
- fail('Canvas control is not available in this session (not a nodeterm Claude node).')
-}
-var NODE_ID = process.env.NODETERM_NODE_ID || ''
-
-// Read live port/token from the endpoint env file (survives app restarts).
-function endpoint() {
- var p = process.env.NODETERM_HOOK_ENDPOINT
- var port = process.env.NODETERM_HOOK_PORT, token = process.env.NODETERM_HOOK_TOKEN
- try {
- if (p) {
- String(fs.readFileSync(p, 'utf-8')).split('\\n').forEach(function (ln) {
- var i = ln.indexOf('='); if (i < 0) return
- var k = ln.slice(0, i), val = ln.slice(i + 1)
- if (k === 'NODETERM_HOOK_PORT') port = val
- if (k === 'NODETERM_HOOK_TOKEN') token = val
- })
- }
- } catch (e) {}
- return { port: port, token: token }
-}
+# Live endpoint (sock/port/token). The file is rewritten on every app start and, for an SSH
+# project, points at that project's reverse-tunnel socket — so a session that outlived a
+# restart or a reconnect still reaches the current server.
+if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then
+ . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :
+fi
-// argv: <verb> [--flag value ...] [--text "..."] (also: positional path for show-image/video)
-var argv = process.argv.slice(2)
-var verb = argv[0] || 'list'
-var args = {}
-for (var i = 1; i < argv.length; i++) {
- if (argv[i].slice(0, 2) === '--') { args[argv[i].slice(2)] = argv[i + 1] || ''; i++ }
- else if (!args.path && (verb === 'show-image' || verb === 'show-video')) { args.path = argv[i] }
- else if (!args.node && (verb === 'write' || verb === 'close' || verb === 'rename' || verb === 'branch')) { args.node = argv[i] }
-}
+nt_verb="list"
+if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi
-var ep = endpoint()
-if (!ep.port || !ep.token) fail('nodeterm control endpoint unavailable.')
+# Translate \`--flag value\` pairs — plus the one bare positional the show-image/show-video and
+# write/close/rename/branch forms accept — into curl --data-urlencode arguments. The positional
+# list doubles as the accumulator: originals are consumed from the front, translated pairs
+# appended at the back, so "$@" holds exactly the curl args once the loop drains.
+nt_seen_pos=0
+nt_count=$#
+nt_i=0
+while [ "$nt_i" -lt "$nt_count" ]; do
+ nt_a="$1"; shift; nt_i=$((nt_i + 1))
+ case "$nt_a" in
+ --*)
+ nt_k=\${nt_a#--}
+ nt_v=""
+ if [ "$nt_i" -lt "$nt_count" ]; then nt_v="$1"; shift; nt_i=$((nt_i + 1)); fi
+ set -- "$@" --data-urlencode "arg.$nt_k=$nt_v"
+ ;;
+ *)
+ if [ "$nt_seen_pos" -eq 0 ]; then
+ nt_seen_pos=1
+ case "$nt_verb" in
+ show-image|show-video) set -- "$@" --data-urlencode "arg.path=$nt_a" ;;
+ write|close|rename|branch) set -- "$@" --data-urlencode "arg.node=$nt_a" ;;
+ esac
+ fi
+ ;;
+ esac
+done
-var body = JSON.stringify({ nodeId: NODE_ID, args: args })
-var reqOpts = {
- host: '127.0.0.1', port: Number(ep.port), method: 'POST',
- path: '/control/' + encodeURIComponent(verb),
- headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body), 'x-nodeterm-hook-token': ep.token }
-}
-var req = http.request(reqOpts, function (res) {
- var data = ''
- res.on('data', function (c) { data += c })
- res.on('end', function () {
- var j = {}
- try { j = JSON.parse(data) } catch (e) {}
- if (res.statusCode >= 200 && res.statusCode < 300 && j.ok) {
- out(j.message || JSON.stringify(j.result || {}))
- } else {
- fail(j.error || ('control request failed (HTTP ' + res.statusCode + ')'))
- }
- })
-})
-req.on('error', function (e) { fail('Could not reach nodeterm: ' + e.message) })
-req.write(body)
-req.end()
+nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-control.$$")
+if [ -n "$NODETERM_HOOK_SOCK" ]; then
+ nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/control/$nt_verb" \\
+ -H "Accept: text/plain" \\
+ -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
+elif [ -n "$NODETERM_HOOK_PORT" ]; then
+ nt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\
+ "http://127.0.0.1:\${NODETERM_HOOK_PORT}/control/$nt_verb" \\
+ -H "Accept: text/plain" \\
+ -H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\
+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
+else
+ rm -f "$nt_out"
+ echo "nodeterm control endpoint unavailable." >&2
+ exit 1
+fi
+
+if [ "$nt_code" = "200" ]; then
+ cat "$nt_out" 2>/dev/null
+ rm -f "$nt_out"
+ exit 0
+fi
+cat "$nt_out" >&2 2>/dev/null
+rm -f "$nt_out"
+if [ -z "$nt_code" ] || [ "$nt_code" = "000" ]; then
+ echo "Could not reach nodeterm (control endpoint unreachable)." >&2
+fi
+exit 1
`
+
+/** The manage-nodeterm-canvas SKILL.md body, pointing at the shim at `shimPath`.
+ * Parameterized because the same skill is installed twice with different paths: into the
+ * desktop's config dirs, and onto an SSH host for remote agent nodes. */
+export function buildCanvasSkillBody(shimPath: string): string {
+ return `---
+name: manage-nodeterm-canvas
+description: Create, organize and control nodes on the nodeterm canvas — open Claude Code / Codex / Gemini / terminal nodes, spawn a team of agents that divide up a task, create git worktrees as bound groups, wrap nodes in labeled groups, arrange/align/rename them, show an image/video/web page, write to or close a terminal. Use whenever the user says "Build with Nodeterm orchestration", asks to create or open nodes/sessions/terminals, split or parallelize work across subagents/agents/sessions/worktrees, delegate parts of a task to other agents, work on several things at once, build something using multiple Claude (or other agent) sessions, organize the canvas into groups by topic, or visualize code/output you produced. Only works inside a nodeterm Claude session.
+---
+
+# Manage the nodeterm canvas
+
+You are running inside a node on the nodeterm canvas. You can create and control nodes by
+running the local CLI shim below. Every node you open is connected to your node by an edge.
+
+Run the shim (absolute path):
+
+\`\`\`sh
+sh "${shimPath}" <verb> [args]
+\`\`\`
+
+Verbs:
+- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
+- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>]\` — open N plain terminals (default 1).
+- \`open-claude [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N Claude sessions (default 1).
+- \`open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N sessions of any agent CLI.
+ \`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
+ hands its worktree path down as the cwd.
+- \`show-image <path>\` — open an image file as a node.
+- \`show-video <path>\` — open a video file as a player node.
+- \`show-web (--url U | --file P.html | --html "<...>")\` — open a web viewer (live URL or local HTML you wrote).
+- \`open-browser --url U\` — open a navigable browser (back/forward/address bar) at a URL.
+- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap nodes in a labeled group frame.
+- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap.
+- \`align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter\` — align edges/centers.
+- \`spawn-team --label "Frontend Team" --team '[{"title":"UI","prompt":"...","agent":"claude"}]'\` —
+ open one agent per role (each prompt starts that member working), arrange them in a grid,
+ wrap them in a labeled group, and connect each to you. Max 8 roles per call.
+- \`open-worktree --branch <name> [--base <ref>] [--path P] [--group <id>]\` — create a git
+ worktree (new branch off base, default: the repo's default branch) and wrap it in a bound
+ group frame (or bind it to an existing empty group). Terminals created inside the group
+ run in the worktree. Local projects only.
+- \`close-worktree --group <id> [--mode unbind|remove]\` — unbind (default) drops the binding
+ and keeps the directory; remove asks the user to confirm deleting the worktree.
+- \`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…).
+- \`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.)
+
+Notes:
+- \`write\` and \`close\` require the user to approve a confirmation dialog; they may be denied.
+- If the CLI says canvas control is unavailable, you are not in a controllable nodeterm session — do not retry.
+
+To orchestrate a team: decide the roles + a concrete starting prompt for each, then one
+\`spawn-team\` call (or \`open-claude\` per role followed by \`group\` + \`arrange\`).
+
+Typical requests this skill covers:
+- "Create Claude Code nodes for X and organize them into groups by subject" → decide the
+ workstreams, then either one \`spawn-team\` per subject (each team is already a labeled
+ group), or \`open-claude\`/\`open-agent\` per node followed by \`group --nodes ... --label\`
+ per subject and \`arrange\` inside each.
+- "Open a codex/gemini session" → \`open-agent --agent codex|gemini\`.
+- "Tidy up / group my terminals" → \`list\`, then \`group\` + \`arrange\` + \`align\`.
+- "Rename this node/group" → \`rename\`.
+
+## Nodeterm orchestration ("Build with Nodeterm orchestration")
+
+When the user says "Build with Nodeterm orchestration" (or asks you to orchestrate a build
+across Nodeterm sessions), be the orchestration chef — plan the kitchen, then run it:
+
+1. Break the task into 2–5 independent workstreams (by subsystem, not by file).
+2. Per workstream, give it its own branch + kitchen station:
+ \`open-worktree --branch <slug>\` → note the returned \`groupId\`, then
+ \`open-agent --agent claude --group <groupId> --prompt "<concrete, self-contained task>"\`.
+ Each stream now works on its own branch in its own worktree group — no tree conflicts.
+3. Keep the kitchen tidy: members opened with \`--group\` land in neat grid slots inside the
+ frame automatically (the frame grows to fit), and successive \`open-worktree\` frames fan
+ out side by side — after opening all stations, align the frames with
+ \`arrange --nodes <groupId,groupId,…> --layout row\` (arrange/align work on top-level
+ nodes, so pass the GROUP ids, not the children). \`rename\` each group by subject.
+4. Track progress (their status badges show working/waiting) and coordinate: when a stream
+ finishes, the user merges from the group's chip (never merge for them); release a finished
+ station with \`close-worktree --group <id>\` (unbind keeps the directory).
+`
+}
diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.ts
new file mode 100644
index 000000000..7aaca8c3d
--- /dev/null
+++ b/src/main/canvas-control-shim.test.ts
@@ -0,0 +1,234 @@
+// End-to-end test for the POSIX-sh canvas-control CLI: the real shim script, run by the real
+// /bin/sh, against the real hook server. The shim is generated source that no compiler ever
+// checks, and it is the ONLY canvas-control client after the Electron-as-Node CLI was retired —
+// a quoting slip in it fails silently at runtime on the user's machine (and, for SSH projects,
+// on a machine we cannot even inspect). So it is exercised for real rather than asserted against.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { CONTROL_SHIM_SCRIPT } from './canvas-control-core'
+import { hookServer, parseControlBody } from '../core/agents/hook-server'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { fakePlatform } from '../core/platform-fake'
+
+const run = promisify(execFile)
+
+let dir = ''
+let shim = ''
+let received: { verb: string; nodeId: string; args: Record<string, string> }[] = []
+
+beforeAll(async () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-shim-'))
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ shim = path.join(dir, 'nodeterm.sh')
+ fs.writeFileSync(shim, CONTROL_SHIM_SCRIPT, { mode: 0o755 })
+ await hookServer.start()
+ hookServer.setControlHandler(async (cmd) => {
+ received.push(cmd)
+ if (cmd.verb === 'boom') return { ok: false, error: 'that verb exploded' }
+ return { ok: true, message: `did ${cmd.verb}` }
+ })
+})
+
+afterAll(() => {
+ hookServer.stop()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+/** Invoke the shim the way an agent does, with the env a nodeterm-spawned session carries. */
+function callShim(
+ args: string[],
+ env: Record<string, string> = {}
+): Promise<{ stdout: string; stderr: string }> {
+ return run('/bin/sh', [shim, ...args], {
+ env: {
+ PATH: process.env.PATH ?? '',
+ NODETERM_CANVAS_CONTROL: '1',
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_PORT: String(hookServer.getPort()),
+ NODETERM_HOOK_TOKEN: hookServer.getToken(),
+ ...env
+ }
+ })
+}
+
+describe('canvas-control shim', () => {
+ beforeAll(() => {
+ received = []
+ })
+
+ it('is valid POSIX sh', async () => {
+ await expect(run('/bin/sh', ['-n', shim])).resolves.toBeTruthy()
+ })
+
+ it('sends verb, node id and --flag pairs, and prints the server message', async () => {
+ const { stdout } = await callShim(['open-claude', '--count', '2', '--cwd', '/srv/app'])
+ expect(stdout.trim()).toBe('did open-claude')
+ const last = received.at(-1)
+ expect(last?.verb).toBe('open-claude')
+ expect(last?.nodeId).toBe('node-1')
+ expect(last?.args).toEqual({ count: '2', cwd: '/srv/app' })
+ })
+
+ it('defaults to `list` when called with no verb', async () => {
+ await callShim([])
+ expect(received.at(-1)?.verb).toBe('list')
+ })
+
+ // The reason this transport is form-urlencoded rather than JSON: these values reach curl as
+ // ordinary argv and must survive verbatim. Hand-rolled JSON quoting in sh broke on every one.
+ it('carries values containing quotes, newlines, $ and backslashes verbatim', async () => {
+ const nasty = 'He said "hi";\nrm -rf $HOME `echo x` \\ 100% & <tag>'
+ await callShim(['open-claude', '--prompt', nasty])
+ expect(received.at(-1)?.args.prompt).toBe(nasty)
+ })
+
+ it('carries a JSON --team payload through unchanged', async () => {
+ const team = JSON.stringify([{ title: 'UI', prompt: 'build the "header"', agent: 'claude' }])
+ await callShim(['spawn-team', '--label', 'Frontend', '--team', team])
+ expect(received.at(-1)?.args.team).toBe(team)
+ })
+
+ it('maps the bare positional to --path / --node per verb', async () => {
+ await callShim(['show-image', '/tmp/a b.png'])
+ expect(received.at(-1)?.args).toEqual({ path: '/tmp/a b.png' })
+ await callShim(['close', 'node-9'])
+ expect(received.at(-1)?.args).toEqual({ node: 'node-9' })
+ })
+
+ it('accepts a trailing flag with no value', async () => {
+ await callShim(['rename', '--node', 'n1', '--title'])
+ expect(received.at(-1)?.args).toEqual({ node: 'n1', title: '' })
+ })
+
+ it('reports server-side failures on stderr with a non-zero exit', async () => {
+ await expect(callShim(['boom'])).rejects.toMatchObject({
+ code: 1,
+ stderr: expect.stringContaining('that verb exploded')
+ })
+ })
+
+ it('refuses outside a canvas-control session instead of calling anything', async () => {
+ const before = received.length
+ await expect(
+ run('/bin/sh', [shim, 'list'], { env: { PATH: process.env.PATH ?? '' } })
+ ).rejects.toMatchObject({ stderr: expect.stringContaining('not a nodeterm agent node') })
+ expect(received.length).toBe(before)
+ })
+
+ it('rejects a wrong token (the server answers 403, the shim exits non-zero)', async () => {
+ await expect(callShim(['list'], { NODETERM_HOOK_TOKEN: 'wrong' })).rejects.toMatchObject({
+ code: 1
+ })
+ })
+
+ it('says so when no endpoint is advertised at all', async () => {
+ await expect(
+ callShim(['list'], { NODETERM_HOOK_PORT: '', NODETERM_HOOK_TOKEN: '' })
+ ).rejects.toMatchObject({ stderr: expect.stringContaining('endpoint unavailable') })
+ })
+
+ // The SSH path: the endpoint file is the only place a remote session learns its socket/token,
+ // and it is re-read per invocation so a session that outlived an app restart still connects.
+ it('sources sock/token from the endpoint file rather than the env', async () => {
+ const endpoint = path.join(dir, 'hook-endpoint.env')
+ fs.writeFileSync(
+ endpoint,
+ `NODETERM_HOOK_PORT=${hookServer.getPort()}\nNODETERM_HOOK_TOKEN=${hookServer.getToken()}\n`
+ )
+ const { stdout } = await callShim(['list'], {
+ NODETERM_HOOK_PORT: '',
+ NODETERM_HOOK_TOKEN: '',
+ NODETERM_HOOK_ENDPOINT: endpoint
+ })
+ expect(stdout.trim()).toBe('did list')
+ })
+})
+
+// The branch every SSH project actually uses. On a remote host there is no loopback port to
+// reach the desktop on — only the reverse-forwarded unix socket — so if this branch is broken
+// the feature is broken on exactly the surface it was built for, and nowhere else.
+describe('canvas-control shim over a unix socket', () => {
+ let sock = ''
+ let server: import('node:http').Server
+ // A holder plus an accessor rather than a bare `let`: clearing it in one test would otherwise
+ // narrow the variable to `never` for every read that follows in the same flow.
+ const state: { seen: { path: string; token: string; body: string } | null } = { seen: null }
+ const lastSeen = (): typeof state.seen => state.seen
+
+ beforeAll(async () => {
+ const http = await import('node:http')
+ sock = path.join(dir, 'hook.sock')
+ server = http.createServer((req, res) => {
+ let body = ''
+ req.on('data', (c) => (body += c))
+ req.on('end', () => {
+ state.seen = {
+ path: req.url ?? '',
+ token: String(req.headers['x-nodeterm-hook-token'] ?? ''),
+ body
+ }
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end('opened 2 sessions\n')
+ })
+ })
+ await new Promise<void>((r) => server.listen(sock, r))
+ })
+
+ afterAll(() => {
+ server.close()
+ })
+
+ it('posts through the socket and prints the reply', async () => {
+ const { stdout } = await callShim(['open-claude', '--count', '2'], {
+ NODETERM_HOOK_PORT: '',
+ NODETERM_HOOK_SOCK: sock,
+ NODETERM_HOOK_TOKEN: 'tok-remote'
+ })
+ expect(stdout.trim()).toBe('opened 2 sessions')
+ expect(lastSeen()?.path).toBe('/control/open-claude')
+ expect(lastSeen()?.token).toBe('tok-remote')
+ expect(parseControlBody(lastSeen()?.body ?? '', 'application/x-www-form-urlencoded')).toEqual({
+ nodeId: 'node-1',
+ args: { count: '2' }
+ })
+ })
+
+ it('prefers the socket over a port when both are advertised', async () => {
+ state.seen = null
+ await callShim(['list'], { NODETERM_HOOK_SOCK: sock })
+ expect(lastSeen()?.path).toBe('/control/list')
+ })
+
+ it('fails loudly when the socket is dead rather than hanging or printing success', async () => {
+ await expect(
+ callShim(['list'], {
+ NODETERM_HOOK_PORT: '',
+ NODETERM_HOOK_SOCK: path.join(dir, 'no-such.sock')
+ })
+ ).rejects.toMatchObject({ code: 1, stderr: expect.stringContaining('Could not reach nodeterm') })
+ })
+})
+
+describe('parseControlBody', () => {
+ it('reads the shim dialect: nodeId plus arg.<name> fields', () => {
+ expect(
+ parseControlBody('nodeId=n1&arg.count=2&arg.cwd=%2Fsrv&version=1', 'application/x-www-form-urlencoded')
+ ).toEqual({ nodeId: 'n1', args: { count: '2', cwd: '/srv' } })
+ })
+
+ it('still reads the JSON dialect the desktop callers use', () => {
+ expect(parseControlBody('{"nodeId":"n1","args":{"a":"b"}}', 'application/json')).toEqual({
+ nodeId: 'n1',
+ args: { a: 'b' }
+ })
+ })
+
+ it('degrades to an empty command on garbage rather than throwing', () => {
+ expect(parseControlBody('not json', 'application/json')).toEqual({ nodeId: '', args: {} })
+ })
+})
diff --git a/src/main/canvas-control.ts b/src/main/canvas-control.ts
index 15c302f69..09685b209 100644
--- a/src/main/canvas-control.ts
+++ b/src/main/canvas-control.ts
@@ -1,15 +1,19 @@
// Installs the outbound canvas-control CLI + per-agent discovery docs. Mirrors
-// context-link.ts: a self-contained CLI (canvas-control-cli.mjs, run via Electron-as-Node
-// through nodeterm.sh) POSTs to the hook server's /control/* routes; a Claude skill /
-// codex-gemini instruction blocks tell the agent how + when to call it. The CLI no-ops
-// unless NODETERM_CANVAS_CONTROL is set.
+// context-link.ts: a self-contained POSIX-sh CLI (nodeterm.sh) POSTs to the hook server's
+// /control/* routes; a Claude skill / codex-gemini instruction blocks tell the agent how +
+// when to call it. The CLI no-ops unless NODETERM_CANVAS_CONTROL is set.
+//
+// The SSH counterpart of this file is RemoteHooks.installCanvasControl, which writes the very
+// same shim + skill onto the remote host — the shim carries no machine-specific paths, so one
+// script serves both sides.
import fs from 'fs'
import os from 'os'
import path from 'path'
import { app } from 'electron'
import {
- CONTROL_CLI_SCRIPT,
+ CONTROL_SHIM_SCRIPT,
buildCanvasControlInstructions,
+ buildCanvasSkillBody,
mergeCanvasControlBlock
} from './canvas-control-core'
import { opencodeConfigDir } from '../core/agents/hooks/opencode'
@@ -17,113 +21,32 @@ import { opencodeConfigDir } from '../core/agents/hooks/opencode'
function dir(): string {
return path.join(app.getPath('userData'), 'canvas-control')
}
-function cliScriptPath(): string {
- return path.join(dir(), 'canvas-control-cli.mjs')
-}
function shimPath(): string {
return path.join(dir(), 'nodeterm.sh')
}
function skillPathIn(configDir: string): string {
return path.join(configDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md')
}
+function skillBody(): string {
+ return buildCanvasSkillBody(shimPath())
+}
function writeCliFiles(): void {
const d = dir()
fs.mkdirSync(d, { recursive: true })
- fs.writeFileSync(cliScriptPath(), CONTROL_CLI_SCRIPT)
- const shim = `#!/bin/sh
-# nodeterm canvas-control CLI shim (auto-generated — do not edit).
-ELECTRON_RUN_AS_NODE=1 exec "${process.execPath}" "${cliScriptPath()}" "$@"
-`
- fs.writeFileSync(shimPath(), shim)
+ fs.writeFileSync(shimPath(), CONTROL_SHIM_SCRIPT)
try {
fs.chmodSync(shimPath(), 0o755)
} catch {
/* fail open */
}
-}
-
-function skillBody(): string {
- return `---
-name: manage-nodeterm-canvas
-description: Create, organize and control nodes on the nodeterm canvas — open Claude Code / Codex / Gemini / terminal nodes, spawn a team of agents that divide up a task, create git worktrees as bound groups, wrap nodes in labeled groups, arrange/align/rename them, show an image/video/web page, write to or close a terminal. Use whenever the user says "Build with Nodeterm orchestration", asks to create or open nodes/sessions/terminals, split or parallelize work across subagents/agents/sessions/worktrees, delegate parts of a task to other agents, work on several things at once, build something using multiple Claude (or other agent) sessions, organize the canvas into groups by topic, or visualize code/output you produced. Only works inside a nodeterm Claude session.
----
-
-# Manage the nodeterm canvas
-
-You are running inside a node on the nodeterm canvas. You can create and control nodes by
-running the local CLI shim below. Every node you open is connected to your node by an edge.
-
-Run the shim (absolute path):
-
-\`\`\`sh
-sh "${shimPath()}" <verb> [args]
-\`\`\`
-
-Verbs:
-- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
-- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>]\` — open N plain terminals (default 1).
-- \`open-claude [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N Claude sessions (default 1).
-- \`open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N sessions of any agent CLI.
- \`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
- hands its worktree path down as the cwd.
-- \`show-image <path>\` — open an image file as a node.
-- \`show-video <path>\` — open a video file as a player node.
-- \`show-web (--url U | --file P.html | --html "<...>")\` — open a web viewer (live URL or local HTML you wrote).
-- \`open-browser --url U\` — open a navigable browser (back/forward/address bar) at a URL.
-- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap nodes in a labeled group frame.
-- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap.
-- \`align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter\` — align edges/centers.
-- \`spawn-team --label "Frontend Team" --team '[{"title":"UI","prompt":"...","agent":"claude"}]'\` —
- open one agent per role (each prompt starts that member working), arrange them in a grid,
- wrap them in a labeled group, and connect each to you. Max 8 roles per call.
-- \`open-worktree --branch <name> [--base <ref>] [--path P] [--group <id>]\` — create a git
- worktree (new branch off base, default: the repo's default branch) and wrap it in a bound
- group frame (or bind it to an existing empty group). Terminals created inside the group
- run in the worktree. Local projects only.
-- \`close-worktree --group <id> [--mode unbind|remove]\` — unbind (default) drops the binding
- and keeps the directory; remove asks the user to confirm deleting the worktree.
-- \`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…).
-- \`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.)
-
-Notes:
-- \`write\` and \`close\` require the user to approve a confirmation dialog; they may be denied.
-- If the CLI says canvas control is unavailable, you are not in a controllable nodeterm session — do not retry.
-
-To orchestrate a team: decide the roles + a concrete starting prompt for each, then one
-\`spawn-team\` call (or \`open-claude\` per role followed by \`group\` + \`arrange\`).
-
-Typical requests this skill covers:
-- "Create Claude Code nodes for X and organize them into groups by subject" → decide the
- workstreams, then either one \`spawn-team\` per subject (each team is already a labeled
- group), or \`open-claude\`/\`open-agent\` per node followed by \`group --nodes ... --label\`
- per subject and \`arrange\` inside each.
-- "Open a codex/gemini session" → \`open-agent --agent codex|gemini\`.
-- "Tidy up / group my terminals" → \`list\`, then \`group\` + \`arrange\` + \`align\`.
-- "Rename this node/group" → \`rename\`.
-
-## Nodeterm orchestration ("Build with Nodeterm orchestration")
-
-When the user says "Build with Nodeterm orchestration" (or asks you to orchestrate a build
-across Nodeterm sessions), be the orchestration chef — plan the kitchen, then run it:
-
-1. Break the task into 2–5 independent workstreams (by subsystem, not by file).
-2. Per workstream, give it its own branch + kitchen station:
- \`open-worktree --branch <slug>\` → note the returned \`groupId\`, then
- \`open-agent --agent claude --group <groupId> --prompt "<concrete, self-contained task>"\`.
- Each stream now works on its own branch in its own worktree group — no tree conflicts.
-3. Keep the kitchen tidy: members opened with \`--group\` land in neat grid slots inside the
- frame automatically (the frame grows to fit), and successive \`open-worktree\` frames fan
- out side by side — after opening all stations, align the frames with
- \`arrange --nodes <groupId,groupId,…> --layout row\` (arrange/align work on top-level
- nodes, so pass the GROUP ids, not the children). \`rename\` each group by subject.
-4. Track progress (their status badges show working/waiting) and coordinate: when a stream
- finishes, the user merges from the group's chip (never merge for them); release a finished
- station with \`close-worktree --group <id>\` (unbind keeps the directory).
-`
+ // Sweep the retired Electron-as-Node CLI off upgraders' disks — the shim no longer execs it,
+ // so it would sit there forever pointing at a binary path that moves with every app update.
+ try {
+ fs.rmSync(path.join(d, 'canvas-control-cli.mjs'), { force: true })
+ } catch {
+ /* fail open */
+ }
}
/**
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index b277916a4..2a3e5be5b 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -168,3 +168,87 @@ describe('RemoteHooks.teardown', () => {
).toBe(true)
})
})
+
+describe('RemoteHooks.installCanvasControl', () => {
+ const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)
+
+ it('writes an executable shim + the skill, and merges the codex/gemini/opencode blocks', async () => {
+ const { rh, calls } = mk()
+ await rh.installCanvasControl(conn, '/s.sock', '/home/u')
+ const joined = calls.map((c) => c.args.join(' '))
+ // The shim must land executable: the skill tells the agent to run it via `sh <path>`, but the
+ // instruction blocks and a user's own habits may exec it directly.
+ expect(joined.some((j) => j.includes('cat > \'/home/u/.nodeterm/nodeterm.sh\'') && j.includes('chmod 755'))).toBe(true)
+ // It is the POSIX shim, NOT the retired Electron-as-Node one — nothing may reference a local
+ // interpreter path, which is exactly what made the old CLI unusable off the desktop.
+ const shim = calls.find((c) => isWriteTo(c.args, '/home/u/.nodeterm/nodeterm.sh'))?.stdin ?? ''
+ expect(shim).toContain('#!/bin/sh')
+ expect(shim).toContain('--unix-socket')
+ expect(shim).not.toContain('ELECTRON_RUN_AS_NODE')
+ // The skill points at the REMOTE shim path (a desktop path would resolve to nothing here).
+ const skill = calls.find((c) => isWriteTo(c.args, '/home/u/.claude/skills/manage-nodeterm-canvas/SKILL.md'))?.stdin ?? ''
+ expect(skill).toContain('name: manage-nodeterm-canvas')
+ expect(skill).toContain('sh "/home/u/.nodeterm/nodeterm.sh"')
+ // codex/gemini get the marker block; opencode's path is expanded by the REMOTE shell, since
+ // the desktop's XDG_CONFIG_HOME says nothing about the host's.
+ expect(joined.some((j) => j.includes('/home/u/.codex/AGENTS.md'))).toBe(true)
+ expect(joined.some((j) => j.includes('/home/u/.gemini/GEMINI.md'))).toBe(true)
+ expect(joined.some((j) => j.includes('${XDG_CONFIG_HOME:-/home/u/.config}/opencode/AGENTS.md'))).toBe(true)
+ expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:manage-canvas:start'))).toBe(true)
+ // no unexpanded tilde survives in any remote path.
+ expect(joined.some((j) => j.includes('~/'))).toBe(false)
+ })
+
+ it('preserves existing instruction-file content and rewrites its own block only', async () => {
+ const existing = '# my notes\n\n<!-- nodeterm:manage-canvas:start -->\nSTALE\n<!-- nodeterm:manage-canvas:end -->\n'
+ const calls: { args: string[]; stdin?: string }[] = []
+ const run = vi.fn(async (args: string[], stdin?: string) => {
+ calls.push({ args, stdin })
+ const joined = args.join(' ')
+ if (joined.includes('.codex/AGENTS.md') && !joined.includes('cat >')) return { code: 0, stdout: existing }
+ return { code: 0, stdout: '' }
+ })
+ await new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')
+ const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))
+ expect(write?.stdin).toContain('# my notes')
+ expect(write?.stdin).not.toContain('STALE')
+ expect(write?.stdin).toContain('nodeterm canvas')
+ })
+
+ it('skips the write when the block is already current (idempotent reconnects)', async () => {
+ // A connect happens on every app start and every reconnect; rewriting an unchanged file each
+ // time would churn the user's instruction files (and their mtimes) for nothing.
+ const first = mk()
+ await first.rh.installCanvasControl(conn, '/s.sock', '/home/u')
+ const merged = first.calls.find((c) => c.args.join(' ').includes('cat > \'/home/u/.gemini/GEMINI.md\''))?.stdin ?? ''
+ expect(merged).toBeTruthy()
+
+ const calls: { args: string[]; stdin?: string }[] = []
+ const run = vi.fn(async (args: string[], stdin?: string) => {
+ calls.push({ args, stdin })
+ const joined = args.join(' ')
+ if (joined.includes('.gemini/GEMINI.md') && !joined.includes('cat >')) return { code: 0, stdout: merged }
+ return { code: 0, stdout: '' }
+ })
+ await new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')
+ expect(calls.some((c) => isWriteTo(c.args, '/home/u/.gemini/GEMINI.md'))).toBe(false)
+ })
+
+ it('installs the skill into a remote managed-account config dir', async () => {
+ // claude resolves user skills relative to CLAUDE_CONFIG_DIR, so an account session never sees
+ // ~/.claude/skills — the same gap installIntoAccountDir exists for on the hook side.
+ const { rh, calls } = mk()
+ await rh.installCanvasSkillIntoAccountDir(conn, '/s.sock', '/home/u', 'acc-1')
+ const target = '/home/u/.nodeterm/claude-accounts/acc-1/skills/manage-nodeterm-canvas/SKILL.md'
+ expect(calls.some((c) => isWriteTo(c.args, target))).toBe(true)
+ // the shim is (re)written too — installCanvasControl may have failed open earlier.
+ expect(calls.some((c) => isWriteTo(c.args, '/home/u/.nodeterm/nodeterm.sh'))).toBe(true)
+ })
+
+ it('fails open when the remote runner throws', async () => {
+ const run = vi.fn(async () => {
+ throw new Error('ssh died')
+ })
+ await expect(new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()
+ })
+})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 325f3a955..96b233817 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -8,8 +8,21 @@ import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileCo
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
import { mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'
import { ensureFullscreenTui, type TuiSettings } from '../../core/agents/hooks/claude-tui'
+import {
+ CONTROL_SHIM_SCRIPT,
+ buildCanvasControlInstructions,
+ buildCanvasSkillBody,
+ mergeCanvasControlBlock
+} from '../canvas-control-core'
import { posixQuote, type SshConnection } from '../../shared/ssh'
+/** POSIX dirname of an absolute remote path. `path.dirname` would apply the LOCAL separator
+ * rules, which is wrong the moment the desktop is Windows and the host is Linux. */
+function dirnameOf(p: string): string {
+ const i = p.lastIndexOf('/')
+ return i > 0 ? p.slice(0, i) : '/'
+}
+
export interface RemoteRunner {
/** Run one ssh child command (over the master); optional stdin written to the child. */
run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
@@ -171,6 +184,109 @@ export class RemoteHooks {
}
}
+ /**
+ * Install the canvas-control CLI + its discovery docs on the REMOTE host, so an agent running
+ * in an SSH project can create and organize canvas nodes exactly like a local one.
+ *
+ * The desktop installs the same two artifacts into its own home (`canvas-control.ts`); this is
+ * the SSH counterpart. Nothing machine-specific crosses over: the shim is pure sh + curl and
+ * reads its endpoint from `$NODETERM_HOOK_ENDPOINT` (the per-project file `setup()` wrote), so
+ * the *remote* copy reaches this desktop through the same reverse tunnel the status hooks use.
+ * The old Electron-as-Node shim could not be installed here at any price — it hardcoded the
+ * desktop's `process.execPath`.
+ *
+ * The CALLER gates this on `setup()` having verified the tunnel: a skill pointing at a socket
+ * that answers nothing is worse than no skill, because the agent retries a dead endpoint
+ * instead of telling the user canvas control is unavailable. Fail-open per step otherwise.
+ */
+ async installCanvasControl(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {
+ try {
+ const shim = `${remoteHome}/.nodeterm/nodeterm.sh`
+ await this.writeCanvasShim(conn, controlPath, shim)
+ await this.installCanvasSkillAt(conn, controlPath, `${remoteHome}/.claude`, shim)
+ // codex / gemini / opencode have no skill system — same marker-delimited instruction block
+ // the desktop merges into their global instruction files. The opencode path is expanded by
+ // the REMOTE shell (it is XDG-respecting and the local value says nothing about the host).
+ const block = buildCanvasControlInstructions(shim)
+ const targets = [
+ posixQuote(`${remoteHome}/.codex/AGENTS.md`),
+ posixQuote(`${remoteHome}/.gemini/GEMINI.md`),
+ `"\${XDG_CONFIG_HOME:-${remoteHome}/.config}/opencode/AGENTS.md"`
+ ]
+ for (const target of targets) {
+ await this.mergeRemoteInstructions(conn, controlPath, target, block)
+ }
+ } catch {
+ /* fail-open: the remote agent simply runs without canvas control */
+ }
+ }
+
+ /**
+ * Same skill, installed into a REMOTE managed-account config dir. Claude Code resolves user
+ * skills relative to CLAUDE_CONFIG_DIR, so an account session sees `~/.claude/skills` not at
+ * all — the exact reason `installIntoAccountDir` exists for the status hook.
+ */
+ async installCanvasSkillIntoAccountDir(
+ conn: SshConnection,
+ controlPath: string,
+ remoteHome: string,
+ accountId: string
+ ): Promise<void> {
+ try {
+ const shim = `${remoteHome}/.nodeterm/nodeterm.sh`
+ // Idempotently (re)write the shim: installCanvasControl may not have run (fail-open) yet.
+ await this.writeCanvasShim(conn, controlPath, shim)
+ const accountDir = `${remoteHome}/.nodeterm/claude-accounts/${accountId}`
+ await this.installCanvasSkillAt(conn, controlPath, accountDir, shim)
+ } catch {
+ /* fail-open */
+ }
+ }
+
+ private async writeCanvasShim(conn: SshConnection, controlPath: string, shim: string): Promise<void> {
+ const q = posixQuote(shim)
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(dirnameOf(shim))} && cat > ${q} && chmod 755 ${q}`),
+ CONTROL_SHIM_SCRIPT
+ )
+ }
+
+ private async installCanvasSkillAt(
+ conn: SshConnection,
+ controlPath: string,
+ configDir: string,
+ shim: string
+ ): Promise<void> {
+ const skill = `${configDir}/skills/manage-nodeterm-canvas/SKILL.md`
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(dirnameOf(skill))} && cat > ${posixQuote(skill)}`),
+ buildCanvasSkillBody(shim)
+ )
+ }
+
+ /** Read-merge-write one marker-delimited instructions block at a remote path EXPRESSION
+ * (already quoted / shell-expandable). Everything outside the markers is preserved. */
+ private async mergeRemoteInstructions(
+ conn: SshConnection,
+ controlPath: string,
+ pathExpr: string,
+ block: string
+ ): Promise<void> {
+ try {
+ const { stdout: existing } = await this.r.run(
+ childArgs(conn, controlPath, `cat ${pathExpr} 2>/dev/null || true`)
+ )
+ const merged = mergeCanvasControlBlock(existing, block)
+ if (merged === existing) return
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`),
+ merged
+ )
+ } catch {
+ /* fail-open: one unwritable instruction file must never break the connect */
+ }
+ }
+
/**
* Ensure `"tui": "fullscreen"` in the REMOTE host's `~/.claude/settings.json` — write-if-absent,
* so a remote Claude session takes the alternate screen + mouse and behaves natively in the
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 1514f894c..45b0c37c5 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -352,6 +352,15 @@ export class SshProjectManager {
/* fail-open: no conf → remote tmux uses host defaults */
}
}
+ // Canvas control for remote agent nodes. Gated on BOTH the resolved home (every remote
+ // path must be absolute) and a verified tunnel (`hookEndpointPath` is only set once
+ // setup() proved the reverse forward reaches this app run) — installing a skill whose
+ // endpoint answers nothing would have the agent retry a dead socket instead of reporting
+ // canvas control as unavailable. Not awaited: it is several remote round-trips of pure
+ // best-effort setup, and holding the connect on them would delay every terminal.
+ if (remoteHome && hookEndpointPath) {
+ void this.remoteHooks.installCanvasControl(conn, controlPath, remoteHome)
+ }
const entry = this.conns.get(projectId)
if (entry) {
entry.hookEndpointPath = hookEndpointPath
@@ -631,6 +640,11 @@ export class SshProjectManager {
// Install the managed hook into the account dir's settings.json (needs the absolute $HOME so the
// merged `sh "…"` command has no unexpanded ~). Fail-open when the home never resolved.
if (c.remoteHome) await this.remoteHooks.installIntoAccountDir(c.conn, c.controlPath, c.remoteHome, accountId)
+ // Same gap for the canvas-control SKILL: claude resolves user skills relative to
+ // CLAUDE_CONFIG_DIR, so an account session never sees the one in `~/.claude/skills`.
+ if (c.remoteHome && c.hookEndpointPath) {
+ await this.remoteHooks.installCanvasSkillIntoAccountDir(c.conn, c.controlPath, c.remoteHome, accountId)
+ }
// One remote `claude --version` gates both the keychain-scoping answer (>= 2.1, fail-open true)
// AND the fullscreen-tui write (>= 2.1.89, write-if-absent) into the account dir.
const version = await this.remoteClaudeVersion(c.conn, c.controlPath)