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
perf: fix scan regressions + land second-sweep findings
enes48d7e8147c48
diff --git a/src/main/agents/hook-server.ts b/src/main/agents/hook-server.tsindex cc8bc3743..3a1b18fa2 100644--- a/src/main/agents/hook-server.ts+++ b/src/main/agents/hook-server.ts@@ -11,12 +11,17 @@ const SLOWLORIS_MS = 2000function readBody(req: IncomingMessage): Promise<string> {return new Promise((resolve) => {- let data = ''- req.on('data', (c) => {- data += c- if (data.length > 5_000_000) req.destroy() // cap absurd bodies+ // Collect Buffers and decode ONCE at the end: `data += chunk` coerced every chunk through+ // a string concat (quadratic churn on big bodies) and could split a multibyte UTF-8+ // sequence at a chunk boundary, corrupting the decoded text.+ const chunks: Buffer[] = []+ let bytes = 0+ req.on('data', (c: Buffer) => {+ chunks.push(c)+ bytes += c.length+ if (bytes > 5_000_000) req.destroy() // cap absurd bodies})- req.on('end', () => resolve(data))+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))req.on('error', () => resolve(''))})}diff --git a/src/main/context-link.ts b/src/main/context-link.tsindex 0bf04def1..3fd56425a 100644--- a/src/main/context-link.ts+++ b/src/main/context-link.ts@@ -89,13 +89,14 @@ to read — do not retry.let pty: PtyManager | undefined// Write one enriched link file per node id present in the map. Removed links should not-// linger, so we clear stale per-node files first.-function writeLinkFiles(map: ContextLinkMap): void {+// linger, so we clear stale per-node files first. Async fs throughout — this runs on edge+// changes and scales with node/link count, and sync I/O here sits on the main event loop.+async function writeLinkFiles(map: ContextLinkMap): Promise<void> {const d = contextLinkDir()const bin = pty?.getTmuxBin() ?? nulltry {- for (const f of fs.readdirSync(d)) {- if (f.endsWith('.json')) fs.rmSync(path.join(d, f), { force: true })+ for (const f of await fs.promises.readdir(d)) {+ if (f.endsWith('.json')) await fs.promises.rm(path.join(d, f), { force: true })}} catch {/* dir may not exist yet */@@ -107,7 +108,7 @@ function writeLinkFiles(map: ContextLinkMap): void {tmuxSocket: TMUX_SOCKET})try {- fs.writeFileSync(path.join(d, `${nodeId}.json`), JSON.stringify(doc, null, 2))+ await fs.promises.writeFile(path.join(d, `${nodeId}.json`), JSON.stringify(doc, null, 2))} catch (e) {console.warn('[context-link] write link file failed', e)}@@ -128,8 +129,13 @@ export function initContextLink(win: BrowserWindow, ptyManager: PtyManager): voiconsole.error('[context-link] setup failed', e)return}+ // Serialize writes: writeLinkFiles is a multi-step async clear-then-write; two overlapping+ // calls could interleave (B's clear runs before A's writes land) and leave a just-removed+ // link file behind — which is a read-authorization leak, not just a perf nit.+ let writeChain: Promise<void> = Promise.resolve()ipcMain.handle(IPC.contextLinkSetLinks, (_e, map: ContextLinkMap) => {- writeLinkFiles(map && typeof map === 'object' ? map : {})+ writeChain = writeChain.then(() => writeLinkFiles(map && typeof map === 'object' ? map : {}))+ return writeChain})// win is reserved for future link-activity events; referenced to satisfy noUnusedParameters.void windiff --git a/src/main/context-tail.ts b/src/main/context-tail.tsindex 8e04dd8d7..ae4db3158 100644--- a/src/main/context-tail.ts+++ b/src/main/context-tail.ts@@ -98,6 +98,9 @@ export function createContextTail(win: BrowserWindow): ContextTail {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+ // Cap deltas too: a huge append burst (resume/compact rewriting MBs between ticks)+ // shouldn't allocate it all — only the LATEST usage matters, so jump to the tail.+ if (size - t.offset > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAPif (size > t.offset) {let chunk = ''try {@@ -126,6 +129,7 @@ export function createContextTail(win: BrowserWindow): ContextTail {if (t.model) void resolveModelWindow(t.model)const win = cachedWindowFor(t.model)+ if (!sessions.has(sessionId)) return // untracked while this async read was in flightif (t.used > 0 &&(t.used !== t.lastUsed || t.model !== t.lastModel || win !== t.lastWindow)diff --git a/src/main/index.ts b/src/main/index.tsindex 2036fcdca..974f3c277 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -657,12 +657,24 @@ app.whenReady().then(async () => {})app.on('window-all-closed', () => {- ptyManager.killAll()- sshProjectManager?.disconnectAll()- if (process.platform !== 'darwin') app.quit()+ // On macOS the app stays alive, so the async final snapshots inside killAll can complete+ // in the background; on other platforms quitting goes through before-quit below.+ if (process.platform !== 'darwin') {+ app.quit()+ } else {+ void ptyManager.killAll()+ sshProjectManager?.disconnectAll()+ }})-app.on('before-quit', () => {- ptyManager.killAll()+// The final scrollback snapshots are async (capture subprocess + fs.promises write) — hold+// the quit just long enough for them to land, capped so a hung tmux can never block quit.+let quitFlushed = false+app.on('before-quit', (e) => {sshProjectManager?.disconnectAll()+ if (quitFlushed) return+ quitFlushed = true+ e.preventDefault()+ const flush = ptyManager.killAll()+ void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))]).finally(() => app.quit())})diff --git a/src/main/media-protocol.ts b/src/main/media-protocol.tsindex cec86f5a0..33a0aa958 100644--- a/src/main/media-protocol.ts+++ b/src/main/media-protocol.ts@@ -1,7 +1,7 @@// nt-media:// — a privileged streaming protocol for local media (video) + large images.// Files are served ONLY if they are on the per-session allowlist (path jail), so the// renderer/agent can never read an arbitrary local file. Supports HTTP Range so <video> seeks.-import { createReadStream, statSync, lstatSync, mkdirSync, writeFileSync } from 'fs'+import { createReadStream, mkdirSync, writeFileSync, promises as fsp } from 'fs'import { normalize } from 'path'import { app, protocol } from 'electron'@@ -62,6 +62,10 @@ const AGENT_HTML_CSP ="default-src 'none'; img-src nt-media: data:; media-src nt-media:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src data:"let htmlSeq = 0+// Bounded: each call wrote a new timestamped file that was never deleted — permanent disk+// growth under <userData>/agent-web. Keep the most recent N; prune allowlist entries too.+const AGENT_HTML_KEEP = 20+const agentHtmlPaths: string[] = []/** Write raw HTML to a per-session file under userData, allowlist it, return its abs path. */export function writeAgentHtml(html: string): string {const d = agentWebDir()@@ -69,9 +73,28 @@ export function writeAgentHtml(html: string): string {const p = `${d}/${Date.now().toString(36)}-${++htmlSeq}.html`writeFileSync(p, html, { encoding: 'utf8', mode: 0o600 })allowMediaPath(p)+ agentHtmlPaths.push(p)+ while (agentHtmlPaths.length > AGENT_HTML_KEEP) {+ const old = agentHtmlPaths.shift()!+ allowed.delete(old)+ void fsp.rm(old, { force: true })+ }return p}+/** Best-effort startup sweep: agent-HTML files from PRIOR sessions are unreachable (the+ * allowlist is in-memory), so they're pure disk litter — delete them. */+async function pruneStaleAgentHtml(): Promise<void> {+ const d = agentWebDir()+ try {+ for (const f of await fsp.readdir(d)) {+ if (f.endsWith('.html')) await fsp.rm(`${d}/${f}`, { force: true })+ }+ } catch {+ // dir may not exist yet+ }+}+/** Call BEFORE app.whenReady(): declares the scheme privileged (secure + streamable). */export function registerMediaScheme(): void {protocol.registerSchemesAsPrivileged([@@ -84,6 +107,7 @@ export function registerMediaScheme(): void {/** Call AFTER app is ready: serve allowed files with Range support. */export function initMediaProtocol(): void {+ void pruneStaleAgentHtml()protocol.handle(MEDIA_SCHEME, async (req) => {const url = new URL(req.url)const abs = resolveMediaPath(url.pathname, allowed)@@ -91,15 +115,15 @@ export function initMediaProtocol(): void {// Symlink jail: reject a final-component symlink so an allowlisted entry can't be// turned into an arbitrary-file read. lstat does NOT follow the final link (it follows// intermediate dir symlinks like macOS /tmp→/private/tmp, which is fine and avoids the- // realpath-equality pitfalls with those system dirs).- try {- if (lstatSync(abs).isSymbolicLink()) return new Response('Not found', { status: 404 })- } catch {- return new Response('Not found', { status: 404 })- }+ // realpath-equality pitfalls with those system dirs). One async lstat covers the jail+ // check AND the size (final component isn't a link, so lstat size == stat size) — the+ // previous sync lstat+stat pair blocked the main thread per request, and <video> seeking+ // issues many Range requests.let size: numbertry {- size = statSync(abs).size+ const st = await fsp.lstat(abs)+ if (st.isSymbolicLink()) return new Response('Not found', { status: 404 })+ size = st.size} catch {return new Response('Not found', { status: 404 })}diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 3295d8cfa..27536845b 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -214,7 +214,11 @@ export class PtyManager {anyPersisted = trueif (!session.outputSinceSnapshot) continue // idle since the last capture — skip the spawnsession.outputSinceSnapshot = false- void this.snapshotScrollback(session.persistKey, session.sshRemote)+ void this.snapshotScrollback(session.persistKey, session.sshRemote).then((ok) => {+ // Transient capture failure (ssh blip, tmux busy): put the dirty bit back so the next+ // tick retries — otherwise a quiet session would never be snapshotted again.+ if (!ok) session.outputSinceSnapshot = true+ })}if (!anyPersisted && this.snapshotTimer) {clearInterval(this.snapshotTimer)@@ -726,15 +730,17 @@ export class PtyManager {/*** Snapshot a node's recent scrollback (with colors, `-e`) to disk for cold-restart replay.* Best-effort: a missing session / unavailable tmux just leaves the prior snapshot in place.+ * Returns false when the capture failed, so the periodic tick can re-mark the session dirty+ * and retry (the dirty bit is cleared optimistically before the capture starts).*/private async snapshotScrollback(persistKey: string,sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>- ): Promise<void> {+ ): Promise<boolean> {if (sshRemote) {// Remote (ssh-project) node: capture from the REMOTE tmux over the project's ControlMaster.const ssh = findSsh()- if (!ssh) return+ if (!ssh) return falsetry {const { stdout } = await runAsync(ssh,@@ -742,12 +748,13 @@ export class PtyManager {{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })if (stdout) await writeScrollback(persistKey, stdout)+ return true} catch {// remote session gone / master down — keep the last good snapshot+ return false}- return}- if (!this.tmuxPath) return+ if (!this.tmuxPath) return falsetry {const { stdout } = await runAsync(this.tmuxPath,@@ -755,8 +762,10 @@ export class PtyManager {{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 })if (stdout) await writeScrollback(persistKey, stdout)+ return true} catch {// session gone / tmux unavailable — keep the last good snapshot+ return false}}@@ -808,21 +817,25 @@ export class PtyManager {* On quit, detach all clients (do NOT kill tmux sessions — that's the whole point* of persistence). The tmux server keeps the sessions alive for next launch.*/- killAll(): void {+ /** Returns a promise of the final scrollback snapshots: the capture + write are async, so+ * the quit path must hold `before-quit` briefly (see index.ts) or the process exits before+ * they land and the last ≤15s of output is missing from a post-reboot cold restore. */+ killAll(): Promise<void> {if (this.snapshotTimer) {clearInterval(this.snapshotTimer)this.snapshotTimer = null}+ const finals: Promise<unknown>[] = []for (const session of this.sessions.values()) {if (session.flushTimer) clearTimeout(session.flushTimer)- // Best-effort final scrollback snapshot on quit so a reboot can replay it. Fire-and-forget:- // the tmux server (and the snapshot capture against it) outlives this process. Skipped for- // sessions with no output since the last periodic capture (unchanged pane content).+ // Final scrollback snapshot on quit so a reboot can replay it. Skipped for sessions with+ // no output since the last periodic capture (unchanged pane content).if (session.persistKey && session.outputSinceSnapshot)- void this.snapshotScrollback(session.persistKey, session.sshRemote)+ finals.push(this.snapshotScrollback(session.persistKey, session.sshRemote))session.proc.kill()}this.sessions.clear()+ return Promise.all(finals).then(() => undefined)}private send(webContentsId: number, channel: string, payload: unknown): void {diff --git a/src/main/subagent-tail.ts b/src/main/subagent-tail.tsindex 7472ae0a3..d923c09e9 100644--- a/src/main/subagent-tail.ts+++ b/src/main/subagent-tail.ts@@ -14,6 +14,10 @@ interface Tracked {dir: stringfile: string | nulloffset: number+ /** An async read is in flight — the next tick skips this entry instead of double-reading. */+ reading?: boolean+ /** Meta files already parsed and rejected — don't re-read them on every 400ms tick. */+ seenMetas?: Set<string>}function textOf(content: unknown): string {@@ -117,45 +121,56 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {if (chunk && !win.isDestroyed()) win.webContents.send(IPC.agentSubagentActivity, { toolUseId, chunk })}- const readOne = (toolUseId: string, e: Tracked) => {+ // Async fs throughout: this ticks every 400ms per active subagent, and the sync version's+ // readdir + per-meta reads sat on the main event loop alongside all PTY/IPC traffic.+ const readOne = async (toolUseId: string, e: Tracked): Promise<void> => {+ if (e.reading) return+ e.reading = truetry {if (!e.file) {let metas: string[]try {- metas = fs.readdirSync(e.dir)+ metas = await fs.promises.readdir(e.dir)} catch {return // dir not created yet}+ const seen = (e.seenMetas ??= new Set())for (const m of metas) {- if (!m.endsWith('.meta.json')) continue+ if (!m.endsWith('.meta.json') || seen.has(m)) continuetry {- const meta = JSON.parse(fs.readFileSync(path.join(e.dir, m), 'utf-8'))+ const meta = JSON.parse(await fs.promises.readFile(path.join(e.dir, m), 'utf-8'))if (meta.toolUseId === toolUseId) {e.file = path.join(e.dir, m.replace(/\.meta\.json$/, '.jsonl'))break}+ seen.add(m) // belongs to another subagent — skip it on future ticks} catch {- // ignore unparseable meta+ // unparseable (possibly still being written) — retry next tick, don't blacklist}}if (!e.file) return}- const size = fs.statSync(e.file).size+ const size = (await fs.promises.stat(e.file)).sizeif (size <= e.offset) returnconst buf = Buffer.alloc(size - e.offset)- const fd = fs.openSync(e.file, 'r')- fs.readSync(fd, buf, 0, buf.length, e.offset)- fs.closeSync(fd)+ const fd = await fs.promises.open(e.file, 'r')+ try {+ await fd.read(buf, 0, buf.length, e.offset)+ } finally {+ await fd.close()+ }e.offset = sizeconst out = formatSubagentChunk(buf.toString('utf-8'))if (out) send(toolUseId, out + '\n')} catch {// file may not exist yet / transient read error+ } finally {+ e.reading = false}}const tick = () => {- for (const [toolUseId, e] of tracked) readOne(toolUseId, e)+ for (const [toolUseId, e] of tracked) void readOne(toolUseId, e)if (!tracked.size && timer) {clearInterval(timer)timer = null@@ -171,7 +186,7 @@ export function createSubagentTail(win: BrowserWindow): SubagentTail {},finish(toolUseId) {const e = tracked.get(toolUseId)- if (e) readOne(toolUseId, e) // final flush+ if (e) void readOne(toolUseId, e) // final flush (completes well within the grace delay)setTimeout(() => tracked.delete(toolUseId), 1500)}}diff --git a/src/main/transcript-reader.ts b/src/main/transcript-reader.tsindex 24906ef2b..9af3f8919 100644--- a/src/main/transcript-reader.ts+++ b/src/main/transcript-reader.ts@@ -190,7 +190,17 @@ const transcriptPathCache = new Map<string, string>()export async function resolveTranscriptPath(sessionId: string): Promise<string | undefined> {if (!SESSION_ID_RE.test(sessionId)) return undefinedconst cached = transcriptPathCache.get(sessionId)- if (cached) return cached+ if (cached) {+ // One cheap access() per hit (vs the O(project-dirs) scan below): heals a stale entry for+ // EVERY caller (chat/search/context-ensure too, not just the title poll) if the transcript+ // was deleted — otherwise they'd keep getting a dead path and skip their cwd fallbacks.+ try {+ await fs.promises.access(cached)+ return cached+ } catch {+ transcriptPathCache.delete(sessionId)+ }+ }const root = path.join(os.homedir(), '.claude', 'projects')let dirs: string[]try {@@ -263,16 +273,10 @@ export function pickSessionName(text: string): string | null {const TITLE_TAIL_BYTES = 128 * 1024export async function readSessionName(sessionId: string): Promise<string | null> {if (!sessionId) return null+ // Stale cache entries are healed inside resolveTranscriptPath (access-checked per hit).const p = await resolveTranscriptPath(sessionId)if (!p) return null- 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)- }+ const tail = await readSmallTail(p, TITLE_TAIL_BYTES)if (!tail) return nullreturn pickSessionName(tail)}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a4e1d0516..43dfe9c85 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -139,6 +139,39 @@ const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {ephemeralEdges: []}+const minimapNodeColor = (n: Node): string =>+ (n.data as { color?: string })?.color ?? '#0a84ff'++// The minimap subscribes to agent status HERE, in its own tiny component — not in Canvas.+// Canvas must not subscribe to the whole status map (every working/waiting flip would re-render+// the entire canvas), but the minimap's working/attention/unread strokes DO need to track those+// flips live; a fresh `nodeStrokeColor` identity per status change is what busts React Flow's+// internal MiniMap memo so it repaints. Re-render cost is confined to this component.+function StatusAwareMiniMap() {+ const statusById = useAgentStatus((s) => s.byId)+ const nodeStrokeColor = useCallback(+ (n: Node): string => {+ const st = statusById[n.id]+ if (st?.state === 'working') return '#30d158'+ if (st?.state === 'waiting' || st?.state === 'blocked') return '#ff9f0a'+ if (st?.unread) return '#0a84ff'+ return (n.data as { color?: string })?.color ?? '#0a84ff'+ },+ [statusById]+ )+ return (+ <MiniMap+ className="minimap"+ position="bottom-right"+ pannable+ zoomable+ maskColor="rgba(10,12,18,0.6)"+ nodeColor={minimapNodeColor}+ nodeStrokeColor={nodeStrokeColor}+ />+ )+}+export function Canvas() {const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])// Persistent context links between Claude nodes (separate from ephemeral subagent/loop edges).@@ -592,9 +625,11 @@ export function Canvas() {loadingRef.current = false// The broadcast effect early-returns while `loadingRef` is set and isn't re-triggered by the// reset, so push the freshly-loaded project's canvas once now — otherwise a connected client- // keeps mirroring the previous project until the host's next edit. Benign with no client- // attached (main only forwards to a live client).- window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })+ // keeps mirroring the previous project until the host's next edit. Gated like the effect:+ // when not hosting, the serialize itself is the waste (main would drop the payload anyway).+ if (useRemoteHosting.getState().hosting) {+ window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })+ }// Consume a cross-project focus request (notification click on a background node).const pending = pendingFocusRef.currentif (pending) {@@ -2883,6 +2918,16 @@ export function Canvas() {addSshTerminal])+ // Build the palette's command list only when its inputs change — the inline `buildCommands()`+ // at the call site rebuilt the whole list (JSX icons for every node + project) on every Canvas+ // render while the palette was open. `nodes` is a dep because the list reads nodesRef.current;+ // capture-cache refreshes arrive via buildCommands' own identity (bufferCache is its dep).+ const paletteCommands = useMemo(+ () => (paletteOpen ? buildCommands() : []),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- nodes stands in for nodesRef.current+ [paletteOpen, buildCommands, nodes]+ )+return (<div className="canvas-root"><TabBar@@ -3026,21 +3071,7 @@ export function Canvas() {/><Controls showInteractive={false} position="bottom-left" /><UsageIndicator />- <MiniMap- className="minimap"- position="bottom-right"- pannable- zoomable- maskColor="rgba(10,12,18,0.6)"- nodeColor={(n) => (n.data as { color?: string })?.color ?? '#0a84ff'}- nodeStrokeColor={(n) => {- const st = useAgentStatus.getState().byId[n.id]- if (st?.state === 'working') return '#30d158'- if (st?.state === 'waiting' || st?.state === 'blocked') return '#ff9f0a'- if (st?.unread) return '#0a84ff'- return (n.data as { color?: string })?.color ?? '#0a84ff'- }}- />+ <StatusAwareMiniMap /></ReactFlow>{(!hasProjects || welcomeOpen) && (@@ -3094,7 +3125,7 @@ export function Canvas() {{paletteOpen && (<CommandPalette- commands={buildCommands()}+ commands={paletteCommands}fileIndex={fileIndex}onOpenFile={openProjectFile}onRevealFile={revealProjectFile}diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsxindex 83fc5e2bc..6ccd3c226 100644--- a/src/renderer/components/SessionsSidebar.tsx+++ b/src/renderer/components/SessionsSidebar.tsx@@ -65,28 +65,36 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null// Inline group rename: the group node id being edited + its draft title.const [editGroup, setEditGroup] = useState<{ id: string; draft: string } | null>(null)- // Look up the current git branch for each project cwd (best-effort, cached).+ // Look up the current git branch for each project cwd (best-effort, cached). Gated on `open`+ // and caches a NEGATIVE result too — without the '' fallback a non-git cwd re-fired a git+ // subprocess on every projects-store change, forever.useEffect(() => {+ if (!open) returnlet cancelled = falseprojects.forEach((p) => {if (!p.cwd || branches[p.id] !== undefined) returnwindow.nodeTerminal.git.status(p.cwd).then((st) => {- if (!cancelled && st && typeof st.branch === 'string') {- setBranches((b) => ({ ...b, [p.id]: st.branch }))- }+ if (cancelled) return+ const branch = st && typeof st.branch === 'string' ? st.branch : ''+ setBranches((b) => ({ ...b, [p.id]: branch }))+ })+ .catch(() => {+ if (!cancelled) setBranches((b) => ({ ...b, [p.id]: '' }))})- .catch(() => {})})return () => {cancelled = true}- }, [projects, branches])+ }, [open, projects, branches])+ // Gated on `open`: this component stays mounted while the sidebar is closed (the common+ // case), and the O(projects × nodes) rebuild re-ran on every agent hook event otherwise.const groups = useMemo(- () => buildSessionList(projects, liveActiveNodes, activeProjectId, statusById, filter),- [projects, liveActiveNodes, activeProjectId, statusById, filter]+ () =>+ open ? buildSessionList(projects, liveActiveNodes, activeProjectId, statusById, filter) : [],+ [open, projects, liveActiveNodes, activeProjectId, statusById, filter])const projectCount = (g: (typeof groups)[number]): number =>diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex cbb654e4b..d025b4e0c 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useMemo, useState } from 'react'import { createPortal } from 'react-dom'import { useProjects } from '../state/projects'import { useAgentStatus } from '../state/agentStatus'@@ -29,10 +29,20 @@ export function TabBar({onCloseProject,onRemoteAccess}: TabBarProps) {+ // Select the raw array and filter in a memo — a `.filter()` inside the selector returns a+ // fresh array every store snapshot, which re-rendered the TabBar on EVERY projects change.+ const allProjects = useProjects((s) => s.projects)// Closed projects are hidden here (reopen them from the start screen's "Recently closed").- const projects = useProjects((s) => s.projects.filter((p) => !p.closed))+ const projects = useMemo(() => allProjects.filter((p) => !p.closed), [allProjects])const activeId = useProjects((s) => s.activeProjectId)- const statusById = useAgentStatus((s) => s.byId)+ // Unread dots need only the unread id set — subscribing to the whole status map re-rendered+ // the TabBar on every working/waiting flip of any agent. Primitive signature → rare updates.+ const unreadIds = useAgentStatus((s) => {+ let ids = ''+ for (const [id, st] of Object.entries(s.byId)) if (st?.unread) ids += `${id}|`+ return ids+ })+ const unreadSet = useMemo(() => new Set(unreadIds.split('|').filter(Boolean)), [unreadIds])const [menuId, setMenuId] = useState<string | null>(null)const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null)const [editingId, setEditingId] = useState<string | null>(null)@@ -105,7 +115,7 @@ export function TabBar({<div className="tabbar__tabs">{projects.map((p) => {const active = p.id === activeId- const unreadCount = p.nodes.filter((n) => statusById[n.id]?.unread).length+ const unreadCount = p.nodes.filter((n) => unreadSet.has(n.id)).lengthreturn (<divkey={p.id}diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex f727c180f..7dfc4119f 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -1,8 +1,15 @@-import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react'+import { memo, useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'import { renderMarkdown } from '../lib/markdown'import { useAgentStatus } from '../state/agentStatus'import type { ChatMessage } from '@shared/types'+// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each+// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.+const MarkdownText = memo(function MarkdownText({ text }: { text: string }) {+ const html = useMemo(() => renderMarkdown(text), [text])+ return <div className="term-chat__text" dangerouslySetInnerHTML={{ __html: html }} />+})+interface ChatPanelProps {nodeId: stringsessionId?: string@@ -78,11 +85,7 @@ export function ChatPanel({ nodeId, sessionId, cwd }: ChatPanelProps) {<div key={i} className={`term-chat__msg term-chat__msg--${m.role}`}>{m.parts.map((p, j) =>p.kind === 'text' ? (- <div- key={j}- className="term-chat__text"- dangerouslySetInnerHTML={{ __html: renderMarkdown(p.text) }}- />+ <MarkdownText key={j} text={p.text} />) : (<details key={j} className="term-chat__tool"><summary>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex c047c0a3a..ce4d0bb95 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -192,9 +192,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst t = termRef.currentif (!t) return ''const b = t.buffer.active- let s = ''- for (let i = 0; i < b.length; i++) s += (b.getLine(i)?.translateToString() ?? '') + '\n'- return s+ // Array + join, not `s +=`: repeated concat over up to 50k lines churns O(n²) string bytes.+ const lines = new Array<string>(b.length)+ for (let i = 0; i < b.length; i++) lines[i] = b.getLine(i)?.translateToString() ?? ''+ return lines.join('\n')}, [])const search = useTerminalSearch({diff --git a/src/renderer/terminal/useTerminalSearch.ts b/src/renderer/terminal/useTerminalSearch.tsindex e16bef93a..0612221e7 100644--- a/src/renderer/terminal/useTerminalSearch.ts+++ b/src/renderer/terminal/useTerminalSearch.ts@@ -83,15 +83,19 @@ export function useTerminalSearch({// readBuffer must be stable (useCallback in the caller) to avoid rebuilds.}, [open, nodeId, sessionId, cwd, searchTranscript, readBuffer])+ // Lowercase once per snapshot, not per keystroke — the snapshot can be tens of thousands of+ // lines (full scrollback + transcript), and re-lowercasing all of it on every typed character+ // made find-as-you-type O(lines × keystrokes).+ const lowerSource = useMemo(() => source.map((s) => s.text.toLowerCase()), [source])const matches = useMemo(() => {const q = query.trim().toLowerCase()if (!q) return [] as number[]const out: number[] = []- for (let i = 0; i < source.length; i++) {- if (source[i].text.toLowerCase().includes(q)) out.push(i)+ for (let i = 0; i < lowerSource.length; i++) {+ if (lowerSource[i].includes(q)) out.push(i)}return out- }, [query, source])+ }, [query, lowerSource])// Reset the cursor to the first match whenever the result set changes.// `matches` is a fresh array on every query/source change (useMemo), so this