Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

perf: unblock main-process I/O and cut renderer churn

enes74fd8cd11360
diff --git a/package-lock.json b/package-lock.json
index c4c34d5d7..48305094d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -29,6 +29,7 @@
"@vitejs/plugin-react": "^4.3.1",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.15.0",
+ "@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.3.0",
"electron": "^31.3.0",
@@ -2850,6 +2851,16 @@
"@xterm/xterm": "^5.0.0"
}
},
+ "node_modules/@xterm/addon-webgl": {
+ "version": "0.18.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.18.0.tgz",
+ "integrity": "sha512-xCnfMBTI+/HKPdRnSOHaJDRqEpq2Ugy8LEj9GiY4J3zJObo3joylIFaMvzBwbYRg8zLtkO0KQaStCeSfoaI2/w==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@xterm/xterm": "^5.0.0"
+ }
+ },
"node_modules/@xterm/xterm": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
diff --git a/package.json b/package.json
index 1bb1697f2..3ab794545 100644
--- a/package.json
+++ b/package.json
@@ -85,6 +85,7 @@
"@vitejs/plugin-react": "^4.3.1",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.15.0",
+ "@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.3.0",
"electron": "^31.3.0",
diff --git a/src/main/context-tail.ts b/src/main/context-tail.ts
index 09619ca6a..8e04dd8d7 100644
--- a/src/main/context-tail.ts
+++ b/src/main/context-tail.ts
@@ -51,6 +51,8 @@ interface Tracked {
lastUsed: number
lastModel: string | null
lastWindow: number
+ /** An async read is in flight — the next tick skips this session instead of double-reading. */
+ reading: boolean
}
export interface ContextTail {
@@ -80,56 +82,67 @@ export function createContextTail(win: BrowserWindow): ContextTail {
// Read newly-appended transcript bytes (if any), reconcile the window from the model
// resolver, and push when the used tokens / model / window changed since the last push.
- const read = (sessionId: string, t: Tracked): void => {
- let size = -1
+ // Async fs throughout: this runs every second per tracked session, and sync syscalls here
+ // sat on the same main thread that services all PTY streaming and IPC.
+ const read = async (sessionId: string, t: Tracked): Promise<void> => {
+ if (t.reading) return
+ t.reading = true
try {
- size = fs.statSync(t.path).size
- } catch {
- // file not created yet / unreadable — skip the byte read, still reconcile below
- }
- if (size >= 0) {
- if (size < t.offset) t.offset = 0 // truncated/rotated → re-read from start
- // First read of a large transcript: skip to the last INITIAL_READ_CAP bytes.
- if (t.offset === 0 && size > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAP
- if (size > t.offset) {
- let chunk = ''
- try {
- const fd = fs.openSync(t.path, 'r')
- const buf = Buffer.alloc(size - t.offset)
- fs.readSync(fd, buf, 0, buf.length, t.offset)
- fs.closeSync(fd)
- chunk = buf.toString('utf-8')
- t.offset = size
- } catch {
- return
- }
- const latest = parseLatestUsage(chunk)
- if (latest) {
- t.used = latest.used
- t.model = latest.model ?? t.model
+ let size = -1
+ try {
+ size = (await fs.promises.stat(t.path)).size
+ } catch {
+ // file not created yet / unreadable — skip the byte read, still reconcile below
+ }
+ if (size >= 0) {
+ if (size < t.offset) t.offset = 0 // truncated/rotated → re-read from start
+ // First read of a large transcript: skip to the last INITIAL_READ_CAP bytes.
+ if (t.offset === 0 && size > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAP
+ if (size > t.offset) {
+ let chunk = ''
+ try {
+ const fd = await fs.promises.open(t.path, 'r')
+ try {
+ const buf = Buffer.alloc(size - t.offset)
+ await fd.read(buf, 0, buf.length, t.offset)
+ chunk = buf.toString('utf-8')
+ t.offset = size
+ } finally {
+ await fd.close()
+ }
+ } catch {
+ return
+ }
+ const latest = parseLatestUsage(chunk)
+ if (latest) {
+ t.used = latest.used
+ t.model = latest.model ?? t.model
+ }
}
}
- }
- // Reconcile the window every tick: kick off async API resolution once per model
- // (self-gating), and use the best cached/static value now.
- if (t.model) void resolveModelWindow(t.model)
- const win = cachedWindowFor(t.model)
+ // Reconcile the window every tick: kick off async API resolution once per model
+ // (self-gating), and use the best cached/static value now.
+ if (t.model) void resolveModelWindow(t.model)
+ const win = cachedWindowFor(t.model)
- if (
- t.used > 0 &&
- (t.used !== t.lastUsed || t.model !== t.lastModel || win !== t.lastWindow)
- ) {
- t.window = win
- push(sessionId, t)
- t.lastUsed = t.used
- t.lastModel = t.model
- t.lastWindow = win
+ if (
+ t.used > 0 &&
+ (t.used !== t.lastUsed || t.model !== t.lastModel || win !== t.lastWindow)
+ ) {
+ t.window = win
+ push(sessionId, t)
+ t.lastUsed = t.used
+ t.lastModel = t.model
+ t.lastWindow = win
+ }
+ } finally {
+ t.reading = false
}
}
const tick = (): void => {
- for (const [sessionId, t] of sessions) read(sessionId, t)
+ for (const [sessionId, t] of sessions) void read(sessionId, t)
if (!sessions.size && timer) {
clearInterval(timer)
timer = null
@@ -155,10 +168,11 @@ export function createContextTail(win: BrowserWindow): ContextTail {
model: null,
lastUsed: 0,
lastModel: null,
- lastWindow: 0
+ lastWindow: 0,
+ reading: false
}
sessions.set(sessionId, t)
- read(sessionId, t) // immediate first value (resumed sessions already have content)
+ void read(sessionId, t) // immediate first value (resumed sessions already have content)
if (!timer) timer = setInterval(tick, POLL_MS)
},
untrack(sessionId) {
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts
index b4d79c237..d04aefe5b 100644
--- a/src/main/pty-manager.ts
+++ b/src/main/pty-manager.ts
@@ -106,6 +106,51 @@ function findSsh(): string | null {
return cachedSsh ?? null
}
+/**
+ * Resolve the user's REAL login-shell PATH once, and cache it.
+ *
+ * A GUI app launched from Finder/Dock inherits only a minimal PATH
+ * (`/usr/bin:/bin:/usr/sbin:/sbin`) — it never sees `/usr/local/bin`, Homebrew
+ * (`/opt/homebrew/bin`), `~/.local/bin`, nvm, bun, etc. So terminals we spawn would report
+ * `command not found: claude` even though the tool is installed. We run the user's login +
+ * interactive shell (so BOTH profile files and `.zshrc`/`.bashrc` PATH additions are seen) and
+ * read back `$PATH`, printed between sentinels to survive any dotfile noise. Bounded by a timeout;
+ * on any failure (hang, dotfile error, non-POSIX shell, Windows) we fall back to the inherited PATH.
+ */
+let cachedShellPath: string | null | undefined
+let shellPathPromise: Promise<string | null> | null = null
+function resolveShellPath(): Promise<string | null> {
+ if (cachedShellPath !== undefined) return Promise.resolve(cachedShellPath)
+ if (shellPathPromise) return shellPathPromise
+ if (os.platform() === 'win32') {
+ cachedShellPath = null
+ return Promise.resolve(null)
+ }
+ const shell = process.env.SHELL || '/bin/bash'
+ const START = '__NT_PATH_START__'
+ const END = '__NT_PATH_END__'
+ // `-ilc` = login + interactive (matches VS Code's shell-env resolution): sources the profile
+ // files AND the interactive rc (`.zshrc`/`.bashrc`) where users commonly add nvm/bun/etc.
+ // Dotfiles routinely take hundreds of ms (nvm/conda init) and can hang, so this MUST be
+ // async — a synchronous probe here froze every window and all IPC for up to the 5s timeout.
+ // Prewarmed from init(); create() awaits it, so terminals still always get the real PATH.
+ // stderr is captured separately by execFile, so prompt/compinit noise can't pollute stdout.
+ shellPathPromise = runAsync(shell, ['-ilc', `command printf '${START}%s${END}' "$PATH"`], {
+ encoding: 'utf-8',
+ timeout: 5000
+ })
+ .then(({ stdout }) => {
+ const m = stdout.match(new RegExp(`${START}([\\s\\S]*?)${END}`))
+ return m?.[1]?.trim() || null
+ })
+ .catch(() => null) // login shell hung / errored / isn't POSIX — inherited-PATH fallback
+ .then((resolved) => {
+ cachedShellPath = resolved
+ return resolved
+ })
+ return shellPathPromise
+}
+
interface Session {
proc: pty.IPty
/** Renderer webContents to stream output to over IPC, or null for a detached (host) session. */
@@ -157,6 +202,8 @@ export class PtyManager {
/** Must run after app is ready (needs userData path). */
init(getSettings: () => Settings): void {
this.getSettings = getSettings
+ // Prewarm the login-shell PATH probe now so the first terminal spawn doesn't wait on it.
+ void resolveShellPath()
this.tmuxPath = findTmux()
if (!this.tmuxPath) return
this.confPath = path.join(app.getPath('userData'), 'tmux.conf')
@@ -222,16 +269,19 @@ export class PtyManager {
// For an SSH-project node, "fresh" is decided by the REMOTE tmux server (over the project's
// ControlMaster), not the local one. The remote `has-session` is a full network round-trip,
// so it MUST be async (`runAsync`) — a synchronous probe here would freeze every window/IPC
- // for its duration. Falls through to the local tmux/plain logic otherwise (a local socket
- // probe is cheap and stays synchronous).
+ // for its duration. Falls through to the local tmux/plain logic otherwise (also async: a
+ // bulk project load fires one create() per node, and even cheap probes add up serialized).
const fresh = options.sshRemote
? !(await this.remoteSessionExists(
options.sshRemote,
sessionName(options.persistKey as string)
))
: tmuxBacked
- ? !this.tmuxSessionExists(options.persistKey as string)
+ ? !(await this.tmuxSessionExists(options.persistKey as string))
: true
+ // Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)
+ // so the session env below picks it up — awaiting keeps the event loop free either way.
+ await resolveShellPath()
const sessionId = this.spawnSession(options, webContentsId, undefined)
return { sessionId, fresh }
}
@@ -273,13 +323,13 @@ export class PtyManager {
return { controlPath: s.sshRemote.controlPath, conn: s.sshRemote.conn }
}
- /** Whether a tmux session for this node id currently exists (server alive + session present). */
- private tmuxSessionExists(persistKey: string): boolean {
+ /** Whether a tmux session for this node id currently exists (server alive + session present).
+ * Async like the remote probe: a bulk project load fires one `create()` per terminal node,
+ * and a synchronous subprocess per probe would serialize on the main event loop. */
+ private async tmuxSessionExists(persistKey: string): Promise<boolean> {
if (!this.tmuxPath) return false
try {
- execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)], {
- stdio: 'ignore'
- })
+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)])
return true
} catch {
return false
@@ -342,7 +392,17 @@ export class PtyManager {
// For a remote (ssh-project) node the local PTY just holds the ssh client, so its local cwd
// must be a real LOCAL directory (options.cwd is a REMOTE path that wouldn't exist locally and
// would make pty.spawn throw). The remote working dir is passed to tmux via sshRemote.remoteCwd.
- const cwd = options.sshRemote ? os.homedir() : options.cwd || os.homedir()
+ let cwd = options.sshRemote ? os.homedir() : options.cwd || os.homedir()
+ // `|| os.homedir()` only catches an EMPTY cwd. A cwd that is set but STALE — a project folder
+ // the user deleted/unmounted — still reaches pty.spawn and makes posix_spawn fail. Verify the
+ // directory actually exists and fall back to home if not, so a dead folder never kills the node.
+ if (!options.sshRemote) {
+ try {
+ if (!fs.statSync(cwd).isDirectory()) cwd = os.homedir()
+ } catch {
+ cwd = os.homedir()
+ }
+ }
// Strip TMUX so tmux doesn't refuse to nest if the app itself was launched
// from inside a tmux session.
@@ -350,6 +410,15 @@ export class PtyManager {
delete env.TMUX
delete env.TMUX_PANE
+ // A GUI app launched from Finder/Dock inherits only a minimal PATH, so spawned terminals
+ // couldn't find tools in /usr/local/bin, Homebrew, ~/.local/bin, nvm, bun, etc. (the classic
+ // `command not found: claude`). Replace PATH with the user's real login-shell PATH so every
+ // terminal — and any agent CLI it launches — resolves exactly what a normal terminal would.
+ // Reads the cache filled by the async probe: create() awaits it, and the detached/host
+ // paths spawn late enough that the init()-time prewarm has long since settled.
+ const shellPath = cachedShellPath ?? null
+ if (shellPath) env.PATH = shellPath
+
// Agent hooks: each session carries the hook-server coordinates + its node/agent id.
// Our managed hook (installed globally in each agent's config, but a no-op without these
// vars) then posts state back to us for any agent run in this session.
@@ -423,6 +492,10 @@ export class PtyManager {
// The hook-server env (port/token/node id/agent id) is passed explicitly via `-e`
// (one `-e KEY=VALUE` per key) since the shared tmux server can't rely on inherited env.
const hookEnvArgs = Object.entries(hookEnv).flatMap(([k, v]) => ['-e', `${k}=${v}`])
+ // Set the session PATH explicitly too: the tmux server is shared and long-lived (it outlives
+ // the app), so a session created after an app update must NOT inherit a stale minimal PATH
+ // baked into the server env at first launch — `-e` overrides it per new session at creation.
+ const pathEnvArgs = env.PATH ? ['-e', `PATH=${env.PATH}`] : []
const attachFlags = sinks ? ['-A'] : ['-A', '-D']
args = [
'-L',
@@ -432,6 +505,7 @@ export class PtyManager {
'new-session',
...attachFlags,
...hookEnvArgs,
+ ...pathEnvArgs,
'-c',
cwd,
'-s',
@@ -452,13 +526,30 @@ export class PtyManager {
args = program ? programArgs : []
}
- const proc = pty.spawn(file, args, {
- name: 'xterm-256color',
- cols: options.cols,
- rows: options.rows,
- cwd,
- env
- })
+ let proc: pty.IPty
+ try {
+ proc = pty.spawn(file, args, {
+ name: 'xterm-256color',
+ cols: options.cols,
+ rows: options.rows,
+ cwd,
+ env
+ })
+ } catch (err) {
+ // node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno,
+ // so we can't tell EAGAIN/ENFILE apart here. The dominant cause is running out of PTYs/fds
+ // (macOS caps system-wide PTYs at kern.tty.ptmx_max, and this app keeps tmux sessions — and
+ // thus their PTYs — alive across restarts, so they accumulate). Re-throw with the resolved
+ // program + cwd + open-PTY count so the renderer surfaces an actionable message instead of
+ // an opaque stack, and the caller (create) rejects cleanly rather than leaving a blank node.
+ const openPtys = this.sessions.size
+ const reason = err instanceof Error ? err.message : String(err)
+ throw new Error(
+ `Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, live PTYs: ${openPtys}. ` +
+ `On macOS the system PTY limit (kern.tty.ptmx_max) may be exhausted — close unused ` +
+ `terminals or run \`tmux -L ${TMUX_SOCKET} kill-server\` to reclaim leaked sessions.`
+ )
+ }
// tmux-backed sessions snapshot their scrollback to disk periodically so a machine reboot
// (which kills the tmux server) can still replay recent output on cold restart. A remote
@@ -631,7 +722,7 @@ export class PtyManager {
remoteCapturePaneArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey), false),
{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
)
- if (stdout) writeScrollback(persistKey, stdout)
+ if (stdout) await writeScrollback(persistKey, stdout)
} catch {
// remote session gone / master down — keep the last good snapshot
}
@@ -644,7 +735,7 @@ export class PtyManager {
['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', '-1500'],
{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
)
- if (stdout) writeScrollback(persistKey, stdout)
+ if (stdout) await writeScrollback(persistKey, stdout)
} catch {
// session gone / tmux unavailable — keep the last good snapshot
}
@@ -670,11 +761,11 @@ export class PtyManager {
/** Permanently end a node's persistent tmux session (called when the user closes it). */
async destroySession(persistKey: string): Promise<void> {
- // The node is gone for good — drop its cold-restore snapshot too.
- deleteScrollback(persistKey)
// destroy() is called (close button) while the session is still live, so its sshRemote is
// known. Capture it synchronously before any await.
const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
+ // The node is gone for good — drop its cold-restore snapshot too.
+ await deleteScrollback(persistKey)
if (sshRemote) {
// Remote (ssh-project) node: there is no local tmux session — end the REMOTE one.
const ssh = findSsh()
diff --git a/src/main/scrollback-store.ts b/src/main/scrollback-store.ts
index 36764d1fb..b9a09205f 100644
--- a/src/main/scrollback-store.ts
+++ b/src/main/scrollback-store.ts
@@ -34,30 +34,37 @@ function trailing(data: string): Buffer {
return bytes.subarray(start)
}
-export function writeScrollback(persistKey: string, data: string): void {
+// All async (fs.promises): snapshots fire per session on a 15s timer and in bursts when many
+// nodes detach at once (project switch / quit) — sync writes here blocked the main event loop,
+// which stalls PTY streaming and all IPC.
+let writeSeq = 0
+export async function writeScrollback(persistKey: string, data: string): Promise<void> {
if (!data) return
+ const file = snapshotPath(persistKey)
+ // Unique tmp per call: overlapping writes for the same key (timer tick + detach snapshot)
+ // must not interleave into one tmp file and rename a torn write into place.
+ const tmp = `${file}.${++writeSeq}.tmp`
try {
- fs.mkdirSync(dir(), { recursive: true })
- const file = snapshotPath(persistKey)
- const tmp = `${file}.tmp`
- fs.writeFileSync(tmp, trailing(data))
- fs.renameSync(tmp, file)
+ await fs.promises.mkdir(dir(), { recursive: true })
+ await fs.promises.writeFile(tmp, trailing(data))
+ await fs.promises.rename(tmp, file)
} catch {
// best-effort: a failed snapshot just means no cold-restore replay for this node
+ await fs.promises.rm(tmp, { force: true }).catch(() => {})
}
}
-export function readScrollback(persistKey: string): string {
+export async function readScrollback(persistKey: string): Promise<string> {
try {
- return fs.readFileSync(snapshotPath(persistKey), 'utf-8')
+ return await fs.promises.readFile(snapshotPath(persistKey), 'utf-8')
} catch {
return ''
}
}
-export function deleteScrollback(persistKey: string): void {
+export async function deleteScrollback(persistKey: string): Promise<void> {
try {
- fs.rmSync(snapshotPath(persistKey), { force: true })
+ await fs.promises.rm(snapshotPath(persistKey), { force: true })
} catch {
// ignore
}
diff --git a/src/main/transcript-reader.ts b/src/main/transcript-reader.ts
index e38dc0134..24906ef2b 100644
--- a/src/main/transcript-reader.ts
+++ b/src/main/transcript-reader.ts
@@ -181,8 +181,16 @@ export const SESSION_ID_RE = /^[0-9a-fA-F-]{8,64}$/
// Fallback when context-tail isn't tracking the session (e.g. resumed after restart):
// find <sessionId>.jsonl anywhere under ~/.claude/projects/*.
+//
+// The hit is cached: session ids are immutable and a transcript never moves once created,
+// and the renderer polls readSessionName every few seconds PER agent node — without the
+// cache each poll re-scanned every project dir under ~/.claude/projects (heavy Claude users
+// have hundreds). readSessionName drops the entry if the cached path stops being readable.
+const transcriptPathCache = new Map<string, string>()
export async function resolveTranscriptPath(sessionId: string): Promise<string | undefined> {
if (!SESSION_ID_RE.test(sessionId)) return undefined
+ const cached = transcriptPathCache.get(sessionId)
+ if (cached) return cached
const root = path.join(os.homedir(), '.claude', 'projects')
let dirs: string[]
try {
@@ -194,6 +202,7 @@ export async function resolveTranscriptPath(sessionId: string): Promise<string |
const p = path.join(root, d, `${sessionId}.jsonl`)
try {
await fs.promises.access(p)
+ transcriptPathCache.set(sessionId, p)
return p
} catch {
/* keep looking */
@@ -256,7 +265,14 @@ export async function readSessionName(sessionId: string): Promise<string | null>
if (!sessionId) return null
const p = await resolveTranscriptPath(sessionId)
if (!p) return null
- const tail = await readSmallTail(p, TITLE_TAIL_BYTES)
+ let tail = await readSmallTail(p, TITLE_TAIL_BYTES)
+ if (tail === undefined && transcriptPathCache.get(sessionId) === p) {
+ // The cached path went stale (transcript deleted/moved) — rescan once, don't poll a corpse.
+ transcriptPathCache.delete(sessionId)
+ const fresh = await resolveTranscriptPath(sessionId)
+ if (!fresh) return null
+ tail = await readSmallTail(fresh, TITLE_TAIL_BYTES)
+ }
if (!tail) return null
return pickSessionName(tail)
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 338ac9cd5..45c3b9bd7 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -18,8 +18,7 @@ import type { Edge, Node } from '@xyflow/react'
import { TerminalNode, setMoveIntoWorktreeHandler } from '../nodes/TerminalNode'
import { StickyNode } from '../nodes/StickyNode'
import { GroupNode, setWorktreeActionHandler } from '../nodes/GroupNode'
-import { EditorNode } from '../nodes/EditorNode'
-import { DiffNode } from '../nodes/DiffNode'
+import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'
import { DinoNode } from '../nodes/DinoNode'
import BrowserNode from '../nodes/BrowserNode'
import { normalizeAddress } from '../nodes/browserUrl'
@@ -265,8 +264,8 @@ export function Canvas() {
terminal: withNodeBoundary(TerminalNode),
sticky: withNodeBoundary(StickyNode),
group: withNodeBoundary(GroupNode),
- editor: withNodeBoundary(EditorNode),
- diff: withNodeBoundary(DiffNode),
+ editor: withNodeBoundary(LazyEditorNode),
+ diff: withNodeBoundary(LazyDiffNode),
subagent: withNodeBoundary(SubagentNode),
loop: withNodeBoundary(LoopNode),
dino: withNodeBoundary(DinoNode),
@@ -283,14 +282,27 @@ export function Canvas() {
const ephemeralPos = useAgentNodes((s) => s.positions)
const ephSizes = useAgentNodes((s) => s.sizes)
const ephExpanded = useAgentNodes((s) => s.expanded)
- const claudeById = useAgentStatus((s) => s.byId)
+ // Deliberately NOT `useAgentStatus((s) => s.byId)`: that map's identity changes on every
+ // working/waiting flip of any agent node, which re-rendered the whole canvas per hook event.
+ // Canvas only needs the /loop entries (for the ephemeral LoopNodes), so subscribe to a
+ // primitive signature that changes only when a loop's visible fields do; the memo below
+ // reads the actual entries via getState().
+ const loopSig = useAgentStatus((s) => {
+ let sig = ''
+ for (const [id, st] of Object.entries(s.byId)) {
+ if (!st.loop) continue
+ sig += `${id}${st.loop.kind ?? ''}${st.loop.count}${st.loop.items?.length ?? 0}${st.loop.task ?? ''}${st.loop.schedule ?? ''}${st.state === 'working' ? 1 : 0}`
+ }
+ return sig
+ })
// 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 claudeById = useAgentStatus.getState().byId // re-read on loopSig change (see above)
+ const hasLoops = loopSig !== ''
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).
@@ -376,7 +388,6 @@ export function Canvas() {
subagentTokens: v.tokens,
subagentToolUses: v.toolUses,
subagentResult: v.result,
- subagentActivity: v.activity,
ephExpanded: !!ephExpanded[cid]
}
} as CanvasNode)
@@ -391,7 +402,8 @@ export function Canvas() {
})
}
return { ephemeralNodes: eNodes, ephemeralEdges: eEdges }
- }, [agentById, claudeById, ephemeralPos, ephSizes, ephExpanded, ephSel, nodes])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- loopSig stands in for the byId read
+ }, [agentById, loopSig, 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.
@@ -838,10 +850,16 @@ export function Canvas() {
}, [linkEdges, nodes, setLinkEdges])
// Reflect Claude nodes with unread output as a macOS Dock badge count (across all projects).
+ // Subscribes to the derived count (a primitive), not the byId map, for the same reason as
+ // loopSig above — state flips must not re-render the canvas.
+ const unreadCount = useAgentStatus((s) => {
+ let count = 0
+ for (const st of Object.values(s.byId)) if (st?.unread) count++
+ return count
+ })
useEffect(() => {
- const count = Object.values(claudeById).filter((s) => s?.unread).length
- window.nodeTerminal.setBadgeCount(count)
- }, [claudeById])
+ window.nodeTerminal.setBadgeCount(unreadCount)
+ }, [unreadCount])
// Feed per-session context-window fill from main into the transient store.
useEffect(() => {
diff --git a/src/renderer/canvas/RemoteSessionView.tsx b/src/renderer/canvas/RemoteSessionView.tsx
index ce89df17e..51ebba608 100644
--- a/src/renderer/canvas/RemoteSessionView.tsx
+++ b/src/renderer/canvas/RemoteSessionView.tsx
@@ -14,8 +14,7 @@ import type { CanvasMutation, CanvasNodeState } from '@shared/types'
import { TerminalNode } from '../nodes/TerminalNode'
import { StickyNode } from '../nodes/StickyNode'
import { GroupNode } from '../nodes/GroupNode'
-import { EditorNode } from '../nodes/EditorNode'
-import { DiffNode } from '../nodes/DiffNode'
+import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'
import { withNodeBoundary } from '../components/NodeBoundary'
import { flowToNodeStates, nodeStatesToFlow, type CanvasNode } from '../state/workspace'
@@ -96,8 +95,8 @@ function RemoteSessionCanvas({
terminal: withNodeBoundary(TerminalNode),
sticky: withNodeBoundary(StickyNode),
group: withNodeBoundary(GroupNode),
- editor: withNodeBoundary(EditorNode),
- diff: withNodeBoundary(DiffNode)
+ editor: withNodeBoundary(LazyEditorNode),
+ diff: withNodeBoundary(LazyDiffNode)
}),
[]
)
diff --git a/src/renderer/nodes/SubagentNode.tsx b/src/renderer/nodes/SubagentNode.tsx
index 74f20d935..fcfd8c03e 100644
--- a/src/renderer/nodes/SubagentNode.tsx
+++ b/src/renderer/nodes/SubagentNode.tsx
@@ -25,7 +25,9 @@ export function SubagentNode({ id, data, selected }: NodeProps<CanvasNode>) {
const tokens = data.subagentTokens as number | undefined
const toolUses = data.subagentToolUses as number | undefined
const result = (data.subagentResult as string) || ''
- const activity = (data.subagentActivity as string) || ''
+ // Live transcript: subscribed here per-id (not passed through Canvas's ephemeral node data)
+ // so streaming chunks re-render only this card, never the whole canvas.
+ const activity = useAgentNodes((s) => s.activityById[id]) || ''
const body = activity || result
const expanded = !!data.ephExpanded
const bodyRef = useRef<HTMLDivElement>(null)
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 162a42b80..4581e2809 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -10,6 +10,7 @@ import {
import { Terminal } from '@xterm/xterm'
import { FitAddon } from '@xterm/addon-fit'
import { SearchAddon } from '@xterm/addon-search'
+import { WebglAddon } from '@xterm/addon-webgl'
import { renderMarkdown } from '../lib/markdown'
import { ChatPanel } from './ChatPanel'
import { transport as localTransport } from '../terminal/local-transport'
@@ -258,6 +259,17 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
searchAddonRef.current = searchAddon
term.loadAddon(searchAddon)
term.open(container)
+ // GPU renderer: xterm's default DOM renderer doesn't scale to many terminals streaming
+ // at once. Must load after open(). Browsers cap live WebGL contexts (~16), so with many
+ // mounted terminals the oldest context gets evicted — onContextLoss disposes the addon
+ // and that terminal falls back to the DOM renderer instead of going blank.
+ try {
+ const webgl = new WebglAddon()
+ webgl.onContextLoss(() => webgl.dispose())
+ term.loadAddon(webgl)
+ } catch {
+ // WebGL2 unavailable — DOM renderer remains active.
+ }
fit.fit()
patchTerminalScale(term, getZoom)
@@ -599,11 +611,17 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
const sid = status?.sessionId ?? ''
if (!sid) return
let cancelled = false
+ // Poll fast (4s) only until the session's name is first seen — a session is named once
+ // early and rarely renamed after, so back off to 15s then. Each poll is an IPC + a small
+ // transcript tail read in main, so N agent nodes each shave 3/4 of that steady load.
+ let delayMs = 4000
+ let timer: ReturnType<typeof setTimeout> | undefined
const sync = async () => {
if (!titleAutoRef.current || editingTitleRef.current) return
const name = await window.nodeTerminal.pty.readSessionName(sid)
+ if (cancelled) return
+ if (name) delayMs = 15000
if (
- !cancelled &&
name &&
titleAutoRef.current &&
!editingTitleRef.current &&
@@ -612,11 +630,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
updateNodeData(id, { title: name })
}
}
- void sync()
- const timer = setInterval(() => void sync(), 4000)
+ const tick = async () => {
+ await sync()
+ if (!cancelled) timer = setTimeout(() => void tick(), delayMs)
+ }
+ void tick()
return () => {
cancelled = true
- clearInterval(timer)
+ if (timer) clearTimeout(timer)
}
}, [id, canRenameNode, status?.sessionId, data.titleAuto, updateNodeData])
diff --git a/src/renderer/nodes/lazyMonacoNodes.tsx b/src/renderer/nodes/lazyMonacoNodes.tsx
new file mode 100644
index 000000000..41f0642d4
--- /dev/null
+++ b/src/renderer/nodes/lazyMonacoNodes.tsx
@@ -0,0 +1,46 @@
+import { Suspense, lazy } from 'react'
+import type { NodeProps } from '@xyflow/react'
+import type { CanvasNode } from '../state/workspace'
+
+// EditorNode/DiffNode pull in the whole of monaco-editor (several MB of JS). Importing them
+// statically put Monaco in the startup chunk for every launch — including the common canvas
+// of terminals with no editor node at all. These wrappers are what goes into `nodeTypes`;
+// Monaco's chunk is fetched the first time an editor/diff node actually mounts.
+const EditorInner = lazy(() => import('./EditorNode').then((m) => ({ default: m.EditorNode })))
+const DiffInner = lazy(() => import('./DiffNode').then((m) => ({ default: m.DiffNode })))
+
+function LoadingBody() {
+ return (
+ <div
+ style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: '#1e1e1e',
+ borderRadius: 10,
+ color: 'rgba(255,255,255,0.4)',
+ fontSize: 12
+ }}
+ >
+ Loading editor…
+ </div>
+ )
+}
+
+export function LazyEditorNode(props: NodeProps<CanvasNode>) {
+ return (
+ <Suspense fallback={<LoadingBody />}>
+ <EditorInner {...props} />
+ </Suspense>
+ )
+}
+
+export function LazyDiffNode(props: NodeProps<CanvasNode>) {
+ return (
+ <Suspense fallback={<LoadingBody />}>
+ <DiffInner {...props} />
+ </Suspense>
+ )
+}
diff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.ts
index 1c020c7e6..c333b5526 100644
--- a/src/renderer/state/agentNodes.ts
+++ b/src/renderer/state/agentNodes.ts
@@ -21,8 +21,6 @@ export interface SubagentViz {
toolUses?: number
/** What the subagent produced (shown when the node is expanded). */
result?: string
- /** Live transcript text streamed while the subagent runs (shown when expanded). */
- activity?: string
}
export interface SubagentResult {
@@ -34,6 +32,13 @@ export interface SubagentResult {
interface AgentNodesState {
byId: Record<string, SubagentViz>
+ /**
+ * Live transcript text per subagent, streamed while it runs — kept OUT of `byId` on purpose:
+ * Canvas subscribes to `byId` to lay out the ephemeral nodes, and chunks arrive several times
+ * a second, so routing them through `byId` re-rendered the whole canvas per chunk. Only the
+ * expanded SubagentNode subscribes here, per id.
+ */
+ activityById: Record<string, string>
/** Per-ephemeral-node UI overrides (keyed by node id: subagent ids + `loop-<parentId>`). */
positions: Record<string, { x: number; y: number }>
sizes: Record<string, { width: number; height: number }>
@@ -51,6 +56,7 @@ interface AgentNodesState {
export const useAgentNodes = create<AgentNodesState>((set) => ({
byId: {},
+ activityById: {},
positions: {},
sizes: {},
expanded: {},
@@ -73,26 +79,29 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
appendActivity: (toolUseId, chunk) =>
set((s) => {
- const prev = s.byId[toolUseId]
- if (!prev) return s
- const activity = ((prev.activity ?? '') + chunk).slice(-12000) // keep the tail bounded
- return { byId: { ...s.byId, [toolUseId]: { ...prev, activity } } }
+ if (!s.byId[toolUseId]) return s
+ const activity = ((s.activityById[toolUseId] ?? '') + chunk).slice(-12000) // bounded tail
+ return { activityById: { ...s.activityById, [toolUseId]: activity } }
}),
clearForParent: (parentNodeId) =>
set((s) => {
const ids = Object.keys(s.byId).filter((id) => s.byId[id].parentNodeId === parentNodeId)
const byId = { ...s.byId }
+ const activityById = { ...s.activityById }
const positions = { ...s.positions }
const sizes = { ...s.sizes }
const expanded = { ...s.expanded }
const drop = [...ids, `loop-${parentNodeId}`]
- for (const id of ids) delete byId[id]
+ for (const id of ids) {
+ delete byId[id]
+ delete activityById[id]
+ }
for (const id of drop) {
delete positions[id]
delete sizes[id]
delete expanded[id]
}
- return { byId, positions, sizes, expanded }
+ return { byId, activityById, positions, sizes, expanded }
})
}))