Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(ssh): context link works in SSH projects
enes4c9fa2b6f3b4
diff --git a/docs/ssh-agent-skills.md b/docs/ssh-agent-skills.mdindex 6d092e002..0e0d43126 100644--- a/docs/ssh-agent-skills.md+++ b/docs/ssh-agent-skills.md@@ -79,6 +79,49 @@ dropped connection — the session runs, just without canvas control. Outside asession the shim exits immediately on its env gate, so it stays inert in the user's ownterminals (same discipline as the managed hook script).+## What shipped: context link over SSH++`get-linked-context` could not use the canvas-control trick as-is: its CLI was a ~230-line parser+for three transcript formats (claude JSONL, codex rollout, gemini event-sourced, plus an opencode+export), too much to express in sh — and the host may have no `node` at all.++So the same rule was applied one level deeper: **the desktop does the reading and the parsing.**++1. **The parsing moved out of the CLI** into `core/context-link-render.ts` — ordinary, tested TS+ instead of JavaScript embedded in a template literal. `renderContextLink` takes a link document+ and three injected fetchers and returns the text to print; it knows nothing about ssh, fs, or+ tmux.+2. **A `/context-link/<verb>` route** on the hook server answers with `text/plain`, and+ `context.sh` — the sh+curl twin of `nodeterm.sh` — is the only client. The local path uses the+ same route, so there is one implementation, not a local one and a remote one that drift.+3. **Remote reads were already reachable** from the desktop: a remote node's hook-fed+ `transcriptPath` *is* a remote path, read over the ControlMaster with `RemoteFile.readTail`+ (bounded — a long session's transcript is tens of MB and a `summary` shows 15 lines), and+ `PtyManager.captureSession` was already remote-aware, so `terminal` needed no new code. The+ three deps are injected by `src/main` (`initContextLink(ptyManager, deps)`); the Server Edition+ passes none and keeps its local-only behavior.+4. **A missing link in the hook path**: the remote branch of the raw hook listener never called+ `setNodeTranscript`, so a remote node had no known transcript at all. It does now — with the+ path already jailed by `isSafeRemoteTranscriptPath`, so a forged POST cannot aim a link read at+ an arbitrary remote file.+5. **`resolveLinkTranscript` refuses the local locators for a remote node.** They search *this*+ machine's disk and would have returned some unrelated local session's file — the linked agent+ would have read a stranger's conversation with nothing to indicate it. For a remote node the+ hook-fed path is the only trustworthy source; without it there is simply nothing to read yet.++### Authorization++The link document is chosen by the **requester's own node id**, and `pickLinkNode` will only+return a node listed in it. So a caller holding the hook token still cannot read a node it was+never linked to, and cannot read *through* an edge it does not itself hold (the link map is+directional). The token remains the outer boundary, exactly as for status hooks. The one value+that reaches a remote command line — an opencode session id — is shell-quoted at that site.++`docs/`-worthy consequence: `src/server` never calls `initContextLink`, so context link is absent+on the Server Edition (it was before this change too). The route and the renderer are both in+`src/core`, so wiring it there is now just a call plus a decision about what "remote" means when+the server *is* the host.+## Testing`canvas-control-shim.test.ts` runs the **real shim** under `/bin/sh` against a **real** hook@@ -87,27 +130,10 @@ checks, and it is now the only canvas-control client. It covers the nasty-value(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.+`context-link.cli.test.ts` does the same for the context-link shim, carrying over the fixtures and+expectations of the suite that tested the retired Node CLI, so the rewrite answers for the+behavior it inherited. `context-link.handler.test.ts` drives the real handler: authorization,+the local/remote read split, and the locator guard.## Out of scopediff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex ac53aecee..d4d78ab6e 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -85,6 +85,11 @@ class HookServer {error?: string}>)| null = null+ // Context-link reads. Same shape as the control handler, but it answers with TEXT (a rendered+ // transcript / summary / terminal capture) rather than acting on the canvas.+ private contextLinkHandler:+ | ((req: { verb: string; nodeId: string; args: Record<string, string> }) => Promise<string>)+ | null = nullprivate endpointPath = ''endpointFilePath(): string {@@ -116,6 +121,10 @@ class HookServer {this.controlHandler = cb}+ setContextLinkHandler(cb: NonNullable<HookServer['contextLinkHandler']>): void {+ this.contextLinkHandler = cb+ }+async start(): Promise<void> {if (this.server) returnthis.token = randomUUID()@@ -157,6 +166,21 @@ class HookServer {res.end(JSON.stringify(result))return}+ if (reqUrl.pathname.startsWith('/context-link/')) {+ const verb = decodeURIComponent(reqUrl.pathname.replace(/^\/context-link\//, ''))+ const { nodeId, args } = parseControlBody(+ await readBody(req),+ String(req.headers['content-type'] ?? '')+ )+ // Always text: the caller is the sh shim, and the payload IS prose (a rendered+ // transcript). The handler owns the authorization — see context-link.ts.+ const text = this.contextLinkHandler+ ? await this.contextLinkHandler({ verb, nodeId, args })+ : 'Context link is unavailable in this session.'+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })+ res.end(`${text}\n`)+ return+ }const agentId = decodeURIComponent(reqUrl.pathname.replace(/^\/hook\//, ''))const form = parseForm(await readBody(req))const nodeId = form.nodeId ?? ''diff --git a/src/core/context-link-core.test.ts b/src/core/context-link-core.test.tsindex 4c3c99abc..c7bc516f1 100644--- a/src/core/context-link-core.test.ts+++ b/src/core/context-link-core.test.ts@@ -90,6 +90,29 @@ describe('resolveLinkTranscript', () => {codex: async (sid: string) => `/x/${sid}.jsonl`,gemini: async (sid: string) => `/g/${sid}.jsonl`}+ // A REMOTE node's transcript is on the host; these locators search THIS machine's disk. Without+ // the guard they resolve happily and the agent reads an unrelated local session's conversation+ // with no sign anything is wrong — so the guard must win even where a locator WOULD have answered.+ it('never consults the local locators for a remote node', async () => {+ const link = { id: 'n1', title: 'T', agentId: 'codex', sessionId: 's1' }+ const local = await resolveLinkTranscript(link, { hooked: () => '', locators })+ expect(local).toBe('/x/s1.jsonl') // proves the locator WOULD have answered+ const remote = await resolveLinkTranscript(link, {+ hooked: () => '',+ locators,+ isRemote: () => true+ })+ expect(remote).toBe('')+ })++ it("still prefers a remote node's hook-fed path (the only trustworthy source there)", async () => {+ const p = await resolveLinkTranscript(+ { id: 'n1', title: 'T', agentId: 'claude', sessionId: 's1' },+ { hooked: () => '/remote/jailed.jsonl', locators, isRemote: () => true }+ )+ expect(p).toBe('/remote/jailed.jsonl')+ })+it('claude prefers the hook-fed path', async () => {const p = await resolveLinkTranscript({ id: 'n1', title: 'T', agentId: 'claude', sessionId: 's1' },diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex 86566dd01..c71d313ef 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -19,11 +19,16 @@ export type TranscriptLocator = (sessionId: string, accountId?: string) => Promi* Resolve one link entry's transcript path. Claude (and legacy entries without an* agentId) prefer the hook-fed path; every agent falls back to its locator by* sessionId. Notes, unknown agents, and locator errors resolve to '' (fail open —- * the CLI prints a clear "no transcript yet" message).+ * the reader then prints a clear "no transcript yet" message).*/export async function resolveLinkTranscript(link: { id: string; title?: string; agentId?: string; sessionId?: string; accountId?: string; note?: string },- deps: { hooked: (id: string) => string; locators: Record<string, TranscriptLocator> }+ deps: {+ hooked: (id: string) => string+ locators: Record<string, TranscriptLocator>+ /** True for a node whose session runs on an SSH project's remote host. */+ isRemote?: (id: string) => boolean+ }): Promise<string> {if (link.note != null) return ''const agent = link.agentId ?? 'claude'@@ -31,6 +36,12 @@ export async function resolveLinkTranscript(const hooked = deps.hooked(link.id)if (hooked) return hooked}+ // A REMOTE node's transcript lives on the host. The locators search THIS machine's disk and+ // would happily return some unrelated local session's file — the linked agent would then read+ // a stranger's conversation with no sign anything was wrong. The hook-fed path (jailed where+ // the payload arrives) is the only trustworthy source for a remote node; without it there is+ // simply nothing to read yet.+ if (deps.isRemote?.(link.id)) return ''const locate = deps.locators[agent]if (!locate || !link.sessionId) return ''try {@@ -124,240 +135,111 @@ export function buildLinkDoc(}}-// The standalone CLI, written to disk by context-link.ts and run via Electron-as-Node.-// Self-contained (no deps) and uses no backticks / ${} so it can live in this template literal.-export const CLI_SCRIPT = `// nodeterm context-link CLI (auto-generated — do not edit).-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-import { fileURLToPath } from 'node:url'-import { execFileSync } from 'node:child_process'--var DIR = path.dirname(fileURLToPath(import.meta.url))-var NODE_ID = process.env.NODETERM_NODE_ID || ''--function out(s) { process.stdout.write(s + '\\n') }--function loadLinks() {- if (!NODE_ID) { out('Not a nodeterm session (NODETERM_NODE_ID unset) — nothing to read.'); process.exit(0) }- try {- var data = JSON.parse(fs.readFileSync(path.join(DIR, NODE_ID + '.json'), 'utf-8'))- return data && Array.isArray(data.links) ? data : { links: [] }- } catch (e) { return { links: [] } }-}--function pickNode(doc, want) {- var links = doc.links- if (!links.length) { out('No linked nodes. Draw a context-link edge from this node to another on the canvas.'); process.exit(0) }- if (want) {- var q = String(want).toLowerCase()- var m = links.find(function (n) { return String(n.id).toLowerCase() === q || String(n.title || '').toLowerCase() === q })- if (!m) { out('No linked node matches "' + want + '". Linked: ' + links.map(function (n) { return n.title }).join(', ')); process.exit(0) }- return m- }- if (links.length === 1) return links[0]- out('Several linked nodes — re-run with --node <id|title>:')- links.forEach(function (n) { out('- ' + n.title + (n.note != null ? ' (note)' : '') + ' (id: ' + n.id + ')') })- process.exit(0)-}--// ~/.claude/projects/<cwd with / and . -> ->/ newest .jsonl (fallback when path unknown).-function transcriptForCwd(cwd) {- if (!cwd) return ''- var d = path.join(os.homedir(), '.claude', 'projects', String(cwd).replace(/[/.]/g, '-'))- var newest = '', best = 0- try {- fs.readdirSync(d).forEach(function (e) {- if (!e.endsWith('.jsonl')) return- var p = path.join(d, e)- try { var st = fs.statSync(p); if (st.mtimeMs > best) { best = st.mtimeMs; newest = p } } catch (e2) {}- })- } catch (e) {}- return newest-}--function resolveTranscript(node) {- if (node.transcriptPath && fs.existsSync(node.transcriptPath)) return node.transcriptPath- if (node.agent && node.agent !== 'claude') return ''- return transcriptForCwd(node.cwd)-}--function textOf(content) {- if (typeof content === 'string') return content- if (Array.isArray(content)) return content.map(function (c) { return c && c.type === 'text' ? (c.text || '') : '' }).filter(Boolean).join('\\n')- return ''-}--// Flatten codex/gemini content: string, or array of parts carrying a .text field.-function flatText(c) {- if (typeof c === 'string') return c- if (Array.isArray(c)) return c.map(function (x) { return x && typeof x.text === 'string' ? x.text : '' }).filter(Boolean).join('\\n')- return ''-}+// The context-link CLI, as a POSIX sh script. It replaced a ~230-line Node CLI that was written+// to disk and run via Electron-as-Node: that CLI did its own transcript parsing, which meant it+// had to run where the transcripts are — impossible for an SSH project, where the transcripts are+// on the host and the interpreter it needed is on the desktop. The parsing now lives on the+// desktop (context-link-render.ts) behind the hook server's /context-link/ route, and this shim is+// the thin client that reaches it — over the reverse tunnel's unix socket for a remote node, over+// loopback for a local one. Same script either way; sh + curl only.+export const CONTEXT_SHIM_SCRIPT = `#!/bin/sh+# nodeterm context-link CLI (auto-generated — do not edit).++if [ -z "$NODETERM_NODE_ID" ]; then+ echo "Not a nodeterm session (NODETERM_NODE_ID unset) — nothing to read."+ exit 0+fi++# Live endpoint (sock/port/token); for an SSH project this names that project's reverse-tunnel+# socket, so the read is served by the desktop that owns the canvas.+if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then+ . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :+fi++nt_verb="list"+if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi++# Translate the flags into curl --data-urlencode pairs (curl does the escaping). The positional+# list is the accumulator: originals consumed from the front, translated pairs appended at the back.+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+ --node|-n)+ nt_k="node"+ [ "$nt_a" = "-n" ] && nt_k="n"+ 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"+ ;;+ *) ;;+ esac+done++nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-context.$$")+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/context-link/$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}/context-link/$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 is not reachable from this session — nothing to read." >&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"+echo "Could not read linked context (nodeterm unreachable)." >&2+exit 1+`-// codex rollout line ({type:'response_item', payload}) -> 0..n display strings.-function linesFromCodex(raw) {- var o- try { o = JSON.parse(raw) } catch (e) { return [] }- if (o.type !== 'response_item' || !o.payload) return []- var p = o.payload- var res = []- if (p.type === 'message') {- var role = p.role === 'user' ? 'user' : 'assistant'- var t = flatText(p.content)- if (t) res.push(role + ': ' + t)- } else if (p.type === 'function_call') {- var a = typeof p.arguments === 'string' ? p.arguments : JSON.stringify(p.arguments || '')- res.push(' $ ' + (p.name || 'tool') + ' ' + String(a).slice(0, 200))- } else if (p.type === 'function_call_output') {- var s = flatText(p.output).split('\\n').slice(0, 3).join(' ').slice(0, 500)- if (s) res.push(' = ' + s)- }- return res-}+/** The get-linked-context 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 buildContextLinkSkillBody(shimPath: string): string {+ return `---+name: get-linked-context+description: Read the conversation/transcript, a recent summary, or the terminal output of another agent node (Claude, Codex or Gemini) you are linked to on the nodeterm canvas. Use when you need to know what a connected node has been doing, hand off, or continue its work. Only meaningful inside a nodeterm session with a context-link edge. Also reads sticky notes linked to this node as context.+----// gemini chat file is event-sourced: replay $set/$push/bare-message lines, then flatten.-function linesFromGeminiFile(buf) {- var messages = []- buf.split('\\n').forEach(function (raw) {- var t = raw.trim()- if (!t) return- var o- try { o = JSON.parse(t) } catch (e) { return }- if (o.$set && typeof o.$set === 'object' && Array.isArray(o.$set.messages)) { messages = o.$set.messages; return }- if (o.$push && typeof o.$push === 'object') {- var m = o.$push.messages- if (Array.isArray(m)) messages = messages.concat(m)- else if (m && typeof m === 'object') messages.push(m)- return- }- if (o.content !== undefined && o.sessionId === undefined) messages.push(o)- })- var res = []- messages.forEach(function (m) {- var role = m.type === 'user' ? 'user' : (m.type === 'gemini' || m.type === 'model') ? 'assistant' : String(m.type || 'message')- var t = flatText(m.content)- if (t) res.push(role + ': ' + t)- })- return res-}+# Get linked context-// opencode >=1.18 stores sessions in SQLite — never parse its disk. The CLI exports a-// session as JSON: 'opencode export <sessionID>'. Shape read defensively: a messages array-// whose items carry role + parts[] (text / tool) or a plain content string.-function linesFromOpencodeExport(node) {- if (!node.sessionId) { out('"' + node.title + '" has no session id yet.'); return [] }- var raw- try {- raw = execFileSync('opencode', ['export', String(node.sessionId)], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] })- } catch (e) { out('Could not export "' + node.title + '" session (is opencode installed?).'); return [] }- var o- try { o = JSON.parse(raw) } catch (e) { out('Unreadable opencode export for "' + node.title + '".'); return [] }- var msgs = Array.isArray(o) ? o : (o && (o.messages || (o.data && o.data.messages))) || []- var res = []- msgs.forEach(function (m) {- if (!m) return- var role = (m.role || (m.info && m.info.role)) === 'user' ? 'user' : 'assistant'- var parts = m.parts || (Array.isArray(m.content) ? m.content : null)- if (typeof m.content === 'string' && m.content) { res.push(role + ': ' + m.content); return }- if (!Array.isArray(parts)) return- parts.forEach(function (c) {- if (!c) return- if (typeof c.text === 'string' && c.text && (c.type === 'text' || !c.type)) res.push(role + ': ' + c.text)- else if (c.type === 'tool' || c.type === 'tool_use' || c.tool) {- var name = c.tool || c.name || 'tool'- var input = c.state && c.state.input ? c.state.input : c.input- var a = input && (input.command || input.filePath || input.file_path || input.pattern || input.description)- res.push(' $ ' + name + (typeof a === 'string' ? ' ' + a.slice(0, 200) : ''))- }- })- })- if (!res.length) out('"' + node.title + '" export contained no readable messages.')- return res-}+On the nodeterm canvas, this Claude session may be connected to other agent nodes (Claude, Codex or Gemini) by a+context-link edge. When you are linked, you can READ the other node's context on demand by+running the local CLI shim below. Nothing is pushed to you automatically — pull what you need.-// Parse one transcript JSONL line into 0..n display strings.-function linesFrom(raw) {- var o- try { o = JSON.parse(raw) } catch (e) { return [] }- var content = o.message && o.message.content- var res = []- if (o.type === 'assistant' && Array.isArray(content)) {- content.forEach(function (c) {- if (c.type === 'text' && c.text) res.push('assistant: ' + c.text)- else if (c.type === 'tool_use') {- var a = c.input && (c.input.command || c.input.file_path || c.input.path || c.input.pattern || c.input.description || c.input.prompt)- res.push(' $ ' + (c.name || 'tool') + (typeof a === 'string' ? ' ' + a.slice(0, 200) : ''))- }- })- } else if (o.type === 'user' && Array.isArray(content)) {- content.forEach(function (c) {- if (c.type === 'text' && c.text) res.push('user: ' + c.text)- else if (c.type === 'tool_result') { var s = textOf(c.content).split('\\n').slice(0, 3).join(' ').slice(0, 500); if (s) res.push(' = ' + s) }- })- } else if (o.type === 'user' && typeof content === 'string') {- res.push('user: ' + content)- }- return res-}+Run the shim (absolute path):-function readTranscript(node) {- // opencode has no transcript file (SQLite) — export by session id before any path resolution.- if (node.agent === 'opencode') return linesFromOpencodeExport(node)- var p = resolveTranscript(node)- if (!p) { out('"' + node.title + '" has no conversation transcript yet.'); return [] }- var buf- try { buf = fs.readFileSync(p, 'utf-8') } catch (e) { out('Could not read "' + node.title + '" transcript.'); return [] }- if (node.agent === 'gemini') return linesFromGeminiFile(buf)- var parse = node.agent === 'codex' ? linesFromCodex : linesFrom- var lines = []- buf.split('\\n').forEach(function (raw) { if (raw.trim()) lines.push.apply(lines, parse(raw)) })- return lines-}+\`\`\`sh+sh "${shimPath}" <command> [--node <id|title>] [-n <N>]+\`\`\`-function readTerminal(doc, node) {- if (!doc.tmuxBin) { out('Terminal capture unavailable (tmux not found).'); return }- try {- var o = execFileSync(doc.tmuxBin, ['-L', doc.tmuxSocket, 'capture-pane', '-p', '-t', node.tmux, '-S', '-200'], { encoding: 'utf-8' })- out(o.replace(/\\s+$/, ''))- } catch (e) { out('"' + node.title + '" terminal session is not running.') }-}+Commands:+- \`list\` — list the nodes you are linked to (start here).+- \`summary [--node X] [-n 15]\` — the last N lines of a linked node's conversation.+- \`transcript [--node X]\` — the linked node's full conversation transcript.+- \`terminal [--node X]\` — the linked node's recent terminal output (visible buffer).-var argv = process.argv.slice(2)-var cmd = argv[0] || 'list'-function flag(name) { var i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined }+Linked sticky notes appear in \`list\` marked \`(note)\`; \`summary\` or \`transcript\` on a note+prints its **current** text (the note is read live from the canvas, so it may have changed+since it was first linked).-var doc = loadLinks()-if (cmd === 'list') {- if (!doc.links.length) { out('No linked nodes.'); process.exit(0) }- out('Linked nodes:')- doc.links.forEach(function (n) { out('- ' + n.title + (n.note != null ? ' (note)' : '') + ' (id: ' + n.id + ')') })- process.exit(0)-}-var node = pickNode(doc, flag('--node'))-// Sticky notes carry their text in the link file — every command just prints it.-if (node.note != null) {- if (cmd === 'terminal') {- out('"' + node.title + '" is a sticky note — it has no terminal.')- } else {- out('=== ' + node.title + ' — note ===')- out(node.note || '(empty note)')- }- process.exit(0)-}-if (cmd === 'summary') {- var n = parseInt(flag('-n') || '15', 10) || 15- var ls = readTranscript(node)- out('=== ' + node.title + ' — last ' + n + ' lines ===')- ls.slice(-n).forEach(out)-} else if (cmd === 'transcript') {- var all = readTranscript(node)- out('=== ' + node.title + ' — full transcript (' + all.length + ' lines) ===')- all.forEach(out)-} else if (cmd === 'terminal') {- out('=== ' + node.title + ' — terminal ===')- readTerminal(doc, node)-} else {- out('Unknown command. Use: list | summary [--node X] [-n N] | transcript [--node X] | terminal [--node X]')-}+\`--node\` is optional when you are linked to exactly one node; otherwise pass the id or title+from \`list\`. If the CLI says "Not a nodeterm session" or "No linked nodes", there is nothing+to read — do not retry.`+}diff --git a/src/core/context-link-render.ts b/src/core/context-link-render.tsnew file mode 100644index 000000000..81d8c9203--- /dev/null+++ b/src/core/context-link-render.ts@@ -0,0 +1,328 @@+// Pure rendering for the context-link feature: transcript parsers for every agent format, node+// selection, and the text each command prints. No fs / child_process / electron — every byte the+// renderer needs is handed in, so the same code serves a LOCAL node (read from this machine's+// disk) and a REMOTE one in an SSH project (read over the project's ControlMaster).+//+// This used to live inside `CLI_SCRIPT` — a ~230-line JavaScript program embedded in a template+// literal, shipped to disk and run via Electron-as-Node. That shape made it untestable and, more+// to the point, unusable in SSH projects: the CLI had to run where the transcripts are, and the+// interpreter it needed exists only on the desktop. Moving the parsing here inverts it — the+// remote side becomes a thin sh+curl client and the desktop does the reading and the parsing.+import type { LinkDoc, LinkDocEntry } from './context-link-core'++export type ContextLinkVerb = 'list' | 'summary' | 'transcript' | 'terminal'++export const CONTEXT_LINK_VERBS: ContextLinkVerb[] = ['list', 'summary', 'transcript', 'terminal']++const SUMMARY_DEFAULT_LINES = 15+const TOOL_ARG_MAX = 200+const TOOL_RESULT_MAX = 500++/** Claude tool_result content: a string, or content parts carrying `.text`. */+function textOf(content: unknown): string {+ if (typeof content === 'string') return content+ if (Array.isArray(content)) {+ return content+ .map((c) => {+ const part = c as { type?: string; text?: string }+ return part && part.type === 'text' ? part.text ?? '' : ''+ })+ .filter(Boolean)+ .join('\n')+ }+ return ''+}++/** codex/gemini content: a string, or an array of parts each carrying a `.text` field. */+function flatText(content: unknown): string {+ if (typeof content === 'string') return content+ if (Array.isArray(content)) {+ return content+ .map((x) => {+ const part = x as { text?: string }+ return part && typeof part.text === 'string' ? part.text : ''+ })+ .filter(Boolean)+ .join('\n')+ }+ return ''+}++function toolArg(input: unknown): string {+ const i = input as Record<string, unknown> | undefined+ if (!i) return ''+ const a = i.command ?? i.file_path ?? i.path ?? i.pattern ?? i.description ?? i.prompt+ return typeof a === 'string' ? ` ${a.slice(0, TOOL_ARG_MAX)}` : ''+}++function parseJson(raw: string): unknown {+ try {+ return JSON.parse(raw)+ } catch {+ return undefined+ }+}++/** One claude transcript JSONL line -> 0..n display strings. */+export function linesFromClaude(raw: string): string[] {+ const o = parseJson(raw) as { type?: string; message?: { content?: unknown } } | undefined+ if (!o) return []+ const content = o.message?.content+ const res: string[] = []+ if (o.type === 'assistant' && Array.isArray(content)) {+ for (const c of content as { type?: string; text?: string; name?: string; input?: unknown }[]) {+ if (c.type === 'text' && c.text) res.push(`assistant: ${c.text}`)+ else if (c.type === 'tool_use') res.push(` $ ${c.name || 'tool'}${toolArg(c.input)}`)+ }+ } else if (o.type === 'user' && Array.isArray(content)) {+ for (const c of content as { type?: string; text?: string; content?: unknown }[]) {+ if (c.type === 'text' && c.text) res.push(`user: ${c.text}`)+ else if (c.type === 'tool_result') {+ const s = textOf(c.content).split('\n').slice(0, 3).join(' ').slice(0, TOOL_RESULT_MAX)+ if (s) res.push(` = ${s}`)+ }+ }+ } else if (o.type === 'user' && typeof content === 'string') {+ res.push(`user: ${content}`)+ }+ return res+}++/** One codex rollout line ({type:'response_item', payload}) -> 0..n display strings. */+export function linesFromCodex(raw: string): string[] {+ const o = parseJson(raw) as { type?: string; payload?: Record<string, unknown> } | undefined+ if (!o || o.type !== 'response_item' || !o.payload) return []+ const p = o.payload as {+ type?: string+ role?: string+ content?: unknown+ name?: string+ arguments?: unknown+ output?: unknown+ }+ const res: string[] = []+ if (p.type === 'message') {+ const role = p.role === 'user' ? 'user' : 'assistant'+ const t = flatText(p.content)+ if (t) res.push(`${role}: ${t}`)+ } else if (p.type === 'function_call') {+ const a = typeof p.arguments === 'string' ? p.arguments : JSON.stringify(p.arguments ?? '')+ res.push(` $ ${p.name || 'tool'} ${String(a).slice(0, TOOL_ARG_MAX)}`)+ } else if (p.type === 'function_call_output') {+ const s = flatText(p.output).split('\n').slice(0, 3).join(' ').slice(0, TOOL_RESULT_MAX)+ if (s) res.push(` = ${s}`)+ }+ return res+}++/** The whole gemini chat file: event-sourced ($set / $push / bare message), replayed then flattened. */+export function linesFromGemini(buf: string): string[] {+ type Msg = { type?: string; content?: unknown }+ let messages: Msg[] = []+ for (const raw of buf.split('\n')) {+ const t = raw.trim()+ if (!t) continue+ const o = parseJson(t) as+ | { $set?: { messages?: Msg[] }; $push?: { messages?: Msg | Msg[] }; content?: unknown; sessionId?: string }+ | undefined+ if (!o) continue+ if (o.$set && Array.isArray(o.$set.messages)) {+ messages = o.$set.messages+ continue+ }+ if (o.$push && typeof o.$push === 'object') {+ const m = o.$push.messages+ if (Array.isArray(m)) messages = messages.concat(m)+ else if (m && typeof m === 'object') messages.push(m)+ continue+ }+ if (o.content !== undefined && o.sessionId === undefined) messages.push(o as Msg)+ }+ const res: string[] = []+ for (const m of messages) {+ const role =+ m.type === 'user' ? 'user' : m.type === 'gemini' || m.type === 'model' ? 'assistant' : String(m.type || 'message')+ const t = flatText(m.content)+ if (t) res.push(`${role}: ${t}`)+ }+ return res+}++/**+ * An `opencode export <sessionID>` JSON document -> display strings. opencode >= 1.18 keeps+ * sessions in SQLite, so its disk is never parsed; the export is the contract. Shapes are read+ * defensively: a messages array whose items carry role + parts[] (text / tool) or a plain string.+ */+export function linesFromOpencodeExport(raw: string): string[] | null {+ const o = parseJson(raw) as+ | { messages?: unknown[]; data?: { messages?: unknown[] } }+ | unknown[]+ | undefined+ if (o === undefined) return null+ const msgs: unknown[] = Array.isArray(o) ? o : o?.messages ?? o?.data?.messages ?? []+ const res: string[] = []+ for (const raw of msgs) {+ const m = raw as {+ role?: string+ info?: { role?: string }+ parts?: unknown[]+ content?: unknown+ }+ if (!m) continue+ const role = (m.role ?? m.info?.role) === 'user' ? 'user' : 'assistant'+ if (typeof m.content === 'string' && m.content) {+ res.push(`${role}: ${m.content}`)+ continue+ }+ const parts = m.parts ?? (Array.isArray(m.content) ? (m.content as unknown[]) : null)+ if (!Array.isArray(parts)) continue+ for (const p of parts) {+ const c = p as {+ type?: string+ text?: string+ tool?: string+ name?: string+ input?: Record<string, unknown>+ state?: { input?: Record<string, unknown> }+ }+ if (!c) continue+ if (typeof c.text === 'string' && c.text && (c.type === 'text' || !c.type)) {+ res.push(`${role}: ${c.text}`)+ } else if (c.type === 'tool' || c.type === 'tool_use' || c.tool) {+ const name = c.tool || c.name || 'tool'+ const input = c.state?.input ?? c.input+ const a = input && (input.command ?? input.filePath ?? input.file_path ?? input.pattern ?? input.description)+ res.push(` $ ${name}${typeof a === 'string' ? ` ${a.slice(0, TOOL_ARG_MAX)}` : ''}`)+ }+ }+ }+ return res+}++/** Parse a whole transcript buffer with the parser its agent's format needs. */+export function renderTranscriptLines(agent: string | undefined, buf: string): string[] {+ if (agent === 'gemini') return linesFromGemini(buf)+ const parse = agent === 'codex' ? linesFromCodex : linesFromClaude+ const lines: string[] = []+ for (const raw of buf.split('\n')) {+ if (raw.trim()) lines.push(...parse(raw))+ }+ return lines+}++/**+ * Resolve which linked node a command targets. This is also the AUTHORIZATION boundary: a+ * request may only ever name a node inside the requester's own link document, so a caller+ * holding the hook token still cannot read a node it was never linked to.+ */+export function pickLinkNode(doc: LinkDoc, want?: string): { node: LinkDocEntry } | { message: string } {+ const links = doc.links+ if (!links.length) {+ return { message: 'No linked nodes. Draw a context-link edge from this node to another on the canvas.' }+ }+ if (want) {+ const q = want.toLowerCase()+ const m = links.find((n) => n.id.toLowerCase() === q || (n.title || '').toLowerCase() === q)+ if (!m) {+ return {+ message: `No linked node matches "${want}". Linked: ${links.map((n) => n.title).join(', ')}`+ }+ }+ return { node: m }+ }+ if (links.length === 1) return { node: links[0] }+ return {+ message: [+ 'Several linked nodes — re-run with --node <id|title>:',+ ...links.map((n) => `- ${n.title}${n.note != null ? ' (note)' : ''} (id: ${n.id})`)+ ].join('\n')+ }+}++export function renderList(doc: LinkDoc): string {+ if (!doc.links.length) return 'No linked nodes.'+ return [+ 'Linked nodes:',+ ...doc.links.map((n) => `- ${n.title}${n.note != null ? ' (note)' : ''} (id: ${n.id})`)+ ].join('\n')+}++/** A sticky note carries its text in the link doc — every command just prints it. */+export function renderNote(node: LinkDocEntry, verb: ContextLinkVerb): string {+ if (verb === 'terminal') return `"${node.title}" is a sticky note — it has no terminal.`+ return `=== ${node.title} — note ===\n${node.note || '(empty note)'}`+}++export function renderSummary(node: LinkDocEntry, lines: string[], n: number): string {+ return [`=== ${node.title} — last ${n} lines ===`, ...lines.slice(-n)].join('\n')+}++export function renderFullTranscript(node: LinkDocEntry, lines: string[]): string {+ return [`=== ${node.title} — full transcript (${lines.length} lines) ===`, ...lines].join('\n')+}++export function renderTerminal(node: LinkDocEntry, capture: string): string {+ const body = capture.replace(/\s+$/, '')+ return [+ `=== ${node.title} — terminal ===`,+ body || `"${node.title}" terminal session is not running.`+ ].join('\n')+}++export function parseSummaryCount(raw: string | undefined): number {+ const n = parseInt(raw || '', 10)+ return Number.isFinite(n) && n > 0 ? n : SUMMARY_DEFAULT_LINES+}++/** Everything the renderer needs fetched from the outside (local fs or over ssh). */+export interface ContextLinkFetch {+ /** The linked node's raw transcript bytes, or null when there is none / it is unreadable. */+ transcript: (node: LinkDocEntry) => Promise<string | null>+ /** The linked node's recent terminal output ('' when the session is not running). */+ terminal: (node: LinkDocEntry) => Promise<string>+ /** `opencode export <sessionId>` output, or null when it could not be produced. */+ opencodeExport: (node: LinkDocEntry) => Promise<string | null>+}++/**+ * Render one context-link command. Pure apart from the injected fetchers, which is what lets a+ * remote node's transcript be read over ssh without this file knowing ssh exists.+ */+export async function renderContextLink(+ doc: LinkDoc,+ verb: ContextLinkVerb,+ args: { node?: string; n?: string },+ fetch: ContextLinkFetch+): Promise<string> {+ if (verb === 'list') return renderList(doc)++ const picked = pickLinkNode(doc, args.node)+ if ('message' in picked) return picked.message+ const node = picked.node++ if (node.note != null) return renderNote(node, verb)++ if (verb === 'terminal') return renderTerminal(node, await fetch.terminal(node))++ const lines = await transcriptLinesFor(node, fetch)+ if (typeof lines === 'string') return lines // an explanatory message, not content+ return verb === 'summary'+ ? renderSummary(node, lines, parseSummaryCount(args.n))+ : renderFullTranscript(node, lines)+}++/** Transcript lines for a node, or a human-readable reason there are none. */+async function transcriptLinesFor(node: LinkDocEntry, fetch: ContextLinkFetch): Promise<string[] | string> {+ if (node.agent === 'opencode') {+ if (!node.sessionId) return `"${node.title}" has no session id yet.`+ const raw = await fetch.opencodeExport(node)+ if (raw == null) return `Could not export "${node.title}" session (is opencode installed?).`+ const lines = linesFromOpencodeExport(raw)+ if (lines == null) return `Unreadable opencode export for "${node.title}".`+ if (!lines.length) return `"${node.title}" export contained no readable messages.`+ return lines+ }+ const buf = await fetch.transcript(node)+ if (buf == null) return `"${node.title}" has no conversation transcript yet.`+ return renderTranscriptLines(node.agent, buf)+}diff --git a/src/core/context-link.cli.test.ts b/src/core/context-link.cli.test.tsindex 0927daee4..2516dd432 100644--- a/src/core/context-link.cli.test.ts+++ b/src/core/context-link.cli.test.ts@@ -1,36 +1,41 @@+// The context-link read path, end to end: the REAL POSIX-sh shim, run by the real /bin/sh,+// against the real hook server and the real renderer. This replaces an identical suite that+// exercised the retired Node CLI — same fixtures and same expectations, so the rewrite answers+// for the behavior it inherited, plus the remote (SSH) case the old shape could not express.import { describe, it, expect, beforeAll, afterAll } from 'vitest'-import { execFileSync } from 'node:child_process'+import { execFile } from 'node:child_process'import { mkdtempSync, writeFileSync, rmSync, chmodSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { CLI_SCRIPT } from './context-link-core'+import { promisify } from 'node:util'+import { CONTEXT_SHIM_SCRIPT, type LinkDoc } from './context-link-core'+import { renderContextLink, type ContextLinkFetch, type ContextLinkVerb } from './context-link-render'+import { hookServer } from './agents/hook-server'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'-let dir: string-let binDir: string+const run = promisify(execFile)-beforeAll(() => {+let dir = ''+let shim = ''+let doc: LinkDoc++/** What the fetchers were asked for — how the remote-routing assertions see the difference. */+const asked: { transcripts: string[]; terminals: string[]; exports: string[] } = {+ transcripts: [],+ terminals: [],+ exports: []+}++beforeAll(async () => {dir = mkdtempSync(join(tmpdir(), 'ctxlink-'))- writeFileSync(join(dir, 'context-cli.mjs'), CLI_SCRIPT)- // A fake `opencode` on PATH: `opencode export <id>` prints a session-export JSON blob.- // opencode stores sessions in SQLite, so the CLI shells out to `opencode export` instead- // of reading a file — we stub that binary to return a fixture payload.- binDir = mkdtempSync(join(tmpdir(), 'ctxlink-bin-'))- const opencodeExport = JSON.stringify({- messages: [- { role: 'user', parts: [{ type: 'text', text: 'add rerank' }] },- {- role: 'assistant',- parts: [- { type: 'text', text: 'done, added rerank.ts' },- { type: 'tool', tool: 'bash', state: { input: { command: 'npm test' } } }- ]- }- ]- })- writeFileSync(join(binDir, 'export.json'), opencodeExport)- writeFileSync(join(binDir, 'opencode'), `#!/bin/sh\ncat "${join(binDir, 'export.json')}"\n`)- chmodSync(join(binDir, 'opencode'), 0o755)- const transcript = [+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ shim = join(dir, 'context.sh')+ writeFileSync(shim, CONTEXT_SHIM_SCRIPT, { mode: 0o755 })+ chmodSync(shim, 0o755)++ const claudeTranscript = [JSON.stringify({ type: 'user', message: { content: 'deploy the app' } }),JSON.stringify({type: 'assistant',@@ -42,7 +47,6 @@ beforeAll(() => {}})].join('\n')- writeFileSync(join(dir, 'b.jsonl'), transcript)const codexTranscript = [JSON.stringify({ type: 'session_meta', payload: { id: 'sess-x' } }),JSON.stringify({@@ -59,111 +63,192 @@ beforeAll(() => {}),JSON.stringify({ type: 'response_item', payload: { type: 'function_call_output', output: '2 passed' } })].join('\n')- writeFileSync(join(dir, 'codex.jsonl'), codexTranscript)const geminiTranscript = [JSON.stringify({ sessionId: 'g-sess', projectHash: 'abc' }),JSON.stringify({ $set: { messages: [{ type: 'user', content: 'hello gemini' }] } }),JSON.stringify({ $push: { messages: { type: 'gemini', content: 'hello back' } } })].join('\n')- writeFileSync(join(dir, 'gemini.jsonl'), geminiTranscript)- writeFileSync(- join(dir, 'node-A.json'),- JSON.stringify({- self: { id: 'node-A' },- links: [- { id: 'node-B', title: 'Builder', cwd: '', transcriptPath: join(dir, 'b.jsonl'), tmux: 'nt-node-B' },- { id: 'node-X', title: 'Coder', cwd: '', transcriptPath: join(dir, 'codex.jsonl'), tmux: 'nt-node-X', agent: 'codex' },- { id: 'node-G', title: 'Gem', cwd: '', transcriptPath: join(dir, 'gemini.jsonl'), tmux: 'nt-node-G', agent: 'gemini' },- { id: 'node-Y', title: 'ColdCoder', cwd: '/nowhere', transcriptPath: '', tmux: 'nt-node-Y', agent: 'codex' },- { id: 'node-O', title: 'OpenCoder', cwd: '', transcriptPath: '', tmux: 'nt-node-O', agent: 'opencode', sessionId: 'ses_abc' },- { id: 'node-O2', title: 'NoSession', cwd: '', transcriptPath: '', tmux: 'nt-node-O2', agent: 'opencode' },- { id: 'note-1', title: 'Deploy notes', cwd: '', transcriptPath: '', tmux: '', note: 'use the staging key' }- ],- tmuxBin: null,- tmuxSocket: 'node-terminal'- })- )+ const opencodeExport = JSON.stringify({+ messages: [+ { role: 'user', parts: [{ type: 'text', text: 'add rerank' }] },+ {+ role: 'assistant',+ parts: [+ { type: 'text', text: 'done, added rerank.ts' },+ { type: 'tool', tool: 'bash', state: { input: { command: 'npm test' } } }+ ]+ }+ ]+ })++ const bodies: Record<string, string> = {+ 'node-B': claudeTranscript,+ 'node-X': codexTranscript,+ 'node-G': geminiTranscript,+ // A REMOTE node: this fixture stands in for bytes fetched over the ControlMaster.+ 'node-R': claudeTranscript+ }++ doc = {+ self: { id: 'node-A' },+ links: [+ { id: 'node-B', title: 'Builder', cwd: '', transcriptPath: join(dir, 'b.jsonl'), tmux: 'nt-node-B' },+ { id: 'node-X', title: 'Coder', cwd: '', transcriptPath: join(dir, 'codex.jsonl'), tmux: 'nt-node-X', agent: 'codex' },+ { id: 'node-G', title: 'Gem', cwd: '', transcriptPath: join(dir, 'gemini.jsonl'), tmux: 'nt-node-G', agent: 'gemini' },+ { id: 'node-Y', title: 'ColdCoder', cwd: '/nowhere', transcriptPath: '', tmux: 'nt-node-Y', agent: 'codex' },+ { id: 'node-O', title: 'OpenCoder', cwd: '', transcriptPath: '', tmux: 'nt-node-O', agent: 'opencode', sessionId: 'ses_abc' },+ { id: 'node-O2', title: 'NoSession', cwd: '', transcriptPath: '', tmux: 'nt-node-O2', agent: 'opencode' },+ { id: 'node-R', title: 'RemoteBuilder', cwd: '', transcriptPath: '/home/u/.claude/projects/x/r.jsonl', tmux: 'nt-node-R' },+ { id: 'note-1', title: 'Deploy notes', cwd: '', transcriptPath: '', tmux: '', note: 'use the staging key' }+ ],+ tmuxBin: null,+ tmuxSocket: 'node-terminal'+ }++ // Fetchers standing in for the real ones (local fs / ssh / tmux): what is under test here is+ // the shim ⇄ route ⇄ renderer path, not the filesystem.+ const fetchers: ContextLinkFetch = {+ transcript: async (node) => {+ asked.transcripts.push(node.id)+ return bodies[node.id] ?? null+ },+ terminal: async (node) => {+ asked.terminals.push(node.id)+ return node.id === 'node-B' ? 'last build ok\n' : ''+ },+ opencodeExport: async (node) => {+ asked.exports.push(node.id)+ return node.id === 'node-O' ? opencodeExport : null+ }+ }++ await hookServer.start()+ hookServer.setContextLinkHandler(async (req) => {+ // Mirrors handleContextLinkRequest's authorization: the document is chosen by the REQUESTER's+ // id, never by anything in the request body.+ if (req.nodeId !== 'node-A') {+ return 'No linked nodes. Draw a context-link edge from this node to another on the canvas.'+ }+ return renderContextLink(doc, req.verb as ContextLinkVerb, req.args, fetchers)+ })})afterAll(() => {+ hookServer.stop()rmSync(dir, { recursive: true, force: true })- rmSync(binDir, { recursive: true, force: true })})-function run(nodeId: string, args: string[]): string {- return execFileSync(process.execPath, [join(dir, 'context-cli.mjs'), ...args], {- encoding: 'utf-8',- env: { ...process.env, NODETERM_NODE_ID: nodeId, PATH: `${binDir}:${process.env.PATH ?? ''}` }- })+async function shimRun(nodeId: string, args: string[]): Promise<string> {+ const { stdout } = await run('/bin/sh', [shim, ...args], {+ env: {+ PATH: process.env.PATH ?? '',+ NODETERM_NODE_ID: nodeId,+ NODETERM_HOOK_PORT: String(hookServer.getPort()),+ NODETERM_HOOK_TOKEN: hookServer.getToken()+ },+ maxBuffer: 10 * 1024 * 1024+ })+ return stdout}-describe('context-cli', () => {- it('list shows the linked node', () => {- const out = run('node-A', ['list'])+describe('context-link CLI', () => {+ it('list shows the linked node', async () => {+ const out = await shimRun('node-A', ['list'])expect(out).toContain('Builder')expect(out).toContain('node-B')})- it('summary prints recent conversation lines', () => {- const out = run('node-A', ['summary', '-n', '10', '--node', 'node-B'])+ it('summary prints recent conversation lines', async () => {+ const out = await shimRun('node-A', ['summary', '-n', '10', '--node', 'node-B'])expect(out).toContain('deploy the app')expect(out).toContain('On it.')expect(out).toContain('npm run build')})- it('transcript prints the full conversation', () => {- const out = run('node-A', ['transcript', '--node', 'node-B'])+ it('transcript prints the full conversation', async () => {+ const out = await shimRun('node-A', ['transcript', '--node', 'node-B'])expect(out).toContain('full transcript')expect(out).toContain('deploy the app')})- it('terminal mode reports when tmux is unavailable', () => {- const out = run('node-A', ['terminal', '--node', 'node-B'])- expect(out).toContain('Terminal capture unavailable')+ it('terminal prints the captured pane', async () => {+ const out = await shimRun('node-A', ['terminal', '--node', 'node-B'])+ expect(out).toContain('Builder — terminal')+ expect(out).toContain('last build ok')})- it('is a no-op without NODETERM_NODE_ID', () => {- const out = run('', ['list'])+ it('terminal reports a session that is not running', async () => {+ const out = await shimRun('node-A', ['terminal', '--node', 'node-X'])+ expect(out).toContain('not running')+ })+ it('is a no-op without NODETERM_NODE_ID', async () => {+ const out = await shimRun('', ['list'])expect(out).toContain('Not a nodeterm session')})- it('list marks sticky notes', () => {- const out = run('node-A', ['list'])+ it('list marks sticky notes', async () => {+ const out = await shimRun('node-A', ['list'])expect(out).toContain('Deploy notes (note)')})- it('summary of a note prints its text', () => {- const out = run('node-A', ['summary', '--node', 'note-1'])+ it('summary of a note prints its text', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'note-1'])expect(out).toContain('Deploy notes — note')expect(out).toContain('use the staging key')})- it('transcript of a note prints its text too', () => {- const out = run('node-A', ['transcript', '--node', 'Deploy notes'])+ it('transcript of a note prints its text too', async () => {+ const out = await shimRun('node-A', ['transcript', '--node', 'Deploy notes'])expect(out).toContain('use the staging key')})- it('terminal of a note explains there is no terminal', () => {- const out = run('node-A', ['terminal', '--node', 'note-1'])+ it('terminal of a note explains there is no terminal', async () => {+ const out = await shimRun('node-A', ['terminal', '--node', 'note-1'])expect(out).toContain('sticky note')expect(out).toContain('no terminal')})- it('renders a codex rollout transcript', () => {- const out = run('node-A', ['summary', '-n', '20', '--node', 'node-X'])+ it('renders a codex rollout transcript', async () => {+ const out = await shimRun('node-A', ['summary', '-n', '20', '--node', 'node-X'])expect(out).toContain('user: fix the tests')expect(out).toContain('assistant: Sure, running them.')expect(out).toContain('$ shell')expect(out).toContain('= 2 passed')})- it('renders a gemini chat transcript (event-sourced replay)', () => {- const out = run('node-A', ['transcript', '--node', 'node-G'])+ it('renders a gemini chat transcript (event-sourced replay)', async () => {+ const out = await shimRun('node-A', ['transcript', '--node', 'node-G'])expect(out).toContain('user: hello gemini')expect(out).toContain('assistant: hello back')})- it('non-claude agent without a resolved path gets no cwd fallback', () => {- const out = run('node-A', ['summary', '--node', 'node-Y'])+ it('non-claude agent without a resolved path gets no cwd fallback', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'node-Y'])expect(out).toContain('no conversation transcript yet')})- it('renders an opencode transcript via `opencode export`', () => {- const out = run('node-A', ['transcript', '--node', 'node-O'])+ it('renders an opencode transcript via the export', async () => {+ const out = await shimRun('node-A', ['transcript', '--node', 'node-O'])expect(out).toContain('user: add rerank')expect(out).toContain('assistant: done, added rerank.ts')expect(out).toContain('$ bash npm test')})- it('opencode without a session id reports friendly, does not throw', () => {- const out = run('node-A', ['summary', '--node', 'node-O2'])+ it('opencode without a session id reports friendly, does not throw', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'node-O2'])expect(out).toContain('has no session id yet')})++ // The whole point of Phase 2: the transcript is on another machine, and the desktop serves the+ // read over the project's ControlMaster. The command an agent types is unchanged.+ it('reads a REMOTE node through the same command', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'node-R'])+ expect(out).toContain('deploy the app')+ expect(asked.transcripts).toContain('node-R')+ })++ it('matches a node by title, case-insensitively', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'builder'])+ expect(out).toContain('deploy the app')+ })++ it('lists what IS linked when the target is unknown', async () => {+ const out = await shimRun('node-A', ['summary', '--node', 'nope'])+ expect(out).toContain('No linked node matches')+ expect(out).toContain('Builder')+ })++ // Authorization: a caller holding the hook token still only ever gets ITS OWN document.+ it('gives an unlinked node nothing, whatever it asks for', async () => {+ const out = await shimRun('node-Z', ['transcript', '--node', 'node-B'])+ expect(out).toContain('No linked nodes')+ expect(out).not.toContain('deploy the app')+ })})diff --git a/src/core/context-link.handler.test.ts b/src/core/context-link.handler.test.tsnew file mode 100644index 000000000..3eaed956c--- /dev/null+++ b/src/core/context-link.handler.test.ts@@ -0,0 +1,177 @@+// The REAL request handler — link-map ingest, authorization, and the local/remote read split.+// The cli test drives the shim against a stand-in handler; this one drives the actual code that+// decides WHICH bytes a request may see, which is the part with teeth.+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { handleContextLinkRequest, initContextLink, type ContextLinkDeps } from './context-link'+import { setNodeTranscript } from './context-link-core'+import { IPC } from '../shared/ipc'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import type { ContextLinkMap } from '../shared/types'+import type { PtyManager } from './pty-manager'++const dir = mkdtempSync(join(tmpdir(), 'ctxlink-h-'))+let plat: FakePlatform+let captured: string[] = []++/** Enough PtyManager for context-link: the tmux binary it stamps into the doc, and the capture+ * call that is already remote-aware in the real thing. */+function fakePty(): PtyManager {+ return {+ getTmuxBin: () => '/usr/bin/tmux',+ captureSession: async (key: string) => {+ captured.push(key)+ return `pane of ${key}`+ }+ } as unknown as PtyManager+}++async function setLinks(map: ContextLinkMap): Promise<void> {+ await plat.handlers[IPC.contextLinkSetLinks](map)+}++function start(deps: ContextLinkDeps = {}): void {+ resetPlatformForTests()+ plat = fakePlatform({ userDataDir: dir })+ initPlatform(plat)+ captured = []+ initContextLink(fakePty(), deps)+}++beforeEach(() => start())++afterAll(() => rmSync(dir, { recursive: true, force: true }))++const CLAUDE_LINE = JSON.stringify({ type: 'user', message: { content: 'ship it' } })++describe('handleContextLinkRequest — authorization', () => {+ it('serves only the requester\'s own document', async () => {+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder' }] })+ const mine = await handleContextLinkRequest({ verb: 'list', nodeId: 'node-A', args: {} })+ expect(mine).toContain('Builder')+ // node-B was LINKED FROM node-A but has no document of its own: the link map is directional,+ // and a node may not read through an edge it does not itself hold.+ const theirs = await handleContextLinkRequest({ verb: 'list', nodeId: 'node-B', args: {} })+ expect(theirs).toContain('No linked nodes')+ })++ it('refuses a target that is not in the requester\'s links, even by exact id', async () => {+ await setLinks({+ 'node-A': [{ id: 'node-B', title: 'Builder' }],+ 'node-C': [{ id: 'node-SECRET', title: 'Secret' }]+ })+ const out = await handleContextLinkRequest({+ verb: 'transcript',+ nodeId: 'node-A',+ args: { node: 'node-SECRET' }+ })+ expect(out).toContain('No linked node matches')+ expect(out).not.toContain('Secret —')+ })++ it('answers an empty node id without touching anything', async () => {+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: '', args: {} })).toContain(+ 'Not a nodeterm session'+ )+ })++ it('rejects an unknown verb with the usage line', async () => {+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder' }] })+ const out = await handleContextLinkRequest({ verb: 'rm -rf', nodeId: 'node-A', args: {} })+ expect(out).toContain('Unknown command')+ })++ it('drops documents for links that were removed', async () => {+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder' }] })+ await setLinks({})+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-A', args: {} })).toContain(+ 'No linked nodes'+ )+ })+})++describe('handleContextLinkRequest — local reads', () => {+ it('reads a local transcript off this machine\'s disk', async () => {+ const p = join(dir, 'local.jsonl')+ writeFileSync(p, CLAUDE_LINE)+ setNodeTranscript('node-B', 'sess-1', p)+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder', agentId: 'claude' }] })+ const out = await handleContextLinkRequest({ verb: 'summary', nodeId: 'node-A', args: {} })+ expect(out).toContain('user: ship it')+ })++ it('captures the terminal through the pty manager', async () => {+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder' }] })+ const out = await handleContextLinkRequest({ verb: 'terminal', nodeId: 'node-A', args: {} })+ expect(out).toContain('pane of node-B')+ expect(captured).toEqual(['node-B'])+ })+})++describe('handleContextLinkRequest — remote (SSH) reads', () => {+ const remoteDeps = (over: Partial<ContextLinkDeps> = {}): ContextLinkDeps => ({+ isRemoteNode: (id) => id === 'node-R',+ readRemoteFile: async () => CLAUDE_LINE,+ runRemoteCommand: async () => null,+ ...over+ })++ it('routes a remote node\'s transcript over the injected remote reader', async () => {+ const readRemoteFile = vi.fn(async () => CLAUDE_LINE)+ start(remoteDeps({ readRemoteFile }))+ setNodeTranscript('node-R', 'sess-r', '/home/u/.claude/projects/x/r.jsonl')+ await setLinks({ 'node-A': [{ id: 'node-R', title: 'Remote', agentId: 'claude' }] })+ const out = await handleContextLinkRequest({ verb: 'summary', nodeId: 'node-A', args: {} })+ expect(out).toContain('user: ship it')+ expect(readRemoteFile).toHaveBeenCalledWith('node-R', '/home/u/.claude/projects/x/r.jsonl', expect.any(Number))+ })++ it('never asks the LOCAL locators for a remote node\'s transcript', async () => {+ // The locators search this machine's disk. For a remote node they would return some unrelated+ // local session's file and the agent would read a stranger's conversation, silently.+ const readRemoteFile = vi.fn(async () => CLAUDE_LINE)+ start(remoteDeps({ readRemoteFile }))+ // No hook-fed path for node-R: a codex node with a sessionId is exactly the shape the+ // locator fallback would have resolved locally.+ await setLinks({ 'node-A': [{ id: 'node-R', title: 'Remote', agentId: 'codex', sessionId: 'sess-x' }] })+ const out = await handleContextLinkRequest({ verb: 'summary', nodeId: 'node-A', args: {} })+ expect(out).toContain('no conversation transcript yet')+ expect(readRemoteFile).not.toHaveBeenCalled()+ })++ it('reports a failed remote read as "no transcript yet" rather than an error', async () => {+ start(remoteDeps({ readRemoteFile: async () => null }))+ setNodeTranscript('node-R', 'sess-r', '/home/u/.claude/projects/x/r.jsonl')+ await setLinks({ 'node-A': [{ id: 'node-R', title: 'Remote', agentId: 'claude' }] })+ const out = await handleContextLinkRequest({ verb: 'summary', nodeId: 'node-A', args: {} })+ expect(out).toContain('no conversation transcript yet')+ })++ it('shell-quotes the session id it sends to a remote opencode export', async () => {+ const sent: string[] = []+ const runRemoteCommand = async (_nodeId: string, command: string): Promise<string> => {+ sent.push(command)+ return '{"messages":[]}'+ }+ start(remoteDeps({ runRemoteCommand }))+ await setLinks({+ 'node-A': [{ id: 'node-R', title: 'Remote', agentId: 'opencode', sessionId: "x'; rm -rf ~ #" }]+ })+ await handleContextLinkRequest({ verb: 'transcript', nodeId: 'node-A', args: {} })+ expect(sent[0]).toBe(`opencode export 'x'\\''; rm -rf ~ #'`)+ })++ it('falls back to local behavior when the shell injected no remote deps (Server Edition)', async () => {+ const p = join(dir, 'srv.jsonl')+ writeFileSync(p, CLAUDE_LINE)+ start() // no deps at all+ setNodeTranscript('node-B', 'sess-1', p)+ await setLinks({ 'node-A': [{ id: 'node-B', title: 'Builder', agentId: 'claude' }] })+ expect(await handleContextLinkRequest({ verb: 'summary', nodeId: 'node-A', args: {} })).toContain(+ 'user: ship it'+ )+ })+})diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex c5bc5b550..1b91793c4 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -1,12 +1,17 @@-// Context Link — lets two Claude nodes on the canvas read each other's context on demand.+// Context Link — lets two agent nodes on the canvas read each other's context on demand.//-// Connecting two Claude nodes means "these two may READ each other." No messages flow. The-// renderer pushes the current link map to main (context-link:set-links); main writes one-// enriched file per node to <userData>/context-links/<nodeId>.json (linked nodes' titles,-// transcript paths learned from hooks, cwds, tmux session names). A self-contained CLI-// (context-cli.mjs, run via Electron-as-Node through context.sh) reads that file and prints-// the linked node's transcript / summary / terminal output. A globally-installed Claude-// skill tells the agent how + when to call it.+// Connecting two agent nodes means "these two may READ each other." No messages flow. The+// renderer pushes the current link map to main (context-link:set-links); main builds one link+// document per node (linked nodes' titles, transcript paths learned from hooks, cwds, tmux+// session names) and answers reads over the hook server's /context-link/ route. A POSIX-sh shim+// (context.sh) is the client; a globally-installed Claude skill (plus instruction blocks for the+// agents that have no skill system) tells the agent how + when to call it.+//+// The reading and parsing happen HERE, on the desktop, not in the CLI. That is what lets an SSH+// project's remote agent use the feature at all: its transcripts live on the host, reachable over+// the project's ControlMaster (injected as `deps`), and its terminal is captured by a PtyManager+// that already knows the difference. The link documents are also still written to+// <userData>/context-links/ as a debugging aid.import fs from 'fs'import os from 'os'import path from 'path'@@ -16,13 +21,23 @@ import type { ContextLinkMap } from '../shared/types'import { type PtyManager } from './pty-manager'import { TMUX_SOCKET } from './tmux-naming'import {- CLI_SCRIPT,+ CONTEXT_SHIM_SCRIPT,+ buildContextLinkSkillBody,buildLinkDoc,buildLinkedContextInstructions,mergeInstructionsBlock,resolveLinkTranscript,- transcriptPathOf+ transcriptPathOf,+ type LinkDoc,+ type LinkDocEntry} from './context-link-core'+import {+ CONTEXT_LINK_VERBS,+ renderContextLink,+ type ContextLinkFetch,+ type ContextLinkVerb+} from './context-link-render'+import { hookServer } from './agents/hook-server'import { locateClaude, locateCodex, locateGemini } from './handoff/locate'import { opencodeConfigDir } from './agents/hooks/opencode'@@ -33,9 +48,6 @@ export function contextLinkDir(): string {if (!dir) dir = path.join(platform().userDataDir, 'context-links')return dir}-function cliScriptPath(): string {- return path.join(contextLinkDir(), 'context-cli.mjs')-}function cliShimPath(): string {return path.join(contextLinkDir(), 'context.sh')}@@ -46,54 +58,25 @@ function skillPath(): string {function writeCliFiles(): void {const d = contextLinkDir()fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(cliScriptPath(), CLI_SCRIPT)- const shim = `#!/bin/sh-# nodeterm context-link CLI shim (auto-generated — do not edit).-ELECTRON_RUN_AS_NODE=1 exec "${process.execPath}" "${cliScriptPath()}" "$@"-`- fs.writeFileSync(cliShimPath(), shim)+ fs.writeFileSync(cliShimPath(), CONTEXT_SHIM_SCRIPT)try {fs.chmodSync(cliShimPath(), 0o755)} catch {/* fail open */}+ // Sweep the retired Electron-as-Node CLI off upgraders' disks: the shim no longer execs it,+ // and it would sit there pointing at a binary path that moves with every app update.+ try {+ fs.rmSync(path.join(d, 'context-cli.mjs'), { force: true })+ } catch {+ /* fail open */+ }}function installSkill(): void {- const body = `----name: get-linked-context-description: Read the conversation/transcript, a recent summary, or the terminal output of another agent node (Claude, Codex or Gemini) you are linked to on the nodeterm canvas. Use when you need to know what a connected node has been doing, hand off, or continue its work. Only meaningful inside a nodeterm session with a context-link edge. Also reads sticky notes linked to this node as context.------# Get linked context--On the nodeterm canvas, this Claude session may be connected to other agent nodes (Claude, Codex or Gemini) by a-context-link edge. When you are linked, you can READ the other node's context on demand by-running the local CLI shim below. Nothing is pushed to you automatically — pull what you need.--Run the shim (absolute path):--\`\`\`sh-sh "${cliShimPath()}" <command> [--node <id|title>] [-n <N>]-\`\`\`--Commands:-- \`list\` — list the nodes you are linked to (start here).-- \`summary [--node X] [-n 15]\` — the last N lines of a linked node's conversation.-- \`transcript [--node X]\` — the linked node's full conversation transcript.-- \`terminal [--node X]\` — the linked node's recent terminal output (visible buffer).--Linked sticky notes appear in \`list\` marked \`(note)\`; \`summary\` or \`transcript\` on a note-prints its **current** text (the note is read live from the canvas, so it may have changed-since it was first linked).--\`--node\` is optional when you are linked to exactly one node; otherwise pass the id or title-from \`list\`. If the CLI says "Not a nodeterm session" or "No linked nodes", there is nothing-to read — do not retry.-`try {fs.mkdirSync(path.dirname(skillPath()), { recursive: true })- fs.writeFileSync(skillPath(), body, 'utf8')+ fs.writeFileSync(skillPath(), buildContextLinkSkillBody(cliShimPath()), 'utf8')} catch (e) {console.warn('[context-link] skill install failed', e)}@@ -125,9 +108,34 @@ function installAgentInstructions(): void {}let pty: PtyManager | undefined+let deps: ContextLinkDeps = {}++/**+ * The shell-specific reach the reads need. Everything here is about ONE question — is this node+ * on a remote host, and if so how do I reach it — which `src/core` must not answer for itself+ * (SshProjectManager and the ControlMaster wiring are desktop-only). The Server Edition passes+ * nothing and gets the local-only behavior it had before.+ */+export interface ContextLinkDeps {+ /** True when the node is a live session on an SSH project's remote host. */+ isRemoteNode?: (nodeId: string) => boolean+ /** Read (at most `maxBytes` of) a file on a remote node's host. null = unreadable. */+ readRemoteFile?: (nodeId: string, filePath: string, maxBytes: number) => Promise<string | null>+ /** Run one command on a remote node's host and return stdout. null = it failed. */+ runRemoteCommand?: (nodeId: string, command: string) => Promise<string | null>+}++// Remote transcripts are read from the END: a long-running session's file reaches tens of MB,+// and the whole thing would cross an ssh channel for a `summary` that shows 15 lines. A tail can+// start mid-line, which only costs that one line (it fails to parse and is dropped).+const REMOTE_TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024const LINK_LOCATORS = { claude: locateClaude, codex: locateCodex, gemini: locateGemini }+// The link documents, by node id — the same objects written to disk, kept in memory because they+// are what authorizes a read (a node may only ever name a link inside ITS OWN document).+const linkDocs = new Map<string, LinkDoc>()+// Write one enriched link file per node id present in the map. Removed links should not// linger, so we clear stale per-node files first. Async fs throughout — this runs on edge// changes and scales with node/link count, and sync I/O here sits on the main event loop.@@ -147,15 +155,24 @@ async function writeLinkFiles(map: ContextLinkMap): Promise<void> {for (const links of Object.values(map)) {for (const n of links) {if (n.note != null || resolved.has(n.id)) continue- resolved.set(n.id, await resolveLinkTranscript(n, { hooked: transcriptPathOf, locators: LINK_LOCATORS }))+ resolved.set(+ n.id,+ await resolveLinkTranscript(n, {+ hooked: transcriptPathOf,+ locators: LINK_LOCATORS,+ isRemote: deps.isRemoteNode+ })+ )}}+ linkDocs.clear()for (const [nodeId, links] of Object.entries(map)) {const doc = buildLinkDoc(nodeId, links, {transcriptOf: (id) => resolved.get(id) ?? '',tmuxBin: bin,tmuxSocket: TMUX_SOCKET})+ linkDocs.set(nodeId, doc)try {await fs.promises.writeFile(path.join(d, `${nodeId}.json`), JSON.stringify(doc, null, 2))} catch (e) {@@ -164,8 +181,89 @@ async function writeLinkFiles(map: ContextLinkMap): Promise<void> {}}-export function initContextLink(ptyManager: PtyManager): void {+/** Read a linked node's transcript bytes — from the remote host when it lives there, else from+ * this machine's disk. null when there is no path yet or it could not be read. */+async function fetchTranscript(node: LinkDocEntry): Promise<string | null> {+ if (!node.transcriptPath) return null+ if (deps.isRemoteNode?.(node.id)) {+ // The path was jailed at ingest (isSafeRemoteTranscriptPath, where the hook payload arrives),+ // so what reaches here is already confined to the host's transcript roots.+ return deps.readRemoteFile+ ? await deps.readRemoteFile(node.id, node.transcriptPath, REMOTE_TRANSCRIPT_MAX_BYTES)+ : null+ }+ try {+ return await fs.promises.readFile(node.transcriptPath, 'utf-8')+ } catch {+ return null+ }+}++async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {+ if (!node.sessionId) return null+ if (deps.isRemoteNode?.(node.id)) {+ return deps.runRemoteCommand+ ? await deps.runRemoteCommand(node.id, `opencode export ${shellQuote(node.sessionId)}`)+ : null+ }+ try {+ const { execFile } = await import('node:child_process')+ return await new Promise<string | null>((resolve) => {+ execFile('opencode', ['export', node.sessionId ?? ''], { encoding: 'utf-8' }, (err, stdout) =>+ resolve(err ? null : stdout)+ )+ })+ } catch {+ return null+ }+}++/** Single-quote for a POSIX shell. The session id reaches a remote command line, and it is+ * ultimately provider-supplied data — never interpolate it raw. */+function shellQuote(s: string): string {+ return `'${s.replace(/'/g, `'\\''`)}'`+}++const fetchers: ContextLinkFetch = {+ transcript: fetchTranscript,+ // captureSession already knows a remote node's tmux lives on the host, so this one call+ // covers both surfaces.+ terminal: async (node) => (pty ? await pty.captureSession(node.id) : ''),+ opencodeExport: fetchOpencodeExport+}++/**+ * Answer one /context-link/ request. AUTHORIZATION: the document is chosen by the REQUESTER's+ * node id and `pickLinkNode` (inside renderContextLink) will only ever return a node listed in+ * it — so a caller that holds the hook token still cannot read a node it was never linked to.+ * The token remains the outer boundary, exactly as it is for status hooks.+ */+export async function handleContextLinkRequest(req: {+ verb: string+ nodeId: string+ args: Record<string, string>+}): Promise<string> {+ if (!req.nodeId) return 'Not a nodeterm session — nothing to read.'+ if (!CONTEXT_LINK_VERBS.includes(req.verb as ContextLinkVerb)) {+ return 'Unknown command. Use: list | summary [--node X] [-n N] | transcript [--node X] | terminal [--node X]'+ }+ const doc = linkDocs.get(req.nodeId)+ if (!doc) {+ return 'No linked nodes. Draw a context-link edge from this node to another on the canvas.'+ }+ try {+ return await renderContextLink(doc, req.verb as ContextLinkVerb, req.args, fetchers)+ } catch (e) {+ console.warn('[context-link] read failed', e)+ return 'Could not read linked context.'+ }+}++export function initContextLink(ptyManager: PtyManager, platformDeps: ContextLinkDeps = {}): void {pty = ptyManager+ deps = platformDeps+ linkDocs.clear()+ hookServer.setContextLinkHandler(handleContextLinkRequest)try {const d = contextLinkDir()fs.mkdirSync(d, { recursive: true })diff --git a/src/main/index.ts b/src/main/index.tsindex 5b89bd671..1f4cd1d47 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1132,6 +1132,12 @@ app.whenReady().then(async () => {remoteTranscriptBySession.set(p.session_id, ref)}if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)+ // Context Link: remember the node's transcript path for remote nodes too. This branch used+ // to `return` without it, which is why a remote node was never readable through a link —+ // the local locators are no substitute (they search the wrong machine's disk, so+ // resolveLinkTranscript deliberately refuses them for remote nodes). The path stored is the+ // JAILED one, so a forged POST cannot aim a link read at an arbitrary remote file.+ if (nodeId && p.session_id && transcriptPath) setNodeTranscript(nodeId, p.session_id, transcriptPath)if (p.hook_event_name === 'SessionEnd' && p.session_id) {remoteContextTail.untrack(p.session_id)remoteTranscriptBySession.delete(p.session_id)@@ -1275,7 +1281,32 @@ app.whenReady().then(async () => {})initMediaProtocol()- initContextLink(ptyManager)+ // Context Link reads happen HERE, on the desktop, which is what lets a remote (SSH-project)+ // node's transcript be read at all: it lives on the host, behind the project's ControlMaster.+ // These three deps are the whole of what `src/core` cannot answer for itself. Fail-open+ // throughout — a failed remote read renders as "no transcript yet", never as an error.+ initContextLink(ptyManager, {+ isRemoteNode: (nodeId) => !!ptyManager.sshRemoteForNode(nodeId),+ readRemoteFile: async (nodeId, filePath, maxBytes) => {+ const rt = ptyManager.sshRemoteForNode(nodeId)+ if (!rt) return null+ const text = await remoteFile.readTail(+ { conn: rt.conn, controlPath: rt.controlPath, path: filePath },+ maxBytes+ )+ return text || null+ },+ runRemoteCommand: async (nodeId, command) => {+ const rt = ptyManager.sshRemoteForNode(nodeId)+ if (!rt || !sshProjectManager) return null+ try {+ const { code, stdout } = await sshProjectManager.sshRun(childArgs(rt.conn, rt.controlPath, command))+ return code === 0 ? stdout : null+ } catch {+ return null+ }+ }+ })initCanvasControl()// Usage service + the mobile `usage` mirror block (mobile-usage-inbox): poll all local managed// accounts alongside the system account, and re-flush the mirror on every cache update. Thediff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex 2a3e5be5b..89156d332 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -252,3 +252,59 @@ describe('RemoteHooks.installCanvasControl', () => {await expect(new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()})})++describe('RemoteHooks.installContextLink', () => {+ const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)++ it('writes an executable shim + the skill, and merges the instruction blocks', async () => {+ const { rh, calls } = mk()+ await rh.installContextLink(conn, '/s.sock', '/home/u')+ const joined = calls.map((c) => c.args.join(' '))+ expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/context.sh'") && j.includes('chmod 755'))).toBe(true)+ // The shim is the thin client: it POSTs and prints. All transcript parsing stays on the+ // desktop, which is what makes the host's missing `node` irrelevant.+ const shim = calls.find((c) => isWriteTo(c.args, '/home/u/.nodeterm/context.sh'))?.stdin ?? ''+ expect(shim).toContain('#!/bin/sh')+ expect(shim).toContain('/context-link/')+ expect(shim).toContain('--unix-socket')+ expect(shim).not.toContain('ELECTRON_RUN_AS_NODE')+ const skill = calls.find((c) => isWriteTo(c.args, '/home/u/.claude/skills/get-linked-context/SKILL.md'))?.stdin ?? ''+ expect(skill).toContain('name: get-linked-context')+ expect(skill).toContain('sh "/home/u/.nodeterm/context.sh"')+ expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:get-linked-context:start'))).toBe(true)+ expect(joined.some((j) => j.includes('~/'))).toBe(false)+ })++ it('leaves the canvas-control block in the same file alone', async () => {+ // Both features merge into ~/.codex/AGENTS.md under DIFFERENT markers. Installing one must+ // not evict the other, or every connect would leave the host with exactly one of the two.+ const existing =+ '<!-- nodeterm:manage-canvas:start -->\nCANVAS BLOCK\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 }).installContextLink(conn, '/s.sock', '/home/u')+ const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))+ expect(write?.stdin).toContain('CANVAS BLOCK')+ expect(write?.stdin).toContain('nodeterm:get-linked-context:start')+ })++ it('installs the skill into a remote managed-account config dir', async () => {+ const { rh, calls } = mk()+ await rh.installContextLinkSkillIntoAccountDir(conn, '/s.sock', '/home/u', 'acc-1')+ const target = '/home/u/.nodeterm/claude-accounts/acc-1/skills/get-linked-context/SKILL.md'+ expect(calls.some((c) => isWriteTo(c.args, target))).toBe(true)+ expect(calls.some((c) => isWriteTo(c.args, '/home/u/.nodeterm/context.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 }).installContextLink(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()+ })+})diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 96b233817..f2b45fa80 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -14,6 +14,12 @@ import {buildCanvasSkillBody,mergeCanvasControlBlock} from '../canvas-control-core'+import {+ CONTEXT_SHIM_SCRIPT,+ buildContextLinkSkillBody,+ buildLinkedContextInstructions,+ mergeInstructionsBlock+} from '../../core/context-link-core'import { posixQuote, type SshConnection } from '../../shared/ssh'/** POSIX dirname of an absolute remote path. `path.dirname` would apply the LOCAL separator@@ -202,8 +208,14 @@ export class RemoteHooks {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)+ await this.writeRemoteShim(conn, controlPath, shim, CONTROL_SHIM_SCRIPT)+ await this.writeRemoteSkill(+ conn,+ controlPath,+ `${remoteHome}/.claude`,+ 'manage-nodeterm-canvas',+ buildCanvasSkillBody(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).@@ -214,7 +226,7 @@ export class RemoteHooks {`"\${XDG_CONFIG_HOME:-${remoteHome}/.config}/opencode/AGENTS.md"`]for (const target of targets) {- await this.mergeRemoteInstructions(conn, controlPath, target, block)+ await this.mergeRemoteInstructions(conn, controlPath, target, block, mergeCanvasControlBlock)}} catch {/* fail-open: the remote agent simply runs without canvas control */@@ -235,48 +247,119 @@ export class RemoteHooks {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)+ await this.writeRemoteShim(conn, controlPath, shim, CONTROL_SHIM_SCRIPT)const accountDir = `${remoteHome}/.nodeterm/claude-accounts/${accountId}`- await this.installCanvasSkillAt(conn, controlPath, accountDir, shim)+ await this.writeRemoteSkill(+ conn,+ controlPath,+ accountDir,+ 'manage-nodeterm-canvas',+ buildCanvasSkillBody(shim)+ )+ } catch {+ /* fail-open */+ }+ }++ /**+ * Install the context-link CLI + its discovery docs on the REMOTE host, so a linked agent node+ * in an SSH project can read what its neighbours are doing.+ *+ * Same thin-client shape as canvas control, for a sharper reason: reading and parsing the+ * transcripts happens on the desktop (three formats, and the host may have no node at all), so+ * all the host needs is sh + curl aimed at the reverse tunnel. Gated by the caller on a+ * verified tunnel; fail-open per step.+ */+ async installContextLink(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {+ try {+ const shim = `${remoteHome}/.nodeterm/context.sh`+ await this.writeRemoteShim(conn, controlPath, shim, CONTEXT_SHIM_SCRIPT)+ await this.writeRemoteSkill(+ conn,+ controlPath,+ `${remoteHome}/.claude`,+ 'get-linked-context',+ buildContextLinkSkillBody(shim)+ )+ const block = buildLinkedContextInstructions(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, mergeInstructionsBlock)+ }+ } catch {+ /* fail-open: the remote agent simply runs without context link */+ }+ }++ /** The context-link skill for a REMOTE managed-account config dir (see the canvas twin). */+ async installContextLinkSkillIntoAccountDir(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ accountId: string+ ): Promise<void> {+ try {+ const shim = `${remoteHome}/.nodeterm/context.sh`+ await this.writeRemoteShim(conn, controlPath, shim, CONTEXT_SHIM_SCRIPT)+ await this.writeRemoteSkill(+ conn,+ controlPath,+ `${remoteHome}/.nodeterm/claude-accounts/${accountId}`,+ 'get-linked-context',+ buildContextLinkSkillBody(shim)+ )} catch {/* fail-open */}}- private async writeCanvasShim(conn: SshConnection, controlPath: string, shim: string): Promise<void> {+ private async writeRemoteShim(+ conn: SshConnection,+ controlPath: string,+ shim: string,+ body: 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+ body)}- private async installCanvasSkillAt(+ private async writeRemoteSkill(conn: SshConnection,controlPath: string,configDir: string,- shim: string+ name: string,+ body: string): Promise<void> {- const skill = `${configDir}/skills/manage-nodeterm-canvas/SKILL.md`+ const skill = `${configDir}/skills/${name}/SKILL.md`await this.r.run(childArgs(conn, controlPath, `mkdir -p ${posixQuote(dirnameOf(skill))} && cat > ${posixQuote(skill)}`),- buildCanvasSkillBody(shim)+ body)}/** Read-merge-write one marker-delimited instructions block at a remote path EXPRESSION- * (already quoted / shell-expandable). Everything outside the markers is preserved. */+ * (already quoted / shell-expandable). Everything outside the markers is preserved — including+ * the OTHER feature's block, which is why the merge function is a parameter: canvas control and+ * context link own different markers in the same files. */private async mergeRemoteInstructions(conn: SshConnection,controlPath: string,pathExpr: string,- block: string+ block: string,+ merge: (existing: string, block: string) => 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)+ const merged = merge(existing, block)if (merged === existing) returnawait this.r.run(childArgs(conn, controlPath, `mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`),diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 45b0c37c5..05114aaa2 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -360,6 +360,7 @@ export class SshProjectManager {// best-effort setup, and holding the connect on them would delay every terminal.if (remoteHome && hookEndpointPath) {void this.remoteHooks.installCanvasControl(conn, controlPath, remoteHome)+ void this.remoteHooks.installContextLink(conn, controlPath, remoteHome)}const entry = this.conns.get(projectId)if (entry) {@@ -644,6 +645,7 @@ export class SshProjectManager {// 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)+ await this.remoteHooks.installContextLinkSkillIntoAccountDir(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.