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: coalesce hot-path work and cap oversized file reads
enes643f26aa4404
diff --git a/src/main/fs-ops.ts b/src/main/fs-ops.tsindex 748cd528c..2529bb7cb 100644--- a/src/main/fs-ops.ts+++ b/src/main/fs-ops.ts@@ -13,6 +13,7 @@ import { sep } from 'path'import { execFile, spawn } from 'child_process'import { promisify } from 'util'import type { DirEntry } from '../shared/types'+import { FS_READ_MAX_BYTES, FS_READ_BINARY_MAX_BYTES, tooLargeSentinel } from '../shared/fsLimits'import {buildRgArgsForQuickOpen,buildGitLsFilesArgs,@@ -64,18 +65,23 @@ export async function listDir(dirPath: string): Promise<DirEntry[]> {}}-/** Read a file's UTF-8 text. Returns `''` on any error. */+/** Read a file's UTF-8 text. Returns `''` on any error, a too-large sentinel above the cap. */export async function readText(filePath: string): Promise<string> {try {+ const { size } = await fs.stat(filePath)+ if (size > FS_READ_MAX_BYTES) return tooLargeSentinel(size)return await fs.readFile(filePath, 'utf-8')} catch {return ''}}-/** Read a file as base64 (for image/binary previews). Returns `''` on any error. */+/** Read a file as base64 (for image/binary previews). Returns `''` on any error, a too-large+ * sentinel above the cap (base64 inflates the payload a further 1.33×). */export async function readBinary(filePath: string): Promise<string> {try {+ const { size } = await fs.stat(filePath)+ if (size > FS_READ_BINARY_MAX_BYTES) return tooLargeSentinel(size)const buf = await fs.readFile(filePath)return buf.toString('base64')} catch {diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex d04aefe5b..3295d8cfa 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -166,8 +166,8 @@ interface Session {persistKey?: string/** When set, the session runs on a remote host via ssh; kill/capture target the REMOTE tmux. */sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>- /** Periodic scrollback-to-disk snapshot timer (tmux-backed sessions only). */- snapshotTimer: ReturnType<typeof setInterval> | null+ /** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */+ outputSinceSnapshot: boolean}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -198,6 +198,29 @@ export class PtyManager {private tmuxPath: string | null = nullprivate confPath = ''private getSettings: () => Settings = () => DEFAULT_SETTINGS+ /** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned+ * one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */+ private snapshotTimer: ReturnType<typeof setInterval> | null = null++ private ensureSnapshotTimer(): void {+ if (this.snapshotTimer) return+ this.snapshotTimer = setInterval(() => this.snapshotTick(), SCROLLBACK_SNAPSHOT_MS)+ }++ private snapshotTick(): void {+ let anyPersisted = false+ for (const session of this.sessions.values()) {+ if (!session.persistKey) continue+ anyPersisted = true+ if (!session.outputSinceSnapshot) continue // idle since the last capture — skip the spawn+ session.outputSinceSnapshot = false+ void this.snapshotScrollback(session.persistKey, session.sshRemote)+ }+ if (!anyPersisted && this.snapshotTimer) {+ clearInterval(this.snapshotTimer)+ this.snapshotTimer = null+ }+ }/** Must run after app is ready (needs userData path). */init(getSettings: () => Settings): void {@@ -571,20 +594,14 @@ export class PtyManager {flushTimer: null,persistKey: persisted ? options.persistKey : undefined,sshRemote: remote,- snapshotTimer: null- }- if (persisted && options.persistKey) {- const key = options.persistKey- session.snapshotTimer = setInterval(() => {- void this.snapshotScrollback(key, remote)- }, SCROLLBACK_SNAPSHOT_MS)+ outputSinceSnapshot: true // capture the initial screen on the first tick}+ if (persisted) this.ensureSnapshotTimer()this.sessions.set(sessionId, session)proc.onData((data) => this.queueData(sessionId, session, data))proc.onExit(({ exitCode }) => {- if (session.snapshotTimer) clearInterval(session.snapshotTimer)this.flush(sessionId, session) // deliver any buffered output before the exit signalif (session.onExit) {session.onExit(exitCode)@@ -599,6 +616,7 @@ export class PtyManager {/** Buffer a chunk; flush immediately past the byte cap, otherwise on a short timer. */private queueData(sessionId: string, session: Session, data: string): void {+ session.outputSinceSnapshot = truesession.buf.push(data)session.bufBytes += data.lengthif (session.bufBytes >= MAX_BUF_BYTES) {@@ -661,10 +679,11 @@ export class PtyManager {const session = this.sessions.get(sessionId)if (!session) returnif (session.flushTimer) clearTimeout(session.flushTimer)- if (session.snapshotTimer) clearInterval(session.snapshotTimer)// Final snapshot on detach (node unmount / app quit) so the very latest scrollback survives// a reboot. The tmux session itself keeps running, so this only races a same-instant capture.- if (session.persistKey) void this.snapshotScrollback(session.persistKey, session.sshRemote)+ // Skipped when nothing arrived since the last periodic capture (pane content is unchanged).+ if (session.persistKey && session.outputSinceSnapshot)+ void this.snapshotScrollback(session.persistKey, session.sshRemote)session.proc.kill()this.sessions.delete(sessionId)}@@ -790,12 +809,17 @@ export class PtyManager {* of persistence). The tmux server keeps the sessions alive for next launch.*/killAll(): void {+ if (this.snapshotTimer) {+ clearInterval(this.snapshotTimer)+ this.snapshotTimer = null+ }for (const session of this.sessions.values()) {if (session.flushTimer) clearTimeout(session.flushTimer)- if (session.snapshotTimer) clearInterval(session.snapshotTimer)// 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.- if (session.persistKey) void this.snapshotScrollback(session.persistKey, session.sshRemote)+ // 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).+ if (session.persistKey && session.outputSinceSnapshot)+ void this.snapshotScrollback(session.persistKey, session.sshRemote)session.proc.kill()}this.sessions.clear()diff --git a/src/main/workspace-store.ts b/src/main/workspace-store.tsindex 28a9613c5..410f1d755 100644--- a/src/main/workspace-store.ts+++ b/src/main/workspace-store.ts@@ -37,8 +37,11 @@ export class WorkspaceStore {// 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).+ // Compact stringify (no pretty-print): the save runs on an 800ms debounce and serializes+ // EVERY project's nodes — indentation roughly doubled both the string-build cost and the+ // bytes written, for a file nobody reads by hand.const tmp = `${this.filePath}.tmp`- await fs.writeFile(tmp, JSON.stringify(workspace, null, 2), 'utf-8')+ await fs.writeFile(tmp, JSON.stringify(workspace), 'utf-8')await fs.rename(tmp, this.filePath)}}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 45c3b9bd7..57db9a396 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -97,6 +97,7 @@ import { relativeTime } from '../lib/relativeTime'import { AgentIcon } from '../lib/agentIcons'import { branchClaudeSession } from '../lib/claudeBranch'import { useSettings } from '../state/settings'+import { useRemoteHosting } from '../state/remoteHosting'import { useContextWindow } from '../state/contextWindow'import { useSessionNaming } from '../state/sessionNaming'import { useSshServers } from '../state/sshServers'@@ -291,7 +292,7 @@ export function Canvas() {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}`+ 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})@@ -499,25 +500,29 @@ export function Canvas() {// Serialized inputs for the active project's terminal/agent nodes (the sidebar reads the// serialized nodes of *inactive* projects directly from the store, but the active project's- // live state lives in React Flow — pass it through here).- const liveActiveNodes = useMemo<SessionNodeInput[]>(+ // live state lives in React Flow — pass it through here). Skipped entirely while the sidebar+ // is closed (the common case): this memo recomputes on every `nodes` change, i.e. every drag+ // frame, and the filter+map over all nodes would be pure waste with nobody consuming it.+ const liveActiveNodes = useMemo<SessionNodeInput[] | null>(() =>- nodes- .filter((n) => {- const k = n.type ?? 'terminal'- return k === 'terminal' || k === 'group'- })- .map((n) => ({- id: n.id,- kind: (n.type ?? 'terminal') as SessionNodeInput['kind'],- title: n.data.title ?? n.id,- color: n.data.color ?? '#888',- agentId: n.data.agentId,- cwd: n.data.cwd,- ssh: n.data.ssh,- parentId: n.parentId- })),- [nodes]+ sessionsOpen+ ? nodes+ .filter((n) => {+ const k = n.type ?? 'terminal'+ return k === 'terminal' || k === 'group'+ })+ .map((n) => ({+ id: n.id,+ kind: (n.type ?? 'terminal') as SessionNodeInput['kind'],+ title: n.data.title ?? n.id,+ color: n.data.color ?? '#888',+ agentId: n.data.agentId,+ cwd: n.data.cwd,+ ssh: n.data.ssh,+ parentId: n.parentId+ }))+ : null,+ [nodes, sessionsOpen])// 1) Load the whole workspace once and hydrate the projects store.@@ -647,17 +652,19 @@ export function Canvas() {// ---- remote canvas mirror (host side) ----// While hosting, push the serialized active-project canvas to main (debounced ~120ms) on every- // change, so a connected client mirrors the layout. Main holds the latest snapshot regardless- // of whether a client is connected and only broadcasts when one is — so this is safe to send- // unconditionally (no host-mode flag in the renderer). Skips programmatic loads to avoid a- // redundant push on project switch (the post-load value is captured by the next real change).+ // change, so a connected client mirrors the layout. Gated on the hosting flag: without it every+ // canvas edit paid a full flowToNodeStates serialize + IPC even with no client ever connecting.+ // When hosting flips on, the effect fires once immediately, so main's snapshot is fresh before+ // a client joins. Skips programmatic loads to avoid a redundant push on project switch (the+ // post-load value is captured by the next real change).+ const hosting = useRemoteHosting((s) => s.hosting)useEffect(() => {- if (loadingRef.current) return+ if (!hosting || loadingRef.current) returnconst t = setTimeout(() => {window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })}, 120)return () => clearTimeout(t)- }, [nodes])+ }, [nodes, hosting])// Apply a client's mutation to React Flow — the host's single writer. Serialize the live nodes,// apply the mutation, and convert back. A direct `setNodes(...)` bypasses `handleNodesChange`,@@ -1909,23 +1916,38 @@ 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]- )+ // Signatures are cached per data-object reference: a drag/resize creates new node objects but+ // keeps each node's `data` ref, so drag frames do pointer lookups + compares only — the old+ // version rebuilt one string per node (plus a big join) on every frame of a drag.+ const dataSigCacheRef = useRef(new WeakMap<object, string>())+ const lastDataSigsRef = useRef<string[] | null>(null)useEffect(() => {- markDirty()- }, [dataSignature, markDirty])+ const cache = dataSigCacheRef.current+ const sigs = new Array<string>(nodes.length)+ for (let i = 0; i < nodes.length; i++) {+ const n = nodes[i]+ let sig = cache.get(n.data)+ if (sig === undefined) {+ sig = `${n.id}:${n.data.title}:${n.data.color}:${n.data.text ?? ''}:${+ n.data.collapsed ? 1 : 0+ }:${((n.data.tags as string[]) ?? []).join(',')}`+ cache.set(n.data, sig)+ }+ sigs[i] = sig+ }+ const last = lastDataSigsRef.current+ lastDataSigsRef.current = sigs+ if (!last || last.length !== sigs.length) {+ markDirty() // mount/load runs are suppressed inside markDirty via loadingRef+ return+ }+ for (let i = 0; i < sigs.length; i++) {+ if (sigs[i] !== last[i]) {+ markDirty()+ return+ }+ }+ }, [nodes, markDirty])const zoomRafRef = useRef<number | null>(null)const onMove = useCallback(diff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsxindex 599c66494..8405956c1 100644--- a/src/renderer/components/RemoteAccessDialog.tsx+++ b/src/renderer/components/RemoteAccessDialog.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react'import { createPortal } from 'react-dom'import { useEntitlement } from '../state/entitlement'+import { useRemoteHosting } from '../state/remoteHosting'import { Button } from '@renderer/ui/Button'import { CopyButton } from '@renderer/ui/CopyButton'import { Input } from '@renderer/ui/Input'@@ -42,6 +43,7 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.try {const { offer } = await window.nodeTerminal.remoteHost.start()setHostOffer(offer)+ useRemoteHosting.getState().setHosting(true) // Canvas starts mirroring the canvas to main} catch (err) {setError((err as Error).message)setHostBusy(false)@@ -49,6 +51,7 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.}const stopHosting = async () => {await window.nodeTerminal.remoteHost.stop()+ useRemoteHosting.getState().setHosting(false)setHostOffer('')setHostBusy(false)}diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsxindex a27232229..3eec07241 100644--- a/src/renderer/components/SourceControlPanel.tsx+++ b/src/renderer/components/SourceControlPanel.tsx@@ -124,6 +124,33 @@ export function SourceControlPanel({refreshRef.current = refresh}, [refresh])+ // Coalesce refreshes: every stage/unstage/discard click triggers one, and each status()+ // fans out ~9 concurrent git subprocesses (history adds one more). The first call runs+ // immediately (instant feedback for a single click); calls landing while one is in flight+ // fold into exactly ONE follow-up run, so rapid-clicking N files costs 2 refreshes, not N.+ const refreshingRef = useRef(false)+ const refreshQueuedRef = useRef(false)+ const refreshHistoryRef = useRef(refreshHistory)+ useEffect(() => {+ refreshHistoryRef.current = refreshHistory+ }, [refreshHistory])+ const requestRefreshAll = useCallback(async () => {+ if (refreshingRef.current) {+ refreshQueuedRef.current = true+ return+ }+ refreshingRef.current = true+ try {+ do {+ refreshQueuedRef.current = false+ await refreshRef.current()+ await refreshHistoryRef.current()+ } while (refreshQueuedRef.current)+ } finally {+ refreshingRef.current = false+ }+ }, [])+// Auto-fetch while the panel is open so ahead/behind ("Synced") stays accurate — git's ahead/// behind is computed against the local remote-tracking ref, which only updates on `git fetch`.// SSH-project repos fetch on the remote via the Phase-4 chokepoint. Silent + fail-open: a failed@@ -156,8 +183,7 @@ export function SourceControlPanel({const r = await fn()setError(r.ok ? '' : r.message)setBusy(false)- await refresh()- void refreshHistory()+ await requestRefreshAll()}const discard = (f: GitFileChange) => {@@ -674,8 +700,7 @@ export function SourceControlPanel({setBusy(false)if (r.ok) {setError('')- await refresh()- await refreshHistory()+ await requestRefreshAll()return}if (r.needsAuth) {diff --git a/src/renderer/components/settings/sections/RemoteSection.tsx b/src/renderer/components/settings/sections/RemoteSection.tsxindex 9ac9e0948..73277c0d4 100644--- a/src/renderer/components/settings/sections/RemoteSection.tsx+++ b/src/renderer/components/settings/sections/RemoteSection.tsx@@ -1,5 +1,6 @@import { useState } from 'react'import { useEntitlement } from '../../../state/entitlement'+import { useRemoteHosting } from '../../../state/remoteHosting'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'@@ -35,6 +36,7 @@ export function RemoteSection({try {const { offer } = await window.nodeTerminal.remoteHost.start()setHostOffer(offer)+ useRemoteHosting.getState().setHosting(true) // Canvas starts mirroring the canvas to main} catch (err) {setRemoteError((err as Error).message)setHostBusy(false)@@ -42,6 +44,7 @@ export function RemoteSection({}const stopHosting = async () => {await window.nodeTerminal.remoteHost.stop()+ useRemoteHosting.getState().setHosting(false)setHostOffer('')setHostBusy(false)}diff --git a/src/renderer/nodes/DiffNode.tsx b/src/renderer/nodes/DiffNode.tsxindex 8e4dc2ca8..6a272d7d6 100644--- a/src/renderer/nodes/DiffNode.tsx+++ b/src/renderer/nodes/DiffNode.tsx@@ -1,10 +1,11 @@-import { useEffect, useRef } from 'react'+import { useEffect, useRef, useState } from 'react'import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'import { monaco } from '../editor/monaco-setup'import { useSettings } from '../state/settings'import { useProjects } from '../state/projects'import { sshFs } from '../terminal/ssh-fs'import type { CanvasNode } from '../state/workspace'+import { tooLargeSize, formatBytes } from '@shared/fsLimits'/*** A Monaco diff editor node for a changed file. Staged diff = HEAD vs index;@@ -13,6 +14,7 @@ import type { CanvasNode } from '../state/workspace'export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {const { deleteElements } = useReactFlow()const bodyRef = useRef<HTMLDivElement>(null)+ const [loadError, setLoadError] = useState('')const cwd = (data.cwd as string) ?? ''const rel = (data.filePath as string) ?? ''const staged = !!data.diffStaged@@ -50,6 +52,13 @@ export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {Promise.all([origP, modP]).then(([orig, mod]) => {if (disposed) return+ // The working-tree side goes through fs:read, which refuses very large files with a+ // sentinel — surface that instead of diffing the sentinel text as file content.+ const tooBig = tooLargeSize(orig) ?? tooLargeSize(mod)+ if (tooBig != null) {+ setLoadError(`File too large to diff here (${formatBytes(tooBig)}).`)+ return+ }const base = monaco.Uri.file(abs)const s = useSettings.getState().settingsoriginal = monaco.editor.createModel(orig, undefined, base.with({ fragment: `${id}-o` }))@@ -99,7 +108,15 @@ export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {</button></div>- <div className="editor-node__body nodrag nowheel" ref={bodyRef} />+ {loadError ? (+ <div className="editor-node__body nodrag">+ <div className="editor-node__image">+ <span className="editor-node__loading">{loadError}</span>+ </div>+ </div>+ ) : (+ <div className="editor-node__body nodrag nowheel" ref={bodyRef} />+ )}</div>)}diff --git a/src/renderer/nodes/EditorNode.tsx b/src/renderer/nodes/EditorNode.tsxindex d910c076c..001174ba4 100644--- a/src/renderer/nodes/EditorNode.tsx+++ b/src/renderer/nodes/EditorNode.tsx@@ -7,6 +7,7 @@ import { remoteFs } from '../terminal/remote-fs'import { sshFs } from '../terminal/ssh-fs'import { useProjects } from '../state/projects'import type { CanvasNode } from '../state/workspace'+import { tooLargeSize, formatBytes } from '@shared/fsLimits'// Image extensions get a visual preview instead of the Monaco text editor.const IMAGE_MIME: Record<string, string> = {@@ -38,6 +39,7 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {const [imageSrc, setImageSrc] = useState('')const [imageDims, setImageDims] = useState('')const [imageError, setImageError] = useState('')+ const [loadError, setLoadError] = useState('')const filePath = (data.filePath as string) ?? ''// Backend pick (the `FsApi` shape is identical across all three, so the rest of the component is// unchanged): a relay session operates on the HOST's filesystem via the relay; an SSH-project@@ -93,7 +95,9 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {readBinary(filePath).then((b64) => {if (disposed) return- if (b64) setImageSrc(`data:${IMAGE_MIME[ext]};base64,${b64}`)+ const tooBig = b64 ? tooLargeSize(b64) : null+ if (tooBig != null) setImageError(`Image too large to preview (${formatBytes(tooBig)}).`)+ else if (b64) setImageSrc(`data:${IMAGE_MIME[ext]};base64,${b64}`)else setImageError('Couldn’t read this image.')}).catch(() => {@@ -112,6 +116,13 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {fs.read(filePath).then((content) => {if (disposed) return+ const tooBig = tooLargeSize(content)+ if (tooBig != null) {+ // Refuse to open rather than showing an empty buffer: ⌘S on a placeholder would+ // overwrite the real (large) file with nothing.+ setLoadError(`File too large to open here (${formatBytes(tooBig)}).`)+ return+ }const s = useSettings.getState().settings// Unique model per node (fragment), language still inferred from the path extension.const uri = monaco.Uri.file(filePath).with({ fragment: id })@@ -216,6 +227,10 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {<span className="editor-node__loading">{imageError || 'Loading…'}</span>)}</div>+ ) : loadError ? (+ <div className="editor-node__image nodrag">+ <span className="editor-node__loading">{loadError}</span>+ </div>) : (<><div className="editor-node__monaco nodrag nowheel" ref={bodyRef} />diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 4581e2809..c047c0a3a 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -434,12 +434,21 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// fit can throw when the size is 0 (e.g. collapsed); ignore.}}- const observer = new ResizeObserver(resize)+ // Coalesce observer bursts: dragging the NodeResizer fires per animation frame, and every+ // call is a full cell-geometry measure + a resize IPC → node-pty → tmux (which redraws the+ // whole pane). One trailing fit per settle is enough — the canvas node frame itself still+ // tracks the drag live; only the terminal reflow waits for the pause.+ let resizeTimer: ReturnType<typeof setTimeout> | null = null+ const observer = new ResizeObserver(() => {+ if (resizeTimer) clearTimeout(resizeTimer)+ resizeTimer = setTimeout(resize, 80)+ })observer.observe(container)return () => {disposed = trueobserver.disconnect()+ if (resizeTimer) clearTimeout(resizeTimer)if (dwellRef.current) clearTimeout(dwellRef.current)cleanups.forEach((fn) => fn())useAgentStatus.getState().setActive(id, false)diff --git a/src/renderer/state/remoteHosting.ts b/src/renderer/state/remoteHosting.tsnew file mode 100644index 000000000..7dd92bfd9--- /dev/null+++ b/src/renderer/state/remoteHosting.ts@@ -0,0 +1,15 @@+import { create } from 'zustand'++/**+ * Whether THIS instance is currently serving remote clients (host mode). Set by the hosting+ * UIs around remoteHost.start()/stop(). Canvas gates its canvas-mirror IPC on it: without the+ * flag every canvas edit serialized the full node array and IPC'd it to main — pure waste for+ * the (default) non-hosting case. Fail-open: if teardown happens main-side without stop(),+ * the flag stays true and we merely keep mirroring, which is the old always-on behavior.+ */+export const useRemoteHosting = create<{ hosting: boolean; setHosting(v: boolean): void }>(+ (set) => ({+ hosting: false,+ setHosting: (hosting) => set({ hosting })+ })+)diff --git a/src/renderer/state/settings.ts b/src/renderer/state/settings.tsindex 9e7f2b997..af9bec8b0 100644--- a/src/renderer/state/settings.ts+++ b/src/renderer/state/settings.ts@@ -9,6 +9,31 @@ interface SettingsState {update(patch: Partial<Settings>): void}+// Coalesce disk writes: the settings inputs fire update() per keystroke/step-click, and each+// save is a full temp-file write + rename in main. The in-memory store stays synchronous (UI+// and xterm/Monaco react immediately); only the persistence trails, at most one write per+// window, always with the latest snapshot.+const SAVE_COALESCE_MS = 300+let saveTimer: ReturnType<typeof setTimeout> | null = null+let pendingSave: Settings | null = null+function scheduleSave(next: Settings): void {+ pendingSave = next+ if (saveTimer) return+ saveTimer = setTimeout(() => {+ saveTimer = null+ if (pendingSave) void window.nodeTerminal.settings.save(pendingSave)+ pendingSave = null+ }, SAVE_COALESCE_MS)+}+// Reload/quit inside the coalesce window must not lose the last edit. (Guarded: this module+// is transitively imported by node-environment unit tests, where `window` doesn't exist.)+if (typeof window !== 'undefined') {+ window.addEventListener('beforeunload', () => {+ if (pendingSave) void window.nodeTerminal.settings.save(pendingSave)+ pendingSave = null+ })+}+export const useSettings = create<SettingsState>((set, get) => ({settings: DEFAULT_SETTINGS,hydrated: false,@@ -21,6 +46,6 @@ export const useSettings = create<SettingsState>((set, get) => ({update(patch) {const next = { ...get().settings, ...patch }set({ settings: next })- void window.nodeTerminal.settings.save(next)+ scheduleSave(next)}}))diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 7af67d2d6..bda52ebfe 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -424,25 +424,41 @@ body,/* Unread (agent finished while unfocused): a blue glow around the whole node so it'sobvious at a glance, not just the small header badge. Pulses gently to draw the eye.- Selecting the node clears unread, so this never fights the selection ring. */+ Selecting the node clears unread, so this never fights the selection ring.+ The pulse animates OPACITY on a pseudo-element, never box-shadow: shadow animation forces+ a repaint of every glowing node each frame, which adds up with several unread agents. The+ pseudo lives on the React Flow wrapper (via :has) because .term-node is overflow:hidden+ and would clip its own ::after. */.term-node.unread {border-color: var(--accent);+ box-shadow:+ 0 0 0 1px rgba(10, 132, 255, 0.5),+ 0 0 16px 1px rgba(10, 132, 255, 0.35),+ 0 8px 28px rgba(0, 0, 0, 0.4);+}++.react-flow__node:has(.term-node.unread)::after {+ content: '';+ position: absolute;+ inset: 0;+ border-radius: 10px;+ pointer-events: none;+ z-index: -1;+ box-shadow:+ 0 0 0 1px rgba(10, 132, 255, 0.8),+ 0 0 26px 4px rgba(10, 132, 255, 0.6);+ opacity: 0;animation: nt-unread-glow 2s ease-in-out infinite;+ will-change: opacity;}@keyframes nt-unread-glow {0%,100% {- box-shadow:- 0 0 0 1px rgba(10, 132, 255, 0.5),- 0 0 16px 1px rgba(10, 132, 255, 0.35),- 0 8px 28px rgba(0, 0, 0, 0.4);+ opacity: 0;}50% {- box-shadow:- 0 0 0 1px rgba(10, 132, 255, 0.8),- 0 0 26px 4px rgba(10, 132, 255, 0.6),- 0 8px 28px rgba(0, 0, 0, 0.4);+ opacity: 1;}}diff --git a/src/shared/fsLimits.ts b/src/shared/fsLimits.tsnew file mode 100644index 000000000..62f8046a5--- /dev/null+++ b/src/shared/fsLimits.ts@@ -0,0 +1,29 @@+// Size guard for whole-file IPC reads (fs:read / fs:read-binary). The payload is loaded fully+// in the main process, then structured-cloned across to the renderer — an unbounded read of a+// huge file (a giant log, a video accidentally opened as text) spikes memory in BOTH processes+// in one shot. Reads above the cap return a sentinel string instead of content; it starts with+// a NUL byte, which no valid text/base64 payload can, so consumers can distinguish it cheaply+// and show "file too large" — critically, the editor must NOT open an empty buffer for such a+// file (saving it would truncate the real file).+export const FS_READ_MAX_BYTES = 10 * 1024 * 1024+export const FS_READ_BINARY_MAX_BYTES = 24 * 1024 * 1024++const TOO_LARGE_PREFIX = '\u0000nodeterm:too-large:'++export function tooLargeSentinel(sizeBytes: number): string {+ return `${TOO_LARGE_PREFIX}${sizeBytes}`+}++/** The file's byte size if `s` is a too-large sentinel, else null. */+export function tooLargeSize(s: string): number | null {+ if (!s.startsWith(TOO_LARGE_PREFIX)) return null+ const n = Number(s.slice(TOO_LARGE_PREFIX.length))+ return Number.isFinite(n) ? n : null+}++export function formatBytes(n: number): string {+ if (n >= 1024 * 1024 * 1024) return `${(n / (1024 * 1024 * 1024)).toFixed(1)} GB`+ if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`+ if (n >= 1024) return `${Math.round(n / 1024)} KB`+ return `${n} B`+}