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: cut startup payload and per-frame canvas work
enesc4c856e76218
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex f079a0dcc..ea7aba9fb 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -73,25 +73,29 @@ import {IconUngroup,IconUnlock} from '../components/icons'-import { SettingsPage } from '../components/settings/SettingsPage'import type { SettingsSectionId } from '../components/settings/nav'-import { SourceControlPanel } from '../components/SourceControlPanel'-import { WelcomeScreen } from '../components/WelcomeScreen'-import { CloneRepoDialog } from '../components/CloneRepoDialog'-import { ShortcutsPanel } from '../components/ShortcutsPanel'-import { OnboardingFlow } from '../components/onboarding/OnboardingFlow'+// Overlay surfaces (settings, source control, explorer, kanban, onboarding, dictation, …) are+// code-split: they render behind a flag and must not sit in the startup chunk. See lazyPanels.import {+ SettingsPage,+ SourceControlPanel,+ ExplorerPanel,+ ShortcutsPanel,+ OnboardingFlow,+ DictationOverlay,+ BugReportDialog,+ PhonePairPopover,MobileLaunchCard,- markMobileLaunchSeen,- shouldShowMobileLaunch-} from '../components/MobileLaunchCard'-import { DictationOverlay, type DictationTarget } from '../components/DictationOverlay'-import { BugReportDialog } from '../components/BugReportDialog'+ KanbanView+} from '../components/lazyPanels'+import { WelcomeScreen } from '../components/WelcomeScreen'+import { CloneRepoDialog } from '../components/CloneRepoDialog'+import { markMobileLaunchSeen, shouldShowMobileLaunch } from '../lib/mobileLaunch'+import type { DictationTarget } from '../components/DictationOverlay'import { describeOs, REPO_URL } from '../lib/bugReport'import { UpdateCard } from '../components/UpdateCard'import { AnnouncementBanner } from '../components/AnnouncementBanner'import { TmuxBanner } from '../components/TmuxBanner'-import { PhonePairPopover } from '../components/PhonePairPopover'import { ConflictBar } from '../components/ConflictBar'import { ConfirmDialog } from '../components/ConfirmDialog'import { ConsentNotice } from '../remote/ConsentNotice'@@ -101,7 +105,6 @@ import { UpgradeDialog } from '../components/UpgradeDialog'import { RemotePicker } from '../components/RemotePicker'import { WorktreeDialog } from '../components/WorktreeDialog'import { NotifyConsentDialog } from '../components/NotifyConsentDialog'-import { ExplorerPanel } from '../components/ExplorerPanel'import { SessionsSidebar } from '../components/SessionsSidebar'import type { SessionNodeInput } from '../lib/sessionList'import { UsageIndicator } from '../components/UsageIndicator'@@ -207,7 +210,7 @@ import { useEntitlement } from '../state/entitlement'import type { SshServer, SshConnection } from '@shared/ssh'import { sshHostKey } from '@shared/ssh'import type { CanvasNodeState, Project, ProjectKanban, SshProjectStatus, TranscriptHit } from '@shared/types'-import { KanbanView, type KanbanCreateChoice, type KanbanSession } from '../components/kanban/KanbanView'+import type { KanbanCreateChoice, KanbanSession } from '../components/kanban/KanbanView'import { assignNode, defaultKanban, labelsForCard, migrateProjectTags } from '../lib/kanban'import { registerWorkspaceDirty } from '../state/workspaceDirty'import { isHidden } from '../lib/ui-visibility'@@ -413,6 +416,57 @@ const minimapNodeColor = (n: Node): string =>const restartAgentIdOf = (n: Node | undefined): string | undefined =>!n || n.type !== 'terminal' ? undefined : createdAgentId(n.data)+/** One canvas node as a board card, or null when this kind is not a card at all (a group frame, an+ * editor, a diff). The board derives its cards from the canvas live, so this is the single+ * definition of that mapping — the card list and the board-log's `cardTitle` lookup must agree on+ * what a node is called, or a title change would log as a card appearing and disappearing. */+function toKanbanSession(n: CanvasNode): KanbanSession | null {+ if (n.type === 'browser') {+ return {+ id: n.id,+ title: (n.data.title as string) || 'Browser',+ color: (n.data.color as string) ?? NODE_COLORS[0],+ kind: 'browser',+ url: n.data.url as string | undefined,+ spawn: {}+ }+ }+ if (n.type === 'sticky') {+ const text = ((n.data.text as string) ?? '').trim()+ return {+ id: n.id,+ // A note has no title of its own — its first line is the card label.+ title: text.split('\n')[0].slice(0, 80) || 'Note',+ color: (n.data.color as string) ?? NODE_COLORS[2],+ kind: 'sticky',+ text,+ // Sticky cards never open a live terminal — the modal reads no spawn info.+ spawn: {}+ }+ }+ if (n.type !== 'terminal') return null+ return {+ id: n.id,+ title: (n.data.title as string) ?? '',+ color: (n.data.color as string) ?? NODE_COLORS[0],+ kind: 'terminal',+ agentId: n.data.agentId as string | undefined,+ // What the card modal's co-attach terminal needs to join THIS node's session the same way the+ // canvas TerminalNode does.+ spawn: {+ shell: n.data.shell as string | undefined,+ cwd: n.data.cwd as string | undefined,+ agentId: n.data.agentId as string | undefined,+ accountId: n.data.accountId as string | undefined,+ ssh: n.data.ssh as SshConnection | undefined,+ sshRemoteTmux: !!n.data.sshRemoteTmux+ }+ }+}++/** Stable empty card list, so the closed board's memo never churns array identity. */+const NO_KANBAN_SESSIONS: KanbanSession[] = []+/** Drop the separators a hidden row leaves dangling: the menu's rules are written between blocks,* so hiding every row of a block would otherwise emit two rules in a row (or one hanging at the* top / bottom). Also drops a rule directly under a section label, which reads as a double line.@@ -749,10 +803,6 @@ export function Canvas() {const settings = useSettings((s) => s.settings)const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })const nodesRef = useRef<CanvasNode[]>(nodes)- // Live mirror of the derived board cards (defined far below), so the board-log emission funnel- // in onKanbanChange — declared above kanbanSessions — can resolve a node's card title without a- // dep cycle. Assigned right after that useMemo, same render-mirror idiom as nodesRef.- const kanbanSessionsRef = useRef<KanbanSession[]>([])// focusNodeById, for callbacks declared ABOVE its definition (openFile's dedupe focuses the// already-open node). Assigned right after the definition, same render-mirror idiom as nodesRef.const focusNodeRef = useRef<(nodeId: string) => void>(() => {})@@ -1119,6 +1169,44 @@ export function Canvas() {.join('|'),[nodes])+ // Dep edges (`--after`) are DERIVED from node data, so the obvious thing is to build them inside+ // displayEdges off `nodes` — which is what this used to do, and it made `nodes` a dependency of+ // the edge list. `nodes` gets a fresh identity on every drag FRAME, so dragging one node rebuilt+ // every context link, rope and dep edge on the canvas ~60×/s (new object identities, so React+ // Flow re-rendered all of them too). Same discipline as `stickySig`/`loopSig`: reduce the part+ // that comes from `nodes` to a SIGNATURE, and hang the styled objects off that.+ //+ // The pairs themselves stay in `dependencyEdges` (the tested producer of both the id format and+ // the liveness rule); the ref carries them from the cheap per-frame pass to the styled memo,+ // which only re-runs when the signature — i.e. the actual set of pending dependencies — changes.+ const depPairsRef = useRef<ReturnType<typeof dependencyEdges>>([])+ const depEdgeSig = useMemo(() => {+ // Fast path: no armed node → no Set allocation, no pairs, and the signature stays ''.+ if (!nodes.some((n) => n.data.pendingLaunch)) {+ depPairsRef.current = []+ return ''+ }+ const pairs = dependencyEdges(nodes as unknown as ArmedNode[], new Set(nodes.map((n) => n.id)))+ depPairsRef.current = pairs+ return pairs.map((e) => e.id).join('|')+ }, [nodes])+ const depEdges = useMemo(+ () =>+ depPairsRef.current.map((e) => ({+ ...e,+ type: 'default' as const,+ animated: true,+ label: '⏳ waits for',+ labelStyle: { fill: '#8e8e93', fontSize: 11, fontWeight: 600 },+ labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },+ labelBgPadding: [6, 3] as [number, number],+ labelBgBorderRadius: 5,+ style: { stroke: '#8e8e93', strokeWidth: 1.5, strokeDasharray: '6 4' },+ markerEnd: { type: MarkerType.ArrowClosed, color: '#8e8e93', width: 14, height: 14 }+ })),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- depEdgeSig IS the ref's signature+ [depEdgeSig]+ )const displayEdges = useMemo(() => {const stickyIds = new Set(stickySig ? stickySig.split('|') : [])// ONE edge per pair. A node an agent opens gets both a rope (lineage) and a context bridge@@ -1172,29 +1260,16 @@ export function Canvas() {: e)// Waiting edges for armed nodes (`--after`): dep → dependent, dashed and animated while the- // wait is on. Derived from node data every time rather than persisted — a pending dependency- // is a STATE that ends when the launch fires, unlike the context bridge `--after` also draws,- // which is a durable relation and stays.- const deps = dependencyEdges(nodes as unknown as ArmedNode[], new Set(nodes.map((n) => n.id))).map(- (e) => ({- ...e,- type: 'default' as const,- animated: true,- label: '⏳ waits for',- labelStyle: { fill: '#8e8e93', fontSize: 11, fontWeight: 600 },- labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },- labelBgPadding: [6, 3] as [number, number],- labelBgBorderRadius: 5,- style: { stroke: '#8e8e93', strokeWidth: 1.5, strokeDasharray: '6 4' },- markerEnd: { type: MarkerType.ArrowClosed, color: '#8e8e93', width: 14, height: 14 }- })- )+ // wait is on. Derived from node data rather than persisted — a pending dependency is a STATE+ // that ends when the launch fires, unlike the context bridge `--after` also draws, which is a+ // durable relation and stays. Built above (depEdges), keyed on the dependency signature so a+ // drag frame does not rebuild it.const extra =- ephemeralEdges.length || ropes.length || deps.length- ? [...ephemeralEdges, ...ropes, ...deps]+ ephemeralEdges.length || ropes.length || depEdges.length+ ? [...ephemeralEdges, ...ropes, ...depEdges]: []return extra.length ? [...decorated, ...extra] : decorated- }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig, nodes])+ }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig, depEdges])// Header pin button (and ⌘⇧L): toggle the persisted pin preference. Clears the transient// dismiss so (re)pinning shows the docked panel; unpinning collapses it to hover-peek.@@ -1501,11 +1576,13 @@ export function Canvas() {markDirty() // rides the existing debounced persist (commitActiveToStore + workspace.save)// cardTitle must return '' for — and ONLY for — nodes that no longer exist (the diff reads// '' as "pruned removal, not a move"). A LIVE node with an empty title maps to 'Untitled',- // never '' (see boardLogEvents' JSDoc).- const sessions = kanbanSessionsRef.current+ // never '' (see boardLogEvents' JSDoc). Resolved from the live nodes through the same+ // `toKanbanSession` the card list uses, so the two can't disagree about a node's name — and+ // so this does not depend on the derived list, which only exists while the board is open.const cardTitle = (nodeId: string): string => {- const s = sessions.find((x) => x.id === nodeId)- return s ? s.title || 'Untitled' : ''+ const n = nodesRef.current.find((x) => x.id === nodeId)+ const card = n ? toKanbanSession(n) : null+ return card ? card.title || 'Untitled' : ''}for (const { nodeId, event } of boardLogEvents(prev, next, cardTitle)) {useBoardLog.getState().append(api, id, { kind: 'event', nodeId, event })@@ -1516,9 +1593,15 @@ export function Canvas() {// The node states that go on the wire: React Flow's managed nodes minus the ephemeral cards// (subagent / loop), which every client derives for itself from the agent:status stream.- const publishableNow = useCallback((flow: CanvasNode[]): CanvasNodeState[] => {+ //+ // Returns a THUNK, and the publisher decides whether to call it (see CanvasSnapshot). The+ // serialize is the expensive half of publishing and this runs from an effect keyed on `nodes` —+ // once per drag FRAME — so handing over an array meant a solo user paid the whole cost of a+ // feature the publisher's own solo gate then declined to use. What must NOT be deferred is the+ // ephemeral-id set: it is read from a live store, so it is captured here, as of this call.+ const publishableLater = useCallback((flow: CanvasNode[]): (() => CanvasNodeState[]) => {const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))- return publishableStates(flowToNodeStates(flow), ephIds)+ return () => publishableStates(flowToNodeStates(flow), ephIds)}, [])// ---- persistence helpers ----@@ -1779,13 +1862,13 @@ export function Canvas() {useEffect(() => {const pub = publisherRef.currentif (!pub) return- const states = publishableNow(nodes)+ const states = publishableLater(nodes)if (loadingRef.current) {pub.adopt(states)return}pub.publish(states, { throttle: draggingRef.current })- }, [nodes, publishableNow])+ }, [nodes, publishableLater])// Receiving side: apply an incoming mutation. Deliberately separate from the relay// `remoteHost.onApplyMutation` effect above — that one is host↔client, this one is peer↔peer.@@ -1840,7 +1923,7 @@ export function Canvas() {// Keep the ref in step immediately: a burst (a peer's bulk delete) arrives within one tick,// before React re-renders, and each mutation must build on the previous one.nodesRef.current = flow- publisherRef.current?.adopt(publishableNow(flow))+ publisherRef.current?.adopt(publishableLater(flow))// Undo stays LOCAL — but it must not EAT a local entry either. REBASE the committed baseline// by applying the peer's mutation to it, rather than replacing it with the current nodes:// replacing it made `nodes === committedRef.current`, so a local edit still inside the 300 ms@@ -1851,7 +1934,7 @@ export function Canvas() {setNodes(flow)markDirty()})- }, [activeSession.api, setNodes, markDirty, publishableNow])+ }, [activeSession.api, setNodes, markDirty, publishableLater])// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).useEffect(() => {@@ -2088,6 +2171,9 @@ export function Canvas() {// Prune ropes whose endpoints were deleted (mirrors the context-link pruning below).useEffect(() => {+ // Nothing to prune → don't build the id set. This effect runs on every drag FRAME (`nodes`+ // identity), and most canvases have no ropes at all.+ if (!controlEdgesRef.current.length) returnconst ids = new Set(nodes.map((n) => n.id))setControlEdges((es) => {const valid = es.filter((e) => ids.has(e.source) && ids.has(e.target))@@ -4875,55 +4961,18 @@ export function Canvas() {focusNodeRef.current = focusNodeById// Session board cards are derived LIVE from the canvas nodes; the board stores only assignments.+ // Only while the board is OPEN: `nodes` gets a fresh identity on every drag frame, so a closed+ // board was rebuilding a card object per node ~60×/s for a surface that is not mounted. The+ // board's own consumer is rendered under the same `kanbanOpen` flag, and the board-log's+ // `cardTitle` reads the nodes directly (see onKanbanChange), so nothing else depends on this+ // list existing while the canvas is what you are looking at.const kanbanSessions = useMemo(() =>- nodes- .filter((n) => n.type === 'terminal' || n.type === 'sticky' || n.type === 'browser')- .map((n) => {- if (n.type === 'browser') {- return {- id: n.id,- title: (n.data.title as string) || 'Browser',- color: (n.data.color as string) ?? NODE_COLORS[0],- kind: 'browser' as const,- url: n.data.url as string | undefined,- spawn: {}- }- }- if (n.type === 'sticky') {- const text = ((n.data.text as string) ?? '').trim()- return {- id: n.id,- // A note has no title of its own — its first line is the card label.- title: text.split('\n')[0].slice(0, 80) || 'Note',- color: (n.data.color as string) ?? NODE_COLORS[2],- kind: 'sticky' as const,- text,- // Sticky cards never open a live terminal — the modal reads no spawn info.- spawn: {}- }- }- return {- id: n.id,- title: (n.data.title as string) ?? '',- color: (n.data.color as string) ?? NODE_COLORS[0],- kind: 'terminal' as const,- agentId: n.data.agentId as string | undefined,- // What the card modal's co-attach terminal needs to join THIS node's session the same- // way the canvas TerminalNode does.- spawn: {- shell: n.data.shell as string | undefined,- cwd: n.data.cwd as string | undefined,- agentId: n.data.agentId as string | undefined,- accountId: n.data.accountId as string | undefined,- ssh: n.data.ssh as SshConnection | undefined,- sshRemoteTmux: !!n.data.sshRemoteTmux- }- }- }),- [nodes]+ kanbanOpen+ ? nodes.map(toKanbanSession).filter((s): s is KanbanSession => s !== null)+ : NO_KANBAN_SESSIONS,+ [nodes, kanbanOpen])- kanbanSessionsRef.current = kanbanSessions// Create a node from the board's per-column "+ New" menu: it lands on the canvas (view// center) and, for a real column, is assigned there. The assignment is written directly —diff --git a/src/renderer/components/BugReportDialog.tsx b/src/renderer/components/BugReportDialog.tsxindex 885f3e4a5..1db4bc6a4 100644--- a/src/renderer/components/BugReportDialog.tsx+++ b/src/renderer/components/BugReportDialog.tsx@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'import { useDialogStack } from './dialog-stack'import { BODY_BUDGET, buildBugReportUrl, envBlock, type BugReportEnv } from '../lib/bugReport'-interface BugReportDialogProps {+export interface BugReportDialogProps {env: BugReportEnv/** Receives the composed issues/new URL; the caller opens it (shell.openExternal). */onOpen: (url: string) => voiddiff --git a/src/renderer/components/DictationOverlay.tsx b/src/renderer/components/DictationOverlay.tsxindex ad9e271fc..cc3cd6cbe 100644--- a/src/renderer/components/DictationOverlay.tsx+++ b/src/renderer/components/DictationOverlay.tsx@@ -24,7 +24,7 @@ export interface DictationTarget {title: string}-interface DictationOverlayProps {+export interface DictationOverlayProps {target: DictationTarget | null/** Bumped by Canvas's toggleDictation on a second shortcut/Dock-mic press while the overlay is* already open. A no-op prop change is the signal (any new value ≠ close-then-reopen — thediff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsxindex ec128e4ba..7831dce58 100644--- a/src/renderer/components/ExplorerPanel.tsx+++ b/src/renderer/components/ExplorerPanel.tsx@@ -11,7 +11,7 @@ import { ancestorDirs, createTargetDir, newEntryPath, parentDir } from '../lib/eimport { canRevealLocally, downloadRoute, triggerBrowserDownload } from '../lib/download'import { isBrowserRuntime } from '../bridge/runtime'-interface ExplorerPanelProps {+export interface ExplorerPanelProps {onClose: () => void/** Open a file as an editor node. `sshFs` is true for SSH projects (the path is remote, read/* written over the project's ControlMaster fs); false/omitted for local + relay projects. */diff --git a/src/renderer/components/MobileLaunchCard.tsx b/src/renderer/components/MobileLaunchCard.tsxindex 69c57bda6..1c6881777 100644--- a/src/renderer/components/MobileLaunchCard.tsx+++ b/src/renderer/components/MobileLaunchCard.tsx@@ -2,27 +2,9 @@ import { useEffect } from 'react'import { createPortal } from 'react-dom'import { ScenePhone } from './onboarding/scenes'import { IOS_APP_STORE_URL } from '@renderer/lib/links'--/** One-shot flag: the mobile-launch announcement has been shown and closed (or pre-empted by- * the setup tour, whose phone step makes the same pitch to fresh installs). localStorage, not- * settings — it is per-machine presentation state, like dismissed announcement banners. */-const MOBILE_LAUNCH_SEEN_KEY = 'nodeterm.seenMobileLaunch'--export function markMobileLaunchSeen(): void {- try {- localStorage.setItem(MOBILE_LAUNCH_SEEN_KEY, '1')- } catch {- // storage unavailable: worst case the card shows again next launch- }-}--export function shouldShowMobileLaunch(): boolean {- try {- return localStorage.getItem(MOBILE_LAUNCH_SEEN_KEY) == null- } catch {- return false- }-}+// The seen-flag helpers live in lib/mobileLaunch: Canvas reads them on every launch, and importing+// them from here would defeat this component's (and the onboarding scenes') code splitting.+export { markMobileLaunchSeen, shouldShowMobileLaunch } from '@renderer/lib/mobileLaunch'/*** One-time launch announcement for nodeterm mobile (App Store release): a centered card overdiff --git a/src/renderer/components/ShortcutsPanel.tsx b/src/renderer/components/ShortcutsPanel.tsxindex 994795867..c8dc0a187 100644--- a/src/renderer/components/ShortcutsPanel.tsx+++ b/src/renderer/components/ShortcutsPanel.tsx@@ -6,7 +6,7 @@ import { useSettings } from '../state/settings'const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)import { keyLabel } from '@shared/platform-utils'-interface ShortcutsPanelProps {+export interface ShortcutsPanelProps {onClose: () => void}diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsxindex cc0c50134..d0654f4da 100644--- a/src/renderer/components/SourceControlPanel.tsx+++ b/src/renderer/components/SourceControlPanel.tsx@@ -18,7 +18,7 @@ import { PublishDialog } from './PublishDialog'import { defaultScmScope, type ScmScope } from '@shared/scm-scope'import { hintLabel } from '@shared/platform-utils'-interface SourceControlPanelProps {+export interface SourceControlPanelProps {onClose: () => void// Every callback that opens something takes the ACTIVE SCOPE's cwd: the paths this panel hands// out are relative to the checkout it is showing, so the caller must root them there instead ofdiff --git a/src/renderer/components/kanban/KanbanColumn.tsx b/src/renderer/components/kanban/KanbanColumn.tsxindex ce3a3d5e1..2efea57b4 100644--- a/src/renderer/components/kanban/KanbanColumn.tsx+++ b/src/renderer/components/kanban/KanbanColumn.tsx@@ -1,6 +1,5 @@import { useState } from 'react'import type { KanbanColumn as KanbanColumnT } from '@shared/types'-import type { AgentNodeStatus } from '../../state/agentStatus'import { NODE_COLORS } from '../../state/workspace'import { SessionCard } from './SessionCard'import type { KanbanCardMeta, KanbanLabel } from '@shared/types'@@ -10,7 +9,6 @@ interface KanbanColumnProps {/** null = the virtual Ungrouped column: fixed label, no rename/recolor/delete, header not draggable. */column: KanbanColumnT | nullcards: KanbanSession[]- statusById: Record<string, AgentNodeStatus>onRename?: (title: string) => voidonRecolor?: (color: string) => voidonDelete?: () => void@@ -35,7 +33,7 @@ interface KanbanColumnProps {}export function KanbanColumn({- column, cards, statusById, metaOf, labelsOf, onRename, onRecolor, onDelete, onOpenCard, onCardContext,+ column, cards, metaOf, labelsOf, onRename, onRecolor, onDelete, onOpenCard, onCardContext,createOptions, onCreate, onCardDragStart, onColumnDragStart, onDragEnd, onDropOnColumn,onDropAtCard}: KanbanColumnProps) {@@ -135,7 +133,6 @@ export function KanbanColumn({<SessionCardkey={s.id}session={s}- status={statusById[s.id]}meta={metaOf(s.id)}labels={labelsOf(s.id)}onOpen={() => onOpenCard(s.id)}diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsxindex 1943d9d75..699974df8 100644--- a/src/renderer/components/kanban/KanbanView.tsx+++ b/src/renderer/components/kanban/KanbanView.tsx@@ -49,7 +49,7 @@ export interface KanbanCreateOption {icon: JSX.Element}-interface KanbanViewProps {+export interface KanbanViewProps {board: ProjectKanbansessions: KanbanSession[]onChange: (next: ProjectKanban) => void@@ -110,7 +110,6 @@ export function KanbanView({setModalNodeId(requestedCardNodeId)useViewMode.getState().clearCardRequest()}, [requestedCardNodeId])- const statusById = useAgentStatus((s) => s.byId)// Primitive selectors (not one object) — an object selector would re-render on every store set.const projectName = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.name)const projectColor = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.color)@@ -248,7 +247,6 @@ export function KanbanView({<KanbanColumncolumn={null}cards={sessionsFor(visible(unassigned(board, sessions.map((s) => s.id))))}- statusById={statusById}metaOf={(id) => cardMeta(board, id)}labelsOf={(id) => labelsForCard(board, id)}onOpenCard={setModalNodeId}@@ -265,8 +263,7 @@ export function KanbanView({key={col.id}column={col}cards={sessionsFor(visible(assignedTo(board, col.id)))}- statusById={statusById}- metaOf={(id) => cardMeta(board, id)}+ metaOf={(id) => cardMeta(board, id)}labelsOf={(id) => labelsForCard(board, id)}onRename={(t) => commit(renameColumn(board, col.id, t))}onRecolor={(c) => commit(recolorColumn(board, col.id, c))}diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex 6565355af..f13e35ae2 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -1,13 +1,12 @@import { useState } from 'react'import type { KanbanCardMeta, KanbanLabel, KanbanPriority } from '@shared/types'-import type { AgentNodeStatus } from '../../state/agentStatus'+import { useAgentStatus } from '../../state/agentStatus'import { ContextMeter } from '../ContextMeter'import { LabelChips } from './LabelChips'import type { KanbanSession } from './KanbanView'interface SessionCardProps {session: KanbanSession- status?: AgentNodeStatusmeta?: KanbanCardMeta/** Resolved board labels on this card (LabelChips) — resolved by the board, passed in. */labels?: KanbanLabel[]@@ -21,7 +20,14 @@ interface SessionCardProps {onContext: (x: number, y: number) => void}-export function SessionCard({ session, status, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext }: SessionCardProps) {+export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext }: SessionCardProps) {+ // THIS card's agent status, subscribed per card rather than threaded down from the board.+ // KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:+ // that map's identity changes on every hook event of every node, so one agent's working→idle+ // flip re-rendered the whole board — every column, every card. The same rule Canvas follows+ // (see its loopSig comment) and StatusAwareMiniMap demonstrates: subscribe where the value is+ // read, so the re-render is confined to the one thing that changed.+ const status = useAgentStatus((s) => s.byId[session.id])// Local drag state only styles THIS card (ghost look) — the drag payload lives in KanbanView.const [dragging, setDragging] = useState(false)// Which edge a drag is hovering over → shows the drop line (top = before, bottom = after).diff --git a/src/renderer/components/lazyPanels.tsx b/src/renderer/components/lazyPanels.tsxnew file mode 100644index 000000000..84966dda1--- /dev/null+++ b/src/renderer/components/lazyPanels.tsx@@ -0,0 +1,73 @@+import {+ Suspense,+ lazy,+ type ComponentType,+ type LazyExoticComponent,+ type ReactElement+} from 'react'++// Overlay surfaces, code-split out of the startup chunk.+//+// Every one of these is rendered behind a flag (`{settingsOpen && <SettingsPage …>}`) and most of+// them are never opened in a given session — yet importing them statically put all of them, and+// everything they pull in (the whole Settings tree, the kanban board, the speech capture pipeline,+// `qrcode`), into the bundle the app parses before it can paint a single terminal. The canvas, its+// nodes and the tab bar are the startup path; a panel is not.+//+// Same trick as `nodes/lazyMonacoNodes.tsx`, one layer up: these wrappers keep the exact prop types+// of the components they stand in for, so Canvas's JSX does not change at all — only where the+// names are imported from.+//+// The fallback is `null` deliberately: these are modals and drawers opened by a click, they animate+// in anyway, and a spinner that appears for one frame on a local chunk load is worse than nothing.++/** Wrap a lazily-loaded component so callers can use it exactly like the original. */+function withSuspense<P extends object>(+ Inner: LazyExoticComponent<ComponentType<P>>+): (props: P) => ReactElement {+ // Spreading a still-generic `P` into JSX is what TypeScript will not check (it cannot know P has+ // no `ref`/`key` conflict until it is instantiated), so the cast is confined to this one line.+ // The RETURNED signature is exact — every call site is fully type-checked against the real+ // component's props.+ const Component = Inner as unknown as ComponentType<Record<string, unknown>>+ return function Lazy(props: P) {+ return (+ <Suspense fallback={null}>+ <Component {...(props as Record<string, unknown>)} />+ </Suspense>+ )+ }+}++export const SettingsPage = withSuspense(+ lazy(() => import('./settings/SettingsPage').then((m) => ({ default: m.SettingsPage })))+)+export const SourceControlPanel = withSuspense(+ lazy(() => import('./SourceControlPanel').then((m) => ({ default: m.SourceControlPanel })))+)+export const ExplorerPanel = withSuspense(+ lazy(() => import('./ExplorerPanel').then((m) => ({ default: m.ExplorerPanel })))+)+export const ShortcutsPanel = withSuspense(+ lazy(() => import('./ShortcutsPanel').then((m) => ({ default: m.ShortcutsPanel })))+)+export const OnboardingFlow = withSuspense(+ lazy(() => import('./onboarding/OnboardingFlow').then((m) => ({ default: m.OnboardingFlow })))+)+export const DictationOverlay = withSuspense(+ lazy(() => import('./DictationOverlay').then((m) => ({ default: m.DictationOverlay })))+)+export const BugReportDialog = withSuspense(+ lazy(() => import('./BugReportDialog').then((m) => ({ default: m.BugReportDialog })))+)+export const MobileLaunchCard = withSuspense(+ lazy(() => import('./MobileLaunchCard').then((m) => ({ default: m.MobileLaunchCard })))+)+// Pulls `qrcode` (the live pairing QR) — a whole encoder in the startup chunk for a popover most+// launches never open.+export const PhonePairPopover = withSuspense(+ lazy(() => import('./PhonePairPopover').then((m) => ({ default: m.PhonePairPopover })))+)+export const KanbanView = withSuspense(+ lazy(() => import('./kanban/KanbanView').then((m) => ({ default: m.KanbanView })))+)diff --git a/src/renderer/lib/mobileLaunch.ts b/src/renderer/lib/mobileLaunch.tsnew file mode 100644index 000000000..318604184--- /dev/null+++ b/src/renderer/lib/mobileLaunch.ts@@ -0,0 +1,25 @@+/** One-shot flag: the mobile-launch announcement has been shown and closed (or pre-empted by+ * the setup tour, whose phone step makes the same pitch to fresh installs). localStorage, not+ * settings — it is per-machine presentation state, like dismissed announcement banners.+ *+ * Lives apart from `MobileLaunchCard` because Canvas reads the flag on EVERY launch to decide+ * whether to render the card at all: importing it from the component would pull the card — and+ * the onboarding scene artwork it draws — into the startup chunk for the (overwhelmingly common)+ * case where the answer is "no, already seen". */+const MOBILE_LAUNCH_SEEN_KEY = 'nodeterm.seenMobileLaunch'++export function markMobileLaunchSeen(): void {+ try {+ localStorage.setItem(MOBILE_LAUNCH_SEEN_KEY, '1')+ } catch {+ // storage unavailable: worst case the card shows again next launch+ }+}++export function shouldShowMobileLaunch(): boolean {+ try {+ return localStorage.getItem(MOBILE_LAUNCH_SEEN_KEY) == null+ } catch {+ return false+ }+}diff --git a/src/renderer/nodes/GroupNode.tsx b/src/renderer/nodes/GroupNode.tsxindex 666a9b6c9..66e92ddd5 100644--- a/src/renderer/nodes/GroupNode.tsx+++ b/src/renderer/nodes/GroupNode.tsx@@ -1,8 +1,8 @@-import { useEffect, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'import { NODE_COLORS, ungroupNodes, type CanvasNode } from '../state/workspace'import { useProjects } from '../state/projects'-import { useWorktrees, WORKTREE_STATUS_THROTTLE_MS } from '../state/worktrees'+import { useWorktrees, WORKTREE_STATUS_POLL_MS } from '../state/worktrees'export type WorktreeAction = 'merge' | 'remove' | 'unbind'@@ -28,6 +28,8 @@ export function setWorktreeActionHandler(export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {const { updateNodeData, setNodes } = useReactFlow()const [showColors, setShowColors] = useState(false)+ // The frame element, observed for viewport visibility by the worktree-status tick below.+ const frameRef = useRef<HTMLDivElement | null>(null)const wt = data.worktree// The store is the ONLY caller of the worktree/status git IPC; it throttles@@ -54,24 +56,54 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {// e.g. the user restored it, or a git read failed transiently), and the poke carries the group id// so the store can flip staleness live instead of only at project load.//- // `git status` is the full Source-Control read (~10 git subprocesses), so it is gated on page- // visibility: a hidden tab / minimized window polls nothing, and a `visibilitychange` back to- // visible pokes immediately so the chip is correct the moment it is seen again. (Gating here- // rather than hoisting a single store-owned timer keeps the poll tied to the node's own- // mount/unmount lifecycle — no registry to leak — and the store's throttle already coalesces- // several groups on the same path.)+ // `git status` is the full Source-Control read (ELEVEN git subprocesses — see git-service's+ // `status`), and it is per BOUND GROUP: nothing coalesces two worktrees, because they are+ // different paths. So the tick is gated twice and runs slowly:+ // - **page visibility** — a hidden tab / minimized window polls nothing, and a+ // `visibilitychange` back to visible pokes immediately so the chip is correct the moment it+ // is seen again;+ // - **viewport** — React Flow keeps every node MOUNTED regardless of the camera (we do not set+ // `onlyRenderVisibleElements`), so without this a frame parked off-screen kept spawning git+ // for a chip nobody could see. An IntersectionObserver against the document viewport is the+ // same shape the WebGL budget uses; entering the viewport pokes at once.+ // The cadence is WORKTREE_STATUS_POLL_MS, deliberately far slower than the store's throttle+ // floor: the throttle exists so several pokes in one window cost one read, NOT as a target rate.+ // A dirty-file counter on a frame is ambient information (Source Control's own auto-fetch is+ // 180 s); an explicit poke — visibility, viewport entry, mount — still refreshes within the 4 s+ // floor, so the chip stays responsive to the things the user actually does.+ //+ // (Gating here rather than hoisting a single store-owned timer keeps the poll tied to the node's+ // own mount/unmount lifecycle — no registry to leak.)useEffect(() => {if (!wtPath) return+ const el = frameRef.current+ // Assume visible when there is no element to observe (jsdom, or a pre-paint mount): the old+ // behaviour, i.e. never quieter than it needs to be at the cost of a poll.+ let onScreen = trueconst poke = (): void => {- if (document.visibilityState === 'hidden') return+ if (document.visibilityState === 'hidden' || !onScreen) returnvoid useWorktrees.getState().refreshStatus(wtPath, id)}poke()- const t = setInterval(poke, WORKTREE_STATUS_THROTTLE_MS)+ const t = setInterval(poke, WORKTREE_STATUS_POLL_MS)document.addEventListener('visibilitychange', poke)+ const io =+ el && typeof IntersectionObserver !== 'undefined'+ ? new IntersectionObserver(+ (entries) => {+ const next = entries[entries.length - 1]?.isIntersecting ?? true+ const entered = next && !onScreen+ onScreen = next+ if (entered) poke()+ },+ { rootMargin: '200px' }+ )+ : null+ if (el && io) io.observe(el)return () => {clearInterval(t)document.removeEventListener('visibilitychange', poke)+ io?.disconnect()}}, [wtPath, id])@@ -98,6 +130,7 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {return (<div+ ref={frameRef}className={frameClass}style={{borderColor: bound && stale ? undefined : data.color,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 1696f94ae..f6e0fd354 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react'import {Handle,NodeResizer,@@ -11,8 +11,11 @@ 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'+// ChatPanel (the ⌘M transcript view) is code-split with the markdown renderer it uses: neither is+// on the path to painting a terminal, and both were in the startup chunk purely by being imported+// here. `lazy` + a null fallback — the panel replaces the terminal body on a keypress, and a+// one-frame spinner in that slot reads as a glitch.+const ChatPanel = lazy(() => import('./ChatPanel').then((m) => ({ default: m.ChatPanel })))import { LocalTransport } from '../terminal/local-transport'import { droppedPaths, pastedFiles } from '../terminal/file-drop'import type { TerminalTransport } from '../terminal/transport'@@ -1691,7 +1694,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNuseEffect(() => {if (data.mdMode && !useChat) {// Full scrollback (not just the visible viewport) so the whole session renders.- void api.pty.capture(id, true).then((t) => setMdHtml(renderMarkdown(t)))+ // `marked` + DOMPurify are imported HERE rather than at module scope: this node is on the+ // startup path (it is what the canvas is made of), the markdown renderer is not — it runs+ // only after someone presses ⌘M. The capture is already a round trip to main, so the extra+ // chunk fetch is not even on a path the user can perceive.+ void Promise.all([api.pty.capture(id, true), import('../lib/markdown')]).then(+ ([text, md]) => setMdHtml(md.renderMarkdown(text))+ )}}, [data.mdMode, id, useChat])@@ -2087,12 +2096,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN)}{mdMode &&(useChat ? (- <ChatPanel- nodeId={id}- sessionId={status?.sessionId}- cwd={data.cwd as string | undefined}- accountId={data.accountId}- />+ <Suspense fallback={null}>+ <ChatPanel+ nodeId={id}+ sessionId={status?.sessionId}+ cwd={data.cwd as string | undefined}+ accountId={data.accountId}+ />+ </Suspense>) : (<div className="term-md nodrag nowheel"><div className="term-md__bar">diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.tsindex be54f6a11..558e596b4 100644--- a/src/renderer/state/worktrees.ts+++ b/src/renderer/state/worktrees.ts@@ -20,9 +20,23 @@ export interface WorktreeStatus {hasOrigin: boolean}-/** The chip re-renders constantly; without this, every render would spawn a `git status`. */+/**+ * Coalescing FLOOR, not a target rate: the chip re-renders constantly and several groups can poke+ * within one window, so this is what stops every render (and every poke) from spawning a+ * `git status`. An explicit poke — a group frame mounting, the tab becoming visible again, a frame+ * scrolling into view — still gets a fresh read as soon as the floor allows.+ */export const WORKTREE_STATUS_THROTTLE_MS = 4000+/**+ * How often a mounted, VISIBLE, on-screen group frame re-reads its worktree status in the+ * background. `git.status()` is eleven git subprocesses and runs per bound group, so a tick at the+ * throttle floor meant a canvas with three worktrees spawned ~8 processes a second forever, for a+ * dirty-file counter nobody was reading. Ambient information gets an ambient cadence (Source+ * Control's own auto-fetch is 180 s); everything the user actually does still pokes immediately.+ */+export const WORKTREE_STATUS_POLL_MS = 20_000+/*** How many CONSECUTIVE "this is not a repo" reads it takes to declare a bound worktree missing.*diff --git a/src/server/http.test.ts b/src/server/http.test.tsindex d08521ce5..d391a682a 100644--- a/src/server/http.test.ts+++ b/src/server/http.test.ts@@ -3,8 +3,15 @@ import http from 'http'import fs from 'fs'import os from 'os'import path from 'path'+import zlib from 'zlib'import { Auth } from './auth'-import { createHttpHandler, sessionTokenFromCookie, SESSION_COOKIE } from './http'+import {+ createHttpHandler,+ sessionTokenFromCookie,+ negotiateEncoding,+ _resetStaticCacheForTest,+ SESSION_COOKIE+} from './http'import { parseTrustedNets } from './proxy-trust'let dir: string, rendererDir: string, server: http.Server, base: string, auth: Auth@@ -119,6 +126,131 @@ describe('http layer', () => {}})+ // The browser client is the whole point of the Server Edition and it is usually not on this+ // LAN, so how the bundle goes over the wire is a feature, not a detail: the entry chunk is+ // ~2.1 MB raw against ~0.46 MB gzipped, and a reload that revalidates costs a 304 instead of+ // the whole thing.+ describe('static delivery', () => {+ /** Raw request: `fetch` negotiates and transparently decodes, which is exactly what these+ * assertions need to see. */+ function rawGet(+ pathname: string,+ headers: Record<string, string>+ ): Promise<{ status: number; headers: http.IncomingHttpHeaders; body: Buffer }> {+ return new Promise((resolve, reject) => {+ const req = http.get(`${base}${pathname}`, { headers }, (res) => {+ const chunks: Buffer[] = []+ res.on('data', (c: Buffer) => chunks.push(c))+ res.on('end', () =>+ resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) })+ )+ })+ req.on('error', reject)+ })+ }++ /** A hashed asset big enough to be worth compressing (see COMPRESS_MIN_BYTES). */+ function writeAsset(name: string, body: string): string {+ fs.mkdirSync(path.join(rendererDir, 'assets'), { recursive: true })+ fs.writeFileSync(path.join(rendererDir, 'assets', name), body)+ return body+ }++ afterEach(() => _resetStaticCacheForTest())++ it('negotiateEncoding prefers brotli, falls back to gzip, honours q=0', () => {+ expect(negotiateEncoding('gzip, deflate, br')).toBe('br')+ expect(negotiateEncoding('gzip, deflate')).toBe('gzip')+ expect(negotiateEncoding('br;q=0, gzip')).toBe('gzip')+ expect(negotiateEncoding('gzip;q=0')).toBeNull()+ expect(negotiateEncoding('identity')).toBeNull()+ expect(negotiateEncoding(undefined)).toBeNull()+ })++ it('compresses a large asset and serves the exact bytes back', async () => {+ const cookie = await setupAndLogin()+ const source = writeAsset('big-abc123.js', `export const x = "${'y'.repeat(4000)}"\n`)+ const gz = await rawGet('/assets/big-abc123.js', { cookie, 'accept-encoding': 'gzip' })+ expect(gz.headers['content-encoding']).toBe('gzip')+ expect(gz.headers['vary']).toBe('Accept-Encoding')+ expect(zlib.gunzipSync(gz.body).toString('utf8')).toBe(source)+ // Smaller on the wire is the entire point — assert it, so a future "simplification" that+ // quietly stops compressing fails here instead of only showing up as a slow load.+ expect(gz.body.length).toBeLessThan(source.length / 2)++ const br = await rawGet('/assets/big-abc123.js', { cookie, 'accept-encoding': 'br' })+ expect(br.headers['content-encoding']).toBe('br')+ expect(zlib.brotliDecompressSync(br.body).toString('utf8')).toBe(source)+ })++ it('serves identity when the client accepts no encoding, and never compresses tiny files', async () => {+ const cookie = await setupAndLogin()+ writeAsset('big-abc123.js', 'x'.repeat(4000))+ const identity = await rawGet('/assets/big-abc123.js', { cookie })+ expect(identity.headers['content-encoding']).toBeUndefined()+ expect(identity.body.length).toBe(4000)+ // app.js is 14 bytes: a compressed frame plus its headers would be bigger than the file.+ const tiny = await rawGet('/app.js', { cookie, 'accept-encoding': 'gzip, br' })+ expect(tiny.headers['content-encoding']).toBeUndefined()+ expect(tiny.body.toString('utf8')).toBe('console.log(1)')+ })++ it('revalidates by ETag (304) and marks hashed assets immutable', async () => {+ const cookie = await setupAndLogin()+ writeAsset('big-abc123.js', 'x'.repeat(4000))+ const first = await rawGet('/assets/big-abc123.js', { cookie, 'accept-encoding': 'gzip' })+ expect(first.status).toBe(200)+ expect(first.headers['cache-control']).toBe('private, max-age=31536000, immutable')+ const etag = first.headers['etag'] as string+ expect(etag).toBeTruthy()++ const again = await rawGet('/assets/big-abc123.js', {+ cookie,+ 'accept-encoding': 'gzip',+ 'if-none-match': etag+ })+ expect(again.status).toBe(304)+ expect(again.body.length).toBe(0)++ // index.html carries the app's entry point: it must revalidate, never be held for a year.+ const index = await rawGet('/', { cookie })+ expect(index.headers['cache-control']).toBe('private, no-cache')+ const indexAgain = await rawGet('/', {+ cookie,+ 'if-none-match': index.headers['etag'] as string+ })+ expect(indexAgain.status).toBe(304)+ })++ it('keeps the index.html CSP rewrite through compression', async () => {+ const cookie = await setupAndLogin()+ // Pad past COMPRESS_MIN_BYTES so this actually exercises the compressed path — the rewrite+ // happens before compression, and a regression there would be invisible on a small file.+ fs.writeFileSync(+ path.join(rendererDir, 'index.html'),+ `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'" /><div id="root"></div><!--${'p'.repeat(4000)}-->`+ )+ const res = await rawGet('/', { cookie, 'accept-encoding': 'gzip' })+ expect(res.headers['content-encoding']).toBe('gzip')+ expect(zlib.gunzipSync(res.body).toString('utf8')).toContain(`connect-src 'self' ws: wss:`)+ })++ it('re-compresses after the file changes on disk (a rebuild must not serve stale bytes)', async () => {+ const cookie = await setupAndLogin()+ writeAsset('big-abc123.js', 'a'.repeat(4000))+ const before = await rawGet('/assets/big-abc123.js', { cookie, 'accept-encoding': 'gzip' })+ expect(zlib.gunzipSync(before.body).toString('utf8')).toBe('a'.repeat(4000))+ // A rebuild normally changes the hashed name too; same name + new bytes is the harder case.+ const later = new Date(Date.now() + 5000)+ const file = path.join(rendererDir, 'assets', 'big-abc123.js')+ fs.writeFileSync(file, 'b'.repeat(4000))+ fs.utimesSync(file, later, later)+ const after = await rawGet('/assets/big-abc123.js', { cookie, 'accept-encoding': 'gzip' })+ expect(zlib.gunzipSync(after.body).toString('utf8')).toBe('b'.repeat(4000))+ expect(after.headers['etag']).not.toBe(before.headers['etag'])+ })+ })+it('sessionTokenFromCookie parses the session out of a multi-cookie header', () => {expect(sessionTokenFromCookie(`a=b; ${SESSION_COOKIE}=tok123; c=d`)).toBe('tok123')expect(sessionTokenFromCookie(undefined)).toBeUndefined()diff --git a/src/server/http.ts b/src/server/http.tsindex d1d9fa3f5..d1325c30d 100644--- a/src/server/http.ts+++ b/src/server/http.ts@@ -6,6 +6,7 @@import http from 'http'import fs from 'fs'import path from 'path'+import zlib from 'zlib'import type { Auth } from './auth'import { proxyAuthAllowed, type TrustProxyConfig } from './proxy-trust'import { handleDownload } from './download'@@ -30,6 +31,16 @@ const CONTENT_TYPES: Record<string, string> = {// CSP served with the inline login/setup pages (no app assets, no connections).const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'"+/** Types worth compressing. Everything else (png, woff2) is already compressed — running it+ * through gzip only burns CPU and usually grows the payload. */+const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.map', '.json', '.svg'])+/** Below this, a compressed frame plus its headers is not worth the round of CPU. */+const COMPRESS_MIN_BYTES = 1024+/** Total bytes of compressed payloads held in memory. The renderer dir is ~100 files whose gzip+ * total is a couple of MB, so this is headroom, not a working limit — when it is exceeded the+ * whole cache is dropped (simplest correct eviction for a set this small). */+const COMPRESS_CACHE_MAX_BYTES = 32 * 1024 * 1024+export interface HttpHandlerOpts {auth: AuthrendererDir: string@@ -181,12 +192,107 @@ function resolveStaticPath(rendererDir: string, urlPath: string): string | nullreturn candidate}-function serveStatic(+/**+ * Pick a content encoding the client accepts. Brotli first (roughly 15% smaller than gzip on+ * our bundles), gzip as the universal fallback. A `;q=0` on a token is a refusal, so it is+ * honoured — everything else about the q-value ordering is ignored deliberately: we have two+ * candidates and a fixed preference between them.+ */+export function negotiateEncoding(header: string | undefined): 'br' | 'gzip' | null {+ if (!header) return null+ const accepted = new Set<string>()+ for (const part of header.split(',')) {+ const [tokenRaw, ...params] = part.split(';')+ const token = tokenRaw.trim().toLowerCase()+ if (!token) continue+ const refused = params.some((p) => /^\s*q\s*=\s*0(\.0+)?\s*$/i.test(p))+ if (!refused) accepted.add(token)+ }+ if (accepted.has('br')) return 'br'+ if (accepted.has('gzip')) return 'gzip'+ return null+}++/** `<encoding> <path>` → the compressed body for one exact file revision (`sig`). The promise is+ * cached, not just its result, so N concurrent first-hits compress once. */+const compressCache = new Map<string, { sig: string; body: Promise<Buffer | null> }>()+let compressCacheBytes = 0++function compress(buf: Buffer, enc: 'br' | 'gzip'): Promise<Buffer | null> {+ return new Promise((resolve) => {+ const done = (err: Error | null, out: Buffer): void => resolve(err ? null : out)+ if (enc === 'br') {+ zlib.brotliCompress(+ buf,+ // Quality 5 is the knee of the curve for JS/CSS: within a few percent of the default 11+ // at a small fraction of its CPU — and the answer is cached, so this runs once per build.+ { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 5, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: buf.length } },+ done+ )+ } else {+ zlib.gzip(buf, { level: 6 }, done)+ }+ })+}++/** The compressed body for a file revision, or null when compression failed (→ serve identity). */+function compressedBody(+ key: string,+ sig: string,+ enc: 'br' | 'gzip',+ identity: () => Promise<Buffer>+): Promise<Buffer | null> {+ const hit = compressCache.get(key)+ if (hit && hit.sig === sig) return hit.body+ const body = identity()+ .then((buf) => compress(buf, enc))+ .then((out) => {+ if (!out) {+ compressCache.delete(key)+ return null+ }+ compressCacheBytes += out.length+ if (compressCacheBytes > COMPRESS_CACHE_MAX_BYTES) {+ compressCache.clear()+ compressCacheBytes = 0+ }+ return out+ })+ .catch(() => {+ compressCache.delete(key)+ return null+ })+ compressCache.set(key, { sig, body })+ return body+}++/** Test seam: drop the compressed-payload cache. */+export function _resetStaticCacheForTest(): void {+ compressCache.clear()+ compressCacheBytes = 0+}++/**+ * Serve one built renderer file.+ *+ * Three things beyond reading the bytes, all of which matter because the browser client is the+ * whole point of the Server Edition and it is usually NOT on the same LAN:+ * - **Compression.** The entry bundle is ~2.1 MB raw / ~0.46 MB gzipped, and the lazy Monaco+ * chunk 6.2 MB / 1.1 MB. Compressed payloads are cached per file revision, so the CPU is paid+ * once per build, not per request.+ * - **Caching.** Vite content-hashes everything under /assets, so those can be `immutable`;+ * index.html revalidates by ETag (a 304 costs one small round trip instead of the bundle).+ * `private` rather than `public`: the app sits behind auth and a shared proxy has no business+ * holding it.+ * - **Async reads.** This handler shares its event loop with every terminal's WS frames, so a+ * `readFileSync` of a multi-MB chunk stalls output for every attached session.+ */+async function serveStatic(req: http.IncomingMessage,res: http.ServerResponse,rendererDir: string,urlPath: string-): void {+): Promise<void> {const filePath = resolveStaticPath(rendererDir, urlPath)if (!filePath) {sendJson(res, 400, { error: 'bad_path' })@@ -194,7 +300,7 @@ function serveStatic(}let stat: fs.Statstry {- stat = fs.statSync(filePath)+ stat = await fs.promises.stat(filePath)} catch {sendJson(res, 404, { error: 'not_found' })return@@ -204,24 +310,63 @@ function serveStatic(return}const ext = path.extname(filePath).toLowerCase()- const contentType = CONTENT_TYPES[ext] || 'application/octet-stream'- let body: Buffer = fs.readFileSync(filePath)- // CSP rewrite ONLY on index.html: relax connect-src so the WS client can connect.- if (path.basename(filePath) === 'index.html') {- const html = body.toString('utf8')+ const isIndex = path.basename(filePath) === 'index.html'+ const sig = `${stat.size.toString(16)}-${Math.round(stat.mtimeMs).toString(16)}`+ // Weak: index.html's body is rewritten below, so the tag describes the response, not the file.+ const etag = `W/"${sig}"`+ const headers: http.OutgoingHttpHeaders = {+ 'Content-Type': CONTENT_TYPES[ext] || 'application/octet-stream',+ ETag: etag,+ Vary: 'Accept-Encoding',+ 'Cache-Control': urlPath.startsWith('/assets/')+ ? 'private, max-age=31536000, immutable'+ : 'private, no-cache'+ }+ if (req.headers['if-none-match'] === etag) {+ res.writeHead(304, headers)+ res.end()+ return+ }++ const identity = async (): Promise<Buffer> => {+ const raw = await fs.promises.readFile(filePath)+ // CSP rewrite ONLY on index.html: relax connect-src so the WS client can connect.+ if (!isIndex) return raw+ const html = raw.toString('utf8')const marker = "default-src 'self';"- if (html.includes(marker)) {- body = Buffer.from(html.replace(marker, "default-src 'self'; connect-src 'self' ws: wss:;"))- } else {+ if (!html.includes(marker)) {// A silent no-op here would leave the desktop CSP intact and the browser// would block the ws:/wss: WebSocket with no visible error — make sure an// operator sees this in the server logs.console.warn("[nodeterm-server] index.html CSP did not contain the expected `default-src 'self';` marker — the ws: connect-src rewrite did not apply; the browser will block the WebSocket. Rebuild the renderer or update the rewrite.")+ return raw}+ return Buffer.from(html.replace(marker, "default-src 'self'; connect-src 'self' ws: wss:;"))+ }++ const enc =+ COMPRESSIBLE.has(ext) && stat.size >= COMPRESS_MIN_BYTES+ ? negotiateEncoding(req.headers['accept-encoding'] as string | undefined)+ : null+ if (enc) {+ const packed = await compressedBody(`${enc} ${filePath}`, sig, enc, identity)+ if (packed) {+ res.writeHead(200, { ...headers, 'Content-Encoding': enc, 'Content-Length': packed.length })+ res.end(packed)+ return+ }+ // Compression failed (OOM, corrupt read): fall through and serve the bytes as they are.+ }+ let body: Buffer+ try {+ body = await identity()+ } catch {+ sendJson(res, 404, { error: 'not_found' })+ return}- res.writeHead(200, { 'Content-Type': contentType })+ res.writeHead(200, { ...headers, 'Content-Length': body.length })res.end(body)}@@ -350,6 +495,6 @@ export function createHttpHandler(if (downloadTickets && (await handleDownload(req, res, url, downloadTickets))) return// Authenticated: serve static renderer files (index.html fallback for '/').- serveStatic(req, res, rendererDir, pathname)+ await serveStatic(req, res, rendererDir, pathname)}}diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.tsindex 3638743a2..0c8fcb6dd 100644--- a/src/shared/canvas-publish.test.ts+++ b/src/shared/canvas-publish.test.ts@@ -248,6 +248,71 @@ describe('shouldPublish (the solo gate)', () => {})})+// The gate above only skips the DIFF; serializing the canvas to hand it over is the other half of+// the cost, and it happens in a React effect keyed on the nodes array — once per drag frame. A+// thunk snapshot moves that cost behind the gate too.+describe('lazy snapshots', () => {+ it('never resolves the snapshot while solo — not even to keep the baseline', () => {+ const c = collect()+ const snapshot = vi.fn(() => [node('a')])+ const p = createCanvasPublisher(c.send, { shouldPublish: () => false })+ p.publish(snapshot)+ p.publish(snapshot, { throttle: true })+ p.adopt(snapshot)+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS * 4)+ expect(snapshot).not.toHaveBeenCalled()+ expect(c.sent).toEqual([])+ })++ it('resolves a deferred baseline once when a peer arrives, and diffs against it', () => {+ const c = collect()+ let peers = false+ const p = createCanvasPublisher(c.send, { shouldPublish: () => peers })+ const solo = vi.fn(() => [node('a'), node('b')])+ p.publish(solo)+ expect(solo).not.toHaveBeenCalled()++ peers = true+ p.publish(() => [node('a'), node('b', 3)])+ // The deferred baseline was resolved exactly once, and only the changed node was cast — the+ // same result the eager path produced.+ expect(solo).toHaveBeenCalledTimes(1)+ expect(c.sent).toEqual([{ op: 'upsert', node: node('b', 3) }])++ // …and it is not resolved again on the next edit (the baseline is now the resolved snapshot).+ p.publish(() => [node('a'), node('b', 3)])+ expect(solo).toHaveBeenCalledTimes(1)+ })++ it('resolves a coalesced drag frame once, at the trailing edge', () => {+ const c = collect()+ const p = createCanvasPublisher(c.send)+ p.publish([node('a')])+ const frames = [1, 2, 3].map((x) => vi.fn(() => [node('a', x)]))+ for (const f of frames) p.publish(f, { throttle: true })+ // Leading edge took the first frame; the other two coalesced into one trailing send, so the+ // frame in the middle is never serialized at all.+ expect(frames[0]).toHaveBeenCalledTimes(1)+ expect(frames[1]).not.toHaveBeenCalled()+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS)+ expect(frames[1]).not.toHaveBeenCalled()+ expect(frames[2]).toHaveBeenCalledTimes(1)+ expect(c.sent).toEqual([+ { op: 'upsert', node: node('a') }, // the initial publish, before the drag+ { op: 'upsert', node: node('a', 1) },+ { op: 'upsert', node: node('a', 3) }+ ])+ })++ it('an adopted thunk is a real baseline: the next identical snapshot diffs to nothing', () => {+ const c = collect()+ const p = createCanvasPublisher(c.send)+ p.adopt(() => [node('a'), node('b')]) // a peer's mutation applied locally+ p.publish(() => [node('a'), node('b')])+ expect(c.sent).toEqual([])+ })+})+describe('ephemeral nodes are never published', () => {it('isEphemeralNodeId matches subagent cards (by id set) and loop cards (by prefix)', () => {const eph = new Set(['sub-123'])diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.tsindex 263271972..8d1dbc3ad 100644--- a/src/shared/canvas-publish.ts+++ b/src/shared/canvas-publish.ts@@ -29,15 +29,30 @@ import type { CanvasMutation, CanvasNodeState } from './types'/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */export const PUBLISH_INTERVAL_MS = 50+/**+ * A snapshot, or a thunk that produces one.+ *+ * The thunk is what makes the solo gate below actually free. Serializing the canvas is the+ * expensive half of publishing (`flowToNodeStates` + `stableStringify` per node), and the caller+ * runs inside a React effect keyed on the nodes array — i.e. once per DRAG FRAME. Passing an array+ * meant that cost was paid before the publisher could decide it had nothing to do with it; passing+ * a thunk lets it be paid only when a snapshot is actually going to be diffed or sent.+ *+ * A thunk MUST be pure and must close over the state as of the call (React Flow hands us a fresh+ * immutable array per change, so `() => serialize(nodes)` satisfies this): the publisher may+ * resolve it later — at the trailing edge of a throttle window, or when the first peer arrives.+ */+export type CanvasSnapshot = CanvasNodeState[] | (() => CanvasNodeState[])+export interface CanvasPublisher {/** Diff `next` against the last published snapshot and send the mutations.* `throttle` (drag frames) coalesces to at most one send per PUBLISH_INTERVAL_MS.* With no peer attached (`shouldPublish` false) this DEGRADES TO adopt(): the snapshot becomes* the baseline and nothing is diffed or sent — a solo user pays nothing for team sync. */- publish(next: CanvasNodeState[], opts?: { throttle?: boolean }): void+ publish(next: CanvasSnapshot, opts?: { throttle?: boolean }): void/** Take `next` as the new baseline WITHOUT sending — the loop guard (a peer's mutation, or a* programmatic project load). The next diff against it is empty. */- adopt(next: CanvasNodeState[]): void+ adopt(next: CanvasSnapshot): void/** Send any coalesced drag frame immediately (drag settle / unmount). */flush(): voiddispose(): void@@ -92,6 +107,11 @@ function rebaseRefused(* user must not pay for a feature they cannot use. The baseline still tracks the canvas, so the* instant a peer joins the very next edit diffs correctly against what is actually on screen —* there is no resync step and no missed mutation. Default: always publish.+ *+ * With a thunk snapshot the gate covers the SERIALIZATION too, which is where the cost actually+ * was: a solo baseline is kept UNRESOLVED (just the thunk), and the first publish that has a peer+ * resolves it to diff against. Same baseline, same mutations — the work is merely deferred to the+ * moment something reads it, which for a solo user is never.*/export function createCanvasPublisher(send: (m: CanvasMutation) => void | boolean,@@ -99,21 +119,48 @@ export function createCanvasPublisher(): CanvasPublisher {const intervalMs = opts.intervalMs ?? PUBLISH_INTERVAL_MSconst shouldPublish = opts.shouldPublish ?? (() => true)+ /** The baseline, held EITHER resolved (`last`) or unresolved (`lastLazy`) — never both. */let last: CanvasNodeState[] = []- let pending: CanvasNodeState[] | null = null+ let lastLazy: (() => CanvasNodeState[]) | null = null+ let pending: CanvasSnapshot | null = nulllet timer: ReturnType<typeof setTimeout> | null = null- const emit = (next: CanvasNodeState[]): void => {+ const resolve = (s: CanvasSnapshot): CanvasNodeState[] => (typeof s === 'function' ? s() : s)++ /** The baseline to diff against, resolving a deferred one exactly once. */+ const baseline = (): CanvasNodeState[] => {+ if (lastLazy) {+ last = lastLazy()+ lastLazy = null+ }+ return last+ }++ /** Take a snapshot as the baseline. A thunk is stored unresolved — nothing has asked for it yet+ * and, for a solo user, nothing ever will. */+ const setBaseline = (s: CanvasSnapshot): void => {+ if (typeof s === 'function') {+ lastLazy = s+ } else {+ last = s+ lastLazy = null+ }+ }++ const emit = (snapshot: CanvasSnapshot): void => {if (!shouldPublish()) {- last = next // solo: adopt as baseline, diff nothing, send nothing+ setBaseline(snapshot) // solo: adopt as baseline, diff nothing, send nothingreturn}- const mutations = diffToMutations(last, next)+ const prev = baseline()+ const next = resolve(snapshot)+ const mutations = diffToMutations(prev, next)const refused = new Set<string>()for (const m of mutations) {if (send(opts.src ? { ...m, src: opts.src } : m) === false) refused.add(mutationNodeId(m))}- last = refused.size ? rebaseRefused(last, next, refused) : next+ last = refused.size ? rebaseRefused(prev, next, refused) : next+ lastLazy = null}const onTimer = (): void => {@@ -131,7 +178,7 @@ export function createCanvasPublisher(if (timer) clearTimeout(timer)timer = nullpending = null- last = next+ setBaseline(next)return}if (o?.throttle) {@@ -152,7 +199,7 @@ export function createCanvasPublisher(emit(next)},adopt(next) {- last = next+ setBaseline(next)pending = null},flush() {