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(context-link): pure core, CLI source, and tests (dormant)
enesfa2eb708a4f4
diff --git a/src/main/context-link-core.test.ts b/src/main/context-link-core.test.tsnew file mode 100644index 000000000..c023e62d9--- /dev/null+++ b/src/main/context-link-core.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest'+import { buildLinkDoc, setNodeTranscript, transcriptPathOf } from './context-link-core'++describe('buildLinkDoc', () => {+ it('enriches each link with tmux name, injected transcript path, and cwd', () => {+ const doc = buildLinkDoc(+ 'node-A',+ [+ { id: 'node-B', title: 'Builder', cwd: '/proj' },+ { id: 'node-C', title: 'Tester' }+ ],+ {+ transcriptOf: (id) => (id === 'node-B' ? '/t/b.jsonl' : ''),+ tmuxBin: '/usr/bin/tmux',+ tmuxSocket: 'node-terminal'+ }+ )+ expect(doc.self).toEqual({ id: 'node-A' })+ expect(doc.tmuxBin).toBe('/usr/bin/tmux')+ expect(doc.tmuxSocket).toBe('node-terminal')+ expect(doc.links).toEqual([+ { id: 'node-B', title: 'Builder', cwd: '/proj', transcriptPath: '/t/b.jsonl', tmux: 'nt-node-B' },+ { id: 'node-C', title: 'Tester', cwd: '', transcriptPath: '', tmux: 'nt-node-C' }+ ])+ })++ it('sanitizes the tmux session name like the pty manager', () => {+ const doc = buildLinkDoc('x', [{ id: 'a b/c.d', title: 'T' }], {+ transcriptOf: () => '',+ tmuxBin: null,+ tmuxSocket: 's'+ })+ expect(doc.links[0].tmux).toBe('nt-a_b_c_d')+ })+})++describe('setNodeTranscript / transcriptPathOf', () => {+ it('stores and returns the transcript path by node id', () => {+ setNodeTranscript('n1', 'sess', '/path/one.jsonl')+ expect(transcriptPathOf('n1')).toBe('/path/one.jsonl')+ })+ it('ignores empty node id or path', () => {+ setNodeTranscript('', 's', '/p.jsonl')+ setNodeTranscript('n2', 's', '')+ expect(transcriptPathOf('n2')).toBe('')+ })+ it('returns empty string for an unknown node', () => {+ expect(transcriptPathOf('nope')).toBe('')+ })+})diff --git a/src/main/context-link-core.ts b/src/main/context-link-core.tsnew file mode 100644index 000000000..74230d62f--- /dev/null+++ b/src/main/context-link-core.ts@@ -0,0 +1,183 @@+// Pure core for the context-link feature: the nodeId→transcript map, the link-document+// builder, and the standalone CLI source. No electron / node-pty imports, so this module+// (and CLI_SCRIPT) are unit-testable. The electron/fs/ipc wiring lives in context-link.ts.+import type { ContextLinkInfo } from '../shared/types'+import { sessionName } from './tmux-naming'++// nodeId -> latest known transcript path, fed from the raw hook listener (see index.ts).+const nodeTranscript = new Map<string, string>()+export function setNodeTranscript(nodeId: string, _sessionId: string, transcriptPath: string): void {+ if (nodeId && transcriptPath) nodeTranscript.set(nodeId, transcriptPath)+}+export function transcriptPathOf(nodeId: string): string {+ return nodeTranscript.get(nodeId) ?? ''+}++export interface LinkDocEntry {+ id: string+ title: string+ cwd: string+ transcriptPath: string+ tmux: string+}+export interface LinkDoc {+ self: { id: string }+ links: LinkDocEntry[]+ tmuxBin: string | null+ tmuxSocket: string+}++/** Pure: build one node's link document. Injected deps keep it unit-testable. */+export function buildLinkDoc(+ nodeId: string,+ links: ContextLinkInfo[],+ ctx: { transcriptOf: (id: string) => string; tmuxBin: string | null; tmuxSocket: string }+): LinkDoc {+ return {+ self: { id: nodeId },+ links: links.map((n) => ({+ id: n.id,+ title: n.title,+ cwd: n.cwd ?? '',+ transcriptPath: ctx.transcriptOf(n.id),+ tmux: sessionName(n.id)+ })),+ tmuxBin: ctx.tmuxBin,+ tmuxSocket: ctx.tmuxSocket+ }+}++// 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 Claude 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 + ' (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+ 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 ''+}++// 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+}++function readTranscript(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 [] }+ var lines = []+ buf.split('\\n').forEach(function (raw) { if (raw.trim()) lines.push.apply(lines, linesFrom(raw)) })+ return lines+}++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.') }+}++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 }++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 + ' (id: ' + n.id + ')') })+ process.exit(0)+}+var node = pickNode(doc, flag('--node'))+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]')+}+`diff --git a/src/main/context-link.cli.test.ts b/src/main/context-link.cli.test.tsnew file mode 100644index 000000000..df40127cd--- /dev/null+++ b/src/main/context-link.cli.test.ts@@ -0,0 +1,73 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'node:child_process'+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { CLI_SCRIPT } from './context-link-core'++let dir: string++beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), 'ctxlink-'))+ writeFileSync(join(dir, 'context-cli.mjs'), CLI_SCRIPT)+ const transcript = [+ JSON.stringify({ type: 'user', message: { content: 'deploy the app' } }),+ JSON.stringify({+ type: 'assistant',+ message: {+ content: [+ { type: 'text', text: 'On it.' },+ { type: 'tool_use', name: 'Bash', input: { command: 'npm run build' } }+ ]+ }+ })+ ].join('\n')+ writeFileSync(join(dir, 'b.jsonl'), transcript)+ 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' }+ ],+ tmuxBin: null,+ tmuxSocket: 'node-terminal'+ })+ )+})++afterAll(() => rmSync(dir, { 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 }+ })+}++describe('context-cli', () => {+ it('list shows the linked node', () => {+ const out = run('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'])+ 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'])+ 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'])+ expect(out).toContain('Terminal capture unavailable')+ })+ it('is a no-op without NODETERM_NODE_ID', () => {+ const out = run('', ['list'])+ expect(out).toContain('Not a nodeterm session')+ })+})diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 7887d7d42..591c44687 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -8,9 +8,7 @@ import * as pty from 'node-pty'import { IPC } from '../shared/ipc'import { DEFAULT_SETTINGS, type PtyCreateOptions, type Settings } from '../shared/types'import { hookServer } from './agents/hook-server'--// A dedicated tmux socket isolates our sessions from the user's own tmux server.-const TMUX_SOCKET = 'node-terminal'+import { TMUX_SOCKET, sessionName } from './tmux-naming'// Async exec for tmux side-calls (capture / send-keys / kill-session) so they never block// the main event loop — a synchronous capture-pane of a large scrollback would stall every@@ -63,11 +61,6 @@ function findTmux(): string | null {return null}-/** tmux session names may not contain '.', ':' or whitespace. */-function sessionName(persistKey: string): string {- return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`-}-interface Session {proc: pty.IPty/** Renderer webContents to stream output to over IPC, or null for a detached (host) session. */@@ -135,6 +128,11 @@ export class PtyManager {}}+ /** Absolute tmux path (or null if tmux is unavailable). Used by the context-link backend. */+ getTmuxBin(): string | null {+ return this.tmuxPath+ }+registerIpc(): void {ipcMain.handle(IPC.ptyCreate, (event, options: PtyCreateOptions) =>this.create(event.sender.id, options)diff --git a/src/main/tmux-naming.ts b/src/main/tmux-naming.tsnew file mode 100644index 000000000..31fda682b--- /dev/null+++ b/src/main/tmux-naming.ts@@ -0,0 +1,9 @@+// Pure tmux naming helpers shared by the PTY manager and the context-link backend.+// No native/electron imports, so this module is safe to import from unit tests.++export const TMUX_SOCKET = 'node-terminal'++/** Per-node tmux session name. Must stay stable — it is the persistence key. */+export function sessionName(persistKey: string): string {+ return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 96535b149..cfc352157 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -22,6 +22,7 @@ export const IPC = {bridgeConfigPath: 'bridge:config-path',bridgeSetTopology: 'bridge:set-topology',bridgeMessage: 'bridge:message',+ contextLinkSetLinks: 'context-link:set-links',appUpdateAvailable: 'app:update-available',appUpdateDownloaded: 'app:update-downloaded',appUpdateProgress: 'app:update-progress',diff --git a/src/shared/types.ts b/src/shared/types.tsindex c43e6e03f..60d8e36bb 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -443,6 +443,22 @@ export interface BridgeApi {onMessage(listener: (m: BridgeMessage) => void): () => void}+/** One linked node, as the context-link CLI sees it. */+export interface ContextLinkInfo {+ id: string+ title: string+ /** The linked node's working dir — lets the CLI resolve a transcript when the path isn't known yet. */+ cwd?: string+}++/** Map of node id → the nodes it is context-linked to. Sent to main so it can write link files. */+export type ContextLinkMap = Record<string, ContextLinkInfo[]>++export interface ContextLinkApi {+ /** Push the current link map to main; main rewrites the per-node link files. */+ setLinks(map: ContextLinkMap): Promise<void>+}+/** One usage window (5h session or 7d weekly) as shown in the indicator. */export interface ClaudeUsageWindow {/** 0–100; remaining quota. Drives the bar fill (REF shows "remaining"). */