Skip to content

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

fix(renderer): never discard an audible page; keep a reveal from dirtying the workspace

enes764323ee7be4
diff --git a/docs/superpowers/plans/2026-08-10-ram-optimization.md b/docs/superpowers/plans/2026-08-10-ram-optimization.md
index 789b01f11..6140352f5 100644
--- a/docs/superpowers/plans/2026-08-10-ram-optimization.md
+++ b/docs/superpowers/plans/2026-08-10-ram-optimization.md
@@ -648,7 +648,7 @@ Run: `npm run typecheck && npx vitest run src/core src/renderer/terminal`. Commi
## Phase 4 — Browser/web node Memory Saver (one PR)
-Chrome's own "Memory Saver" semantics on canvas webviews: a `BrowserSurface`/`WebNode` webview hidden (offscreen or kanban-covered) for 5 minutes is **discarded** — the `<webview>` loses its `src` (guest renderer process dies), the descriptor `{url, address}` is kept, a plate renders — and restored on visibility. Back/forward stack is lost on restore (Electron webview cannot serialize it); PR body states this openly.
+Chrome's own "Memory Saver" semantics on canvas webviews: a `BrowserSurface`/`WebNode` webview hidden (**offscreen in the canvas viewport**) for 5 minutes is **discarded** — the `<webview>` element is unmounted, so the guest renderer process dies; the descriptor `{url, address}` is kept, a plate renders — and restored on visibility. Back/forward stack is lost on restore (Electron webview cannot serialize it); PR body states this openly.
**Files:**
- Create: `src/renderer/nodes/browser-discard-policy.ts`, `src/renderer/nodes/browser-discard-policy.test.ts`
@@ -756,10 +756,12 @@ Import `useSettings` (same store TerminalNode uses) and the policy module. Add `
- [ ] **Step 6: WebNode.tsx** — same pattern, same policy module, on its root div; on restore re-run the existing `src` effect by re-setting state from `url`/`filePath` (the `media.allow` promise path already handles re-grant).
-- [ ] **Step 7: Verify + commit + PR** — `npm run typecheck && npx vitest run src/renderer/nodes`. Manual: open a browser node, cover it with kanban view for >5 min, verify in Activity Monitor / `ps` that the guest process exited; return to canvas, verify reload. Commit `feat(renderer): browser Memory Saver — discard hidden webviews, restore from URL`.
+- [ ] **Step 7: Verify + commit + PR** — `npm run typecheck && npx vitest run src/renderer/nodes`. Manual: open a browser node, **pan the node fully off-screen** for >5 min, verify in Activity Monitor / `ps` that the guest process exited; pan it back into view and verify the reload. Commit `feat(renderer): browser Memory Saver — discard hidden webviews, restore from URL`.
**Surfaces:** Desktop only in practice (`<webview>` requires Electron; the Server Edition renders browser nodes via the same components but webview doesn't exist in a plain browser — verify how BrowserNode degrades there today and keep that behavior). Mobile: N/A.
+**Deferred by user decision (v1 = pan-only):** "hidden" means **geometrically offscreen**, as reported by an `IntersectionObserver`. Two other senses of hidden were considered and deliberately left out. (1) **Kanban-covered** — the board is an opaque overlay, but the canvas stays MOUNTED beneath it and every node still intersects the viewport, so occlusion is invisible to an IntersectionObserver; discarding on it would need an explicit signal from `KanbanView`. (2) **Window-hidden** (`document.visibilityState`) — a minimized or background window would discard every browser node at once, and every one of them would reload on return. Both are follow-ups, not gaps in v1. A page that is **making sound** is never discarded regardless (Chrome's own rule), and a load in flight blocks a discard until it finishes.
+
---
## Phase 5 — Agent hibernation, opt-in "Eco" (one PR, own device checklist)
diff --git a/src/renderer/nodes/BrowserSurface.tsx b/src/renderer/nodes/BrowserSurface.tsx
index a886ca963..ea45f3ace 100644
--- a/src/renderer/nodes/BrowserSurface.tsx
+++ b/src/renderer/nodes/BrowserSurface.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { searchOrUrl } from './browserUrl'
import { BrowserStartPage } from './BrowserStartPage'
import { useBrowserHistory } from '../state/browserHistory'
-import { useDiscardWhenHidden } from './useDiscardWhenHidden'
+import { useDiscardWhenHidden, webviewAudible } from './useDiscardWhenHidden'
import { DiscardedPlate } from './DiscardedPlate'
// Minimal typing for the Electron <webview> element methods/events we use.
@@ -15,6 +15,8 @@ type WebviewEl = HTMLElement & {
canGoBack(): boolean
canGoForward(): boolean
getWebContentsId(): number
+ /** Throws before the guest attaches — always go through `webviewAudible`. */
+ isCurrentlyAudible?: () => boolean
}
interface BrowserSurfaceProps {
@@ -51,6 +53,10 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
// a callback that must not force the observer to be re-created.
const [discarded, setDiscarded] = useState(false)
const loadingRef = useRef(false)
+ /** Set by a restore, cleared by the first did-navigate after it — that one is an echo. */
+ const restoringNavRef = useRef(false)
+ /** The last title we reported (null = the gate is open for the current page's first title). */
+ const lastTitleRef = useRef<string | null>(null)
/** The page a discard would rebuild from — the last location we actually LOADED, never the
* address input (which holds whatever the user typed, submitted or not). */
const locationRef = useRef(startUrl)
@@ -70,9 +76,20 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
}
const onNav = (e: Event): void => {
const u = (e as unknown as { url: string }).url
+ // A memory-saver restore replays the URL we were already on, and its did-navigate is
+ // indistinguishable from a real one. Reporting it would make MERELY LOOKING at a node dirty
+ // the project (updateNodeData → dirty + rev bump + SSH mirror write) and bump an unchanged
+ // page to the top of Recent. One-shot and value-checked, so a user who navigates for real
+ // immediately after a reveal is still recorded.
+ const echo = restoringNavRef.current && u === locationRef.current
+ restoringNavRef.current = false
setAddress(u)
locationRef.current = u
setFailed('')
+ if (echo) return
+ // A genuine navigation re-opens the title gate below: the first title of the NEW page always
+ // records, however it compares to the old page's.
+ lastTitleRef.current = null
onUrlChange(u)
lastUrlRef.current = u
useBrowserHistory.getState().record(u, u)
@@ -84,6 +101,11 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
}
const onTitle = (e: Event): void => {
const title = (e as unknown as { title: string }).title
+ // The restored page re-announces the title it already had, which would re-dirty the project
+ // and re-bump history through the other half of the same reveal. Suppressing it by VALUE
+ // rather than by a restore flag means a title that genuinely changed still lands.
+ if (title === lastTitleRef.current) return
+ lastTitleRef.current = title
onTitleChange(title)
if (lastUrlRef.current) useBrowserHistory.getState().record(lastUrlRef.current, title)
}
@@ -135,6 +157,7 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
// release and rebuild its page.
useDiscardWhenHidden(rootRef, {
isLoading: () => loadingRef.current,
+ isAudible: () => webviewAudible(ref.current),
hasContent: () => !!locationRef.current,
onDiscard: () => {
setDiscarded(true)
@@ -145,6 +168,8 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
},
onRestore: () => {
setDiscarded(false)
+ // The restore's own did-navigate is an ECHO of where we already were — see `onNav`.
+ restoringNavRef.current = true
// Restore from the descriptor. Setting `src` and `address` to the SAME value preserves the
// `url !== address` guard of the sync effect below, so the restore can't start a reload loop.
const back = locationRef.current
diff --git a/src/renderer/nodes/WebNode.tsx b/src/renderer/nodes/WebNode.tsx
index 624d8d884..ef18892e7 100644
--- a/src/renderer/nodes/WebNode.tsx
+++ b/src/renderer/nodes/WebNode.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { Handle, NodeResizer, Position, useReactFlow, type NodeProps } from '@xyflow/react'
import type { CanvasNode } from '../state/workspace'
import { httpUrl } from './webUrl'
-import { useDiscardWhenHidden } from './useDiscardWhenHidden'
+import { useDiscardWhenHidden, webviewAudible, type AudibleWebview } from './useDiscardWhenHidden'
import { DiscardedPlate } from './DiscardedPlate'
/**
@@ -19,6 +19,8 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
const filePath = (data.filePath as string) ?? ''
const title = (data.title as string) || url || filePath.split('/').pop() || 'web'
const rootRef = useRef<HTMLDivElement | null>(null)
+ /** The guest, for the audible check only — a local html page can hold a playing <video>. */
+ const wvRef = useRef<AudibleWebview | null>(null)
// Memory saver — the same shared hook {@link BrowserSurface} uses: hidden long enough, the
// <webview> is unmounted (its Chromium process exits) and rebuilt on reveal. `revive` is what
// re-runs the source effect below, so the `nt-media://` grant is re-issued for a local file
@@ -76,6 +78,7 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
useDiscardWhenHidden(rootRef, {
isLoading: () => grantingRef.current,
+ isAudible: () => webviewAudible(wvRef.current),
hasContent: () => !!srcRef.current,
onDiscard: () => {
setDiscarded(true)
@@ -140,7 +143,13 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
<DiscardedPlate restoring={restoring} />
) : src ? (
// eslint-disable-next-line react/no-unknown-property
- <webview src={src} style={{ width: '100%', height: '100%' }} />
+ <webview
+ ref={(el) => {
+ wvRef.current = el as unknown as AudibleWebview | null
+ }}
+ src={src}
+ style={{ width: '100%', height: '100%' }}
+ />
) : (
<span className="editor-node__loading">{error || 'No source'}</span>
)}
diff --git a/src/renderer/nodes/browser-discard-policy.test.ts b/src/renderer/nodes/browser-discard-policy.test.ts
index b7ae9d22e..73b8e3d83 100644
--- a/src/renderer/nodes/browser-discard-policy.test.ts
+++ b/src/renderer/nodes/browser-discard-policy.test.ts
@@ -9,6 +9,15 @@ describe('browser discard policy', () => {
expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: false, enabled: false })).toBe(false)
})
+ it('never discards a page that is making sound', () => {
+ // Audible = in use, even off-screen (a call, music, a video being listened to).
+ expect(
+ shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: false, enabled: true, audible: true })
+ ).toBe(false)
+ // A surface that cannot tell (no `audible` at all) is not treated as audible.
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: false, enabled: true })).toBe(true)
+ })
+
it('treats the window boundary as not-yet-elapsed', () => {
// The timer fires on a slack margin past the window, so an exactly-equal reading means the
// clock jumped (sleep/wake) rather than the page having genuinely sat hidden long enough.
diff --git a/src/renderer/nodes/browser-discard-policy.ts b/src/renderer/nodes/browser-discard-policy.ts
index 4e6a07b9a..12a4b19f3 100644
--- a/src/renderer/nodes/browser-discard-policy.ts
+++ b/src/renderer/nodes/browser-discard-policy.ts
@@ -4,11 +4,18 @@
* browser/web nodes it holds. A page that has sat hidden this long is cheaper to rebuild from its
* URL on reveal than to keep resident.
*
- * Two constraints are baked into the predicate:
+ * Three constraints are baked into the predicate:
* - **Never discard mid-load.** Restoring would replay a half-finished navigation (and a POST
* result or an interstitial would simply be lost).
- * - **The setting is read at DECISION time, not at arm time.** A user who switches the saver off
- * while a page is hidden must not have it discarded by a timer armed a minute earlier.
+ * - **Never discard a page making noise.** Audible = in use, even off-screen (a call, music, a
+ * video the user is listening to). Chrome exempts audible tabs for the same reason.
+ * - **The setting is re-read when the timer FIRES, not when it was armed** — so a user who
+ * switches the saver off during a hidden stretch is not discarded by an older timer. The
+ * symmetry is deliberately incomplete: switching the saver ON mid-hide does NOT discard that
+ * page at the end of the current stretch, because the disabled branch arms no retry (pinned by
+ * `useDiscardWhenHidden.test.tsx`). Such a page is picked up on its next hide→show cycle. The
+ * conservative direction is the right one — a user turning the feature off must be obeyed at
+ * once, one turning it on can wait.
*
* The back/forward stack does NOT survive a discard — Electron's `<webview>` cannot serialize it.
* What survives is the descriptor (the current URL) and the user's own history store, which is the
@@ -16,6 +23,12 @@
*/
export const BROWSER_DISCARD_MS = 5 * 60_000
-export function shouldDiscard(i: { hiddenMs: number; loading: boolean; enabled: boolean }): boolean {
- return i.enabled && !i.loading && i.hiddenMs > BROWSER_DISCARD_MS
+export function shouldDiscard(i: {
+ hiddenMs: number
+ loading: boolean
+ enabled: boolean
+ /** Is the page making sound right now? Optional so a surface that cannot tell says nothing. */
+ audible?: boolean
+}): boolean {
+ return i.enabled && !i.loading && !i.audible && i.hiddenMs > BROWSER_DISCARD_MS
}
diff --git a/src/renderer/nodes/useDiscardWhenHidden.test.tsx b/src/renderer/nodes/useDiscardWhenHidden.test.tsx
index b2b4f328d..e24e51e0d 100644
--- a/src/renderer/nodes/useDiscardWhenHidden.test.tsx
+++ b/src/renderer/nodes/useDiscardWhenHidden.test.tsx
@@ -9,6 +9,7 @@ import {
DISCARD_RETRY_MS,
DISCARD_SLACK_MS,
useDiscardWhenHidden,
+ webviewAudible,
type DiscardWhenHiddenOptions
} from './useDiscardWhenHidden'
@@ -40,6 +41,7 @@ function Harness(props: Partial<DiscardWhenHiddenOptions> & { onEl?: (el: HTMLEl
const ref = useRef<HTMLDivElement | null>(null)
useDiscardWhenHidden(ref, {
isLoading: props.isLoading ?? (() => false),
+ isAudible: props.isAudible,
hasContent: props.hasContent ?? (() => true),
onDiscard: props.onDiscard ?? (() => {}),
onRestore: props.onRestore ?? (() => {})
@@ -175,6 +177,38 @@ describe('useDiscardWhenHidden', () => {
expect(onDiscard).toHaveBeenCalledTimes(1)
})
+ it('never discards a page making sound, and reclaims it once it goes quiet', () => {
+ const onDiscard = vi.fn()
+ let audible = true
+ let el!: HTMLElement
+ root = mount({ onDiscard, isAudible: () => audible, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ // Still playing a minute later — still exempt, and still re-armed.
+ advance(DISCARD_RETRY_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ audible = false
+ advance(DISCARD_RETRY_MS)
+ expect(onDiscard).toHaveBeenCalledTimes(1)
+ })
+
+ it('reads audibility through a webview ref that can throw or be absent', () => {
+ // A guest that has not attached yet throws on the call, and a discarded surface has no element
+ // at all — neither is "audible", and neither may take the saver down with it.
+ expect(webviewAudible(null)).toBe(false)
+ expect(webviewAudible(undefined)).toBe(false)
+ expect(webviewAudible({})).toBe(false)
+ expect(
+ webviewAudible({
+ isCurrentlyAudible: () => {
+ throw new Error('The WebView must be attached to the DOM')
+ }
+ })
+ ).toBe(false)
+ expect(webviewAudible({ isCurrentlyAudible: () => true })).toBe(true)
+ })
+
it('honours the setting at FIRE time, not at arm time', () => {
const onDiscard = vi.fn()
let el!: HTMLElement
diff --git a/src/renderer/nodes/useDiscardWhenHidden.ts b/src/renderer/nodes/useDiscardWhenHidden.ts
index b213efa48..7d5c16a2a 100644
--- a/src/renderer/nodes/useDiscardWhenHidden.ts
+++ b/src/renderer/nodes/useDiscardWhenHidden.ts
@@ -5,17 +5,42 @@ import { BROWSER_DISCARD_MS, shouldDiscard } from './browser-discard-policy'
/** Slack past the window so the reading at fire time is strictly PAST it (`shouldDiscard` is `>`). */
export const DISCARD_SLACK_MS = 1000
/**
- * Re-check interval when the ONLY thing blocking a discard was a load in flight. A load ends by
- * itself, so treating it as a decision for the whole hidden stretch would disarm the saver for a
- * page that finished a second later — the one blocker that deserves a retry rather than a wait for
- * the next hide→show cycle. Bounded (a fixed re-arm, never a poll loop): each retry only runs while
- * the element is still hidden, and any reveal clears the timer.
+ * Re-check interval when the only thing blocking a discard was TRANSIENT — a load in flight, or a
+ * page making sound. Both end by themselves, so treating either as a decision for the whole hidden
+ * stretch would disarm the saver for a page that finished (or went quiet) a second later. Bounded
+ * (a fixed re-arm, never a poll loop): each retry only runs while the element is still hidden, and
+ * any reveal clears the timer.
*/
export const DISCARD_RETRY_MS = 60_000
+/** The slice of Electron's `WebviewTag` the audible check needs. */
+export type AudibleWebview = { isCurrentlyAudible?: () => boolean }
+
+/**
+ * Is this webview making sound right now?
+ *
+ * Asked by direct QUERY rather than by tracking `media-started-playing` / `media-paused` into a
+ * flag, and the choice is about which way each is wrong. The query cannot drift: it is the guest's
+ * own answer at the instant we ask. The event pair can — a missed or unpaired event leaves a flag
+ * stuck, and stuck-audible means that node's saver is silently dead forever (the worst failure
+ * here, because nothing surfaces it). The query's only weakness is that it throws before the guest
+ * attaches, and a guest that does not exist yet cannot be playing anything — so `false` there is
+ * the CORRECT answer, not merely a safe one.
+ */
+export function webviewAudible(el: AudibleWebview | null | undefined): boolean {
+ try {
+ return el?.isCurrentlyAudible?.() === true
+ } catch {
+ return false
+ }
+}
+
export interface DiscardWhenHiddenOptions {
/** Is a load in flight right now? A discard mid-load would replay a half-finished navigation. */
isLoading: () => boolean
+ /** Is the page making sound right now? Omitted = this surface cannot tell (never treated as
+ * audible — a surface with no webview has nothing playing). */
+ isAudible?: () => boolean
/** Is there anything to release? (A start page / empty node has no guest process.) */
hasContent: () => boolean
/** Release the page: the caller unmounts its `<webview>` and shows its plate. */
@@ -87,8 +112,11 @@ export function useDiscardWhenHidden(
if (!o.hasContent()) return
const enabled = useSettings.getState().settings.browserMemorySaver
const loading = o.isLoading()
- if (!shouldDiscard({ hiddenMs: Date.now() - hiddenSince, loading, enabled })) {
- if (enabled && loading) arm(DISCARD_RETRY_MS)
+ const audible = o.isAudible?.() ?? false
+ if (!shouldDiscard({ hiddenMs: Date.now() - hiddenSince, loading, enabled, audible })) {
+ // Both blockers END BY THEMSELVES, so they earn a retry rather than disarming the saver for
+ // the whole hidden stretch. A disabled setting does not: see the policy's doc comment.
+ if (enabled && (loading || audible)) arm(DISCARD_RETRY_MS)
return
}
discarded = true