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
fix(canvas): keep browser/web node pages alive across project switches
enes35a86e301474
diff --git a/CLAUDE.md b/CLAUDE.mdindex f1560be0b..ceed930bd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -712,6 +712,58 @@ Monaco is wired in `renderer/editor/monaco-setup.ts` (language workers bundled v`?worker` — no CDN; CSP `worker-src` allows them). Markdown rendering is shared in`renderer/lib/markdown.ts` (`marked` + DOMPurify sanitize).+### Webview keep-alive across project switches (browser/web nodes)++Issue #301: a project switch used to reload every browser node's page — SPA state, forms, scroll,+websockets gone — because the load effect swaps the whole React Flow node array and an Electron+`<webview>`'s guest process dies on DOM detach (a webview cannot be parked like xterm). The fix+keeps the ELEMENT mounted instead of trying to preserve anything through a remount. The facts it+rests on are measured (Electron 42.x probes + in-app verification, 2026-08-26):++- A guest **survives** sibling insert/remove around its element (React reconciliation of kept,+ order-stable keyed children never touches them), and **survives `display:none`** of itself or an+ ancestor — state intact, viewport size and scroll kept (the guest is NOT resized to 0), repaint+ pixel-identical on reveal, timers running throttled like a background tab.+- A guest **dies** on any DOM *move* (`insertBefore`/`appendChild` of an attached element detaches+ first), taking a full page reload with it. React moves a kept child exactly when its RELATIVE+ ORDER among kept children changes (`lastPlacedIndex`), and React Flow renders nodes in+ prop-array order keyed by id (`adoptUserNodes` rebuilds `nodeLookup` in array order) — so the+ merged prop's order discipline IS the feature.++Mechanics (`renderer/lib/webviewKeepAlive.ts` pure + tested, `state/webviewKeepAlive.ts` store,+merged in Canvas exactly like the ephemeral subagent cards — Canvas state, persistence, undo and+the wire never see any of it):++- Every webview-hosting node (`browser`/`web`) renders in ONE stable **pool region** at the tail+ of the `<ReactFlow>` nodes prop, ordered by the pool's entries; entry order never changes while+ an entry lives (append/remove only — `webviewKeepAlive.test.ts` pins the order-stability+ invariant, `webview-keepalive-reconcile.test.tsx` pins the no-detach consequence against real+ React). Visible cost of the hoist: an unselected browser/web node paints above other unselected+ z-0 nodes it overlaps (selection's z 1000 still wins).+- On switch-away the outgoing project's pages become **ghosts**: same node id, `display:none`,+ non-interactive, parked at the origin, `data.ghost` telling the surfaces to route facts at the+ pool (`updateGhostData`) instead of `updateNodeData`. On return the SAME element goes live+ again; `overlayKeepAliveData` folds ghost-time navigations into the loaded nodes inside the one+ `setNodes`, so the `url` prop never moves under the surviving surface (which would navigate it).+- **The merge is keyed on the MOUNTED project (`keepAliveFromRef`), never `activeProjectId`, and a+ mounted entry whose node is missing falls back to its ghost.** Both exist because the pool store+ (zustand/useSyncExternalStore), the ref and `setNodes` do not land in one commit: a switch renders+ interleavings where the id would otherwise drop out of the merged list for one commit — and one+ absent commit is an unmount, i.e. a dead guest ([MEASURED]: the ghost→live direction remounted+ every returning page until the fallback; live→ghost never did). A genuinely deleted node's entry+ is dropped at the deletion funnels (handleNodesChange's `remove`, `deleteNodes`, the peer-mutation+ remove, project deletion/prune), with the next retire as backstop — never by the merge.+- **Memory bounds** (same posture as park/WebGL: a lever must not end live work): a ghost is+ hidden, so the existing Browser Memory Saver discards its guest after `BROWSER_DISCARD_MS`+ unless loading/audible/agent-driven — `onGuestDiscarded` then drops the entry (a husk would hold+ a cap slot). `BACKGROUND_WEBVIEW_MAX` (8) hard-caps live background guests, evicting+ longest-retired first; `activateProject` runs BEFORE `retireProject` on every switch so a+ returning page sheds its background clock before that eviction can pick it.+- E2E-verified under Xvfb (CDP): same webContents across Alpha→Beta→Alpha, typed form text + JS+ state + tick counter continuous, zero reloads; wrapper + webview DOM elements identity-stable in+ both directions. Server Edition: inert (no `<webview>` in a plain browser — ghosts are empty+ husks, nothing to preserve). Mobile: N/A (no canvas).+## Agent support (Claude / Codex / Gemini / Copilot / opencode / Grok / custom)The app is a pluggable multi-agent system: Claude Code is one builtin ofdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 2af6e84e5..26ed6e09c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -86,6 +86,16 @@ need it too, and wire it in the same change.see. Keep a remote temp's own leaf bounded: extending an already-valid maximum-length target leafwith a UUID suffix turns an atomic write into a guaranteed `ENAMETOOLONG` failure.+- **Never unmount, move or re-key a browser/web node's element.** An Electron `<webview>`'s guest+ process dies on DOM detach — and a detach includes any `insertBefore`/`appendChild` MOVE of an+ attached element, which React performs whenever a kept child's relative order among kept keyed+ children changes. That is why webview-hosting nodes render in one stable pool region at the tail+ of the `<ReactFlow>` nodes prop (`renderer/lib/webviewKeepAlive.ts` — read its header before+ touching the merge, the node array swap in Canvas's load effect, or anything that reorders+ nodes), and why a background project's pages stay mounted as hidden ghosts instead of+ unmounting. `display:none` is safe (measured: state, scroll and viewport size survive); a reorder+ or unmount reloads the user's page and loses their in-page state.+These are the ones that come up in review most often. Each exists because its absence caused a realbug.diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 39a527a2b..bffc7d3b7 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -212,6 +212,8 @@ import { PresenceLayer } from '../components/PresenceLayer'import { Facepile } from '../components/Facepile'import { PresenceNamePrompt } from '../components/PresenceNamePrompt'import { nodeTravel, projectTravel } from '../lib/presenceTravel'+import { backgroundNodeIds, mergeWithKeepAlive, overlayKeepAliveData } from '../lib/webviewKeepAlive'+import { useWebviewKeepAlive } from '../state/webviewKeepAlive'import {routeControlSource,needsLiveCanvas,@@ -1159,6 +1161,13 @@ export function Canvas() {* the initial empty `useNodesState([])` can never be committed as some project's canvas.*/const nodesProjectIdRef = useRef<string | null>(null)+ /**+ * The project whose webview nodes the NEXT load must retire into the keep-alive pool. Separate+ * from `nodesProjectIdRef` on purpose: the epoch tag is invalidated on the load effect's+ * bail-outs (welcome screen) while the previous nodes stay MOUNTED — and mounted pages must+ * still be retired, not dropped, when the next project loads.+ */+ const keepAliveFromRef = useRef<string | null>(null)// 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>(() => {})@@ -1225,10 +1234,20 @@ export function Canvas() {// a fixed toll for panels the content never reaches.const fitAll = useCallback(() => {const wrap = flowWrapRef.current- const bounds = getNodesBounds(getNodes())+ // Keep-alive ghosts are invisible stand-ins parked at the origin — framing them would drag+ // every fit toward 0,0. Excluded from BOTH halves: the padding solve's bounds and fitView's+ // own fit set (the explicit `nodes` list; a real node unmeasured this early is dropped by+ // React Flow's measured filter, which at a user-gesture fit means nothing in practice).+ const fitNodes = getNodes().filter((n) => (n as CanvasNode).data?.ghost !== true)+ const bounds = getNodesBounds(fitNodes)const padding = wrap ? solveFitPadding(wrap, bounds.width, bounds.height) : null// Nothing to fit, or chrome swallowing the viewport: let fitView use its own framing.- void fitView({ duration: 300, padding: padding ?? 0.1 })+ void fitView({+ duration: 300,+ padding: padding ?? 0.1,+ // Empty canvas: fall back to the bare call (its no-op), never an empty fit set (origin jump).+ ...(fitNodes.length ? { nodes: fitNodes.map((n) => ({ id: n.id })) } : {})+ })}, [fitView, getNodes, getNodesBounds])/**@@ -1601,11 +1620,19 @@ export function Canvas() {// eslint-disable-next-line react-hooks/exhaustive-deps -- loopSig stands in for the byId read}, [agentById, loopSig, ephemeralPos, ephSizes, ephExpanded, ephSelId, nodes])- // Merge the persisted nodes with the ephemeral ones once per change (not per render),- // so React Flow's array-identity short-circuit holds while panning/zooming.+ // Merge the persisted nodes with the ephemeral ones and the webview keep-alive pool once per+ // change (not per render), so React Flow's array-identity short-circuit holds while+ // panning/zooming. The pool region (active webview nodes hoisted to the tail + background+ // ghosts) is what keeps a `<webview>`'s DOM element stationary across project switches — see+ // lib/webviewKeepAlive.ts for the order invariant this merge must never break.+ const keepAliveEntries = useWebviewKeepAlive((s) => s.entries)const allNodes = useMemo(- () => (ephemeralNodes.length ? [...nodes, ...ephemeralNodes] : nodes),- [nodes, ephemeralNodes]+ // Keyed on the MOUNTED project (whose nodes `nodes` holds — see mergeWithKeepAlive's doc for+ // the one-commit window where that is not the active project). The ref only moves inside the+ // load effect, which also replaces `nodes`, so the deps below always cover it.+ () => mergeWithKeepAlive(nodes, ephemeralNodes, keepAliveEntries, keepAliveFromRef.current),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [nodes, ephemeralNodes, keepAliveEntries])// Context-link edges, statically styled (no per-message activity in the pull model).@@ -1973,7 +2000,28 @@ export function Canvas() {)}loadingRef.current = true- const flow = nodeStatesToFlow(project.nodes)+ // Webview keep-alive (issue #301): move the OUTGOING project's browser/web pages into the+ // background pool before the node swap, so their `<webview>` elements stay mounted (as hidden+ // ghosts in the merged prop) instead of dying with the unmount. `keepAliveFromRef` — not+ // `nodesProjectIdRef` — names the outgoing project because the welcome-screen bail-outs above+ // null the epoch tag while deliberately leaving the previous nodes mounted, and those pages+ // should survive a welcome-screen round trip too.+ const keepAlive = useWebviewKeepAlive.getState()+ const outgoingPid = keepAliveFromRef.current+ // Activate BEFORE retire: the incoming project's entries must shed their background clock+ // before the retire's cap eviction runs, or the pool's oldest page could be evicted at the+ // exact switch that reveals it.+ keepAlive.activateProject(project.id)+ if (outgoingPid && outgoingPid !== project.id) keepAlive.retireProject(outgoingPid, nodesRef.current)+ keepAliveFromRef.current = project.id+ // A RETURNING project's pages navigated while ghosted: load its nodes with the pool's live+ // url/title already applied, in the SAME setNodes — a later correction would move the `url`+ // prop under the surviving surface and navigate the very page the pool preserved.+ const flow = overlayKeepAliveData(+ nodeStatesToFlow(project.nodes),+ useWebviewKeepAlive.getState().entries,+ project.id+ )setNodes(flow)// React Flow now holds THIS project's canvas: the commit guard may pair it with the active id// again. Both refs are assigned HERE, synchronously, because `setNodes` only lands on the next@@ -2085,6 +2133,18 @@ export function Canvas() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [activeProjectId, reloadNonce, setNodes, setViewport])+ // Keep-alive pool hygiene: a PERMANENTLY deleted project's ghosts must die now, not at the next+ // switch (an invisible page is still a live Chromium process). Keyed on the id signature — the+ // projects array is rebuilt on every node serialization, the id set is not. Closed-but-kept+ // projects keep their entries on purpose: closing detaches like a project switch, and the+ // memory saver reaps their pages on its own clock.+ const projectIdsSig = useProjects((s) => s.projects.map((p) => p.id).join(' '))+ useEffect(() => {+ useWebviewKeepAlive+ .getState()+ .prune(new Set(projectIdsSig === '' ? [] : projectIdsSig.split(' ')))+ }, [projectIdsSig])+/*** Counts EDITS (not saves). `writeDisk` captures it before it builds the snapshot and clears* `dirty` only if it is unchanged after the await — see canClearDirty and the field bug it cites.@@ -2584,8 +2644,12 @@ export function Canvas() {if (projectId !== useProjects.getState().activeProjectId) {// Not on screen (a parked / background project): no terminal is mounted, but one may be// PARKED from a recent project switch — dispose it, as an active-project remove does.- if (mutation.op === 'remove')+ if (mutation.op === 'remove') {disposeTerminalOnUnmount(sessionForProject(projectId).id, mutation.id)+ // ...and its keep-alive ghost: a background webview node a peer deleted must not keep+ // its page running invisibly until the next switch.+ useWebviewKeepAlive.getState().drop(mutation.id)+ }if (useProjects.getState().applyNodeMutation(projectId, mutation)) markDirty()return}@@ -2601,6 +2665,9 @@ export function Canvas() {const gone = nodesRef.current.find((n) => n.id === mutation.id)if (gone?.type === 'terminal')disposeTerminalOnUnmount(sessionForProject(projectId).id, gone.id)+ // A removed webview node's keep-alive entry ends with it (see handleNodesChange's remove+ // branch for the local twin of this).+ useWebviewKeepAlive.getState().drop(mutation.id)}// 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.@@ -2685,7 +2752,22 @@ export function Canvas() {// the wire — every client derives them from agent:status), so the two cannot drift.const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))const isEph = (id: string) => isEphemeralNodeId(id, ephIds)+ // Keep-alive GHOSTS (background webview nodes) live outside the managed state too, and+ // nothing about one is a canvas edit: React Flow still emits measure/deselect noise for+ // them (a `display:none` node measures 0), and letting that through would apply changes to+ // ids the state does not hold — and mark the ACTIVE project dirty for a background fact.+ const ghostIds = backgroundNodeIds(+ useWebviewKeepAlive.getState().entries,+ // The MOUNTED project, matching the merge (see mergeWithKeepAlive): during a switch's+ // first commit these changes still describe the outgoing project's canvas.+ keepAliveFromRef.current+ )const managed = changes.filter((c) => {+ if ('id' in c && ghostIds.has(c.id)) return false+ // A real deletion ends the node's keep-alive entry too — the merge deliberately falls+ // back to an invisible ghost when an entry's node is missing (see mergeWithKeepAlive),+ // so without this a closed browser node's page would keep running unseen.+ if (c.type === 'remove') useWebviewKeepAlive.getState().drop(c.id)if ('id' in c && isEph(c.id)) {const store = useAgentNodes.getState()// Stored as an OFFSET from the parent agent, never as a canvas position — see offsetFrom.@@ -4350,6 +4432,9 @@ export function Canvas() {useAgentStatus.getState().remove(n.id)useAgentNodes.getState().clearForParent(n.id)useAgentNodes.getState().clearLoop(n.id)+ // Permanent deletion ends the node's keep-alive entry too — this funnel removes nodes by+ // setNodes, so handleNodesChange's remove branch never sees them.+ useWebviewKeepAlive.getState().drop(n.id)// The open-project attach-consent mirror dies with its caller (review #363 M-1) —// symmetric with main's grant ledger, which clears on the same teardown (ptyDestroy).// A node id revived later faces a fresh dialog, exactly as it faces a fresh grant.@@ -9370,6 +9455,7 @@ export function Canvas() {// Same teardown symmetry as deleteNodes (review #363 M-1): the attach-consent// mirror dies with the node.clearAttachConsent(id)+ useWebviewKeepAlive.getState().drop(id)useProjects.getState().removeNode(projectId, id)void writeDisk()}diff --git a/src/renderer/lib/webviewKeepAlive.test.ts b/src/renderer/lib/webviewKeepAlive.test.tsnew file mode 100644index 000000000..4eaf3dfec--- /dev/null+++ b/src/renderer/lib/webviewKeepAlive.test.ts@@ -0,0 +1,269 @@+import { describe, expect, it } from 'vitest'+import type { CanvasNode } from '../state/workspace'+import {+ activateInPool,+ BACKGROUND_WEBVIEW_MAX,+ backgroundNodeIds,+ evictOverCap,+ ghostFlowNode,+ hasKeepAliveContent,+ isKeepAliveKind,+ mergeWithKeepAlive,+ overlayKeepAliveData,+ retireIntoPool,+ type KeepAliveEntry+} from './webviewKeepAlive'++const node = (id: string, type: string, data: Record<string, unknown> = {}): CanvasNode =>+ ({+ id,+ type,+ position: { x: 10, y: 10 },+ width: 400,+ height: 300,+ data: { title: id, color: '#0a84ff', group: null, ...data }+ }) as unknown as CanvasNode++const browser = (id: string, url = 'https://x.test/'): CanvasNode => node(id, 'browser', { url })++describe('mergeWithKeepAlive', () => {+ it('returns the live array itself when no webview node exists anywhere', () => {+ const live = [node('t1', 'terminal'), node('s1', 'sticky')]+ expect(mergeWithKeepAlive(live, [], [], 'p1')).toBe(live)+ })++ it('appends ephemerals when no webview node exists', () => {+ const live = [node('t1', 'terminal')]+ const eph = [node('sub1', 'subagent')]+ expect(mergeWithKeepAlive(live, eph, [], 'p1').map((n) => n.id)).toEqual(['t1', 'sub1'])+ })++ it('hoists active webview nodes to the tail region, after ephemerals', () => {+ const live = [browser('b1'), node('t1', 'terminal'), node('w1', 'web'), node('t2', 'terminal')]+ const eph = [node('sub1', 'subagent')]+ const merged = mergeWithKeepAlive(live, eph, [], 'p1')+ expect(merged.map((n) => n.id)).toEqual(['t1', 't2', 'sub1', 'b1', 'w1'])+ // Live objects, not copies — position/selection/data must flow through untouched.+ expect(merged[3]).toBe(live[0])+ })++ it('renders pool entries in pool order: live for the active project, ghost otherwise', () => {+ const live = [node('t1', 'terminal'), browser('b1')]+ const entries: KeepAliveEntry[] = [+ { nodeId: 'bg1', projectId: 'p2', node: { type: 'browser', data: { url: 'https://a/' } as never }, retiredAt: 5 },+ { nodeId: 'b1', projectId: 'p1', node: { type: 'browser', data: {} as never }, retiredAt: 0 }+ ]+ const merged = mergeWithKeepAlive(live, [], entries, 'p1')+ expect(merged.map((n) => n.id)).toEqual(['t1', 'bg1', 'b1'])+ expect(merged[1].data.ghost).toBe(true)+ expect(merged[2]).toBe(live[1])+ })++ it('keeps a returning entry as a GHOST through the switch window (nodes not yet swapped)', () => {+ // The regression the real app exposed: after the tab click, one commit renders with the new+ // ACTIVE id while the node array is still the outgoing project's. The merge is keyed on the+ // MOUNTED project for exactly this reason — the returning entry must stay in the output (as+ // its ghost), not take the live branch, miss its node, and unmount for a commit.+ const entries = retireIntoPool([], 'p1', [browser('b1')], 1000)+ const outgoingNodes = [browser('c1')] // p2's canvas, still mounted+ const merged = mergeWithKeepAlive(outgoingNodes, [], entries, 'p2')+ expect(merged.map((n) => n.id)).toEqual(['b1', 'c1'])+ expect(merged[0].data.ghost).toBe(true)+ })++ it("falls back to the GHOST for a mounted entry whose node is missing, and appends actives the pool doesn't know", () => {+ // The miss is USUALLY a cross-store commit interleaving mid-switch (see the merge's doc) — an+ // id absent from one commit is an unmount and a dead guest, so the entry must keep rendering.+ // A genuinely deleted node's entry is dropped by the deletion funnels, not by this merge.+ const live = [browser('new1')]+ const entries: KeepAliveEntry[] = [+ { nodeId: 'gone', projectId: 'p1', node: { type: 'browser', data: {} as never }, retiredAt: 0 }+ ]+ const merged = mergeWithKeepAlive(live, [], entries, 'p1')+ expect(merged.map((n) => n.id)).toEqual(['gone', 'new1'])+ expect(merged[0].data.ghost).toBe(true)+ })+})++describe('ghostFlowNode', () => {+ const entry: KeepAliveEntry = {+ nodeId: 'b1',+ projectId: 'p2',+ node: { type: 'browser', width: 560, height: 400, data: { url: 'https://x/', partition: 'persist:x' } as never },+ retiredAt: 1+ }++ it('is hidden, inert, parked at the origin, and flagged for the surfaces', () => {+ const g = ghostFlowNode(entry)+ expect(g.id).toBe('b1')+ expect(g.type).toBe('browser')+ expect(g.style).toEqual({ display: 'none' })+ expect(g.position).toEqual({ x: 0, y: 0 })+ expect(g.selectable).toBe(false)+ expect(g.draggable).toBe(false)+ expect(g.deletable).toBe(false)+ expect(g.data.ghost).toBe(true)+ expect(g.data.url).toBe('https://x/')+ expect(g.data.partition).toBe('persist:x')+ })++ it('caches by entry identity so a drag-frame merge re-emits the same object', () => {+ expect(ghostFlowNode(entry)).toBe(ghostFlowNode(entry))+ expect(ghostFlowNode({ ...entry })).not.toBe(ghostFlowNode(entry))+ })+})++describe('retireIntoPool', () => {+ it('snapshots content-bearing webview nodes, in array order, and skips the rest', () => {+ const out = retireIntoPool(+ [],+ 'p1',+ [node('t1', 'terminal'), browser('b1'), node('w1', 'web', { filePath: '/x.html' }), browser('empty', '')],+ 1000+ )+ expect(out.map((e) => e.nodeId)).toEqual(['b1', 'w1'])+ expect(out[0]).toMatchObject({ projectId: 'p1', retiredAt: 1000 })+ expect(out[0].node.data.url).toBe('https://x.test/')+ })++ it('keeps an existing entry ORDER SLOT on re-retire and prunes deleted nodes', () => {+ const first = retireIntoPool([], 'p1', [browser('b1'), browser('b2')], 1000)+ const other = retireIntoPool(first, 'p2', [browser('c1')], 2000)+ // p1 comes back with b2 deleted and b3 created; b1 must keep its slot before c1.+ const again = retireIntoPool(other, 'p1', [browser('b3'), browser('b1')], 3000)+ expect(again.map((e) => e.nodeId)).toEqual(['b1', 'c1', 'b3'])+ })++ it('evicts the longest-retired background entries beyond the cap', () => {+ let entries: KeepAliveEntry[] = []+ for (let i = 0; i < BACKGROUND_WEBVIEW_MAX + 3; i++) {+ entries = retireIntoPool(entries, `p${i}`, [browser(`b${i}`)], 1000 + i)+ }+ expect(entries).toHaveLength(BACKGROUND_WEBVIEW_MAX)+ // Oldest three retire clocks are gone.+ expect(entries.map((e) => e.nodeId)).toEqual(+ Array.from({ length: BACKGROUND_WEBVIEW_MAX }, (_, i) => `b${i + 3}`)+ )+ })++ it('activateInPool sheds the background clock BEFORE the next retire can evict it', () => {+ const first = retireIntoPool([], 'p1', [browser('b1')], 1000)+ // Cap 1: without activation, switching p2→p1 would evict b1 at the very switch revealing it.+ const activated = activateInPool(first, 'p1')+ const afterRetire = retireIntoPool(activated, 'p2', [browser('c1')], 2000, 1)+ expect(afterRetire.map((e) => e.nodeId)).toEqual(['b1', 'c1'])+ expect(afterRetire[0].retiredAt).toBe(0)+ })++ it('never counts ACTIVE entries against the cap, and never evicts them', () => {+ const active: KeepAliveEntry[] = Array.from({ length: 5 }, (_, i) => ({+ nodeId: `a${i}`,+ projectId: 'pX',+ node: { type: 'browser', data: {} as never },+ retiredAt: 0+ }))+ const out = evictOverCap([...active], 2)+ expect(out).toHaveLength(5)+ })+})++describe('overlayKeepAliveData', () => {+ it('applies the pool url/title of the returning project and leaves equal nodes untouched', () => {+ const flow = [browser('b1', 'https://old/'), browser('b2', 'https://same/')]+ const entries: KeepAliveEntry[] = [+ { nodeId: 'b1', projectId: 'p1', node: { type: 'browser', data: { url: 'https://new/', title: 'T' } as never }, retiredAt: 1 },+ { nodeId: 'b2', projectId: 'p1', node: { type: 'browser', data: { url: 'https://same/', title: 'b2' } as never }, retiredAt: 1 },+ { nodeId: 'zz', projectId: 'p9', node: { type: 'browser', data: { url: 'https://other/' } as never }, retiredAt: 1 }+ ]+ const out = overlayKeepAliveData(flow, entries, 'p1')+ expect(out[0].data.url).toBe('https://new/')+ expect(out[0].data.title).toBe('T')+ expect(out[1]).toBe(flow[1])+ })+})++describe('backgroundNodeIds', () => {+ it('names only the entries of OTHER projects', () => {+ const entries: KeepAliveEntry[] = [+ { nodeId: 'a', projectId: 'p1', node: { type: 'browser', data: {} as never }, retiredAt: 0 },+ { nodeId: 'b', projectId: 'p2', node: { type: 'browser', data: {} as never }, retiredAt: 1 }+ ]+ expect([...backgroundNodeIds(entries, 'p1')]).toEqual(['b'])+ })+})++describe('helpers', () => {+ it('classify kinds and content', () => {+ expect(isKeepAliveKind(node('x', 'browser'))).toBe(true)+ expect(isKeepAliveKind(node('x', 'web'))).toBe(true)+ expect(isKeepAliveKind(node('x', 'terminal'))).toBe(false)+ expect(hasKeepAliveContent(browser('x'))).toBe(true)+ expect(hasKeepAliveContent(node('x', 'web', { filePath: '/f.html' }))).toBe(true)+ expect(hasKeepAliveContent(browser('x', ''))).toBe(false)+ })+})++/**+ * THE invariant the whole feature rests on (see the lib header): between any two consecutive merge+ * outputs, the ids present in BOTH must appear in the same relative order — React only touches a+ * kept element's DOM (killing a webview guest) when its relative order among kept children changes.+ */+describe('order stability across a switch script', () => {+ const relativeOrderStable = (prev: string[], next: string[]): boolean => {+ const nextIndex = new Map(next.map((id, i) => [id, i]))+ const shared = prev.filter((id) => nextIndex.has(id))+ for (let i = 1; i < shared.length; i++) {+ if ((nextIndex.get(shared[i - 1]) ?? 0) > (nextIndex.get(shared[i]) ?? 0)) return false+ }+ return true+ }++ it('holds across switches, creates, deletes, evictions and prunes', () => {+ // Three projects with webview nodes, plus churn.+ const projects: Record<string, CanvasNode[]> = {+ p1: [node('t1', 'terminal'), browser('b1'), browser('b2')],+ p2: [browser('c1'), node('t2', 'terminal'), node('w2', 'web', { filePath: '/w.html' })],+ p3: [node('t3', 'terminal')]+ }+ let entries: KeepAliveEntry[] = []+ let activePid = 'p1'+ let prevMergedIds: string[] | null = null+ let clock = 1000++ const switchTo = (pid: string): void => {+ // Same order as Canvas's load effect: activate the incoming project, then retire the+ // outgoing one (see activateInPool's doc for why this order is load-bearing).+ entries = activateInPool(entries, pid)+ entries = retireIntoPool(entries, activePid, projects[activePid], ++clock)+ activePid = pid+ }+ const checkMerge = (): void => {+ const merged = mergeWithKeepAlive(projects[activePid], [], entries, activePid).map((n) => n.id)+ // No duplicate ids, ever — one id rendering twice is two elements fighting for one key.+ expect(new Set(merged).size).toBe(merged.length)+ if (prevMergedIds) expect(relativeOrderStable(prevMergedIds, merged)).toBe(true)+ prevMergedIds = merged+ }++ checkMerge()+ switchTo('p2')+ checkMerge()+ // p1's pages navigate in the background; p2 creates a browser node.+ projects.p2.push(browser('c2'))+ checkMerge()+ switchTo('p3')+ checkMerge()+ switchTo('p1')+ checkMerge()+ // Delete b1 while active, then leave.+ projects.p1 = projects.p1.filter((n) => n.id !== 'b1')+ checkMerge()+ switchTo('p2')+ checkMerge()+ switchTo('p3')+ checkMerge()+ // Back to p1: b2 must have kept its slot through everything.+ switchTo('p1')+ checkMerge()+ })+})diff --git a/src/renderer/lib/webviewKeepAlive.ts b/src/renderer/lib/webviewKeepAlive.tsnew file mode 100644index 000000000..f6ff997c8--- /dev/null+++ b/src/renderer/lib/webviewKeepAlive.ts@@ -0,0 +1,292 @@+/**+ * Background keep-alive for webview-hosting nodes (browser/web) across project switches —+ * issue #301's "browser nodes reload their page on every tab change".+ *+ * WHY THIS SHAPE. An Electron `<webview>`'s guest process dies the moment its element leaves the+ * DOM, and — measured on Electron 42.x — it ALSO dies on a DOM *move* (`insertBefore` into a new+ * or even the same parent detaches first), while it survives, state intact, any amount of sibling+ * churn around it and `display:none` of itself or an ancestor (the guest keeps its viewport size+ * and scroll while hidden, repaints pixel-identically on reveal, and its timers keep running,+ * throttled like a background tab). So a page survives a project switch if and only if its+ * `<webview>` element is NEVER unmounted and NEVER reordered relative to the other kept elements —+ * React only calls `insertBefore` on a kept child when its relative order among kept children+ * changes (the `lastPlacedIndex` rule), and that one call is the guest's death.+ *+ * Hence the design: every webview-hosting node renders in ONE stable region at the END of the+ * `<ReactFlow>` nodes prop — the "pool region" — whose internal order is owned by the pool entries+ * here and never changes while an entry lives. The active project's entries render as the live+ * nodes; a background project's render as GHOSTS: same node id (React key stability is the whole+ * point), `display:none`, non-interactive, position parked at the origin. Merging happens at the+ * prop, exactly like the ephemeral subagent cards — Canvas state, persistence, undo and the wire+ * never see a ghost.+ *+ * The invariant every function here preserves, and the one a refactor must not break: **the+ * relative order of surviving entries is identical in consecutive merge outputs.** Appends and+ * removals are fine; a reorder kills a live page. `orderIsStable` in the tests states it directly.+ *+ * Memory bounds (same posture as the park/WebGL budgets — a lever must not end live work):+ * - the Browser Memory Saver already discards any HIDDEN webview after `BROWSER_DISCARD_MS`+ * unless it is loading/audible/agent-driven, and a ghost is hidden by construction — the+ * existing per-surface hook reaps it, and `onGuestDiscarded` then drops the entry (the husk+ * would otherwise hold a cap slot for a guest that no longer exists);+ * - `BACKGROUND_WEBVIEW_MAX` hard-caps how many background guests exist at once, evicting the+ * longest-retired first, for the user who switches through many projects faster than the+ * saver's window (or who turned the saver off).+ */+import type { CanvasNode } from '../state/workspace'+import type { NodeKind } from '@shared/types'++/** Node kinds that host an Electron `<webview>` (a whole Chromium renderer process). */+export const KEEPALIVE_KINDS: ReadonlySet<string> = new Set(['browser', 'web'])++/**+ * Hard cap on simultaneously-alive BACKGROUND guests. Each one is a Chromium renderer+ * (~50–200 MB); the Browser Memory Saver reaps hidden ones after its window, so this cap only+ * bites a fast multi-project switcher — and then evicts the longest-retired page, which is also+ * the one whose in-page state was most likely stale anyway.+ */+export const BACKGROUND_WEBVIEW_MAX = 8++/** One pooled webview node. Immutable — every update replaces the entry object, which is what+ * lets the merge cache ghost node objects by entry identity. */+export interface KeepAliveEntry {+ nodeId: string+ projectId: string+ /** Snapshot of the node as last seen live. `data` carries what the mounted surface needs to+ * keep rendering consistently (url/title/partition/filePath…). */+ node: { type: NodeKind; width?: number; height?: number; data: CanvasNode['data'] }+ /** When this entry went to the background (ms epoch) — LRU key for the cap. 0 = active. */+ retiredAt: number+}++/** Does this live flow node belong in the pool region at all? */+export function isKeepAliveKind(n: { type?: string }): boolean {+ return !!n.type && KEEPALIVE_KINDS.has(n.type)+}++/** Does this node hold a guest worth keeping alive in the background? A start-page browser or an+ * empty web node has no guest process — retiring it would keep a husk for nothing. */+export function hasKeepAliveContent(n: { data?: { url?: unknown; filePath?: unknown } }): boolean {+ return !!(n.data && (n.data.url || n.data.filePath))+}++/** Ghost node objects cached by entry identity, so a drag frame's merge re-emits the SAME object+ * and React Flow / React bail out instead of re-rendering every ghost per frame. */+const ghostCache = new WeakMap<KeepAliveEntry, CanvasNode>()++/**+ * The React Flow node a background entry renders as. Same id (key stability), `display:none`+ * (guest survives, IntersectionObserver reads it as hidden so the memory saver's clock runs),+ * non-interactive on every axis, `parentId`-free and parked at the origin — a hidden node has no+ * geometry, so its position only matters for not skewing minimap/fit bounds.+ */+export function ghostFlowNode(entry: KeepAliveEntry): CanvasNode {+ const cached = ghostCache.get(entry)+ if (cached) return cached+ const node: CanvasNode = {+ id: entry.nodeId,+ type: entry.node.type,+ position: { x: 0, y: 0 },+ width: entry.node.width,+ height: entry.node.height,+ data: { ...entry.node.data, ghost: true },+ style: { display: 'none' },+ draggable: false,+ selectable: false,+ deletable: false,+ connectable: false,+ focusable: false+ }+ ghostCache.set(entry, node)+ return node+}++/**+ * Build the `<ReactFlow>` nodes prop: non-webview live nodes, then the ephemeral cards, then the+ * pool region — every pool entry in pool order (live object for the MOUNTED project, ghost for+ * any other), then any mounted webview node the pool does not know yet (a node created since the+ * last switch), in live array order.+ *+ * `mountedProjectId` is the project `liveNodes` actually BELONGS to (Canvas's+ * `keepAliveFromRef`), and deliberately NOT the active-project id. The two disagree for exactly+ * one commit per switch — the tab click re-renders with the new active id while the load effect+ * has not yet swapped the node array — and pairing entries against the active id there made a+ * returning entry take the live branch, miss its node in the not-yet-swapped array, and drop out+ * of the merged list for that commit: one unmount, guest dead, page reloaded — the precise+ * failure this module exists to prevent ([MEASURED] in the app: ghost→live remounted the wrapper+ * while live→ghost, which has no such window, kept it). Keyed on the mounted project, that+ * commit's output is id-identical to the previous one, and the whole swap lands in the single+ * commit the load effect produces.+ *+ * Hoisting the ACTIVE webview nodes to the tail region is what keeps their DOM position stable+ * across the active↔ghost transitions; the visible cost is a tie-break change — an unselected+ * webview node now paints above other unselected z-0 nodes it overlaps, instead of by creation+ * order. Selection elevation (z 1000) still wins, so anything being dragged or selected stays on+ * top of a page.+ */+export function mergeWithKeepAlive(+ liveNodes: readonly CanvasNode[],+ ephemeralNodes: readonly CanvasNode[],+ entries: readonly KeepAliveEntry[],+ mountedProjectId: string | null+): CanvasNode[] {+ const anyPool = entries.length > 0 || liveNodes.some(isKeepAliveKind)+ if (!anyPool) {+ // No webview node anywhere: hand back the live array ITSELF (React Flow's array-identity+ // short-circuit), byte-identical to the pre-pool merge.+ return ephemeralNodes.length ? [...liveNodes, ...ephemeralNodes] : (liveNodes as CanvasNode[])+ }+ const byId = new Map<string, CanvasNode>()+ for (const n of liveNodes) if (isKeepAliveKind(n)) byId.set(n.id, n)+ const out: CanvasNode[] = []+ for (const n of liveNodes) if (!isKeepAliveKind(n)) out.push(n)+ out.push(...ephemeralNodes)+ const seen = new Set<string>()+ for (const e of entries) {+ seen.add(e.nodeId)+ if (e.projectId === mountedProjectId) {+ // Live object, not the snapshot: position/selection/data flow straight through.+ //+ // A miss FALLS BACK TO THE GHOST rather than dropping the entry from the output. The pool+ // store, `keepAliveFromRef` and `nodes` are three state sources that do not all land in the+ // same commit (zustand rides useSyncExternalStore; `setNodes` is ordinary state), so a+ // switch can render one commit where the entries already say "mounted" while the node array+ // is still the outgoing project's — and an id absent from ONE commit is an unmount, i.e. a+ // dead guest and a page reload ([MEASURED] in the app: this exact interleaving remounted+ // every returning page; the jsdom test cannot see it because it renders atomically).+ // The fallback costs nothing when it fires wrongly for a genuinely DELETED node: the ghost+ // is invisible, and every deletion funnel drops the entry (handleNodesChange's remove+ // branch, the peer-mutation remove, project deletion), with the next retire as the backstop.+ const live = byId.get(e.nodeId)+ out.push(live ?? ghostFlowNode(e))+ } else {+ out.push(ghostFlowNode(e))+ }+ }+ for (const n of liveNodes) {+ if (isKeepAliveKind(n) && !seen.has(n.id)) out.push(n)+ }+ return out+}++/** The node ids currently rendered as GHOSTS (background entries) — the set `handleNodesChange`+ * drops on the floor: nothing about a background node is a canvas edit. */+export function backgroundNodeIds(+ entries: readonly KeepAliveEntry[],+ activeProjectId: string | null+): Set<string> {+ const out = new Set<string>()+ for (const e of entries) if (e.projectId !== activeProjectId) out.add(e.nodeId)+ return out+}++/**+ * Retire a project's webview nodes into the pool: upsert a fresh snapshot for every content-bearing+ * webview node (keeping an existing entry's ORDER SLOT — the invariant), prune the project's+ * entries whose node is gone (deleted, or its content cleared), and evict the longest-retired+ * background entries beyond the cap. Pure; the store owns the state.+ */+export function retireIntoPool(+ entries: readonly KeepAliveEntry[],+ projectId: string,+ outgoingNodes: readonly CanvasNode[],+ now: number,+ cap: number = BACKGROUND_WEBVIEW_MAX+): KeepAliveEntry[] {+ const keep = new Map<string, CanvasNode>()+ for (const n of outgoingNodes) {+ if (isKeepAliveKind(n) && hasKeepAliveContent(n)) keep.set(n.id, n)+ }+ const snapshot = (n: CanvasNode, prior?: KeepAliveEntry): KeepAliveEntry => ({+ nodeId: n.id,+ projectId,+ node: {+ type: n.type as NodeKind,+ width: n.width ?? n.measured?.width ?? undefined,+ height: n.height ?? n.measured?.height ?? undefined,+ // The ghost must render with the values the mounted surface last reported, or the props+ // transition at the switch would navigate the live page (BrowserSurface reloads when its+ // `url` prop moves away from where it is).+ data: { ...n.data }+ },+ // A re-retired entry keeps its original clock only if it was already background (it cannot+ // be: retire runs on the project we are LEAVING, whose entries were active). Fresh clock.+ retiredAt: prior && prior.projectId === projectId && prior.retiredAt ? prior.retiredAt : now+ })+ const next: KeepAliveEntry[] = []+ for (const e of entries) {+ if (e.projectId !== projectId) {+ next.push(e)+ continue+ }+ const live = keep.get(e.nodeId)+ if (!live) continue // node deleted or content gone — entry ends, ghost unmounts+ keep.delete(e.nodeId)+ next.push(snapshot(live, e))+ }+ // Nodes the pool has not seen yet, appended in live array order (their merge position was+ // already "after every entry", so appending preserves each element's relative order).+ for (const n of outgoingNodes) {+ if (keep.has(n.id)) next.push(snapshot(n))+ }+ return evictOverCap(next, cap)+}++/**+ * Mark a project's entries ACTIVE (retiredAt 0). Runs on the way INTO a project, and must run+ * BEFORE the outgoing project's `retireIntoPool` — an incoming entry still carrying its old+ * background clock would be the cap's oldest candidate at the exact moment its page is about to+ * be revealed, and evicting it there would reload the very page the pool preserved.+ */+export function activateInPool(+ entries: readonly KeepAliveEntry[],+ projectId: string+): KeepAliveEntry[] {+ return entries.map((e) => (e.projectId === projectId && e.retiredAt !== 0 ? { ...e, retiredAt: 0 } : e))+}++/** Drop the longest-retired background entries beyond `cap`. Removal never reorders survivors. */+export function evictOverCap(entries: readonly KeepAliveEntry[], cap: number): KeepAliveEntry[] {+ const background = entries.filter((e) => e.retiredAt > 0)+ if (background.length <= cap) return [...entries]+ const evict = new Set(+ background+ .slice()+ .sort((a, b) => a.retiredAt - b.retiredAt)+ .slice(0, background.length - cap)+ .map((e) => e.nodeId)+ )+ return entries.filter((e) => !evict.has(e.nodeId))+}++/**+ * Overlay a returning project's pool data onto its freshly deserialized flow nodes, BEFORE the+ * single `setNodes` — a page that navigated while it was a ghost must come back with `data.url`+ * already at its live location, or the props transition (persisted, stale url) would navigate the+ * surviving webview backwards. Only url/title move; everything else is the file's business.+ */+export function overlayKeepAliveData(+ flow: readonly CanvasNode[],+ entries: readonly KeepAliveEntry[],+ projectId: string+): CanvasNode[] {+ const byId = new Map<string, KeepAliveEntry>()+ for (const e of entries) if (e.projectId === projectId) byId.set(e.nodeId, e)+ if (byId.size === 0) return [...flow]+ return flow.map((n) => {+ const e = byId.get(n.id)+ if (!e) return n+ const url = e.node.data.url+ const title = e.node.data.title+ if ((url === undefined || url === n.data.url) && (title === undefined || title === n.data.title))+ return n+ return {+ ...n,+ data: {+ ...n.data,+ ...(url !== undefined ? { url } : {}),+ ...(title !== undefined ? { title } : {})+ }+ }+ })+}diff --git a/src/renderer/nodes/BrowserNode.tsx b/src/renderer/nodes/BrowserNode.tsxindex 0201d9515..4757a1de2 100644--- a/src/renderer/nodes/BrowserNode.tsx+++ b/src/renderer/nodes/BrowserNode.tsx@@ -3,14 +3,22 @@ import { NODE_MIN_SIZES } from '../lib/nodeSizing'import type { CanvasNode } from '../state/workspace'import { BrowserSurface } from './BrowserSurface'import { BrowserDrivingIndicator } from './BrowserDrivingChip'+import { useWebviewKeepAlive } from '../state/webviewKeepAlive'/*** A navigable Chromium browser node: node chrome (frame/header/resize/close) wrapping the shared* {@link BrowserSurface} (webview + toolbar). The last top-level URL persists to `data.url` so the* node reopens where it was; the same surface backs the kanban card modal's browser popup.+ *+ * A background KEEP-ALIVE GHOST (`data.ghost` — see lib/webviewKeepAlive.ts) renders the same+ * tree (the mounted `<webview>` is the point), hidden by the ghost node's `display:none` style.+ * Only the wiring differs: navigation/title facts go to the pool entry (there is no live node in+ * React Flow to update — `updateNodeData` on a ghost id is a dropped change), and a memory-saver+ * discard ends the entry outright (a ghost without its guest is a husk holding a cap slot).*/export default function BrowserNode({ id, data, selected }: NodeProps<CanvasNode>) {const { deleteElements, updateNodeData } = useReactFlow()+ const ghost = data.ghost === truereturn (<div className={`term-node browser-node${selected ? ' selected' : ''}`} style={{ borderTopColor: data.color }}>@@ -51,8 +59,13 @@ export default function BrowserNode({ id, data, selected }: NodeProps<CanvasNodenodeId={id}url={(data.url as string) ?? ''}partition={data.partition as string | undefined}- onUrlChange={(u) => updateNodeData(id, { url: u })}- onTitleChange={(t) => updateNodeData(id, { title: t })}+ onUrlChange={(u) =>+ ghost ? useWebviewKeepAlive.getState().updateGhostData(id, { url: u }) : updateNodeData(id, { url: u })+ }+ onTitleChange={(t) =>+ ghost ? useWebviewKeepAlive.getState().updateGhostData(id, { title: t }) : updateNodeData(id, { title: t })+ }+ onGuestDiscarded={ghost ? () => useWebviewKeepAlive.getState().drop(id) : undefined}/></div></div>diff --git a/src/renderer/nodes/BrowserSurface.tsx b/src/renderer/nodes/BrowserSurface.tsxindex 11c473752..0bd67da6f 100644--- a/src/renderer/nodes/BrowserSurface.tsx+++ b/src/renderer/nodes/BrowserSurface.tsx@@ -37,6 +37,13 @@ interface BrowserSurfaceProps {onUrlChange: (url: string) => void/** Persist the page title. */onTitleChange: (title: string) => void+ /**+ * The memory saver released this surface's guest process. Optional; today's one caller is a+ * background keep-alive GHOST (see lib/webviewKeepAlive.ts), which answers by dropping its pool+ * entry — a hidden husk with no guest has nothing left to keep alive. An ACTIVE node passes+ * nothing and keeps the plate-and-restore behavior unchanged.+ */+ onGuestDiscarded?: () => void}/**@@ -46,7 +53,14 @@ interface BrowserSurfaceProps {* webview never emits dom-ready, so imperative loadURL before then is a no-op); `did-navigate` only* updates the address, so in-page navigation can't loop.*/-export function BrowserSurface({ nodeId, url, partition, onUrlChange, onTitleChange }: BrowserSurfaceProps) {+export function BrowserSurface({+ nodeId,+ url,+ partition,+ onUrlChange,+ onTitleChange,+ onGuestDiscarded+}: BrowserSurfaceProps) {const ref = useRef<WebviewEl | null>(null)const rootRef = useRef<HTMLDivElement | null>(null)const lastUrlRef = useRef('')@@ -185,6 +199,7 @@ export function BrowserSurface({ nodeId, url, partition, onUrlChange, onTitleCha// A failure banner belongs to the page we just released; the restore re-navigates and will// raise its own if the load fails again.setFailed('')+ onGuestDiscarded?.()},onRestore: () => {setDiscarded(false)diff --git a/src/renderer/nodes/WebNode.tsx b/src/renderer/nodes/WebNode.tsxindex 57b2a1f0f..abff3027c 100644--- a/src/renderer/nodes/WebNode.tsx+++ b/src/renderer/nodes/WebNode.tsx@@ -5,6 +5,7 @@ import type { CanvasNode } from '../state/workspace'import { httpUrl } from './webUrl'import { useDiscardWhenHidden, webviewAudible, type AudibleWebview } from './useDiscardWhenHidden'import { DiscardedPlate } from './DiscardedPlate'+import { useWebviewKeepAlive } from '../state/webviewKeepAlive'/*** A web view node. When `data.url` is set it loads that live URL; otherwise it serves the@@ -85,6 +86,10 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {setDiscarded(true)setSrc('')srcRef.current = ''+ // A background keep-alive GHOST (data.ghost — lib/webviewKeepAlive.ts) whose guest is gone+ // is a husk holding a pool slot: end its entry, which unmounts this whole node. An active+ // node keeps the plate-and-restore behavior unchanged.+ if (data.ghost === true) useWebviewKeepAlive.getState().drop(id)},onRestore: () => {setDiscarded(false)diff --git a/src/renderer/nodes/webview-keepalive-reconcile.test.tsx b/src/renderer/nodes/webview-keepalive-reconcile.test.tsxnew file mode 100644index 000000000..932c8716a--- /dev/null+++ b/src/renderer/nodes/webview-keepalive-reconcile.test.tsx@@ -0,0 +1,145 @@+// @vitest-environment jsdom+//+// Pins the DOM half of the webview keep-alive design (lib/webviewKeepAlive.ts): across project+// switches, the merged node list must never make React DETACH or MOVE a kept webview node's+// element — an Electron `<webview>`'s guest process dies on any removeChild/insertBefore that+// touches its element ([MEASURED, Electron 42.x]: survives sibling churn and display:none;+// dies on a DOM move, reloading the page).+//+// The test renders a keyed list driven by REAL merge outputs over a switch script, instruments+// the DOM mutation methods, and asserts that once a tracked "webview" element is attached, no+// DOM operation ever targets it again while its entry lives. This is precisely React's+// lastPlacedIndex contract: kept children whose relative order is stable are left untouched.+// (The React Flow layer above renders nodes in array order, keyed by id — verified end-to-end+// against the real app; this test guards the React-level invariant the merge order guarantees.)+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, describe, expect, it } from 'vitest'+import type { CanvasNode } from '../state/workspace'+import {+ activateInPool,+ mergeWithKeepAlive,+ retireIntoPool,+ type KeepAliveEntry+} from '../lib/webviewKeepAlive'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const node = (id: string, type: string, data: Record<string, unknown> = {}): CanvasNode =>+ ({+ id,+ type,+ position: { x: 10, y: 10 },+ data: { title: id, color: '#0a84ff', group: null, ...data }+ }) as unknown as CanvasNode++const browser = (id: string): CanvasNode => node(id, 'browser', { url: `https://${id}.test/` })++/** Stand-in node renderer: one keyed div per merged node, exactly how React Flow keys its node+ * wrappers by id. The div IS the "webview" whose DOM identity we track. */+function List({ nodes }: { nodes: CanvasNode[] }) {+ return (+ <div>+ {nodes.map((n) => (+ <div key={n.id} data-id={n.id} data-ghost={n.data.ghost ? '1' : undefined} />+ ))}+ </div>+ )+}++let root: Root | null = null+let host: HTMLElement | null = null+const restores: Array<() => void> = []++afterEach(() => {+ act(() => root?.unmount())+ host?.remove()+ root = null+ host = null+ for (const r of restores.splice(0)) r()+})++/** Record every DOM mutation whose SUBJECT is an already-attached tracked element. Attaching a+ * parent around it, or churning siblings, is free; any call naming the element itself after its+ * first attach is the guest-killer. */+function instrument(tracked: () => Set<Element>): string[] {+ const ops: string[] = []+ const attached = new Set<Node>()+ const wrap = <K extends 'insertBefore' | 'appendChild' | 'removeChild'>(name: K): void => {+ const original = Node.prototype[name] as (...a: never[]) => Node+ const patched = function (this: Node, ...args: never[]): Node {+ const subject = args[0] as unknown as Node+ if (subject instanceof Element && tracked().has(subject)) {+ if (attached.has(subject)) ops.push(`${name}:${(subject as Element).getAttribute('data-id')}`)+ else if (name !== 'removeChild') attached.add(subject)+ }+ return original.apply(this, args)+ }+ Object.defineProperty(Node.prototype, name, { value: patched, configurable: true, writable: true })+ restores.push(() => {+ Object.defineProperty(Node.prototype, name, { value: original, configurable: true, writable: true })+ })+ }+ wrap('insertBefore')+ wrap('appendChild')+ wrap('removeChild')+ return ops+}++describe('webview keep-alive DOM stability', () => {+ it('a webview node element is never detached or moved across project switches', () => {+ const projects: Record<string, CanvasNode[]> = {+ p1: [node('t1', 'terminal'), browser('b1'), node('s1', 'sticky'), browser('b2')],+ p2: [browser('c1'), node('t2', 'terminal')],+ p3: [node('t3', 'terminal')]+ }+ let entries: KeepAliveEntry[] = []+ let activePid = 'p1'+ let clock = 0++ host = document.createElement('div')+ document.body.append(host)+ root = createRoot(host)++ const webviewEls = (): Set<Element> =>+ new Set([...document.querySelectorAll('[data-id^="b"], [data-id^="c"]')])+ // Tracked set is resolved lazily per call — it must include elements attached at any point.+ const everTracked = new Set<Element>()+ const ops = instrument(() => {+ for (const el of webviewEls()) everTracked.add(el)+ return everTracked+ })++ const render = (): void => {+ const merged = mergeWithKeepAlive(projects[activePid], [], entries, activePid)+ act(() => root!.render(<List nodes={merged} />))+ }+ const switchTo = (pid: string): void => {+ entries = activateInPool(entries, pid)+ entries = retireIntoPool(entries, activePid, projects[activePid], ++clock)+ activePid = pid+ render()+ }++ render()+ const b1 = document.querySelector('[data-id="b1"]')+ expect(b1).toBeTruthy()++ switchTo('p2') // b1/b2 become ghosts, c1 goes live+ expect(document.querySelector('[data-id="b1"]')).toBe(b1) // same DOM element+ expect(b1!.getAttribute('data-ghost')).toBe('1')++ projects.p2 = [...projects.p2, browser('c2')] // create a browser mid-session+ render()+ switchTo('p3') // everything webview is a ghost+ switchTo('p1') // b1/b2 return to live+ expect(document.querySelector('[data-id="b1"]')).toBe(b1)+ expect(b1!.getAttribute('data-ghost')).toBeNull()+ switchTo('p2')+ switchTo('p1')++ // The invariant: not one insertBefore/appendChild/removeChild ever named an attached+ // webview element. (Deleting a node legitimately removes its element — not exercised here.)+ expect(ops).toEqual([])+ })+})diff --git a/src/renderer/state/webviewKeepAlive.ts b/src/renderer/state/webviewKeepAlive.tsnew file mode 100644index 000000000..c7a0d4587--- /dev/null+++ b/src/renderer/state/webviewKeepAlive.ts@@ -0,0 +1,57 @@+/**+ * The webview keep-alive pool store — the stateful half of `lib/webviewKeepAlive.ts` (read that+ * file's header first; the ORDER of `entries` is load-bearing and every action here only ever+ * appends, removes, or replaces an entry in place).+ *+ * Renderer-local and transient by design: guests die with the window, so there is nothing to+ * persist. Canvas's project-load effect is the one writer of membership (`retireProject` /+ * `prune`); a GHOST surface writes its own navigation facts (`updateGhostData`) and reports its+ * guest's discard (`drop`).+ */+import { create } from 'zustand'+import type { CanvasNode } from './workspace'+import { activateInPool, retireIntoPool, type KeepAliveEntry } from '../lib/webviewKeepAlive'++interface WebviewKeepAliveState {+ entries: KeepAliveEntry[]+ /** Mark a project's entries active on the way IN — always BEFORE the outgoing project's+ * `retireProject`, so the cap can never evict a page that is about to be revealed. */+ activateProject(projectId: string): void+ /** Move a project's webview nodes into the background: fresh snapshots, order slots kept,+ * gone nodes pruned, cap enforced. Called on the way OUT of a project. */+ retireProject(projectId: string, outgoingNodes: readonly CanvasNode[]): void+ /** A ghost navigated (or re-titled) itself: keep the snapshot current so the ghost keeps+ * rendering with the values its mounted surface reports, and so the switch-back overlay+ * hands the live location to the returning project. */+ updateGhostData(nodeId: string, patch: { url?: string; title?: string }): void+ /** The entry is over — its guest was discarded, or its node/project is gone. */+ drop(nodeId: string): void+ /** Keep only entries whose project still exists (delete-project cleanup). */+ prune(liveProjectIds: ReadonlySet<string>): void+}++export const useWebviewKeepAlive = create<WebviewKeepAliveState>((set, get) => ({+ entries: [],+ activateProject(projectId) {+ const next = activateInPool(get().entries, projectId)+ if (next.some((e, i) => e !== get().entries[i])) set({ entries: next })+ },+ retireProject(projectId, outgoingNodes) {+ set({ entries: retireIntoPool(get().entries, projectId, outgoingNodes, Date.now()) })+ },+ updateGhostData(nodeId, patch) {+ set({+ entries: get().entries.map((e) =>+ e.nodeId === nodeId ? { ...e, node: { ...e.node, data: { ...e.node.data, ...patch } } } : e+ )+ })+ },+ drop(nodeId) {+ if (!get().entries.some((e) => e.nodeId === nodeId)) return+ set({ entries: get().entries.filter((e) => e.nodeId !== nodeId) })+ },+ prune(liveProjectIds) {+ if (get().entries.every((e) => liveProjectIds.has(e.projectId))) return+ set({ entries: get().entries.filter((e) => liveProjectIds.has(e.projectId)) })+ }+}))diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 406908004..d11aa6057 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -117,6 +117,14 @@ export interface NodeData {* through persistence untouched on Server Edition / mobile, where a browser node has no <webview>.*/partition?: string+ /**+ * browser/web-only, NEVER persisted: this node object is a background KEEP-ALIVE GHOST — a+ * `display:none` stand-in merged into the `<ReactFlow>` prop so the `<webview>` of a project the+ * user switched away from stays mounted (its guest process dies on DOM detach). Ghosts live only+ * in `state/webviewKeepAlive.ts` pool entries; Canvas state, persistence, undo and the wire never+ * hold one. The surfaces read it to route their callbacks at the pool instead of React Flow.+ */+ ghost?: booleandiffStaged?: booleancommitOid?: string/** dino-only: best score reached in the T-Rex Runner game. */