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.

feat(renderer): browser Memory Saver — discard hidden webviews, restore from URL

enes24679f5d86bb
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 667310665..20fb761bd 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -28,6 +28,10 @@ const ROWS = {
dragMode: {
title: 'Canvas left-drag',
keywords: ['pan', 'drag', 'select', 'canvas', 'mouse', 'grab', 'figma', 'miro']
+ },
+ browserSaver: {
+ title: 'Browser memory saver',
+ keywords: ['browser', 'memory', 'saver', 'ram', 'webview', 'discard', 'page', 'web']
}
}
const ENTRIES = Object.values(ROWS)
@@ -171,6 +175,19 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
}
/>
</SearchableRow>
+ <SearchableRow {...ROWS.browserSaver}>
+ <FieldRow
+ label="Browser memory saver"
+ description="Free a hidden browser page's memory after 5 minutes; it reloads when shown. Each page is a whole Chromium process."
+ control={
+ <Switch
+ checked={settings.browserMemorySaver}
+ onChange={(v) => update({ browserMemorySaver: v })}
+ ariaLabel="Browser memory saver"
+ />
+ }
+ />
+ </SearchableRow>
</SettingsSection>
)
}
diff --git a/src/renderer/nodes/BrowserSurface.tsx b/src/renderer/nodes/BrowserSurface.tsx
index 4a36cf204..3edadeeda 100644
--- a/src/renderer/nodes/BrowserSurface.tsx
+++ b/src/renderer/nodes/BrowserSurface.tsx
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react'
import { searchOrUrl } from './browserUrl'
import { BrowserStartPage } from './BrowserStartPage'
import { useBrowserHistory } from '../state/browserHistory'
+import { useSettings } from '../state/settings'
+import { BROWSER_DISCARD_MS, shouldDiscard } from './browser-discard-policy'
// Minimal typing for the Electron <webview> element methods/events we use.
type WebviewEl = HTMLElement & {
@@ -35,6 +37,7 @@ interface BrowserSurfaceProps {
*/
export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: BrowserSurfaceProps) {
const ref = useRef<WebviewEl | null>(null)
+ const rootRef = useRef<HTMLDivElement | null>(null)
const lastUrlRef = useRef('')
const [startUrl] = useState(() => url ?? '')
const [src, setSrc] = useState(startUrl)
@@ -43,12 +46,26 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
const [canBack, setCanBack] = useState(false)
const [canFwd, setCanFwd] = useState(false)
const [failed, setFailed] = useState('')
+ // Memory saver (see the discard effect): the page is released while hidden and rebuilt on
+ // reveal. These four are REFS, not state, because the observer below is created once and must
+ // read the CURRENT values without being torn down and re-armed on every state flip.
+ const [discarded, setDiscarded] = useState(false)
+ const discardedRef = useRef(false)
+ const loadingRef = useRef(false)
+ const hiddenSinceRef = useRef<number | 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)
useEffect(() => {
const wv = ref.current
if (!wv) return
- const onStart = (): void => setLoading(true)
+ const onStart = (): void => {
+ loadingRef.current = true
+ setLoading(true)
+ }
const onStop = (): void => {
+ loadingRef.current = false
setLoading(false)
setCanBack(wv.canGoBack())
setCanFwd(wv.canGoForward())
@@ -56,12 +73,17 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
const onNav = (e: Event): void => {
const u = (e as unknown as { url: string }).url
setAddress(u)
+ locationRef.current = u
setFailed('')
onUrlChange(u)
lastUrlRef.current = u
useBrowserHistory.getState().record(u, u)
}
- const onNavInPage = (e: Event): void => setAddress((e as unknown as { url: string }).url)
+ const onNavInPage = (e: Event): void => {
+ const u = (e as unknown as { url: string }).url
+ setAddress(u)
+ locationRef.current = u
+ }
const onTitle = (e: Event): void => {
const title = (e as unknown as { title: string }).title
onTitleChange(title)
@@ -85,8 +107,14 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
wv.removeEventListener('page-title-updated', onTitle)
wv.removeEventListener('did-fail-load', onFail)
}
- }, [onUrlChange, onTitleChange])
+ // `discarded` is a dep because a discard UNMOUNTS the <webview> element (dropping `src` alone
+ // would leave the guest process alive): the restored element is a different node, so the
+ // listeners have to be re-attached to it.
+ }, [onUrlChange, onTitleChange, discarded])
+ // Registers the guest so main can route its new-window requests. `discarded` is a dep for the
+ // same reason as above — and it is what makes a discard UNREGISTER the dead wcId through this
+ // cleanup, rather than leaking it until the node unmounts.
useEffect(() => {
const wv = ref.current
if (!wv) return
@@ -100,7 +128,69 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
wv.removeEventListener('dom-ready', onReady)
if (wcId) window.nodeTerminal.browser.unregister(wcId)
}
- }, [nodeId])
+ }, [nodeId, discarded])
+
+ // ── Memory saver ────────────────────────────────────────────────────────────────────────────
+ // A browser node parked off-screen is a whole Chromium renderer process doing nothing, and the
+ // canvas caps nothing. Hidden past the window (and not mid-load, and with the setting on) the
+ // page is released; entering the viewport rebuilds it from `locationRef`.
+ //
+ // The observer is created ONCE. Putting `discarded`/`loading` in the deps would re-create it —
+ // and IntersectionObserver re-reports on `observe()`, so the hidden timer would restart on every
+ // state flip and a page could sit hidden forever without reaching the window. Everything mutable
+ // is therefore read through a ref, and the SETTING is read at fire time (turning the saver off
+ // must disarm a timer armed minutes earlier).
+ useEffect(() => {
+ const el = rootRef.current
+ if (!el || typeof IntersectionObserver === 'undefined') return
+ let timer: ReturnType<typeof setTimeout> | null = null
+ const clear = (): void => {
+ if (timer) clearTimeout(timer)
+ timer = null
+ }
+ const fire = (): void => {
+ timer = null
+ const since = hiddenSinceRef.current
+ if (since == null || discardedRef.current) return
+ const enabled = useSettings.getState().settings.browserMemorySaver
+ if (!shouldDiscard({ hiddenMs: Date.now() - since, loading: loadingRef.current, enabled }))
+ return
+ // A start page has no guest process to release, and discarding it would replace the one
+ // useful thing on screen with a plate. (A page still loading after the whole window is not
+ // re-checked either: v1 waits for the next hide, rather than polling.)
+ if (!locationRef.current) return
+ discardedRef.current = true
+ setDiscarded(true)
+ setSrc('')
+ // 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('')
+ }
+ const obs = new IntersectionObserver((entries) => {
+ const visible = entries[entries.length - 1]?.isIntersecting ?? true
+ if (!visible) {
+ if (hiddenSinceRef.current == null) hiddenSinceRef.current = Date.now()
+ // +1s slack so the reading at fire time is strictly PAST the window (`shouldDiscard` is >).
+ if (!timer) timer = setTimeout(fire, BROWSER_DISCARD_MS + 1000)
+ return
+ }
+ hiddenSinceRef.current = null
+ clear()
+ if (!discardedRef.current) return
+ discardedRef.current = false
+ setDiscarded(false)
+ // 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
+ setSrc(back)
+ setAddress(back)
+ })
+ obs.observe(el)
+ return () => {
+ obs.disconnect()
+ clear()
+ }
+ }, [])
// Keep the two webviews for one node (canvas + modal) in sync: when `url` changes from the
// OUTSIDE (the other webview navigated → node.data.url updated) and differs from where we are,
@@ -110,6 +200,9 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
if (url && url !== address) {
setSrc(url)
setAddress(url)
+ // Keep the discard descriptor current even while discarded: a node released off-screen must
+ // come back at where the OTHER webview navigated to, not at where it was released.
+ locationRef.current = url
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url])
@@ -122,12 +215,13 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
}
setAddress(safe)
setFailed('')
+ locationRef.current = safe
if (safe === src) ref.current?.reload()
else setSrc(safe)
}
return (
- <div className="browser-surface">
+ <div className="browser-surface" ref={rootRef}>
<div className="browser-node__toolbar nodrag">
<button className="browser-node__btn" disabled={!canBack} onClick={() => ref.current?.goBack()} title="Back">
◀
@@ -154,22 +248,32 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
/>
</div>
<div className="browser-node__view nodrag nowheel">
- {/* eslint-disable-next-line react/no-unknown-property */}
- <webview
- ref={ref as unknown as React.Ref<HTMLElement>}
- src={src || undefined}
- allowpopups={true}
- style={{ width: '100%', height: '100%' }}
- />
- {!src && (
+ {/* The element is UNMOUNTED while discarded — that is what ends the guest process; an
+ emptied `src` attribute does not (Electron ignores a src mutation to nothing). */}
+ {!discarded && (
+ // eslint-disable-next-line react/no-unknown-property
+ <webview
+ ref={ref as unknown as React.Ref<HTMLElement>}
+ src={src || undefined}
+ allowpopups={true}
+ style={{ width: '100%', height: '100%' }}
+ />
+ )}
+ {!src && !discarded && (
<BrowserStartPage
onNavigate={(u) => {
setSrc(u)
setAddress(u)
+ locationRef.current = u
setFailed('')
}}
/>
)}
+ {discarded && (
+ <div className="browser-node__discarded">
+ <span>Page released to save memory — reopens on view</span>
+ </div>
+ )}
{failed && <div className="browser-node__error">{failed}</div>}
</div>
</div>
diff --git a/src/renderer/nodes/WebNode.tsx b/src/renderer/nodes/WebNode.tsx
index a19e08a05..a22061581 100644
--- a/src/renderer/nodes/WebNode.tsx
+++ b/src/renderer/nodes/WebNode.tsx
@@ -1,7 +1,9 @@
-import { useEffect, useState } from 'react'
+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 { useSettings } from '../state/settings'
+import { BROWSER_DISCARD_MS, shouldDiscard } from './browser-discard-policy'
/**
* A web view node. When `data.url` is set it loads that live URL; otherwise it serves the
@@ -16,6 +18,20 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
const url = (data.url as string) ?? ''
const filePath = (data.filePath as string) ?? ''
const title = (data.title as string) || url || filePath.split('/').pop() || 'web'
+ const rootRef = useRef<HTMLDivElement | null>(null)
+ // Memory saver — same policy as {@link BrowserSurface}: 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 exactly as it
+ // was at mount. Mutable inputs are refs because the observer is created once (see BrowserSurface).
+ const [discarded, setDiscarded] = useState(false)
+ const [revive, setRevive] = useState(0)
+ const discardedRef = useRef(false)
+ const hiddenSinceRef = useRef<number | null>(null)
+ const srcRef = useRef('')
+ /** "Loading" here is the media grant being in flight — the only await between mount and a
+ * usable src (a live URL is resolved synchronously). Discarding mid-grant would drop the
+ * answer to a request already made. */
+ const grantingRef = useRef(false)
useEffect(() => {
let alive = true
@@ -23,26 +39,75 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
const safe = httpUrl(url)
if (safe) {
setSrc(safe)
+ srcRef.current = safe
} else {
setError('Unsupported URL scheme — only http/https')
}
} else if (filePath) {
+ grantingRef.current = true
window.nodeTerminal.media
.allow(filePath)
.then((mediaUrl) => {
- if (alive) setSrc(mediaUrl)
+ grantingRef.current = false
+ if (alive) {
+ setSrc(mediaUrl)
+ srcRef.current = mediaUrl
+ }
})
.catch(() => {
+ grantingRef.current = false
if (alive) setError('Couldn’t load this page.')
})
}
return () => {
alive = false
}
- }, [url, filePath])
+ }, [url, filePath, revive])
+
+ useEffect(() => {
+ const el = rootRef.current
+ if (!el || typeof IntersectionObserver === 'undefined') return
+ let timer: ReturnType<typeof setTimeout> | null = null
+ const clear = (): void => {
+ if (timer) clearTimeout(timer)
+ timer = null
+ }
+ const fire = (): void => {
+ timer = null
+ const since = hiddenSinceRef.current
+ if (since == null || discardedRef.current || !srcRef.current) return
+ const enabled = useSettings.getState().settings.browserMemorySaver
+ if (!shouldDiscard({ hiddenMs: Date.now() - since, loading: grantingRef.current, enabled }))
+ return
+ discardedRef.current = true
+ setDiscarded(true)
+ setSrc('')
+ }
+ const obs = new IntersectionObserver((entries) => {
+ const visible = entries[entries.length - 1]?.isIntersecting ?? true
+ if (!visible) {
+ if (hiddenSinceRef.current == null) hiddenSinceRef.current = Date.now()
+ if (!timer) timer = setTimeout(fire, BROWSER_DISCARD_MS + 1000)
+ return
+ }
+ hiddenSinceRef.current = null
+ clear()
+ if (!discardedRef.current) return
+ discardedRef.current = false
+ setDiscarded(false)
+ setError('')
+ setRevive((n) => n + 1)
+ })
+ obs.observe(el)
+ return () => {
+ obs.disconnect()
+ clear()
+ }
+ }, [])
return (
<div
+ ref={rootRef}
className={`term-node web-node${selected ? ' selected' : ''}`}
style={{ borderTopColor: data.color }}
>
@@ -84,7 +149,11 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
<div className="editor-node__body">
<div className="editor-node__image nodrag nowheel">
- {src ? (
+ {discarded ? (
+ <div className="browser-node__discarded">
+ <span>Page released to save memory — reopens on view</span>
+ </div>
+ ) : src ? (
// eslint-disable-next-line react/no-unknown-property
<webview src={src} style={{ width: '100%', height: '100%' }} />
) : (
diff --git a/src/renderer/nodes/browser-discard-policy.test.ts b/src/renderer/nodes/browser-discard-policy.test.ts
new file mode 100644
index 000000000..b7ae9d22e
--- /dev/null
+++ b/src/renderer/nodes/browser-discard-policy.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect } from 'vitest'
+import { BROWSER_DISCARD_MS, shouldDiscard } from './browser-discard-policy'
+
+describe('browser discard policy', () => {
+ it('discards only when enabled, hidden past the window, and not loading', () => {
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: false, enabled: true })).toBe(true)
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS - 1, loading: false, enabled: true })).toBe(false)
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: true, enabled: true })).toBe(false)
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + 1, loading: false, enabled: false })).toBe(false)
+ })
+
+ 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.
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS, loading: false, enabled: true })).toBe(false)
+ })
+
+ it('is five minutes', () => {
+ expect(BROWSER_DISCARD_MS).toBe(5 * 60_000)
+ })
+})
diff --git a/src/renderer/nodes/browser-discard-policy.ts b/src/renderer/nodes/browser-discard-policy.ts
new file mode 100644
index 000000000..4e6a07b9a
--- /dev/null
+++ b/src/renderer/nodes/browser-discard-policy.ts
@@ -0,0 +1,21 @@
+/**
+ * Hidden-webview discard ("Browser Memory Saver", the same idea as Chrome tab discarding): each
+ * Electron `<webview>` is a full Chromium renderer PROCESS, and a canvas has no cap on how many
+ * 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:
+ * - **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.
+ *
+ * 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
+ * same trade Chrome makes.
+ */
+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
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index b6d80ccbe..e889030db 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -6149,6 +6149,21 @@ body,
width: 100%;
height: 100%;
}
+/* Memory saver plate: what stands in for a page whose Chromium process was released while the
+ node sat off-screen. Deliberately quiet — this is an ambient state that heals itself on view,
+ not an error. */
+.browser-node__discarded {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 12px;
+ background: var(--bg);
+ color: var(--muted);
+ font-size: 12px;
+}
.browser-node__error {
position: absolute;
left: 0;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ee0124e44..c7715e1d4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -820,6 +820,14 @@ export interface Settings {
* directly (grab cursor), for mouse users who pan constantly; box-select then moves to
* Shift+drag (React Flow's selectionKeyCode). */
canvasDragMode: 'select' | 'pan'
+ /**
+ * Browser memory saver: release a browser/web node's page after it has been hidden for
+ * `BROWSER_DISCARD_MS` (5 min), reloading it from its URL when it is shown again. Each
+ * `<webview>` is a whole Chromium renderer process and the canvas caps nothing, so an
+ * afternoon of opened pages is otherwise permanently resident. On by default — the cost is a
+ * reload (and the lost back/forward stack, which a webview cannot serialize), not lost work.
+ */
+ browserMemorySaver: boolean
accent: string
tmuxEnabled: boolean
/** GPU (WebGL) terminal rendering. 'off' routes every terminal to xterm's DOM renderer.
@@ -971,6 +979,7 @@ export const DEFAULT_SETTINGS: Settings = {
terminalMiddleClickPaste: false,
wheelZoom: false,
canvasDragMode: 'select',
+ browserMemorySaver: true,
accent: '#0a84ff',
tmuxEnabled: true,
terminalGpuRendering: 'auto',