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): cut over from MCP bridge to pull-based context links
enes148661b30ecb
diff --git a/src/main/bridge.ts b/src/main/bridge.tsdeleted file mode 100644index 9b653cf69..000000000--- a/src/main/bridge.ts+++ /dev/null@@ -1,245 +0,0 @@-// Session Bridge — lets two Claude Code nodes on the canvas talk to each other.-//-// Each nodeterm-spawned `claude` is launched with `--mcp-config <bridgeMcpConfigPath()>`,-// which attaches a tiny stdio MCP server (only to our sessions, never the user's normal-// `claude`). That server exposes two tools to the agent: `list_bridge_nodes` and-// `send_to_bridge`. The server self-identifies via NODETERM_NODE_ID (inherited from the-// tmux session env), reads the current link topology from topology.json, and drops outgoing-// messages as JSON files into outbox/. This main process watches outbox/, validates the link-// still exists, and injects the message into the target node's live tmux session via-// `pty.sendText` — so the receiving Claude gets it as a prompt and can reply with its own-// `send_to_bridge` call (bidirectional). A per-pair exchange counter guards against runaway-// ping-pong loops (auto-resets after a quiet period).-import fs from 'fs'-import path from 'path'-import { app, ipcMain, type BrowserWindow } from 'electron'-import { IPC } from '../shared/ipc'-import type { PtyManager } from './pty-manager'-import type { BridgeTopology } from '../shared/types'--let dir = ''-export function bridgeDir(): string {- if (!dir) dir = path.join(app.getPath('userData'), 'claude-bridge')- return dir-}-export function bridgeMcpConfigPath(): string {- return path.join(bridgeDir(), 'mcp-config.json')-}--// The stdio MCP server, written to disk at init and run via Electron-as-Node. Self-contained-// (no deps) and uses no backticks / ${} so it can live in this template literal verbatim.-const MCP_SCRIPT = `// nodeterm bridge MCP server (auto-generated — do not edit).-import fs from 'node:fs'-import path from 'node:path'-import readline from 'node:readline'--var NODE_ID = process.env.NODETERM_NODE_ID || ''-var DIR = process.env.NODETERM_BRIDGE_DIR || ''-var TOPOLOGY = path.join(DIR, 'topology.json')-var OUTBOX = path.join(DIR, 'outbox')--function linkedNodes() {- try {- var all = JSON.parse(fs.readFileSync(TOPOLOGY, 'utf-8'))- return Array.isArray(all[NODE_ID]) ? all[NODE_ID] : []- } catch (e) {- return []- }-}--var TOOLS = [- {- name: 'list_bridge_nodes',- description: 'List the other Claude sessions this session is linked to on the nodeterm canvas. Call this before send_to_bridge to discover valid targets (by name or id).',- inputSchema: { type: 'object', properties: {}, additionalProperties: false }- },- {- name: 'send_to_bridge',- description: 'Send a message to a linked Claude session (a node connected to this one by a bridge edge on the canvas). The recipient receives it as a prompt and can reply with its own send_to_bridge call. Use it to ask another session a question or to hand off work.',- inputSchema: {- type: 'object',- properties: {- target: { type: 'string', description: 'Name or id of a linked node (see list_bridge_nodes). Optional when exactly one node is linked.' },- message: { type: 'string', description: 'The message to send.' }- },- required: ['message'],- additionalProperties: false- }- }-]--function send(msg) { process.stdout.write(JSON.stringify(msg) + '\\n') }-function reply(id, res) { send({ jsonrpc: '2.0', id: id, result: res }) }-function fail(id, code, message) { send({ jsonrpc: '2.0', id: id, error: { code: code, message: message } }) }-function text(t) { return { content: [{ type: 'text', text: t }] } }--function callTool(name, args) {- if (name === 'list_bridge_nodes') {- var nodes = linkedNodes()- if (!nodes.length) return text('No linked nodes. Draw a bridge edge from this Claude node to another on the canvas first.')- return text('Linked nodes:\\n' + nodes.map(function (n) { return '- ' + n.title + ' (id: ' + n.id + ')' }).join('\\n'))- }- if (name === 'send_to_bridge') {- var message = String((args && args.message) || '').trim()- if (!message) return text('Error: message is required.')- var nodes = linkedNodes()- if (!nodes.length) return text('Error: this session has no linked nodes.')- var target = args && args.target ? String(args.target) : ''- var match = null- if (target) {- var q = target.toLowerCase()- match = nodes.find(function (n) { return String(n.id).toLowerCase() === q || String(n.title || '').toLowerCase() === q })- } else if (nodes.length === 1) {- match = nodes[0]- }- if (!match) return text('Error: target "' + target + '" is not linked. Linked nodes: ' + nodes.map(function (n) { return n.title }).join(', ') + '.')- try {- fs.mkdirSync(OUTBOX, { recursive: true })- var file = path.join(OUTBOX, Date.now() + '-' + Math.random().toString(36).slice(2, 8) + '.json')- fs.writeFileSync(file, JSON.stringify({ from: NODE_ID, target: match.id, message: message }))- } catch (e) {- return text('Error: failed to queue message: ' + (e && e.message ? e.message : e))- }- return text('Sent to ' + match.title + '. They will receive it as a prompt and may reply via send_to_bridge.')- }- return null-}--var rl = readline.createInterface({ input: process.stdin })-rl.on('line', function (line) {- var t = line.trim()- if (!t) return- var msg- try { msg = JSON.parse(t) } catch (e) { return }- var id = msg.id- var method = msg.method- var params = msg.params || {}- if (method === 'initialize') {- reply(id, { protocolVersion: params.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'bridge', version: '1.0.0' } })- } else if (method === 'tools/list') {- reply(id, { tools: TOOLS })- } else if (method === 'tools/call') {- var r = callTool(params.name, params.arguments || {})- if (r) reply(id, r)- else fail(id, -32601, 'Unknown tool')- } else if (method === 'ping') {- reply(id, {})- } else if (id !== undefined && method) {- reply(id, {})- }-})-`--function writeServerFiles(): void {- const d = bridgeDir()- fs.mkdirSync(path.join(d, 'outbox'), { recursive: true })- const scriptPath = path.join(d, 'bridge-mcp.mjs')- fs.writeFileSync(scriptPath, MCP_SCRIPT)- const config = {- mcpServers: {- bridge: {- type: 'stdio',- command: process.execPath,- args: [scriptPath],- env: { ELECTRON_RUN_AS_NODE: '1', NODETERM_BRIDGE_DIR: d }- }- }- }- fs.writeFileSync(bridgeMcpConfigPath(), JSON.stringify(config, null, 2))-}--let topology: BridgeTopology = {}--// Loop guard: cap how many messages a single pair of nodes may exchange before we pause,-// auto-resetting once they've been quiet (a fresh conversation).-const MAX_EXCHANGES = 40-const RESET_AFTER_MS = 60_000-const pairCounts = new Map<string, { count: number; last: number }>()-const pairKey = (a: string, b: string) => [a, b].sort().join('::')--/** Single-line, awareness-carrying wrapper injected into the receiving session. */-function formatBridge(fromTitle: string, message: string): string {- const clean = message.replace(/\r?\n+/g, ' ').trim()- return `[Bridge message from "${fromTitle}"]: ${clean} (To reply, use the send_to_bridge tool with target "${fromTitle}".)`-}--export function initBridge(win: BrowserWindow, pty: PtyManager): void {- const d = bridgeDir()- const outbox = path.join(d, 'outbox')- try {- writeServerFiles()- for (const f of fs.readdirSync(outbox)) fs.rmSync(path.join(outbox, f), { force: true })- fs.writeFileSync(path.join(d, 'topology.json'), '{}')- } catch (e) {- console.error('[bridge] setup failed', e)- return- }-- ipcMain.handle(IPC.bridgeConfigPath, () => bridgeMcpConfigPath())- ipcMain.handle(IPC.bridgeSetTopology, (_e, t: BridgeTopology) => {- topology = t && typeof t === 'object' ? t : {}- try {- fs.writeFileSync(path.join(d, 'topology.json'), JSON.stringify(topology))- } catch {- // ignore — the MCP server tolerates a missing/unreadable topology- }- })-- const handleFile = (file: string): void => {- const full = path.join(outbox, file)- let raw: string- try {- raw = fs.readFileSync(full, 'utf-8')- } catch {- return // already consumed (fs.watch can fire twice)- }- fs.rmSync(full, { force: true })- let msg: { from?: string; target?: string; message?: string }- try {- msg = JSON.parse(raw)- } catch {- return- }- const from = msg.from || ''- const target = msg.target || ''- const message = (msg.message || '').toString()- if (!from || !target || !message) return- // The link must still exist (the agent could reference a since-removed edge).- if (!(topology[from] || []).some((n) => n.id === target)) return- // from's display title, as known by the target's neighbor list.- const fromTitle = (topology[target] || []).find((n) => n.id === from)?.title || from-- const key = pairKey(from, target)- const now = Date.now()- const pc = pairCounts.get(key)- const count = pc && now - pc.last < RESET_AFTER_MS ? pc.count + 1 : 1- pairCounts.set(key, { count, last: now })-- const post = (stopped: boolean) => {- if (!win.isDestroyed())- win.webContents.send(IPC.bridgeMessage, {- from,- to: target,- fromTitle,- message,- count,- max: MAX_EXCHANGES,- stopped- })- }- if (count > MAX_EXCHANGES) {- post(true) // paused — let the UI flag the runaway loop- return- }- pty.sendText(target, formatBridge(fromTitle, message))- post(false)- }-- try {- fs.watch(outbox, (_evt, file) => {- if (file) setTimeout(() => handleFile(file.toString()), 10)- })- } catch (e) {- console.error('[bridge] watch failed', e)- }-}diff --git a/src/main/index.ts b/src/main/index.tsindex 5dbc35427..13377efbb 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -20,7 +20,7 @@ import {SESSION_ID_RE} from './transcript-reader'import { buildHandoff } from './handoff'-import { initBridge } from './bridge'+import { initContextLink, setNodeTranscript } from './context-link'import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'import { initLicense } from './license'@@ -45,8 +45,7 @@ let mainWin: BrowserWindow | null = null// Enforce a single instance. A second instance would re-attach every node's tmux session// (`new-session -A -D`), whose `-D` detaches the first instance's clients — leaving// "[detached (from session ...)]" dead terminals. Bail out and focus the existing window-// instead. (The bridge MCP server runs via ELECTRON_RUN_AS_NODE on its own .mjs entry, so it-// never reaches this code; this guards against a stray real GUI launch.)+// instead. (This guards against a stray real GUI launch.)const gotSingleInstanceLock = NT_MULTI || app.requestSingleInstanceLock()if (!gotSingleInstanceLock) {app.quit()@@ -238,7 +237,7 @@ app.whenReady().then(async () => {hookServer.setListener((e) => {if (!win.isDestroyed()) win.webContents.send(IPC.agentStatus, e)})- hookServer.setRawListener((agentId, _nodeId, payload) => {+ hookServer.setRawListener((agentId, nodeId, payload) => {if (agentId !== 'claude') returnconst p = payload as {hook_event_name?: string@@ -249,6 +248,7 @@ app.whenReady().then(async () => {}// Context-window meter: tail the session transcript (any event carrying both fields).if (p.session_id && p.transcript_path) contextTail.track(p.session_id, p.transcript_path)+ if (nodeId && p.session_id && p.transcript_path) setNodeTranscript(nodeId, p.session_id, p.transcript_path)if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)// Subagent live transcript: track on PreToolUse / finish on PostToolUse for subagent tools.const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])@@ -259,7 +259,7 @@ app.whenReady().then(async () => {})await hookServer.start()- initBridge(win, ptyManager)+ initContextLink(win, ptyManager)initClaudeUsage(win)initTelemetry(() => settingsStore.get())initLicense(win)diff --git a/src/preload/index.ts b/src/preload/index.tsindex eda231527..c994084df 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -230,14 +230,8 @@ const api: NodeTerminalApi = {build: (sessionId, agentId, sourceNodeId, cwd) =>ipcRenderer.invoke(IPC.handoffBuild, sessionId, agentId, sourceNodeId, cwd)},- bridge: {- configPath: () => ipcRenderer.invoke(IPC.bridgeConfigPath),- setTopology: (topology) => ipcRenderer.invoke(IPC.bridgeSetTopology, topology),- onMessage: (listener) => {- const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)- ipcRenderer.on(IPC.bridgeMessage, handler)- return () => ipcRenderer.removeListener(IPC.bridgeMessage, handler)- }+ contextLink: {+ setLinks: (map) => ipcRenderer.invoke(IPC.contextLinkSetLinks, map)},// Per-node subscriptions (each terminal/editor listens) — multiplexed so they don't pile up// ipcRenderer listeners and trip the MaxListeners warning.diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 1110f0902..9f02a394d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -68,7 +68,7 @@ import {hasHooks,canBranch,canTransferFrom,- canBridge,+ canContextLink,AGENT_CONFIG,BUILTIN_AGENT_IDS,type AgentId@@ -90,7 +90,6 @@ import {flowToNodeStates,groupSelectedNodes,nodeStatesToFlow,- setBridgeConfigPath,ungroupNodes,type CanvasNode} from '../state/workspace'@@ -106,14 +105,10 @@ const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {export function Canvas() {const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])- // Persistent bridge links between Claude nodes (separate from ephemeral subagent/loop edges).- const [bridgeEdges, setBridgeEdges, onBridgeEdgesChange] = useEdgesState<Edge>([])- const bridgeEdgesRef = useRef<Edge[]>([])- bridgeEdgesRef.current = bridgeEdges- // Transient per-edge activity (count + paused flag) shown while messages flow.- const [bridgeActivity, setBridgeActivity] = useState<- Record<string, { count: number; stopped: boolean }>- >({})+ // Persistent context links between Claude nodes (separate from ephemeral subagent/loop edges).+ const [linkEdges, setLinkEdges, onLinkEdgesChange] = useEdgesState<Edge>([])+ const linkEdgesRef = useRef<Edge[]>([])+ linkEdgesRef.current = linkEdgesconst [dirty, setDirty] = useState(false)const [zoomPct, setZoomPct] = useState(100)const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)@@ -291,26 +286,18 @@ export function Canvas() {[nodes, ephemeralNodes])- // Bridge edges decorated with live activity (count badge + animation while messaging).+ // Context-link edges, statically styled (no per-message activity in the pull model).const accent = settings.accentconst displayEdges = useMemo(() => {- const decorated = bridgeEdges.map((e) => {- const act = bridgeActivity[e.id]+ const decorated = linkEdges.map((e) => {const sel = !!e.selected- const stroke = sel ? '#ffffff' : act?.stopped ? '#ff9f0a' : accent+ const stroke = sel ? '#ffffff' : accentreturn {...e,type: 'default',- sourceHandle: 'bridge-out',- targetHandle: 'bridge-in',- animated: !!act && !act.stopped,- label: act- ? act.stopped- ? `⇄ paused (${act.count})`- : `⇄ ${act.count}`- : sel- ? '⇄ bridge — ⌫ to remove'- : '⇄ bridge',+ sourceHandle: 'link-out',+ targetHandle: 'link-in',+ label: sel ? '⇄ context — ⌫ to remove' : '⇄ context',labelStyle: { fill: stroke, fontSize: 11, fontWeight: 600 },labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },labelBgPadding: [6, 3] as [number, number],@@ -321,15 +308,11 @@ export function Canvas() {}})return ephemeralEdges.length ? [...decorated, ...ephemeralEdges] : decorated- }, [bridgeEdges, bridgeActivity, ephemeralEdges, accent])+ }, [linkEdges, ephemeralEdges, accent])// 1) Load the whole workspace once and hydrate the projects store.useEffect(() => {let cancelled = false- // Bridge MCP config path → new Claude nodes launch with `--mcp-config` (Session Bridge).- void window.nodeTerminal.bridge.configPath().then((p) => {- if (!cancelled && p) setBridgeConfigPath(p)- })useSettings.getState().hydrate()@@ -358,8 +341,7 @@ export function Canvas() {loadingRef.current = trueconst flow = nodeStatesToFlow(project.nodes)setNodes(flow)- setBridgeEdges((project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target })))- setBridgeActivity({})+ setLinkEdges((project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target })))// Reset history for the newly loaded project.committedRef.current = flowpastRef.current = []@@ -406,7 +388,7 @@ export function Canvas() {id,flowToNodeStates(nodesRef.current),viewportRef.current,- bridgeEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target }))+ linkEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })))}, [])@@ -547,28 +529,28 @@ export function Canvas() {)}, [])- // Bridge links connect two bridge-capable agent sessions (currently Claude only).- const canBridgeNode = useCallback(+ // Context links connect two context-link-capable agent sessions (currently Claude only).+ const canLinkNode = useCallback((id: string) => {const a = agentIdOf(id)- return !!a && canBridge(a)+ return !!a && canContextLink(a)},[agentIdOf])- // Draw a bridge link between two bridge-capable nodes (the connection that lets them message).+ // Draw a context link between two context-link-capable nodes.const onConnect = useCallback((c: Connection) => {if (!c.source || !c.target || c.source === c.target) return- if (!canBridgeNode(c.source) || !canBridgeNode(c.target)) return+ if (!canLinkNode(c.source) || !canLinkNode(c.target)) return// No duplicate link (in either direction).- const exists = bridgeEdgesRef.current.some(+ const exists = linkEdgesRef.current.some((e) =>(e.source === c.source && e.target === c.target) ||(e.source === c.target && e.target === c.source))if (exists) return- setBridgeEdges((es) =>+ setLinkEdges((es) =>addEdge({ id: `bridge-${c.source}-${c.target}`, source: c.source!, target: c.target!, type: 'default' },es@@ -576,60 +558,40 @@ export function Canvas() {)markDirty()},- [canBridgeNode, setBridgeEdges, markDirty]+ [canLinkNode, setLinkEdges, markDirty])- // Double-click a bridge link to remove it (ephemeral subagent/loop edges are left alone).+ // Double-click a context link to remove it (ephemeral subagent/loop edges are left alone).const onEdgeDoubleClick = useCallback((_e: React.MouseEvent, edge: Edge) => {- if (!bridgeEdgesRef.current.some((b) => b.id === edge.id)) return- setBridgeEdges((es) => es.filter((b) => b.id !== edge.id))+ if (!linkEdgesRef.current.some((b) => b.id === edge.id)) return+ setLinkEdges((es) => es.filter((b) => b.id !== edge.id))markDirty()},- [setBridgeEdges, markDirty]+ [setLinkEdges, markDirty])- // Prune links whose endpoints were deleted, then push the topology to main (debounced) so- // the bridge MCP server can resolve `list_bridge_nodes` / route `send_to_bridge`.+ // Prune links whose endpoints were deleted, then push the link map to main (debounced) so+ // it can rewrite the per-node link files the context CLI reads.useEffect(() => {const ids = new Set(nodes.map((n) => n.id))- const valid = bridgeEdges.filter((e) => ids.has(e.source) && ids.has(e.target))- if (valid.length !== bridgeEdges.length) {- setBridgeEdges(valid)+ const valid = linkEdges.filter((e) => ids.has(e.source) && ids.has(e.target))+ if (valid.length !== linkEdges.length) {+ setLinkEdges(valid)return // re-runs with the pruned set}- const titleOf = (id: string) =>- (nodes.find((n) => n.id === id)?.data.title as string) || id- const topo: Record<string, { id: string; title: string }[]> = {}+ const infoOf = (id: string) => {+ const n = nodes.find((nn) => nn.id === id)+ return { id, title: (n?.data.title as string) || id, cwd: (n?.data.cwd as string) || '' }+ }+ const map: Record<string, { id: string; title: string; cwd: string }[]> = {}for (const e of valid) {- ;(topo[e.source] ??= []).push({ id: e.target, title: titleOf(e.target) })- ;(topo[e.target] ??= []).push({ id: e.source, title: titleOf(e.source) })+ ;(map[e.source] ??= []).push(infoOf(e.target))+ ;(map[e.target] ??= []).push(infoOf(e.source))}- const t = setTimeout(() => void window.nodeTerminal.bridge.setTopology(topo), 150)+ const t = setTimeout(() => void window.nodeTerminal.contextLink.setLinks(map), 150)return () => clearTimeout(t)- }, [bridgeEdges, nodes, setBridgeEdges])-- // A bridge message was delivered (or paused): pulse the matching edge with a live count.- useEffect(() => {- return window.nodeTerminal.bridge.onMessage((m) => {- const edge = bridgeEdgesRef.current.find(- (e) =>- (e.source === m.from && e.target === m.to) || (e.source === m.to && e.target === m.from)- )- if (!edge) return- const id = edge.id- setBridgeActivity((prev) => ({ ...prev, [id]: { count: m.count, stopped: !!m.stopped } }))- // Clear the pulse after a beat (keep the paused flag visible a little longer).- const ttl = m.stopped ? 8000 : 2500- window.setTimeout(() => {- setBridgeActivity((prev) => {- const next = { ...prev }- delete next[id]- return next- })- }, ttl)- })- }, [])+ }, [linkEdges, nodes, setLinkEdges])// Reflect Claude nodes with unread output as a macOS Dock badge count (across all projects).useEffect(() => {@@ -916,12 +878,12 @@ export function Canvas() {if (tag === 'input' || tag === 'textarea') returnconst ids = nodesRef.current.filter((n) => n.selected).map((n) => n.id)if (!ids.length) {- // No node selected → remove any selected bridge link(s).- const edgeIds = bridgeEdgesRef.current.filter((b) => b.selected).map((b) => b.id)+ // No node selected → remove any selected context link(s).+ const edgeIds = linkEdgesRef.current.filter((b) => b.selected).map((b) => b.id)if (edgeIds.length) {e.preventDefault()const drop = new Set(edgeIds)- setBridgeEdges((es) => es.filter((b) => !drop.has(b.id)))+ setLinkEdges((es) => es.filter((b) => !drop.has(b.id)))markDirty()}return@@ -937,7 +899,7 @@ export function Canvas() {}window.addEventListener('keydown', onKey)return () => window.removeEventListener('keydown', onKey)- }, [deleteNodes, setBridgeEdges, markDirty])+ }, [deleteNodes, setLinkEdges, markDirty])// Cmd/Ctrl+W (forwarded from main) closes the selected node(s) immediately, like the// node's × button. With nothing selected it falls back to closing the window.@@ -1734,7 +1696,7 @@ export function Canvas() {edges={displayEdges}nodeTypes={nodeTypes}onNodesChange={handleNodesChange}- onEdgesChange={onBridgeEdgesChange}+ onEdgesChange={onLinkEdgesChange}onConnect={onConnect}onEdgeDoubleClick={onEdgeDoubleClick}onMove={onMove}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 1dfa06e31..17c6e6663 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -26,7 +26,7 @@ import { useSettings } from '../state/settings'import { useAgentStatus } from '../state/agentStatus'import { useAgentNodes } from '../state/agentNodes'import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'-import { hasHooks, canRecur, canBridge, hasUsage, agentConfig, type AgentId } from '@shared/agents/config'+import { hasHooks, canRecur, canContextLink, hasUsage, agentConfig, type AgentId } from '@shared/agents/config'/** Backslash-escape shell-special characters, like a native terminal does on file drop. */function escapeDroppedPath(p: string): string {@@ -78,7 +78,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {// Gate each former `isClaude` site by the capability it actually represents.const showStatus = !!agentId && hasHooks(agentId) // status badge + session-title captureconst showLoop = !!agentId && canRecur(agentId) // /loop · /schedule · /cron chrome- const showBridge = !!agentId && canBridge(agentId) // bridge link handles+ const showLink = !!agentId && canContextLink(agentId) // context-link handlesconst showUsage = !!agentId && hasUsage(agentId) // per-node context-window meterconst agentLabel = (agentId ? agentConfig(agentId) : undefined)?.label ?? 'Agent'const status = useAgentStatus((s) => s.byId[id])@@ -135,11 +135,11 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {if (search.query.trim()) searchAddonRef.current?.findPrevious(search.query, findOpts)}, [search])- // The bridge handles are added/positioned dynamically for bridge-capable nodes; make+ // The link handles are added/positioned dynamically for context-link-capable nodes; make// React Flow re-measure them so edges anchor to the (centered) handle, not a stale position.useEffect(() => {- if (showBridge) updateNodeInternals(id)- }, [showBridge, id, updateNodeInternals])+ if (showLink) updateNodeInternals(id)+ }, [showLink, id, updateNodeInternals])// Terminal lifecycle — set up exactly once.useEffect(() => {@@ -444,23 +444,23 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {isConnectable={false}style={{ opacity: 0, pointerEvents: 'none', bottom: 0 }}/>- {/* Bridge link handles (bridge-capable nodes only): drag right→left to connect two+ {/* Context-link handles (context-link-capable nodes only): drag right→left to link twosessions. Vertically centered on the side edges; raised above the body so they're never buried. */}- {showBridge && (+ {showLink && (<><Handle- id="bridge-out"+ id="link-out"type="source"position={Position.Right}className="bridge-handle bridge-handle--out"- data-tip="Bridge out — drag to another bridge-capable node to link their sessions"+ data-tip="Link out — drag to another Claude node so they can read each other's context"/><Handle- id="bridge-in"+ id="link-in"type="target"position={Position.Left}className="bridge-handle bridge-handle--in"- data-tip="Bridge in — drop a link here to connect this Claude session"+ data-tip="Link in — drop a link here to share context with this Claude session"/></>)}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex ace95b848..2d637d939 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -101,23 +101,39 @@ export function createTerminalNode(}/**- * Path to the bridge MCP config, fetched once from main at boot (see Canvas). When set, new- * Claude nodes launch with `--mcp-config <path>` so the Session Bridge tools are available in- * exactly the sessions nodeterm spawns — never the user's own `claude`.+ * Creates a terminal node bound to a REMOTE host over the relay. Identical to a local terminal+ * except `data.remote.connectionId` is set, which makes TerminalNode pick RemoteTransport instead+ * of LocalTransport. Not persisted (see flowToNodeStates).*/-let bridgeConfigPath = ''-export function setBridgeConfigPath(p: string): void {- bridgeConfigPath = p+export function createRemoteTerminalNode(+ connectionId: string,+ index: number,+ center?: { x: number; y: number }+): CanvasNode {+ return {+ id: nextId('remote'),+ type: 'terminal',+ position: placeAt(center, index, TERMINAL_SIZE.width, TERMINAL_SIZE.height),+ width: TERMINAL_SIZE.width,+ height: TERMINAL_SIZE.height,+ style: { width: TERMINAL_SIZE.width, height: TERMINAL_SIZE.height },+ data: {+ title: 'Remote terminal',+ color: NODE_COLORS[index % NODE_COLORS.length],+ group: null,+ tags: [],+ remote: { connectionId }+ }+ }}/*** Command that launches Claude Code. Detection works via hooks installed globally in* ~/.claude/settings.json (gated by NODETERM_* env that the PTY manager sets), so a plain- * `claude` is enough. We add `--mcp-config` to attach the Session Bridge MCP server. Append- * `-r <id>` to resume a specific session (used by Branch).+ * `claude` is enough. Append `-r <id>` to resume a specific session (used by Branch).*/export function claudeLaunchCommand(): string {- return bridgeConfigPath ? `claude --mcp-config "${bridgeConfigPath}"` : 'claude'+ return 'claude'}/** Fallback color for custom / unknown agents that have no config-provided color. */@@ -140,7 +156,7 @@ function resolveAgent(agentId: AgentId): { label: string; color: string; launchC* Creates a terminal node that launches the given agent on open. Title, color, and the* launch command come from the resolved agent config (builtin or custom); the node carries* `agentId` so the rest of the app (hooks, capabilities, UI) can branch on it. For `claude`- * we use `claudeLaunchCommand()` which appends the Session Bridge `--mcp-config` (Claude-only).+ * we use `claudeLaunchCommand()`.*/export function createAgentNode(agentId: AgentId,diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex a1a7395d8..4a887be74 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -49,7 +49,7 @@ export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini'] as constexport const SUBAGENT_CAPABLE = ['claude'] as constexport const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cronexport const BRANCH_CAPABLE = ['claude'] as const-export const BRIDGE_CAPABLE = ['claude'] as const+export const CONTEXT_LINK_CAPABLE = ['claude'] as constexport const USAGE_CAPABLE = ['claude'] as const// Agents whose native transcript we can read + render for cross-agent transfer.export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini'] as const@@ -61,7 +61,7 @@ export const canResume = (id: AgentId): boolean => includes(RESUMABLE_AGENTS, idexport const canSubagent = (id: AgentId): boolean => includes(SUBAGENT_CAPABLE, id)export const canRecur = (id: AgentId): boolean => includes(RECURRING_CAPABLE, id)export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)-export const canBridge = (id: AgentId): boolean => includes(BRIDGE_CAPABLE, id)+export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAPABLE, id)export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex cfc352157..4097ef6ab 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -19,9 +19,6 @@ export const IPC = {appSetBadge: 'app:set-badge',agentStatus: 'agent:status',agentSubagentActivity: 'agent:subagent-activity',- bridgeConfigPath: 'bridge:config-path',- bridgeSetTopology: 'bridge:set-topology',- bridgeMessage: 'bridge:message',contextLinkSetLinks: 'context-link:set-links',appUpdateAvailable: 'app:update-available',appUpdateDownloaded: 'app:update-downloaded',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 60d8e36bb..aa4da64b8 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -411,38 +411,6 @@ export interface SubagentActivity {chunk: string}-/** One linked node, as the bridge MCP server sees it (id + display title). */-export interface BridgeNodeInfo {- id: string- title: string-}--/** Map of node id → the nodes it is bridge-linked to. Sent to main so the MCP server can route. */-export type BridgeTopology = Record<string, BridgeNodeInfo[]>--/** A bridge message delivered (or paused) between two linked Claude nodes. */-export interface BridgeMessage {- from: string- to: string- /** Display title of the sender (for the receiving wrapper + UI). */- fromTitle: string- message: string- /** Exchanges in the current conversation on this pair, and the cap. */- count: number- max: number- /** True when the loop guard paused delivery (cap reached). */- stopped?: boolean-}--export interface BridgeApi {- /** Path to the MCP config that attaches the bridge server (pass to `claude --mcp-config`). */- configPath(): Promise<string>- /** Push the current link topology to main so the MCP server can route messages. */- setTopology(topology: BridgeTopology): Promise<void>- /** Fires when a bridge message is delivered/paused. Returns unsubscribe. */- onMessage(listener: (m: BridgeMessage) => void): () => void-}-/** One linked node, as the context-link CLI sees it. */export interface ContextLinkInfo {id: string@@ -654,7 +622,7 @@ export interface NodeTerminalApi {updates: UpdateApiannouncements: AnnouncementsApilicense: LicenseApi- bridge: BridgeApi+ contextLink: ContextLinkApiusage: UsageApicontext: ContextApiclaude: ClaudeApi