diff --git a/apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md b/apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md index 8589bfbe5ac..36251df4073 100644 --- a/apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md +++ b/apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md @@ -1,13 +1,13 @@ # Memory Profile & Worker Offload Review -2026-07-17. Code sweep across renderer / Electron main / host-service / pty-daemon, then every load-bearing claim verified against the live dev app over CDP (18-terminal stress, heap + RSS sampling, process-table spawn sampling). Claims marked **CDP** were observed at runtime; **code** means verified at the cited line but not behaviorally driven. +2026-07-18. Code sweep across renderer / Electron main / host-service / pty-daemon, then every load-bearing claim verified against the live dev app over CDP (18-terminal stress, heap + RSS sampling, process-table spawn sampling). Claims marked **CDP** were observed at runtime; **code** means verified at the cited line but not behaviorally driven. ## Progress | Item | Ticket | Status | |---|---|---| -| Parked-terminal LRU eviction (terminal half) | SUPER-1545 | **Implemented**, uncommitted. Cap defaults to 12 parked, user-configurable (Settings → Terminal → "Background terminal memory"; local-db `terminal_parked_runtime_cap`, migration 0042, zod-clamped 2–64, live-applied via `terminalRuntimeRegistry.setParkedRuntimeCap`). CDP-verified: default seeds at boot, 16-tab cycle parks exactly 12, lowering to 6 sweeps immediately, persists, out-of-range rejected. Two controlled A/Bs below (18-terminal fill, 24-terminal live-stream; both measured at cap 5 — savings scale down as the cap rises) | -| Parked-webview eviction (second half) | SUPER-1545 | Not started | +| Parked-terminal LRU eviction (terminal half) | SUPER-1545 | **Shipped** in PR #5751. Cap defaults to 12 parked, user-configurable (Settings → Terminal → "Background terminal memory"; local-db `terminal_parked_runtime_cap`, migration 0042, zod-clamped 2–64, live-applied via `terminalRuntimeRegistry.setParkedRuntimeCap`). CDP-verified: default seeds at boot, 16-tab cycle parks exactly 12, lowering to 6 sweeps immediately, persists, out-of-range rejected. Two controlled A/Bs below (18-terminal fill, 24-terminal live-stream; both measured at cap 5 — savings scale down as the cap rises) | +| Parked-webview eviction + alt-screen exemption + quota guard | SUPER-1545 | **Implemented** (hidden-webview LRU cap 3 in `browserRuntimeRegistry`; alternate-screen TUIs exempt from terminal eviction; eviction skipped when the buffer cannot persist). CDP-verified 2026-07-18 | | Chat shiki off main thread | SUPER-1546 | Not started | | Collections preload/window/evict | SUPER-1547 | Not started | | Async process-tree probes | SUPER-1548 | Not started | @@ -62,7 +62,7 @@ Same A/B discipline, harder load: 24 terminal tabs, each running a real PTY proc | Host-service / daemon / GPU CPU | 2% / 1% / 5% | 2% / 1% / 4% | | Tab-switch p50 / p95 under load | 52 / 95 ms | 68 / 114 ms | -The CPU gap is structural: eviction closes the WebSocket of released terminals, so their streams are neither delivered nor parsed — the before build parses all 24 streams into 23 live xterms forever. Heap is also flat under load in the eviction build vs climbing in the before build. +Under this real-PTY streaming workload, eviction closes the WebSocket of released terminals, so their streams are neither delivered nor parsed — the before build parses all 24 streams into 23 live xterms forever. Heap is also flat under load in the eviction build vs climbing in the before build. A later 18-terminal synthetic-output rerun confirmed the memory result (−46% JS heap, −30% renderer RSS) but did not reproduce a CPU reduction (`TaskDuration` 1.41 s before vs 1.80 s after), so treat the 30% → 21% CPU sample as workload-specific rather than a general CPU claim. ## Verified findings — renderer diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts index d1f2cecdf7a..6aecdb4c342 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts @@ -57,6 +57,26 @@ describe("selectRuntimesToEvict", () => { expect(selectRuntimesToEvict(entries, 2)).toEqual([]); expect(ids(selectRuntimesToEvict(entries, 1))).toEqual(["a"]); }); + + it("never selects exempt entries, even when they are the oldest", () => { + const entries = [parked("tui", 1), parked("a", 2), parked("b", 3)]; + const isExempt = (e: { id: string }) => e.id === "tui"; + expect(ids(selectRuntimesToEvict(entries, 2, isExempt))).toEqual(["a"]); + }); + + it("stops early when only exempt entries remain over the cap", () => { + const entries = [parked("tui1", 1), parked("tui2", 2), parked("a", 3)]; + const isExempt = (e: { id: string }) => e.id.startsWith("tui"); + // excess is 2 but only one evictable entry exists + expect(ids(selectRuntimesToEvict(entries, 1, isExempt))).toEqual(["a"]); + }); + + it("exempt entries still occupy the parked count", () => { + const entries = [parked("tui", 1), parked("a", 2)]; + const isExempt = (e: { id: string }) => e.id === "tui"; + // cap 1: tui fills the single slot, so "a" must go despite being newer + expect(ids(selectRuntimesToEvict(entries, 1, isExempt))).toEqual(["a"]); + }); }); describe("normalizeParkedRuntimeCap", () => { diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts index d23cbe7c279..528ce6497c6 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts @@ -1,7 +1,8 @@ /** * Pure selection policy for parked-runtime LRU eviction (SUPER-1545). * Kept dependency-free so it can be unit-tested without pulling the - * xterm/transport import graph into the test process. + * xterm/transport import graph into the test process. Also reused by the + * browser pane registry for hidden-webview eviction. */ interface EvictionCandidate { @@ -18,16 +19,21 @@ export function normalizeParkedRuntimeCap(cap: number): number | null { /** * Pick the parked (live runtime, no container) entries to release, oldest * `lastUsedAt` first, so at most `cap` parked runtimes remain. Attached - * runtimes and runtime-less entries are never candidates. + * runtimes and runtime-less entries are never candidates. Exempt entries + * (e.g. an active alternate-screen TUI) still occupy the parked count but + * are never selected — eviction stops early when only exempt entries remain. */ export function selectRuntimesToEvict( entries: Iterable, cap: number, + isExempt: (entry: T) => boolean = () => false, ): T[] { const parked = Array.from(entries).filter( (entry) => entry.runtime !== null && entry.runtime.container === null, ); - if (parked.length <= cap) return []; - parked.sort((a, b) => a.lastUsedAt - b.lastUsedAt); - return parked.slice(0, parked.length - cap); + const excess = parked.length - cap; + if (excess <= 0) return []; + const evictable = parked.filter((entry) => !isExempt(entry)); + evictable.sort((a, b) => a.lastUsedAt - b.lastUsedAt); + return evictable.slice(0, excess); } diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.test.ts b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.test.ts new file mode 100644 index 00000000000..84d13aa6af7 --- /dev/null +++ b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.test.ts @@ -0,0 +1,180 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; + +mock.module("renderer/lib/trpc-client", () => ({ + electronTrpcClient: { + keyboardLayout: { + changes: { subscribe: () => {} }, + }, + }, +})); + +const { terminalRuntimeRegistry } = await import("./terminal-runtime-registry"); +const { tryPersistRuntimeState } = await import("./terminal-runtime"); + +interface FakeStorageState { + values: Map; + storage: Storage; +} + +function createFakeStorage(): FakeStorageState { + const values = new Map(); + const storage = { + get length() { + return values.size; + }, + clear: () => values.clear(), + getItem: (key: string) => values.get(key) ?? null, + key: (index: number) => Array.from(values.keys())[index] ?? null, + removeItem: (key: string) => values.delete(key), + setItem: (key: string, value: string) => values.set(key, value), + } as Storage; + return { values, storage }; +} + +const originalLocalStorage = globalThis.localStorage; +let fakeStorage: FakeStorageState; + +beforeEach(() => { + fakeStorage = createFakeStorage(); + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: fakeStorage.storage, + }); +}); + +afterEach(() => { + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: originalLocalStorage, + }); +}); + +describe("terminalRuntimeRegistry eviction cleanup", () => { + test("keeps a runtime when dimensions fail to persist", () => { + const terminalId = "dimensions-write-failure"; + const setItem = fakeStorage.storage.setItem.bind(fakeStorage.storage); + fakeStorage.storage.setItem = (key: string, value: string) => { + if (key === `terminal-dims:${terminalId}`) { + throw new Error("dimensions write failed"); + } + setItem(key, value); + }; + const runtime = { + terminalId, + serializeAddon: { serialize: () => "serialized scrollback" }, + lastCols: 120, + lastRows: 32, + }; + + expect( + tryPersistRuntimeState( + runtime as Parameters[0], + ), + ).toBe(false); + expect(fakeStorage.values.get(`terminal-buffer:${terminalId}`)).toBe( + "serialized scrollback", + ); + expect(fakeStorage.values.has(`terminal-dims:${terminalId}`)).toBe(false); + }); + + test("dispose clears persisted state even when eviction already removed the entry", () => { + const terminalId = "evicted-terminal"; + fakeStorage.values.set(`terminal-buffer:${terminalId}`, "scrollback"); + fakeStorage.values.set( + `terminal-dims:${terminalId}`, + JSON.stringify({ cols: 120, rows: 32 }), + ); + + expect(terminalRuntimeRegistry.has(terminalId)).toBe(false); + terminalRuntimeRegistry.dispose(terminalId); + + expect(fakeStorage.values.has(`terminal-buffer:${terminalId}`)).toBe(false); + expect(fakeStorage.values.has(`terminal-dims:${terminalId}`)).toBe(false); + }); + + test("reschedules eviction when a parked terminal changes buffers", () => { + let emitBufferChange: () => void = () => { + throw new Error("buffer listener was not installed"); + }; + let listenerDisposed = false; + const runtime = { + container: {} as HTMLDivElement | null, + terminal: { + buffer: { + onBufferChange: (listener: () => void) => { + emitBufferChange = listener; + return { dispose: () => (listenerDisposed = true) }; + }, + }, + }, + }; + const entry = { + runtime, + disposeBufferChangeListener: null as (() => void) | null, + }; + const registryInternals = terminalRuntimeRegistry as unknown as { + observeBufferChanges: (observedEntry: typeof entry) => void; + pendingEviction: ReturnType | null; + }; + + if (registryInternals.pendingEviction !== null) { + clearTimeout(registryInternals.pendingEviction); + registryInternals.pendingEviction = null; + } + registryInternals.observeBufferChanges(entry); + emitBufferChange(); + expect(registryInternals.pendingEviction).toBeNull(); + + runtime.container = null; + emitBufferChange(); + expect(registryInternals.pendingEviction).not.toBeNull(); + + if (registryInternals.pendingEviction !== null) { + clearTimeout(registryInternals.pendingEviction); + registryInternals.pendingEviction = null; + } + entry.disposeBufferChangeListener?.(); + expect(listenerDisposed).toBe(true); + }); + + test("defers eviction while flushed output is still being parsed", () => { + const terminalId = "parser-busy-terminal"; + let flushed = false; + const gate = { pending: 1, queued: null as (() => void) | null }; + const entry = { + terminalId, + instanceId: terminalId, + runtime: { + container: null, + gate, + terminal: { buffer: { active: { type: "normal" } } }, + }, + transport: { + _writeCoalescer: { + flushSync: () => { + flushed = true; + }, + }, + }, + linkManager: null, + pendingLinkHandlers: null, + lastUsedAt: 1, + }; + const registryInternals = terminalRuntimeRegistry as unknown as { + entries: Map; + evictExcessParkedRuntimes: () => void; + }; + const entryKey = `${terminalId}\u0000${terminalId}`; + registryInternals.entries.set(entryKey, entry); + + try { + registryInternals.evictExcessParkedRuntimes(); + + expect(flushed).toBe(true); + expect(gate.queued).not.toBeNull(); + expect(registryInternals.entries.has(entryKey)).toBe(true); + } finally { + registryInternals.entries.delete(entryKey); + } + }); +}); diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts index 7db0d9f10a0..33a261120d2 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts @@ -2,6 +2,7 @@ import type { ProgressAddon } from "@xterm/addon-progress"; import type { SearchAddon } from "@xterm/addon-search"; import { DEFAULT_TERMINAL_PARKED_RUNTIME_CAP } from "shared/constants"; import type { TerminalAppearance } from "./appearance"; +import { runWhenParserIdle } from "./parser-idle-gate"; import { type LinkHoverInfo, type TerminalLinkHandlers, @@ -9,10 +10,12 @@ import { } from "./terminal-link-manager"; import { attachToContainer, + clearPersistedRuntimeState, createRuntime, detachFromContainer, disposeRuntime, type TerminalRuntime, + tryPersistRuntimeState, updateRuntimeAppearance, } from "./terminal-runtime"; import { @@ -42,6 +45,8 @@ interface RegistryEntry { linkManager: TerminalLinkManager | null; /** Stored until linkManager is created (mount called after setLinkHandlers). */ pendingLinkHandlers: TerminalLinkHandlers | null; + /** Stops the alternate/normal buffer observer installed with the runtime. */ + disposeBufferChangeListener: (() => void) | null; /** Monotonic use counter; bumped on mount/detach, drives parked-LRU eviction. */ lastUsedAt: number; } @@ -86,6 +91,7 @@ class TerminalRuntimeRegistryImpl { transport: createTransport(), linkManager: null, pendingLinkHandlers: null, + disposeBufferChangeListener: null, lastUsedAt: 0, }; @@ -177,6 +183,7 @@ class TerminalRuntimeRegistryImpl { entry.runtime = createRuntime(terminalId, appearance, { initialBuffer: this.serializeExistingRuntime(terminalId, instanceId), }); + this.observeBufferChanges(entry); entry.linkManager = new TerminalLinkManager(entry.runtime.terminal); if (entry.pendingLinkHandlers) { entry.linkManager.setHandlers(entry.pendingLinkHandlers); @@ -197,6 +204,22 @@ class TerminalRuntimeRegistryImpl { ); } + private observeBufferChanges(entry: RegistryEntry) { + entry.disposeBufferChangeListener?.(); + entry.disposeBufferChangeListener = null; + const runtime = entry.runtime; + if (!runtime) return; + + const subscription = runtime.terminal.buffer.onBufferChange(() => { + // Exempt alternate-screen TUIs may put the registry over cap. As soon as + // a parked TUI returns to its normal buffer, reconsider it for eviction. + if (entry.runtime?.container === null) { + this.scheduleParkedEviction(); + } + }); + entry.disposeBufferChangeListener = () => subscription.dispose(); + } + /** * Open (or re-use) the WebSocket transport for this terminal. * The server session must already exist; the WebSocket route only attaches @@ -285,12 +308,43 @@ class TerminalRuntimeRegistryImpl { } private evictExcessParkedRuntimes() { + const parkedEntries = Array.from(this.entries.values()).filter( + (entry) => entry.runtime?.container === null, + ); + + // A pane can detach before the animation-frame output batch has reached + // xterm. Flush it, then wait for xterm's parser callback before checking + // alternate-screen mode or serializing the buffer. + for (const entry of parkedEntries) { + entry.transport._writeCoalescer?.flushSync(); + } + const parsingEntries = parkedEntries.filter( + (entry) => (entry.runtime?.gate.pending ?? 0) > 0, + ); + if (parsingEntries.length > 0) { + for (const entry of parsingEntries) { + const gate = entry.runtime?.gate; + if (gate) { + runWhenParserIdle(gate, () => this.scheduleParkedEviction()); + } + } + return; + } + const victims = selectRuntimesToEvict( this.entries.values(), this.parkedRuntimeCap, + // Alternate-screen TUIs restore as a garbled static snapshot — never evict them. + (entry) => entry.runtime?.terminal.buffer.active.type === "alternate", ); for (const entry of victims) { - this.disposeEntry(entry, { clearPersistedState: false }); + if (!entry.runtime || !tryPersistRuntimeState(entry.runtime)) { + warnPersistFailureOnce(entry.terminalId); + continue; + } + // tryPersistRuntimeState already wrote the snapshot. Preserve it while + // disposing instead of serializing and writing the same buffer twice. + this.disposeEntry(entry, { persistedState: "preserve" }); } } @@ -313,8 +367,10 @@ class TerminalRuntimeRegistryImpl { private disposeEntry( entry: RegistryEntry, - options: { clearPersistedState?: boolean } = {}, + options: { persistedState?: "clear" | "persist" | "preserve" } = {}, ) { + entry.disposeBufferChangeListener?.(); + entry.disposeBufferChangeListener = null; entry.linkManager?.dispose(); disposeTransport(entry.transport); if (entry.runtime) { @@ -335,7 +391,7 @@ class TerminalRuntimeRegistryImpl { ) : this.getEntries(terminalId); for (const entry of entries) { - this.disposeEntry(entry, { clearPersistedState: false }); + this.disposeEntry(entry, { persistedState: "persist" }); } } @@ -348,6 +404,9 @@ class TerminalRuntimeRegistryImpl { sendDispose(entry.transport); this.disposeEntry(entry); } + // Eviction deletes the live registry entry but deliberately leaves its + // snapshot behind. Closing that pane must still clear the orphaned keys. + clearPersistedRuntimeState(terminalId); } getSelection(terminalId: string, instanceId?: string): string { @@ -505,6 +564,15 @@ class TerminalRuntimeRegistryImpl { } } +let persistFailureWarned = false; +function warnPersistFailureOnce(terminalId: string) { + if (persistFailureWarned) return; + persistFailureWarned = true; + console.warn( + `[terminal-registry] state persist failed for ${terminalId}; keeping runtime alive (localStorage quota?)`, + ); +} + // Stable empty reference so useSyncExternalStore on a missing entry doesn't // thrash from getSnapshot returning a fresh array each call. const EMPTY_LOGS: readonly TerminalLogEntry[] = Object.freeze( diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts b/apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts index 9f406bc9b10..1839d78a507 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts @@ -92,19 +92,46 @@ function restoreBuffer(terminalId: string, terminal: XTerm) { } catch {} } +/** + * Persist buffer + dims, reporting success. Eviction must not proceed when + * either write fails or the runtime could not be restored faithfully. + */ +export function tryPersistRuntimeState(runtime: TerminalRuntime): boolean { + try { + const data = runtime.serializeAddon.serialize({ + scrollback: SERIALIZE_SCROLLBACK, + }); + localStorage.setItem(`${STORAGE_KEY_PREFIX}${runtime.terminalId}`, data); + } catch { + return false; + } + return persistDimensions( + runtime.terminalId, + runtime.lastCols, + runtime.lastRows, + ); +} + function clearPersistedBuffer(terminalId: string) { try { localStorage.removeItem(`${STORAGE_KEY_PREFIX}${terminalId}`); } catch {} } -function persistDimensions(terminalId: string, cols: number, rows: number) { +function persistDimensions( + terminalId: string, + cols: number, + rows: number, +): boolean { try { localStorage.setItem( `${DIMS_KEY_PREFIX}${terminalId}`, JSON.stringify({ cols, rows }), ); - } catch {} + return true; + } catch { + return false; + } } function loadSavedDimensions( @@ -129,6 +156,12 @@ function clearPersistedDimensions(terminalId: string) { } catch {} } +/** Clear persisted renderer state even when no live runtime entry remains. */ +export function clearPersistedRuntimeState(terminalId: string): void { + clearPersistedBuffer(terminalId); + clearPersistedDimensions(terminalId); +} + function hostIsVisible(container: HTMLDivElement | null): boolean { if (!container) return false; return container.clientWidth > 0 && container.clientHeight > 0; @@ -359,10 +392,12 @@ export function updateRuntimeAppearance( export function disposeRuntime( runtime: TerminalRuntime, - options: { clearPersistedState?: boolean } = {}, + options: { + persistedState?: "clear" | "persist" | "preserve"; + } = {}, ) { - const clearPersistedState = options.clearPersistedState ?? true; - if (!clearPersistedState) { + const persistedState = options.persistedState ?? "clear"; + if (persistedState === "persist") { persistBuffer(runtime.terminalId, runtime.serializeAddon); persistDimensions(runtime.terminalId, runtime.lastCols, runtime.lastRows); } @@ -378,8 +413,7 @@ export function disposeRuntime( runtime.container = null; runtime.wrapper.remove(); runtime.terminal.dispose(); - if (clearPersistedState) { - clearPersistedBuffer(runtime.terminalId); - clearPersistedDimensions(runtime.terminalId); + if (persistedState === "clear") { + clearPersistedRuntimeState(runtime.terminalId); } } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.test.ts new file mode 100644 index 00000000000..e8ad1191d08 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, mock, spyOn, test } from "bun:test"; + +const unregister = mock(async () => ({ success: true })); + +mock.module("renderer/lib/trpc-client", () => ({ + electronTrpcClient: { + browser: { + register: { mutate: async () => ({ success: true }) }, + unregister: { mutate: unregister }, + }, + browserHistory: { + upsert: { mutate: async () => ({ success: true }) }, + }, + }, +})); + +const { browserRuntimeRegistry } = await import("./browserRuntimeRegistry"); + +describe("browserRuntimeRegistry detached persistence", () => { + test("retains its persistence callback for navigation completion after detach", async () => { + const paneId = "detached-navigation-pane"; + const persisted: string[] = []; + const onPersist = (state: { url: string }) => persisted.push(state.url); + const entry = { + webview: { style: { visibility: "visible" } }, + state: {}, + onPersist, + webContentsId: null, + detachHandlers: () => {}, + placeholder: {}, + resizeObserver: { disconnect: () => {} }, + visible: true, + lastUsedAt: 1, + }; + const registryInternals = browserRuntimeRegistry as unknown as { + entries: Map; + }; + registryInternals.entries.set(paneId, entry); + + try { + browserRuntimeRegistry.detach(paneId); + entry.onPersist?.({ url: "https://example.com/finished-navigation" }); + + expect(persisted).toEqual(["https://example.com/finished-navigation"]); + } finally { + registryInternals.entries.delete(paneId); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + }); + + test("surfaces BrowserManager unregister failures", async () => { + const paneId = "unregister-failure-pane"; + const failure = new Error("unregister failed"); + unregister.mockImplementationOnce(() => Promise.reject(failure)); + const errorSpy = spyOn(console, "error").mockImplementation(() => {}); + const entry = { + webview: { remove: () => {} }, + onPersist: () => {}, + detachHandlers: () => {}, + resizeObserver: { disconnect: () => {} }, + }; + const registryInternals = browserRuntimeRegistry as unknown as { + entries: Map; + }; + registryInternals.entries.set(paneId, entry); + + try { + browserRuntimeRegistry.destroy(paneId); + await Promise.resolve(); + + expect(errorSpy).toHaveBeenCalledWith( + `[browserRuntimeRegistry] unregister failed for ${paneId}:`, + failure, + ); + } finally { + errorSpy.mockRestore(); + registryInternals.entries.delete(paneId); + } + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts index 31ebb1cc4a6..4e38464d8c4 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts @@ -1,3 +1,4 @@ +import { selectRuntimesToEvict } from "renderer/lib/terminal/terminal-runtime-eviction"; import { electronTrpcClient } from "renderer/lib/trpc-client"; import type { BrowserLoadError } from "shared/tabs-types"; import { sanitizeUrl } from "./sanitizeUrl"; @@ -27,8 +28,17 @@ interface RegistryEntry { placeholder: HTMLElement | null; resizeObserver: ResizeObserver | null; visible: boolean; + /** Monotonic use counter; bumped on attach/detach, drives hidden-LRU eviction. */ + lastUsedAt: number; } +/** + * Cap on hidden (detached) webviews kept alive. Each one is a full guest + * Chromium process; past the cap the least-recently-visible are destroyed + * and rebuilt from the pane's persisted URL on next attach. (SUPER-1545) + */ +const MAX_HIDDEN_WEBVIEWS = 3; + const EMPTY_STATE: BrowserRuntimeState = Object.freeze({ currentUrl: "about:blank", pageTitle: "", @@ -44,6 +54,8 @@ const ROOT_CONTAINER_ID = "browser-runtime-root"; class BrowserRuntimeRegistryImpl { private entries = new Map(); private listenersByPaneId = new Map void>>(); + private useSeq = 0; + private pendingEviction: ReturnType | null = null; private rootContainer: HTMLDivElement | null = null; private globalListenersInstalled = false; private windowDragPassthrough = false; @@ -212,6 +224,7 @@ class BrowserRuntimeRegistryImpl { placeholder: null, resizeObserver: null, visible: false, + lastUsedAt: 0, }; const firePersist = () => { @@ -381,6 +394,7 @@ class BrowserRuntimeRegistryImpl { entry.onPersist = onPersist; entry.placeholder = placeholder; entry.visible = true; + entry.lastUsedAt = ++this.useSeq; entry.resizeObserver?.disconnect(); const observer = new ResizeObserver(() => { @@ -397,23 +411,59 @@ class BrowserRuntimeRegistryImpl { detach(paneId: string): void { const entry = this.entries.get(paneId); if (!entry) return; - entry.onPersist = null; + // Keep the persistence callback while hidden. A navigation can finish + // after React detaches the pane; clearing it here would leave only the + // previous URL to rebuild from if this webview is then LRU-evicted. entry.placeholder = null; entry.resizeObserver?.disconnect(); entry.resizeObserver = null; entry.visible = false; entry.webview.style.visibility = "hidden"; + entry.lastUsedAt = ++this.useSeq; + this.scheduleHiddenEviction(); + } + + /** Deferred so a pane-switch (detach then attach) re-adopts before the sweep counts. */ + private scheduleHiddenEviction() { + if (this.pendingEviction !== null) return; + this.pendingEviction = setTimeout(() => { + this.pendingEviction = null; + this.evictExcessHiddenWebviews(); + }, 0); + } + + private evictExcessHiddenWebviews() { + const candidates = Array.from( + this.entries.entries(), + ([paneId, entry]) => ({ + paneId, + runtime: { container: entry.visible ? entry : null }, + lastUsedAt: entry.lastUsedAt, + }), + ); + for (const victim of selectRuntimesToEvict( + candidates, + MAX_HIDDEN_WEBVIEWS, + )) { + this.destroy(victim.paneId); + } } destroy(paneId: string): void { const entry = this.entries.get(paneId); if (!entry) return; + entry.onPersist = null; entry.resizeObserver?.disconnect(); entry.detachHandlers(); entry.webview.remove(); this.entries.delete(paneId); this.listenersByPaneId.delete(paneId); - electronTrpcClient.browser.unregister.mutate({ paneId }).catch(() => {}); + electronTrpcClient.browser.unregister.mutate({ paneId }).catch((err) => { + console.error( + `[browserRuntimeRegistry] unregister failed for ${paneId}:`, + err, + ); + }); } navigate(paneId: string, url: string): void {