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.

refactor(renderer): one shared hidden-discard hook, with its own coverage

enes1fdf0f7845d0
diff --git a/src/renderer/nodes/BrowserSurface.tsx b/src/renderer/nodes/BrowserSurface.tsx
index 3edadeeda..a886ca963 100644
--- a/src/renderer/nodes/BrowserSurface.tsx
+++ b/src/renderer/nodes/BrowserSurface.tsx
@@ -2,8 +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'
+import { useDiscardWhenHidden } from './useDiscardWhenHidden'
+import { DiscardedPlate } from './DiscardedPlate'
// Minimal typing for the Electron <webview> element methods/events we use.
type WebviewEl = HTMLElement & {
@@ -46,13 +46,11 @@ 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.
+ // Memory saver (see `useDiscardWhenHidden`): the page is released while hidden and rebuilt on
+ // reveal. `loadingRef` mirrors the `loading` state because the hook reads it at fire time, from
+ // a callback that must not force the observer to be re-created.
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)
@@ -132,65 +130,28 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
// ── 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
+ // canvas caps nothing. The state machine (observer, timer, fire-time re-checks) lives in the
+ // shared hook; this surface contributes only what "loading"/"content" mean for it and how to
+ // release and rebuild its page.
+ useDiscardWhenHidden(rootRef, {
+ isLoading: () => loadingRef.current,
+ hasContent: () => !!locationRef.current,
+ onDiscard: () => {
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
+ },
+ onRestore: () => {
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,
@@ -269,11 +230,7 @@ export function BrowserSurface({ nodeId, url, onUrlChange, onTitleChange }: Brow
}}
/>
)}
- {discarded && (
- <div className="browser-node__discarded">
- <span>Page released to save memory — reopens on view</span>
- </div>
- )}
+ {discarded && <DiscardedPlate />}
{failed && <div className="browser-node__error">{failed}</div>}
</div>
</div>
diff --git a/src/renderer/nodes/DiscardedPlate.tsx b/src/renderer/nodes/DiscardedPlate.tsx
new file mode 100644
index 000000000..e7051c00f
--- /dev/null
+++ b/src/renderer/nodes/DiscardedPlate.tsx
@@ -0,0 +1,14 @@
+/**
+ * What stands in for a page whose Chromium process was released while the node sat off-screen
+ * ({@link useDiscardWhenHidden}). One component so the two surfaces that host a `<webview>` cannot
+ * drift into two different wordings for the same state.
+ *
+ * Deliberately quiet: this is an ambient state that heals itself on view, not an error.
+ */
+export function DiscardedPlate({ restoring = false }: { restoring?: boolean }): React.JSX.Element {
+ return (
+ <div className="browser-node__discarded">
+ <span>{restoring ? 'Reopening…' : 'Page released to save memory — reopens on view'}</span>
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/WebNode.tsx b/src/renderer/nodes/WebNode.tsx
index a22061581..624d8d884 100644
--- a/src/renderer/nodes/WebNode.tsx
+++ b/src/renderer/nodes/WebNode.tsx
@@ -2,8 +2,8 @@ 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'
+import { useDiscardWhenHidden } from './useDiscardWhenHidden'
+import { DiscardedPlate } from './DiscardedPlate'
/**
* A web view node. When `data.url` is set it loads that live URL; otherwise it serves the
@@ -19,14 +19,13 @@ 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)
- // 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).
+ // 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
+ // exactly as it was at mount. `srcRef` mirrors `src` for the hook's fire-time content check.
const [discarded, setDiscarded] = useState(false)
+ const [restoring, setRestoring] = 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
@@ -35,6 +34,12 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
useEffect(() => {
let alive = true
+ // `settled` ends the restore plate (see `restoring`): the source effect has produced an
+ // outcome — a src, an error, or nothing to load at all. Without the last case a node whose
+ // url/filePath vanished while it was hidden would sit under the plate forever.
+ const settled = (): void => {
+ if (alive) setRestoring(false)
+ }
if (url) {
const safe = httpUrl(url)
if (safe) {
@@ -43,6 +48,7 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
} else {
setError('Unsupported URL scheme — only http/https')
}
+ settled()
} else if (filePath) {
grantingRef.current = true
window.nodeTerminal.media
@@ -53,57 +59,38 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
setSrc(mediaUrl)
srcRef.current = mediaUrl
}
+ settled()
})
.catch(() => {
grantingRef.current = false
if (alive) setError('Couldn’t load this page.')
+ settled()
})
+ } else {
+ settled()
}
return () => {
alive = false
}
}, [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
+ useDiscardWhenHidden(rootRef, {
+ isLoading: () => grantingRef.current,
+ hasContent: () => !!srcRef.current,
+ onDiscard: () => {
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
+ srcRef.current = ''
+ },
+ onRestore: () => {
setDiscarded(false)
+ // Hold the plate until the source effect has re-run to an outcome. A local file's grant is a
+ // round-trip to main, and without this the node flashes "No source" for the whole of it.
+ setRestoring(true)
setError('')
setRevive((n) => n + 1)
- })
- obs.observe(el)
- return () => {
- obs.disconnect()
- clear()
}
- }, [])
+ })
return (
<div
@@ -149,10 +136,8 @@ export default function WebNode({ id, data, selected }: NodeProps<CanvasNode>) {
<div className="editor-node__body">
<div className="editor-node__image nodrag nowheel">
- {discarded ? (
- <div className="browser-node__discarded">
- <span>Page released to save memory — reopens on view</span>
- </div>
+ {discarded || restoring ? (
+ <DiscardedPlate restoring={restoring} />
) : src ? (
// eslint-disable-next-line react/no-unknown-property
<webview src={src} style={{ width: '100%', height: '100%' }} />
diff --git a/src/renderer/nodes/useDiscardWhenHidden.test.tsx b/src/renderer/nodes/useDiscardWhenHidden.test.tsx
new file mode 100644
index 000000000..b2b4f328d
--- /dev/null
+++ b/src/renderer/nodes/useDiscardWhenHidden.test.tsx
@@ -0,0 +1,195 @@
+// @vitest-environment jsdom
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createRoot, type Root } from 'react-dom/client'
+import { act, useRef } from 'react'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { useSettings } from '../state/settings'
+import { BROWSER_DISCARD_MS, shouldDiscard } from './browser-discard-policy'
+import {
+ DISCARD_RETRY_MS,
+ DISCARD_SLACK_MS,
+ useDiscardWhenHidden,
+ type DiscardWhenHiddenOptions
+} from './useDiscardWhenHidden'
+
+// Standalone harness — react-dom + the real zustand settings store, no testing-library
+// dependency (the same shape as CustomAgentsSection.test.tsx).
+
+/** The single observer the harness creates, so a test can drive visibility by hand. */
+let observed: ((visible: boolean) => void) | null = null
+
+class FakeIntersectionObserver {
+ constructor(private cb: (entries: { isIntersecting: boolean }[]) => void) {
+ observed = (visible: boolean) => this.cb([{ isIntersecting: visible }])
+ }
+ observe(): void {}
+ disconnect(): void {
+ observed = null
+ }
+}
+
+/** Geometry the hook re-measures at fire time. jsdom's own rect is all-zero = off-screen. */
+function stubRect(el: HTMLElement, onScreen: boolean): void {
+ el.getBoundingClientRect = () =>
+ (onScreen
+ ? { top: 10, left: 10, bottom: 110, right: 110, width: 100, height: 100 }
+ : { top: -500, left: -500, bottom: -400, right: -400, width: 100, height: 100 }) as DOMRect
+}
+
+function Harness(props: Partial<DiscardWhenHiddenOptions> & { onEl?: (el: HTMLElement) => void }) {
+ const ref = useRef<HTMLDivElement | null>(null)
+ useDiscardWhenHidden(ref, {
+ isLoading: props.isLoading ?? (() => false),
+ hasContent: props.hasContent ?? (() => true),
+ onDiscard: props.onDiscard ?? (() => {}),
+ onRestore: props.onRestore ?? (() => {})
+ })
+ return (
+ <div
+ ref={(el) => {
+ ref.current = el
+ if (el) props.onEl?.(el)
+ }}
+ />
+ )
+}
+
+function mount(props: Parameters<typeof Harness>[0]): Root {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ act(() => {
+ root.render(<Harness {...props} />)
+ })
+ return root
+}
+
+/** Hide the element (geometry + the observer's verdict). */
+function hide(el: HTMLElement): void {
+ stubRect(el, false)
+ act(() => observed?.(false))
+}
+function show(el: HTMLElement): void {
+ stubRect(el, true)
+ act(() => observed?.(true))
+}
+function advance(ms: number): void {
+ act(() => {
+ vi.advanceTimersByTime(ms)
+ })
+}
+
+describe('useDiscardWhenHidden', () => {
+ let root: Root | null = null
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver)
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS } })
+ observed = null
+ })
+ afterEach(() => {
+ act(() => root?.unmount())
+ root = null
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it('does not discard before the window has elapsed', () => {
+ const onDiscard = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('discards once the element has been hidden past the window', () => {
+ const onDiscard = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ expect(onDiscard).toHaveBeenCalledTimes(1)
+ })
+
+ it('cancels the pending discard when the element is revealed', () => {
+ const onDiscard = vi.fn()
+ const onRestore = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onRestore, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS - 1000)
+ show(el)
+ advance(BROWSER_DISCARD_MS * 2)
+ expect(onDiscard).not.toHaveBeenCalled()
+ // Nothing was discarded, so there is nothing to restore either.
+ expect(onRestore).not.toHaveBeenCalled()
+ })
+
+ it('restores exactly once, and only after a discard', () => {
+ const onDiscard = vi.fn()
+ const onRestore = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onRestore, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ show(el)
+ show(el)
+ expect(onDiscard).toHaveBeenCalledTimes(1)
+ expect(onRestore).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not discard a surface that is still on screen when the timer fires', () => {
+ // The timer task and the observer callback are separate tasks: a reveal a frame before the
+ // timer would otherwise flash a plate + reload on a page the user is looking at.
+ const onDiscard = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onEl: (e) => (el = e) })
+ hide(el)
+ stubRect(el, true) // revealed, but the observer entry has not been delivered yet
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('never discards a surface with nothing loaded', () => {
+ const onDiscard = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, hasContent: () => false, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS * 3)
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('blocks on a load in flight at fire time, then retries when it finishes', () => {
+ const onDiscard = vi.fn()
+ let loading = true
+ let el!: HTMLElement
+ root = mount({ onDiscard, isLoading: () => loading, onEl: (e) => (el = e) })
+ hide(el)
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ // The re-arm is what keeps a load from disarming the saver for the whole hidden stretch.
+ loading = false
+ advance(DISCARD_RETRY_MS)
+ expect(onDiscard).toHaveBeenCalledTimes(1)
+ })
+
+ it('honours the setting at FIRE time, not at arm time', () => {
+ const onDiscard = vi.fn()
+ let el!: HTMLElement
+ root = mount({ onDiscard, onEl: (e) => (el = e) })
+ hide(el)
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, browserMemorySaver: false } })
+ advance(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ expect(onDiscard).not.toHaveBeenCalled()
+ // …and a disabled saver does not leave a retry armed either (that branch is loading-only).
+ advance(DISCARD_RETRY_MS * 2)
+ expect(onDiscard).not.toHaveBeenCalled()
+ })
+
+ it('shares one decision with the pure policy', () => {
+ // The hook must not grow its own copy of the threshold.
+ expect(shouldDiscard({ hiddenMs: BROWSER_DISCARD_MS + DISCARD_SLACK_MS, loading: false, enabled: true })).toBe(true)
+ })
+})
diff --git a/src/renderer/nodes/useDiscardWhenHidden.ts b/src/renderer/nodes/useDiscardWhenHidden.ts
new file mode 100644
index 000000000..b213efa48
--- /dev/null
+++ b/src/renderer/nodes/useDiscardWhenHidden.ts
@@ -0,0 +1,120 @@
+import { useEffect, useRef, type RefObject } from 'react'
+import { useSettings } from '../state/settings'
+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.
+ */
+export const DISCARD_RETRY_MS = 60_000
+
+export interface DiscardWhenHiddenOptions {
+ /** Is a load in flight right now? A discard mid-load would replay a half-finished navigation. */
+ isLoading: () => 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. */
+ onDiscard: () => void
+ /** Rebuild the page from the caller's own descriptor. Only ever called after `onDiscard`. */
+ onRestore: () => void
+}
+
+/**
+ * The hidden-webview memory saver, shared by every surface that hosts an Electron `<webview>`
+ * ({@link BrowserSurface}, WebNode). Each webview is a whole Chromium renderer process and the
+ * canvas caps nothing, so a page hidden past {@link BROWSER_DISCARD_MS} is released and rebuilt
+ * from its URL on reveal.
+ *
+ * This lives in ONE place on purpose: the state machine (observer lifecycle, hidden-since stamp,
+ * timer arm/clear, the fire-time re-checks) is the whole risk of the feature, and two copies of it
+ * drift — the first pair already disagreed about guard ORDER and lost half the reasoning comments.
+ * The component keeps only what is genuinely its own: what "loading"/"content" mean for it, and how
+ * to tear down and rebuild its page.
+ *
+ * The observer is created ONCE (mount-stable). Re-creating it on every state flip would re-arm the
+ * hidden timer each time — `observe()` re-reports immediately — so a page could sit hidden forever
+ * without ever reaching the window. Every mutable input is therefore read through a ref at fire
+ * time, including the SETTING: switching the saver off must disarm a timer armed minutes earlier.
+ */
+export function useDiscardWhenHidden(
+ rootRef: RefObject<HTMLElement | null>,
+ opts: DiscardWhenHiddenOptions
+): void {
+ // Re-read on every render so the mount-stable effect below always calls the CURRENT closures
+ // (they capture component state and are re-created each render).
+ const optsRef = useRef(opts)
+ optsRef.current = opts
+
+ useEffect(() => {
+ const el = rootRef.current
+ if (!el || typeof IntersectionObserver === 'undefined') return
+ let timer: ReturnType<typeof setTimeout> | null = null
+ let hiddenSince: number | null = null
+ let discarded = false
+
+ const clear = (): void => {
+ if (timer) clearTimeout(timer)
+ timer = null
+ }
+ const arm = (ms: number): void => {
+ if (!timer) timer = setTimeout(fire, ms)
+ }
+ /** Geometry, not the observer's verdict — see the M1 note in `fire`. */
+ const onScreen = (): boolean => {
+ const r = el.getBoundingClientRect()
+ if (r.width === 0 && r.height === 0) return false
+ return (
+ r.bottom > 0 && r.right > 0 && r.top < window.innerHeight && r.left < window.innerWidth
+ )
+ }
+ function fire(): void {
+ timer = null
+ const o = optsRef.current
+ if (hiddenSince == null || discarded) return
+ // The timer task and the IntersectionObserver callback are separate tasks: a node revealed a
+ // frame before this fires has not delivered its "visible" entry yet, and discarding here
+ // would flash a plate + reload on a page the user is looking at. Re-measure instead of
+ // trusting the last verdict.
+ if (onScreen()) return
+ // Nothing loaded = no guest process to release, and the plate would replace the one useful
+ // thing on screen (a start page). Checked BEFORE the policy so an empty node never even
+ // consults the clock.
+ 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)
+ return
+ }
+ discarded = true
+ o.onDiscard()
+ }
+
+ const obs = new IntersectionObserver((entries) => {
+ const visible = entries[entries.length - 1]?.isIntersecting ?? true
+ if (!visible) {
+ if (hiddenSince == null) hiddenSince = Date.now()
+ arm(BROWSER_DISCARD_MS + DISCARD_SLACK_MS)
+ return
+ }
+ hiddenSince = null
+ clear()
+ if (!discarded) return
+ discarded = false
+ optsRef.current.onRestore()
+ })
+ obs.observe(el)
+ return () => {
+ obs.disconnect()
+ clear()
+ }
+ // Mount-stable by design (see the doc comment). `rootRef` is a ref object; `opts` is read
+ // through `optsRef`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+}