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(claude): add Session Bridge plus PTY perf and robustness fixes
enesdfc440235888
diff --git a/package-lock.json b/package-lock.jsonindex a44058b18..c84ba2c90 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "node-terminal",- "version": "0.1.0",+ "version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "node-terminal",- "version": "0.1.0",+ "version": "0.2.0","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex fbacfe4b2..25e128374 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "node-terminal",- "version": "0.1.0",+ "version": "0.2.0","description": "node-based terminal manager — multiple draggable, zoomable terminals on a single canvas.","author": "enes","license": "SEE LICENSE IN LICENSE",@@ -22,9 +22,17 @@"build": {"appId": "com.nodeterm.app","productName": "nodeterm",- "directories": { "output": "dist", "buildResources": "build" },- "files": ["out/**/*", "package.json"],- "asarUnpack": ["**/node_modules/node-pty/**"],+ "directories": {+ "output": "dist",+ "buildResources": "build"+ },+ "files": [+ "out/**/*",+ "package.json"+ ],+ "asarUnpack": [+ "**/node_modules/node-pty/**"+ ],"mac": {"category": "public.app-category.developer-tools","icon": "build/icon.png",@@ -34,11 +42,26 @@"entitlementsInherit": "build/entitlements.mac.plist","notarize": true,"target": [- { "target": "dmg", "arch": ["arm64", "x64"] },- { "target": "zip", "arch": ["arm64", "x64"] }+ {+ "target": "dmg",+ "arch": [+ "arm64",+ "x64"+ ]+ },+ {+ "target": "zip",+ "arch": [+ "arm64",+ "x64"+ ]+ }]},- "publish": { "provider": "generic", "url": "https://nodeterm.dev/updates" }+ "publish": {+ "provider": "generic",+ "url": "https://nodeterm.dev/updates"+ }},"dependencies": {"dompurify": "^3.4.10",diff --git a/src/main/bridge.ts b/src/main/bridge.tsnew file mode 100644index 000000000..9b653cf69--- /dev/null+++ b/src/main/bridge.ts@@ -0,0 +1,245 @@+// 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/git-service.ts b/src/main/git-service.tsindex d94cca748..2d25a6029 100644Binary files a/src/main/git-service.ts and b/src/main/git-service.ts differdiff --git a/src/main/index.ts b/src/main/index.tsindex 980647bc4..9969f667b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -12,6 +12,7 @@ import { generateCommitMessage, generateTerminalName } from './commit-message'import { initUpdater } from './updater'import { fetchAnnouncements } from './announcements'import { initClaudeHooks } from './claude-hooks'+import { initBridge } from './bridge'const settingsStore = new SettingsStore()const ptyManager = new PtyManager()@@ -22,6 +23,23 @@ const gitService = new GitService()// can check focus and route clicks back to the renderer.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.)+const gotSingleInstanceLock = app.requestSingleInstanceLock()+if (!gotSingleInstanceLock) {+ app.quit()+} else {+ app.on('second-instance', () => {+ if (!mainWin) return+ if (mainWin.isMinimized()) mainWin.restore()+ mainWin.show()+ mainWin.focus()+ })+}+function createWindow(): BrowserWindow {const win = new BrowserWindow({width: 1400,@@ -75,6 +93,7 @@ function createWindow(): BrowserWindow {}app.whenReady().then(() => {+ if (!gotSingleInstanceLock) return // losing second instance — quitting; don't touch tmuxsettingsStore.init()settingsStore.registerIpc()ptyManager.init(() => settingsStore.get())@@ -86,8 +105,8 @@ app.whenReady().then(() => {generateCommitMessage(cwd, settingsStore.get()))- ipcMain.handle(IPC.ptyGenerateName, (_e, persistKey: string, cwd: string) =>- generateTerminalName(ptyManager.captureSession(persistKey), cwd, settingsStore.get())+ ipcMain.handle(IPC.ptyGenerateName, async (_e, persistKey: string, cwd: string) =>+ generateTerminalName(await ptyManager.captureSession(persistKey), cwd, settingsStore.get()))ipcMain.handle(IPC.ptyCapture, (_e, persistKey: string, full?: boolean) =>@@ -96,6 +115,12 @@ app.whenReady().then(() => {ipcMain.on(IPC.appCloseWindow, () => BrowserWindow.getFocusedWindow()?.close())+ // Dock badge: number of Claude nodes with unread output (macOS only). '' clears it.+ ipcMain.on(IPC.appSetBadge, (_e, count: number) => {+ if (process.platform !== 'darwin' || !app.dock) return+ app.dock.setBadge(count > 0 ? String(count) : '')+ })+// Show an OS notification — but only when the window is in the background. Clicking it// brings the app forward and asks the renderer to focus the originating node.ipcMain.handle(@@ -206,6 +231,7 @@ app.whenReady().then(() => {mainWin = wininitUpdater(win)initClaudeHooks(win)+ initBridge(win, ptyManager)app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow()diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 5cd34abf9..191160851 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -1,7 +1,8 @@import os from 'os'import fs from 'fs'import path from 'path'-import { execFileSync } from 'child_process'+import { execFile, execFileSync } from 'child_process'+import { promisify } from 'util'import { app, ipcMain, webContents } from 'electron'import * as pty from 'node-pty'import { IPC } from '../shared/ipc'@@ -11,6 +12,11 @@ import { claudeHookDir } from './claude-hooks'// A dedicated tmux socket isolates our sessions from the user's own tmux server.const TMUX_SOCKET = 'node-terminal'+// 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+// other session's PTY streaming and all IPC for its duration.+const runAsync = promisify(execFile)+// Minimal tmux config so the user's ~/.tmux.conf never interferes. The tmux server// (under our socket) keeps sessions alive while no client is attached, which is what// gives us continuity across node remounts and full app restarts.@@ -54,8 +60,18 @@ function sessionName(persistKey: string): string {interface Session {proc: pty.IPtywebContentsId: number+ /** Pending output chunks, coalesced into one IPC message per flush. */+ buf: string[]+ bufBytes: number+ flushTimer: ReturnType<typeof setTimeout> | null}+// Output coalescing: a fast producer (e.g. `yes`, a verbose build, tmux full-screen+// redraws) emits many small chunks. Buffering them for one short window collapses N+// IPC messages + N xterm writes into one, which is the single hottest path in the app.+const FLUSH_MS = 8+const MAX_BUF_BYTES = 256 * 1024+/*** Manages all live PTY processes and bridges them to the renderer over IPC.*@@ -96,6 +112,9 @@ export class PtyManager {ipcMain.on(IPC.ptyResize, (_event, sessionId: string, cols: number, rows: number) =>this.resize(sessionId, cols, rows))+ ipcMain.on(IPC.ptyFlow, (_event, sessionId: string, resume: boolean) =>+ this.setFlow(sessionId, resume)+ )ipcMain.on(IPC.ptyKill, (_event, sessionId: string) => this.kill(sessionId))ipcMain.on(IPC.ptyDestroy, (_event, persistKey: string) => this.destroySession(persistKey))ipcMain.handle(IPC.ptySendText, (_event, persistKey: string, text: string) =>@@ -166,19 +185,61 @@ export class PtyManager {env})- proc.onData((data) => {- this.send(webContentsId, IPC.ptyData(sessionId), data)- })+ const session: Session = { proc, webContentsId, buf: [], bufBytes: 0, flushTimer: null }+ this.sessions.set(sessionId, session)++ proc.onData((data) => this.queueData(sessionId, session, data))proc.onExit(({ exitCode }) => {+ this.flush(sessionId, session) // deliver any buffered output before the exit signalthis.send(webContentsId, IPC.ptyExit(sessionId), exitCode)this.sessions.delete(sessionId)})- this.sessions.set(sessionId, { proc, webContentsId })return sessionId}+ /** Buffer a chunk; flush immediately past the byte cap, otherwise on a short timer. */+ private queueData(sessionId: string, session: Session, data: string): void {+ session.buf.push(data)+ session.bufBytes += data.length+ if (session.bufBytes >= MAX_BUF_BYTES) {+ this.flush(sessionId, session)+ } else if (!session.flushTimer) {+ session.flushTimer = setTimeout(() => this.flush(sessionId, session), FLUSH_MS)+ }+ }++ /** Send all buffered output for a session as a single IPC message. */+ private flush(sessionId: string, session: Session): void {+ if (session.flushTimer) {+ clearTimeout(session.flushTimer)+ session.flushTimer = null+ }+ if (session.buf.length === 0) return+ const data = session.buf.join('')+ session.buf = []+ session.bufBytes = 0+ this.send(session.webContentsId, IPC.ptyData(sessionId), data)+ }++ /**+ * Flow control: the renderer pauses us when xterm's write backlog grows past a high+ * watermark and resumes once it drains, so a flood can't grow the renderer buffer+ * without bound. node-pty pause()/resume() stops/starts reading the pty fd; the OS+ * pipe applies backpressure to the producing process.+ */+ private setFlow(sessionId: string, resume: boolean): void {+ const session = this.sessions.get(sessionId)+ if (!session) return+ try {+ if (resume) session.proc.resume()+ else session.proc.pause()+ } catch {+ // pause/resume can throw if the proc already exited; ignore.+ }+ }+private write(sessionId: string, data: string): void {this.sessions.get(sessionId)?.proc.write(data)}@@ -197,6 +258,7 @@ export class PtyManager {kill(sessionId: string): void {const session = this.sessions.get(sessionId)if (!session) return+ if (session.flushTimer) clearTimeout(session.flushTimer)session.proc.kill()this.sessions.delete(sessionId)}@@ -205,14 +267,15 @@ export class PtyManager {* Capture a session's output. `full` grabs the entire scrollback (`-S -`, for the* markdown view); otherwise the recent ~200 lines (AI naming, palette search).*/- captureSession(persistKey: string, full = false): string {+ async captureSession(persistKey: string, full = false): Promise<string> {if (!this.tmuxPath) return ''try {- return execFileSync(+ const { stdout } = await runAsync(this.tmuxPath,['-L', TMUX_SOCKET, 'capture-pane', '-p', '-t', sessionName(persistKey), '-S', full ? '-' : '-200'],{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })+ return stdout} catch {return ''}@@ -223,16 +286,13 @@ export class PtyManager {* Works whether or not a client is attached. Returns false if tmux is unavailable or the* session doesn't exist yet.*/- sendText(persistKey: string, text: string): boolean {+ async sendText(persistKey: string, text: string): Promise<boolean> {if (!this.tmuxPath) return falseconst target = sessionName(persistKey)try {- execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, '-l', text], {- stdio: 'ignore'- })- execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, 'Enter'], {- stdio: 'ignore'- })+ // The literal text and the Enter must be sent in order, so await sequentially.+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, '-l', text])+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'send-keys', '-t', target, 'Enter'])return true} catch {return false@@ -240,12 +300,10 @@ export class PtyManager {}/** Permanently end a node's persistent tmux session (called when the user closes it). */- destroySession(persistKey: string): void {+ async destroySession(persistKey: string): Promise<void> {if (!this.tmuxPath) returntry {- execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'kill-session', '-t', sessionName(persistKey)], {- stdio: 'ignore'- })+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'kill-session', '-t', sessionName(persistKey)])} catch {// session may not exist; ignore}@@ -256,7 +314,10 @@ export class PtyManager {* of persistence). The tmux server keeps the sessions alive for next launch.*/killAll(): void {- for (const { proc } of this.sessions.values()) proc.kill()+ for (const session of this.sessions.values()) {+ if (session.flushTimer) clearTimeout(session.flushTimer)+ session.proc.kill()+ }this.sessions.clear()}diff --git a/src/main/settings-store.ts b/src/main/settings-store.tsindex e403aa740..7a96861b0 100644--- a/src/main/settings-store.ts+++ b/src/main/settings-store.ts@@ -33,7 +33,10 @@ export class SettingsStore {ipcMain.handle(IPC.settingsLoad, () => this.cache)ipcMain.handle(IPC.settingsSave, async (_e, settings: Settings) => {this.cache = { ...DEFAULT_SETTINGS, ...settings }- await fs.writeFile(this.filePath, JSON.stringify(this.cache, null, 2), 'utf-8')+ // Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json.+ const tmp = `${this.filePath}.tmp`+ await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), 'utf-8')+ await fs.rename(tmp, this.filePath)})}}diff --git a/src/main/subagent-tail.ts b/src/main/subagent-tail.tsindex 9e882e072..dffbad275 100644--- a/src/main/subagent-tail.ts+++ b/src/main/subagent-tail.ts@@ -27,8 +27,37 @@ function textOf(content: unknown): string {return ''}-// Render one transcript line into readable text. Includes everything substantive-// (assistant text + tool calls, user/tool results); skips pure-metadata lines.+// A short, human-readable argument for a tool call (no raw JSON), e.g.+// Read → workspace.ts Bash → npm test Grep → "NODE_COLORS"+function toolArg(name: string | undefined, input: unknown): string {+ if (!input || typeof input !== 'object') return ''+ const i = input as Record<string, unknown>+ const base = (p: unknown) => (typeof p === 'string' ? p.split('/').pop() || p : '')+ const p = i.file_path ?? i.path ?? i.notebook_path+ if (p) return base(p)+ if (typeof i.command === 'string') return i.command.replace(/\s+/g, ' ').slice(0, 80)+ if (typeof i.pattern === 'string') return `"${i.pattern.slice(0, 60)}"`+ if (typeof i.url === 'string') return i.url+ if (typeof i.query === 'string') return i.query.slice(0, 60)+ const txt = i.description ?? i.prompt+ if (typeof txt === 'string') return txt.replace(/\s+/g, ' ').slice(0, 80)+ void name+ return ''+}++// Collapse a tool result to a one-line summary instead of dumping the full+// (often line-numbered) content — keeps the panel readable like an activity log.+function summarizeResult(content: unknown): string {+ const r = textOf(content).trim()+ if (!r) return ''+ const lines = r.split('\n')+ const first = (lines.find((l) => l.trim()) ?? '').trim().slice(0, 100)+ const extra = lines.length > 1 ? ` … (+${lines.length - 1} lines)` : ''+ return ` ↳ ${first}${extra}`+}++// Render one transcript line as a clean activity log: assistant prose verbatim,+// tool calls as `$ Tool arg`, tool results as a one-line summary. Skips metadata.function formatLine(line: string): string {let o: { type?: string; message?: { content?: unknown } }try {@@ -42,8 +71,8 @@ function formatLine(line: string): string {.map((c: { type?: string; text?: string; name?: string; input?: unknown }) => {if (c.type === 'text') return c.text ?? ''if (c.type === 'tool_use') {- const input = c.input ? JSON.stringify(c.input) : ''- return `→ ${c.name}${input ? ` ${input.slice(0, 120)}` : ''}`+ const arg = toolArg(c.name, c.input)+ return `$ ${c.name}${arg ? ` ${arg}` : ''}`}return ''})@@ -54,10 +83,7 @@ function formatLine(line: string): string {return content.map((c: { type?: string; text?: string; content?: unknown }) => {if (c.type === 'text') return c.text ?? ''- if (c.type === 'tool_result') {- const r = textOf(c.content)- return r ? `⮑ ${r.slice(0, 400)}` : ''- }+ if (c.type === 'tool_result') return summarizeResult(c.content)return ''}).filter(Boolean)diff --git a/src/main/workspace-store.ts b/src/main/workspace-store.tsindex c73553ad4..28a9613c5 100644--- a/src/main/workspace-store.ts+++ b/src/main/workspace-store.ts@@ -34,7 +34,12 @@ export class WorkspaceStore {}async save(workspace: Workspace): Promise<void> {- await fs.writeFile(this.filePath, JSON.stringify(workspace, null, 2), 'utf-8')+ // Atomic write: a crash/kill mid-write to the real file would truncate it, and a+ // corrupt workspace.json silently loads as empty (total layout loss). Write to a+ // temp file then rename (atomic on the same filesystem).+ const tmp = `${this.filePath}.tmp`+ await fs.writeFile(tmp, JSON.stringify(workspace, null, 2), 'utf-8')+ await fs.rename(tmp, this.filePath)}}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 833829f7f..c1c936f2f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,4 +1,4 @@-import { clipboard, contextBridge, ipcRenderer } from 'electron'+import { clipboard, contextBridge, ipcRenderer, webUtils } from 'electron'import { IPC } from '../shared/ipc'import type {NodeTerminalApi,@@ -12,6 +12,7 @@ const api: NodeTerminalApi = {create: (options: PtyCreateOptions) => ipcRenderer.invoke(IPC.ptyCreate, options),write: (sessionId, data) => ipcRenderer.send(IPC.ptyWrite, sessionId, data),resize: (sessionId, cols, rows) => ipcRenderer.send(IPC.ptyResize, sessionId, cols, rows),+ setFlow: (sessionId, resume) => ipcRenderer.send(IPC.ptyFlow, sessionId, resume),kill: (sessionId) => ipcRenderer.send(IPC.ptyKill, sessionId),destroy: (persistKey) => ipcRenderer.send(IPC.ptyDestroy, persistKey),generateName: (persistKey, cwd) => ipcRenderer.invoke(IPC.ptyGenerateName, persistKey, cwd),@@ -92,6 +93,15 @@ const api: NodeTerminalApi = {announcements: {fetch: () => ipcRenderer.invoke(IPC.announcementsFetch)},+ 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)+ }+ },onMarkdownToggle: (listener) => {const handler = () => listener()ipcRenderer.on(IPC.appToggleMarkdown, handler)@@ -103,6 +113,9 @@ const api: NodeTerminalApi = {return () => ipcRenderer.removeListener(IPC.appCloseNode, handler)},closeWindow: () => ipcRenderer.send(IPC.appCloseWindow),+ setBadgeCount: (count) => ipcRenderer.send(IPC.appSetBadge, count),+ // Absolute path of a dropped/picked File (File.path was removed in Electron 30+).+ getPathForFile: (file: File) => webUtils.getPathForFile(file),notify: (payload) => ipcRenderer.invoke(IPC.appNotify, payload),onFocusNode: (listener) => {const handler = (_e: unknown, nodeId: string) => listener(nodeId)diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 34d367a37..d1a58197f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,13 +1,17 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import {+ addEdge,Background,BackgroundVariant,Controls,+ MarkerType,MiniMap,ReactFlow,SelectionMode,+ useEdgesState,useNodesState,useReactFlow,+ type Connection,type Viewport} from '@xyflow/react'import type { Edge, Node } from '@xyflow/react'@@ -59,7 +63,7 @@ import { LoopNode } from '../nodes/LoopNode'import { branchClaudeSession } from '../lib/claudeBranch'import { useSettings } from '../state/settings'import {- CLAUDE_LAUNCH,+ claudeLaunchCommand,COLLAPSED_HEIGHT,createClaudeNode,createDiffNode,@@ -70,14 +74,30 @@ import {flowToNodeStates,groupSelectedNodes,nodeStatesToFlow,+ setBridgeConfigPath,ungroupNodes,type CanvasNode} from '../state/workspace'const GRID = 24+// Stable identity for the common case of no subagent/loop fan-out, so the ephemeral+// memo doesn't allocate fresh arrays on every node change (e.g. each drag frame).+const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {+ ephemeralNodes: [],+ ephemeralEdges: []+}+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 }>+ >({})const [dirty, setDirty] = useState(false)const [zoomPct, setZoomPct] = useState(100)const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)@@ -110,7 +130,7 @@ export function Canvas() {const committedRef = useRef<CanvasNode[]>([])const draggingRef = useRef(false)const [, bumpHist] = useState(0)- const { setViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =+ const { setViewport, getViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =useReactFlow()const activeProjectId = useProjects((s) => s.activeProjectId)@@ -140,6 +160,12 @@ export function Canvas() {// Selection state for ephemeral nodes (they live outside React Flow's managed nodes).const [ephSel, setEphSel] = useState<Record<string, boolean>>({})const { ephemeralNodes, ephemeralEdges } = useMemo(() => {+ // Common case: no /loop running and no subagents → return a stable empty result so+ // this memo (which depends on `nodes`, i.e. recomputes every drag frame) stays cheap+ // and doesn't churn array identity downstream.+ const hasLoops = Object.values(claudeById).some((s) => s.loop)+ const hasAgents = Object.keys(agentById).length > 0+ if (!hasLoops && !hasAgents) return NO_EPHEMERAL// Explicit width/height for an ephemeral node (so it resizes like any other node).// Defaults switch with expand; a user resize override wins.const dims = (id: string, baseW: number, expW: number, baseH: number, expH: number) => {@@ -181,6 +207,7 @@ export function Canvas() {eEdges.push({id: `e-${lid}`,source: pid,+ sourceHandle: 'flow-out',target: lid,animated: st.state === 'working',style: { stroke: '#bf7af0', strokeWidth: 1.5 }@@ -227,6 +254,7 @@ export function Canvas() {eEdges.push({id: `e-${cid}`,source: pid,+ sourceHandle: 'flow-out',target: cid,animated: v.state === 'working',style: { stroke: '#d97757', strokeWidth: 1.5 }@@ -236,9 +264,52 @@ export function Canvas() {return { ephemeralNodes: eNodes, ephemeralEdges: eEdges }}, [agentById, claudeById, ephemeralPos, ephSizes, ephExpanded, ephSel, nodes])+ // Merge the persisted nodes with the ephemeral ones once per change (not per render),+ // so React Flow's array-identity short-circuit holds while panning/zooming.+ const allNodes = useMemo(+ () => (ephemeralNodes.length ? [...nodes, ...ephemeralNodes] : nodes),+ [nodes, ephemeralNodes]+ )++ // Bridge edges decorated with live activity (count badge + animation while messaging).+ const accent = settings.accent+ const displayEdges = useMemo(() => {+ const decorated = bridgeEdges.map((e) => {+ const act = bridgeActivity[e.id]+ const sel = !!e.selected+ const stroke = sel ? '#ffffff' : act?.stopped ? '#ff9f0a' : accent+ return {+ ...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',+ labelStyle: { fill: stroke, fontSize: 11, fontWeight: 600 },+ labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },+ labelBgPadding: [6, 3] as [number, number],+ labelBgBorderRadius: 5,+ style: { stroke, strokeWidth: sel ? 3.5 : 2 },+ markerEnd: { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 },+ markerStart: { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 }+ }+ })+ return ephemeralEdges.length ? [...decorated, ...ephemeralEdges] : decorated+ }, [bridgeEdges, bridgeActivity, 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()@@ -267,6 +338,8 @@ 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({})// Reset history for the newly loaded project.committedRef.current = flowpastRef.current = []@@ -301,7 +374,15 @@ export function Canvas() {// ---- persistence helpers ----const commitActiveToStore = useCallback(() => {const id = useProjects.getState().activeProjectId- if (id) useProjects.getState().commitCanvas(id, flowToNodeStates(nodesRef.current), viewportRef.current)+ if (id)+ useProjects+ .getState()+ .commitCanvas(+ id,+ flowToNodeStates(nodesRef.current),+ viewportRef.current,+ bridgeEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target }))+ )}, [])const writeDisk = useCallback(async () => {@@ -401,6 +482,132 @@ export function Canvas() {[onNodesChange, markDirty])+ const isClaudeNode = useCallback((id: string) => {+ const n = nodesRef.current.find((x) => x.id === id)+ return n?.type === 'terminal' && ((n.data.tags as string[]) ?? []).includes('claude')+ }, [])++ // Draw a bridge link between two Claude nodes (the connection that lets them message).+ const onConnect = useCallback(+ (c: Connection) => {+ if (!c.source || !c.target || c.source === c.target) return+ if (!isClaudeNode(c.source) || !isClaudeNode(c.target)) return+ // No duplicate link (in either direction).+ const exists = bridgeEdgesRef.current.some(+ (e) =>+ (e.source === c.source && e.target === c.target) ||+ (e.source === c.target && e.target === c.source)+ )+ if (exists) return+ setBridgeEdges((es) =>+ addEdge(+ { id: `bridge-${c.source}-${c.target}`, source: c.source!, target: c.target!, type: 'default' },+ es+ )+ )+ markDirty()+ },+ [isClaudeNode, setBridgeEdges, markDirty]+ )++ // Double-click a bridge 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))+ markDirty()+ },+ [setBridgeEdges, 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`.+ 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)+ 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 }[]> = {}+ 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) })+ }+ const t = setTimeout(() => void window.nodeTerminal.bridge.setTopology(topo), 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)+ })+ }, [])++ // Reflect Claude nodes with unread output as a macOS Dock badge count (across all projects).+ useEffect(() => {+ const count = Object.values(claudeById).filter((s) => s?.unread).length+ window.nodeTerminal.setBadgeCount(count)+ }, [claudeById])++ // Prevent a stray file drop (outside a terminal body) from navigating the whole window to+ // the dropped file. Terminal nodes handle their own drop and stopPropagation, so this only+ // catches drops on empty canvas / other UI.+ useEffect(() => {+ const prevent = (e: DragEvent) => {+ if (Array.from(e.dataTransfer?.types ?? []).includes('Files')) e.preventDefault()+ }+ window.addEventListener('dragover', prevent)+ window.addEventListener('drop', prevent)+ return () => {+ window.removeEventListener('dragover', prevent)+ window.removeEventListener('drop', prevent)+ }+ }, [])++ // Pinch-zoom (trackpad / ctrl+wheel) must keep working even over a focused terminal, which+ // carries `nowheel` so plain scroll stays inside xterm. React Flow ignores wheel over a+ // nowheel element, so we zoom-to-cursor manually there; on open canvas React Flow handles it.+ useEffect(() => {+ const wrap = flowWrapRef.current+ if (!wrap) return+ const onWheel = (e: WheelEvent) => {+ if (!e.ctrlKey) return // only the pinch gesture (browsers deliver it as ctrl+wheel)+ const target = e.target as Element | null+ if (!target?.closest('.nowheel')) return // open canvas → leave it to React Flow+ e.preventDefault()+ e.stopPropagation()+ const { x, y, zoom } = getViewport()+ const rect = wrap.getBoundingClientRect()+ const px = e.clientX - rect.left+ const py = e.clientY - rect.top+ const next = Math.min(2, Math.max(0.2, zoom * Math.exp(-e.deltaY * 0.01)))+ if (next === zoom) return+ const k = next / zoom+ setViewport({ x: px - (px - x) * k, y: py - (py - y) * k, zoom: next })+ }+ wrap.addEventListener('wheel', onWheel, { capture: true, passive: false })+ return () => wrap.removeEventListener('wheel', onWheel, { capture: true })+ }, [getViewport, setViewport])+/** Flow-space point at the center of the visible canvas (for dock-added nodes). */const viewCenter = useCallback(() => {const rect = flowWrapRef.current?.getBoundingClientRect()@@ -545,7 +752,17 @@ export function Canvas() {const tag = (document.activeElement?.tagName || '').toLowerCase()if (tag === 'input' || tag === 'textarea') returnconst ids = nodesRef.current.filter((n) => n.selected).map((n) => n.id)- if (!ids.length) return+ if (!ids.length) {+ // No node selected → remove any selected bridge link(s).+ const edgeIds = bridgeEdgesRef.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)))+ markDirty()+ }+ return+ }e.preventDefault()setConfirm({message: `Delete ${ids.length} ${ids.length > 1 ? 'nodes' : 'node'}? Open terminal sessions will end.`,@@ -557,7 +774,7 @@ export function Canvas() {}window.addEventListener('keydown', onKey)return () => window.removeEventListener('keydown', onKey)- }, [deleteNodes])+ }, [deleteNodes, setBridgeEdges, 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.@@ -635,7 +852,7 @@ export function Canvas() {const copy = duplicateNode(source)copy.data = {...copy.data,- initialCommand: `${CLAUDE_LAUNCH} -r ${originalId}`,+ initialCommand: `${claudeLaunchCommand()} -r ${originalId}`,title: `${source.data.title} (original)`}copy.position = {@@ -861,25 +1078,37 @@ export function Canvas() {)// Title/color/text edits go through updateNodeData; watch them so they persist too.+ // Computed only when the `nodes` array changes (not on every Canvas render — e.g. zoom+ // readout, hover, menu — which would otherwise rebuild this whole string each frame).+ const dataSignature = useMemo(+ () =>+ nodes+ .map(+ (n) =>+ `${n.id}:${n.data.title}:${n.data.color}:${n.data.text ?? ''}:${+ n.data.collapsed ? 1 : 0+ }:${((n.data.tags as string[]) ?? []).join(',')}`+ )+ .join('|'),+ [nodes]+ )useEffect(() => {markDirty()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- nodes- .map(- (n) =>- `${n.id}:${n.data.title}:${n.data.color}:${n.data.text ?? ''}:${- n.data.collapsed ? 1 : 0- }:${((n.data.tags as string[]) ?? []).join(',')}`- )- .join('|')- ])+ }, [dataSignature, markDirty])+ const zoomRafRef = useRef<number | null>(null)const onMove = useCallback((_e: unknown, vp: Viewport) => {viewportRef.current = vp- setZoomPct(Math.round(vp.zoom * 100))markDirty()+ // Coalesce the zoom-% readout to one update per frame so a zoom gesture doesn't+ // re-render the whole Canvas on every intermediate viewport event.+ if (zoomRafRef.current == null) {+ zoomRafRef.current = requestAnimationFrame(() => {+ zoomRafRef.current = null+ setZoomPct(Math.round(viewportRef.current.zoom * 100))+ })+ }},[markDirty])@@ -1226,10 +1455,13 @@ export function Canvas() {<div className="flow-wrap" ref={flowWrapRef}><ReactFlow- nodes={ephemeralNodes.length ? [...nodes, ...ephemeralNodes] : nodes}- edges={ephemeralEdges}+ nodes={allNodes}+ edges={displayEdges}nodeTypes={nodeTypes}onNodesChange={handleNodesChange}+ onEdgesChange={onBridgeEdgesChange}+ onConnect={onConnect}+ onEdgeDoubleClick={onEdgeDoubleClick}onMove={onMove}onNodeDragStart={() => (draggingRef.current = true)}onNodeDragStop={() => {diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsxindex dfc54db01..5447f705a 100644--- a/src/renderer/components/SourceControlPanel.tsx+++ b/src/renderer/components/SourceControlPanel.tsx@@ -195,9 +195,12 @@ export function SourceControlPanel({</div><div className="drawer__body scm-body">- {status.ghAvailable && !status.ghAuthed && (+ {/* Only nag when gh is actually needed (publishing a repo with no remote yet).+ With a remote, push/pull/sync use git's credential helper (macOS keychain /+ the same creds your IDE uses), so a gh login isn't required. */}+ {status.ghAvailable && !status.ghAuthed && !status.hasRemote && (<div className="scm-signin">- <span>Not signed in to GitHub.</span>+ <span>Sign in to GitHub to publish this repo.</span><buttononClick={() => {onRunInTerminal('gh auth login')diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex c9b05b597..c3c2cced4 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1,5 +1,12 @@import { useEffect, useRef, useState } from 'react'-import { Handle, NodeResizer, Position, useReactFlow, type NodeProps } from '@xyflow/react'+import {+ Handle,+ NodeResizer,+ Position,+ useReactFlow,+ useUpdateNodeInternals,+ type NodeProps+} from '@xyflow/react'import { Terminal } from '@xterm/xterm'import { FitAddon } from '@xterm/addon-fit'import { renderMarkdown } from '../lib/markdown'@@ -12,21 +19,33 @@ import { useClaudeStatus } from '../state/claudeStatus'import { useAgentNodes } from '../state/agentNodes'import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'+/** Backslash-escape shell-special characters, like a native terminal does on file drop. */+function escapeDroppedPath(p: string): string {+ return p.replace(/([ \t"'`\\()&;|<>$!*?[\]{}#~])/g, '\\$1')+}+/*** A single terminal node: header (collapse + color + title + close), optional tag chips,* and a real xterm.js terminal. A hover guard delays entering the terminal so the canvas* can be panned across terminals without grabbing focus. Cmd/Ctrl+M (while hovered)- * toggles a markdown view of the terminal's output.+ * toggles a markdown view of the terminal's output. Files dropped from Finder are pasted+ * as their (escaped) paths, like a native terminal — so Claude can read dropped images.*/export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {const { updateNodeData, deleteElements, getZoom, setNodes } = useReactFlow()- const settings = useSettings((s) => s.settings)+ // Scoped selectors (not the whole settings object) so this node only re-renders when a+ // field it actually uses changes — not on every unrelated settings edit.+ const panHoverDelay = useSettings((s) => s.settings.panHoverDelay)+ const fontSize = useSettings((s) => s.settings.fontSize)+ const fontFamily = useSettings((s) => s.settings.fontFamily)+ const cursorBlink = useSettings((s) => s.settings.cursorBlink)const bodyRef = useRef<HTMLDivElement>(null)const termRef = useRef<Terminal | null>(null)const fitRef = useRef<FitAddon | null>(null)const dwellRef = useRef<ReturnType<typeof setTimeout> | null>(null)const [showColors, setShowColors] = useState(false)const [armed, setArmed] = useState(true)+ const [dropping, setDropping] = useState(false)const [naming, setNaming] = useState(false)const [mdHtml, setMdHtml] = useState('')const [editingTitle, setEditingTitle] = useState(false)@@ -36,6 +55,13 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {const tags = (data.tags as string[]) ?? []const isClaude = tags.includes('claude')const status = useClaudeStatus((s) => s.byId[id])+ const updateNodeInternals = useUpdateNodeInternals()++ // The bridge handles are added/positioned dynamically for Claude nodes; make React Flow+ // re-measure them so edges anchor to the (centered) handle, not a stale position.+ useEffect(() => {+ if (isClaude) updateNodeInternals(id)+ }, [isClaude, id, updateNodeInternals])// Terminal lifecycle — set up exactly once.useEffect(() => {@@ -95,7 +121,29 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {return}sessionId = sid- cleanups.push(transport.onData(sid, (chunk) => term.write(chunk)))+ // Flow control: track xterm's unprocessed write backlog (bytes handed to+ // term.write but not yet parsed). Past a high watermark we pause the source so+ // a flood can't grow this buffer without bound; we resume once it drains.+ let pending = 0+ let paused = false+ const HIGH_WATER = 1 << 20 // 1 MB+ const LOW_WATER = 1 << 18 // 256 KB+ cleanups.push(+ transport.onData(sid, (chunk) => {+ pending += chunk.length+ if (!paused && pending > HIGH_WATER) {+ paused = true+ transport.setFlow(sid, false)+ }+ term.write(chunk, () => {+ pending -= chunk.length+ if (paused && pending < LOW_WATER) {+ paused = false+ transport.setFlow(sid, true)+ }+ })+ })+ )cleanups.push(transport.onExit(sid, (code) => {term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)@@ -140,15 +188,15 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {useEffect(() => {const term = termRef.currentif (!term) return- term.options.fontSize = settings.fontSize- term.options.fontFamily = settings.fontFamily- term.options.cursorBlink = settings.cursorBlink+ term.options.fontSize = fontSize+ term.options.fontFamily = fontFamily+ term.options.cursorBlink = cursorBlinktry {fitRef.current?.fit()} catch {// ignore}- }, [settings.fontSize, settings.fontFamily, settings.cursorBlink])+ }, [fontSize, fontFamily, cursorBlink])const toggleCollapse = () =>setNodes((ns) =>@@ -175,7 +223,7 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {termRef.current?.focus()useClaudeStatus.getState().setActive(id, true)useClaudeStatus.getState().clearUnread(id)- }, settings.panHoverDelay)+ }, panHoverDelay)}const onBodyLeave = () => {if (dwellRef.current) clearTimeout(dwellRef.current)@@ -189,6 +237,38 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {if (dwellRef.current) clearTimeout(dwellRef.current)}+ // ---- file drop: paste dropped file paths into the terminal (native-terminal behavior) ----+ const onBodyDragOver = (e: React.DragEvent) => {+ if (!Array.from(e.dataTransfer.types).includes('Files')) return+ e.preventDefault()+ e.dataTransfer.dropEffect = 'copy'+ if (!dropping) setDropping(true)+ }+ const onBodyDragLeave = (e: React.DragEvent) => {+ const rt = e.relatedTarget as Node | null+ if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)+ }+ const onBodyDrop = (e: React.DragEvent) => {+ const files = Array.from(e.dataTransfer.files)+ setDropping(false)+ if (!files.length) return+ e.preventDefault()+ e.stopPropagation()+ const paths = files+ .map((f) => window.nodeTerminal.getPathForFile(f))+ .filter(Boolean)+ .map(escapeDroppedPath)+ if (!paths.length) return+ const term = termRef.current+ if (!term) return+ // Enter the terminal and paste the path(s) like a real drop (trailing space to continue).+ if (dwellRef.current) clearTimeout(dwellRef.current)+ setArmed(false)+ term.focus()+ term.paste(paths.join(' ') + ' ')+ useClaudeStatus.getState().setActive(id, true)+ }+const nameWithAi = async () => {setNaming(true)const r = await window.nodeTerminal.pty.generateName(id, (data.cwd as string) ?? '')@@ -224,13 +304,34 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {onMouseLeave={() => (hoveredRef.current = false)}><NodeResizer minWidth={260} minHeight={160} isVisible={selected && !collapsed} color="#0a84ff" />- {/* Invisible source handle so edges to subagent nodes can attach. */}+ {/* Invisible source handle so edges to subagent/loop nodes can attach. */}<Handle+ id="flow-out"type="source"position={Position.Bottom}isConnectable={false}style={{ opacity: 0, pointerEvents: 'none', bottom: 0 }}/>+ {/* Bridge link handles (Claude nodes only): drag right→left to connect two sessions.+ Vertically centered on the side edges; raised above the body so they're never buried. */}+ {isClaude && (+ <>+ <Handle+ id="bridge-out"+ type="source"+ position={Position.Right}+ className="bridge-handle bridge-handle--out"+ data-tip="Bridge out — drag to another Claude node to link their sessions"+ />+ <Handle+ id="bridge-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"+ />+ </>+ )}<div className="term-node__header"><button className="term-node__collapse" title={collapsed ? 'Expand' : 'Collapse'} onClick={toggleCollapse}>@@ -342,7 +443,14 @@ export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {)}{/* Body always mounted (keeps xterm alive); hidden via CSS when collapsed. */}- <div className="term-node__body" onMouseEnter={onBodyEnter} onMouseLeave={onBodyLeave}>+ <div+ className={`term-node__body${dropping ? ' dropping' : ''}`}+ onMouseEnter={onBodyEnter}+ onMouseLeave={onBodyLeave}+ onDragOver={onBodyDragOver}+ onDragLeave={onBodyDragLeave}+ onDrop={onBodyDrop}+ ><div className="term-node__xterm nodrag nowheel" ref={bodyRef} />{armed && !mdMode && (<divdiff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex d29fd3782..1e5705f29 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -1,5 +1,5 @@import { create } from 'zustand'-import type { CanvasNodeState, Project, Viewport, Workspace } from '@shared/types'+import type { BridgeLink, CanvasNodeState, Project, Viewport, Workspace } from '@shared/types'import { createProject } from './workspace'interface ProjectsState {@@ -14,8 +14,8 @@ interface ProjectsState {addProject(name?: string, cwd?: string): ProjectrenameProject(id: string, name: string): voidsetProjectCwd(id: string, cwd: string): void- /** Writes the serialized canvas (nodes + viewport) back into a project. */- commitCanvas(id: string, nodes: CanvasNodeState[], viewport: Viewport): void+ /** Writes the serialized canvas (nodes + viewport + bridge links) back into a project. */+ commitCanvas(id: string, nodes: CanvasNodeState[], viewport: Viewport, bridges?: BridgeLink[]): void/** Removes a project; returns the id that should become active (never deletes the last one). */deleteProject(id: string): string@@ -56,9 +56,11 @@ export const useProjects = create<ProjectsState>((set, get) => ({}))},- commitCanvas(id, nodes, viewport) {+ commitCanvas(id, nodes, viewport, bridges) {set((s) => ({- projects: s.projects.map((p) => (p.id === id ? { ...p, nodes, viewport } : p))+ projects: s.projects.map((p) =>+ p.id === id ? { ...p, nodes, viewport, ...(bridges ? { bridges } : {}) } : p+ )}))},diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 6a121a485..328167e6a 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -83,12 +83,25 @@ 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`.+ */+let bridgeConfigPath = ''+export function setBridgeConfigPath(p: string): void {+ bridgeConfigPath = p+}+/*** 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. Append `-r <id>` to resume a specific session (used by Branch).+ * `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).*/-export const CLAUDE_LAUNCH = 'claude'+export function claudeLaunchCommand(): string {+ return bridgeConfigPath ? `claude --mcp-config "${bridgeConfigPath}"` : 'claude'+}/** Creates a terminal that launches Claude Code (`claude`) on open. */export function createClaudeNode(@@ -109,7 +122,7 @@ export function createClaudeNode(group: null,tags: ['claude'],cwd,- initialCommand: CLAUDE_LAUNCH+ initialCommand: claudeLaunchCommand()}}}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex f987cd0bd..308b81f2f 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -414,6 +414,58 @@ body,border-color: var(--accent);}+/* Bridge link handles (Claude nodes): dots on the header row, on top of the node so they're+ never buried under the terminal body. Subtle until you hover the node, then prominent. */+.react-flow__handle.bridge-handle {+ width: 13px;+ height: 13px;+ background: var(--accent);+ border: 2px solid var(--panel);+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);+ opacity: 0.4;+ z-index: 20;+ transition: opacity 0.12s ease, transform 0.12s ease;+}+.react-flow__node:hover .react-flow__handle.bridge-handle,+.react-flow__node.selected .react-flow__handle.bridge-handle {+ opacity: 1;+}+.react-flow__handle.bridge-handle:hover {+ transform: scale(1.6);+ opacity: 1;+}++/* Hover explanation for the bridge handles (CSS tooltip via the data-tip attribute). */+.react-flow__handle.bridge-handle[data-tip]::after {+ content: attr(data-tip);+ position: absolute;+ bottom: calc(100% + 8px);+ white-space: nowrap;+ padding: 5px 9px;+ border-radius: 6px;+ background: #0a0a0c;+ border: 1px solid var(--border);+ color: var(--label);+ font-size: 11px;+ font-weight: 500;+ line-height: 1;+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.5);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.12s ease;+ z-index: 50;+}+/* Grow inward over the node so the label never runs off-screen. */+.react-flow__handle.bridge-handle--out[data-tip]::after {+ right: 50%;+}+.react-flow__handle.bridge-handle--in[data-tip]::after {+ left: 50%;+}+.react-flow__handle.bridge-handle:hover[data-tip]::after {+ opacity: 1;+}+.term-node__header {display: flex;align-items: center;@@ -605,6 +657,24 @@ body,background: var(--bg);}+/* Drop-target hint while dragging a file from Finder into the terminal. */+.term-node__body.dropping::after {+ content: 'Drop to insert path';+ position: absolute;+ inset: 0;+ z-index: 30;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ font-weight: 600;+ color: var(--accent);+ background: color-mix(in srgb, var(--accent) 12%, transparent);+ border: 2px dashed var(--accent);+ border-radius: 6px;+ pointer-events: none;+}+.term-node__xterm {position: absolute;inset: 0;diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.tsindex 4e568abf7..2224487fe 100644--- a/src/renderer/terminal/local-transport.ts+++ b/src/renderer/terminal/local-transport.ts@@ -23,6 +23,10 @@ export class LocalTransport implements TerminalTransport {this.pty.resize(sessionId, cols, rows)}+ setFlow(sessionId: string, resume: boolean): void {+ this.pty.setFlow(sessionId, resume)+ }+kill(sessionId: string): void {this.pty.kill(sessionId)}diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.tsindex 3be43a485..dad01a6ec 100644--- a/src/renderer/terminal/transport.ts+++ b/src/renderer/terminal/transport.ts@@ -12,6 +12,8 @@ export interface TerminalTransport {create(options: PtyCreateOptions): Promise<string>write(sessionId: string, data: string): voidresize(sessionId: string, cols: number, rows: number): void+ /** Flow control: pause (false) / resume (true) the source when the terminal is backed up. */+ setFlow(sessionId: string, resume: boolean): void/** Detaches the client; with tmux the underlying session survives. */kill(sessionId: string): void/** Permanently ends a node's persistent session. */diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 815233906..cc7d30f65 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -4,6 +4,7 @@ export const IPC = {ptyCreate: 'pty:create',ptyWrite: 'pty:write',ptyResize: 'pty:resize',+ ptyFlow: 'pty:flow',ptyKill: 'pty:kill',ptyDestroy: 'pty:destroy',ptyGenerateName: 'pty:generate-name',@@ -14,8 +15,12 @@ export const IPC = {appCloseWindow: 'app:close-window',appNotify: 'app:notify',appFocusNode: 'app:focus-node',+ appSetBadge: 'app:set-badge',claudeStatus: 'claude:status',claudeSubagentActivity: 'claude:subagent-activity',+ bridgeConfigPath: 'bridge:config-path',+ bridgeSetTopology: 'bridge:set-topology',+ bridgeMessage: 'bridge:message',appUpdateAvailable: 'app:update-available',appUpdateDownloaded: 'app:update-downloaded',appRestartToUpdate: 'app:restart-to-update',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 5a4ea14d6..94a42662b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -48,6 +48,13 @@ export interface Viewport {zoom: number}+/** A persistent "bridge" link between two Claude nodes (lets their sessions message each other). */+export interface BridgeLink {+ id: string+ source: string+ target: string+}+/** A project is one canvas/page: its own nodes, viewport, and default working dir. */export interface Project {id: string@@ -57,6 +64,8 @@ export interface Project {cwd?: stringviewport: Viewportnodes: CanvasNodeState[]+ /** Bridge links between Claude nodes (optional; absent in pre-bridge files). */+ bridges?: BridgeLink[]}/** The full workspace written to / read from disk. */@@ -91,6 +100,8 @@ export interface PtyApi {write(sessionId: string, data: string): void/** Updates the PTY when the terminal is resized. */resize(sessionId: string, cols: number, rows: number): void+ /** Flow control: pause (false) or resume (true) reading the PTY when xterm is backed up. */+ setFlow(sessionId: string, resume: boolean): void/** Detaches/terminates the PTY client (the underlying tmux session survives). */kill(sessionId: string): void/** Permanently ends the persistent session for a node (kills its tmux session). */@@ -341,6 +352,38 @@ 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+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -352,12 +395,17 @@ export interface NodeTerminalApi {fs: FsApiupdates: UpdateApiannouncements: AnnouncementsApi+ bridge: BridgeApi/** Fires when the user presses Cmd/Ctrl+M (toggle markdown view). Returns unsubscribe. */onMarkdownToggle(listener: () => void): () => void/** Fires when the user presses Cmd/Ctrl+W (close selected node). Returns unsubscribe. */onCloseNode(listener: () => void): () => void/** Close the application window (Cmd/Ctrl+W fallback when no node is selected). */closeWindow(): void+ /** Set the macOS Dock badge to the unread-message count (0 clears it). */+ setBadgeCount(count: number): void+ /** Absolute filesystem path for a dropped/picked File (for drag-into-terminal). */+ getPathForFile(file: File): string/** Show an OS notification (main suppresses it if the window is focused). Returns whether shown. */notify(payload: NotifyPayload): Promise<boolean>/** Fires when a notification is clicked, asking the renderer to focus a node. Returns unsubscribe. */