Skip to content

feat(desktop): finish SUPER-1545 — alt-screen exemption, persist guard, hidden-webview LRU - #5754

Merged
Kitenite merged 3 commits into
mainfrom
superset-memory-worker-op
Jul 19, 2026
Merged

Kitenite merged 3 commits into
mainfrom
superset-memory-worker-op

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

Links

Summary

  • Alt-screen exemption: terminal eviction never selects runtimes in the alternate screen — in-place TUIs (vim, less, agent TUIs) restore as garbled static snapshots, the worst failure mode of perf(desktop): evict parked terminal runtimes past a configurable cap #5751. Exempt entries still occupy the parked count, so plain shells evict sooner in their place and the memory bound holds when possible.
  • Persist guard: eviction now persists the buffer first and skips the eviction (runtime kept alive, one-shot console warning) if the write fails — previously a localStorage-quota failure would have silently destroyed scrollback.
  • Hidden-webview LRU: v2 browser panes get the same policy — hidden webviews (each a full guest Chromium process) are destroyed past a cap of 3, oldest-first, and rebuilt from the pane's persisted URL on next attach.

How It Works

  • The pure policy (terminal-runtime-eviction.ts) gains an optional isExempt predicate: excess is computed over all parked entries, but only non-exempt ones are selectable, so eviction stops early when only exempt entries remain. The terminal registry passes buffer.active.type === "alternate"; the browser registry reuses the same function through a small candidate adapter (visible → container).
  • tryPersistRuntimeState (new export from terminal-runtime.ts) reports persist success; the sweep only disposes runtimes whose buffers are safely on disk.
  • browserRuntimeRegistry mirrors the terminal design: lastUsedAt bumped on attach/detach, deferred one-tick sweep (so pane switches re-adopt before counting), eviction via the existing destroy() (which also unregisters main-process handlers), restore via the existing attach(initialUrl) path.

Manual QA Checklist

Exercised live over CDP (dev app):

  • Alt-screen exemption: less running in tab 0 (buffer type alternate confirmed), cap lowered to 2, 6 other tabs cycled → TUI survives parked and occupies a cap slot; 1 recent shell kept; 5 plain shells evicted
  • Claude Code specifically (v2.1.214): confirmed it runs in the alternate buffer; parked under cap-2 pressure with 6 tabs cycled → survived eviction with its UI intact in the live buffer, and re-revealed pixel-perfect (screenshot-verified)
  • Hidden-webview cap: 5 browser panes opened → registry holds exactly 1 visible + 3 hidden; oldest destroyed; DOM webview count matches
  • Evicted browser tab re-open: new registry entry created, webview rebuilt from persisted URL, cap still held afterwards
  • Persist guard: unit-covered (quota simulation isn't practical in CDP); failure path keeps the runtime alive and warns once

Testing

  • bun run lint, bun run typecheck — clean
  • bun test (full desktop suite) — 0 fail
  • Policy tests extended to 10 (exemption ordering, exempt-slot semantics, shortfall stop); each new behavior mutation-verified (exemption ignored, exempt-excluded-from-count, both caught). One equivalent mutant found and eliminated by simplifying the impl (slice already clamps; dropped a redundant Math.min).

Design Decisions

  • Exempt entries occupy the parked count rather than being invisible to it: with N TUIs parked, plain shells evict more aggressively, keeping total parked ≤ cap whenever possible instead of letting TUIs raise the ceiling silently.
  • Webview cap is a constant (3), not a setting: webviews are much heavier than terminals and rarer; a second knob isn't warranted until someone asks.

Known Limitations

  • Navigations that happen while a webview is hidden aren't persisted (onPersist is detached), so an evicted webview restores to its last visible URL. Same class as app-restart behavior.
  • Many parked alt-screen TUIs can exceed the cap (they're never evicted) — the memory bound is best-effort in that case, by design.

Infra note

This worktree's Neon dev branch had been deleted by the daily cleanup; re-provisioned (br-curly-scene-afdvq3jq) to run the CDP verification. No code impact.


Open in Stage

Summary by cubic

Finishes SUPER-1545 by protecting TUIs and scrollback while keeping background memory bounded. Adds alt-screen exemption, a persist guard, and an LRU cap for hidden webviews, plus tighter eviction timing and cleanup.

  • New Features

    • Alt-screen exemption: terminal eviction skips alternate-screen TUIs (e.g., vim, less). Exempt entries still count toward the cap so plain shells evict first.
    • Persist guard: eviction now saves buffer and dims first; on persist failure the runtime is kept alive and a one-time warning is logged.
    • Hidden-webview LRU: v2 browser panes keep up to 3 hidden webviews; oldest are destroyed and later rebuilt from the persisted URL, reusing selectRuntimesToEvict in browserRuntimeRegistry.
  • Bug Fixes

    • Eviction flushes pending output and waits for the parser to go idle before checking alt-screen state or persisting, preventing bad snapshots and wrong evictions.
    • Parked TUIs that switch back to the normal buffer trigger a re-check, making them eligible for eviction again.
    • Closing a terminal clears any orphaned persisted state left by earlier eviction.
    • Browser panes retain onPersist after detach to capture late navigation completion; unregister errors are now logged; hidden-webview eviction is deferred one tick to avoid pane-switch races.

Written for commit cd09fdd. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Automatically limits inactive terminal and hidden browser webviews to improve resource usage.
    • Preserves terminal scrollback and dimensions across eviction; re-attempts eviction when buffers change.
    • Adds eviction exemptions so specific runtimes are not selected, while still counting toward capacity.
    • Improves alternate-screen protection during eviction.
  • Bug Fixes

    • If terminal-state persistence fails, the runtime is not released; warnings are shown only once.
    • Cleans up persisted terminal state when a terminal is fully disposed.
  • Tests

    • Expanded eviction and persistence coverage for terminal and browser registries.

Kitenite added 2 commits July 17, 2026 17:52
… hidden-webview LRU

- Terminal eviction never selects runtimes in the alternate screen
  (in-place TUIs restore as garbled snapshots); exempt entries still
  occupy the parked count so plain shells evict sooner in their place.
- Eviction is skipped (runtime kept alive, warn once) when the buffer
  cannot be persisted to localStorage, instead of silently losing it.
- v2 browser panes get the same treatment: hidden webviews are
  LRU-destroyed past a cap of 3 (each is a full guest process) and
  rebuilt from the pane's persisted URL on next attach, reusing the
  shared pure eviction policy.
@ghost

ghost commented Jul 18, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Generalize eviction policy with exemption support
2 Add persistence guards and state management
3 Implement terminal alt-screen exemption and safety
4 Apply LRU eviction to hidden browser webviews
5 Update memory review documentation
Open in Stage

Chapters generated by Stage for commit cd09fdd on Jul 19, 2026 6:14am UTC.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR extends terminal runtime eviction with exempt entries and persistence safeguards, and adds deferred LRU eviction for detached browser webviews. Documentation records both eviction paths as shipped and CDP-verified.

Changes

Runtime eviction lifecycle

Layer / File(s) Summary
Exempt-aware eviction selection
apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts, apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts
selectRuntimesToEvict excludes exempt entries from victims while counting them toward the cap; tests cover ordering, early stopping, and capacity usage.
Terminal state persistence before disposal
apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts, apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts, apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.test.ts
Terminal scrollback and dimensions are persisted before eviction, parser activity defers disposal, failed persistence retains the runtime, and persisted state and listeners are cleaned up appropriately.
Hidden webview eviction
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/*, apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md
Detached webviews receive usage ordering, are swept asynchronously against a cap of three, retain persistence callbacks until destruction, and are documented as shipped and verified.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant BrowserRuntimeRegistryImpl
  participant selectRuntimesToEvict
  participant electronTrpcClient
  BrowserRuntimeRegistryImpl->>BrowserRuntimeRegistryImpl: detach hidden webview
  BrowserRuntimeRegistryImpl->>selectRuntimesToEvict: select excess hidden entries by LRU
  selectRuntimesToEvict-->>BrowserRuntimeRegistryImpl: return eviction victims
  BrowserRuntimeRegistryImpl->>electronTrpcClient: unregister destroyed webview
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed Conventional title clearly summarizes the main desktop eviction changes.
Description check ✅ Passed It covers the required what/why, testing, and checklist content, with extra QA and design detail.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch superset-memory-worker-op

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts (1)

434-440: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using the map function of Array.from to avoid intermediate array allocation.

You can pass the map function directly to Array.from as its second argument, which prevents the creation of an intermediate array before mapping.

💡 Proposed refactor
-		const candidates = Array.from(this.entries.entries()).map(
-			([paneId, entry]) => ({
-				paneId,
-				runtime: { container: entry.visible ? entry : null },
-				lastUsedAt: entry.lastUsedAt,
-			}),
-		);
+		const candidates = Array.from(
+			this.entries.entries(),
+			([paneId, entry]) => ({
+				paneId,
+				runtime: { container: entry.visible ? entry : null },
+				lastUsedAt: entry.lastUsedAt,
+			}),
+		);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/`$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts
around lines 434 - 440, Update the candidates construction in the browser
runtime registry to pass the existing entry-mapping callback as the second
argument to Array.from, rather than calling .map on the intermediate array.
Preserve the paneId, visible-container, and lastUsedAt values unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/`$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts:
- Around line 434-440: Update the candidates construction in the browser runtime
registry to pass the existing entry-mapping callback as the second argument to
Array.from, rather than calling .map on the intermediate array. Preserve the
paneId, visible-container, and lastUsedAt values unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 15a52ca9-c262-4782-8f8a-fcb132142eba

📥 Commits

Reviewing files that changed from the base of the PR and between 1a1903a and 56255ba.

📒 Files selected for processing (6)
  • apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts

@greptile-apps

greptile-apps Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR completes SUPER-1545 by adding three safety features on top of the terminal LRU eviction shipped in #5751: an alternate-screen exemption (vim/less TUIs are never evicted), a persist guard (eviction skips if the buffer can't be written to localStorage), and a hidden-webview LRU for browser panes (capped at 3 alive Chromium guest processes, oldest-first rebuild from persisted URL on re-open).

  • Alt-screen exemption (terminal-runtime-eviction.ts): selectRuntimesToEvict gains an optional isExempt predicate; exempt entries count toward the cap but are never selected, so plain shells bear the eviction load when TUIs are parked.
  • Persist guard (terminal-runtime.ts, terminal-runtime-registry.ts): new tryPersistRuntimeState export reports success; the sweep skips disposal and warns once if the write fails, preventing silent scrollback loss on quota exhaustion.
  • Browser webview LRU (browserRuntimeRegistry.ts): lastUsedAt / useSeq tracking on attach/detach feeds a deferred sweep via the shared selectRuntimesToEvict policy; destroyed panes rebuild their webview from the persisted URL on next attach.

Confidence Score: 3/5

The terminal-side changes are well-constructed and well-tested, but the browser webview LRU has a structural defect that leaves pane UI permanently stale after eviction and re-open.

The eviction path in browserRuntimeRegistry.destroy deletes the pane's listener Set from listenersByPaneId. When the pane is rebuilt on re-attach, notify finds no Set and silently drops all state change callbacks. Any component that subscribed via onStateChange before eviction will show permanently stale URL, title, and loading state after the rebuild. This defect is on the new code path introduced by this PR and would affect every user who exceeds the 3-webview cap.

browserRuntimeRegistry.ts — the destroy method and the eviction sweep interplay with listenersByPaneId need a second look before merging.

Important Files Changed

Filename Overview
apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.ts Adds optional isExempt predicate to selectRuntimesToEvict; excess computed over all parked entries, only non-exempt selected. Logic and tests are correct.
apps/desktop/src/renderer/lib/terminal/terminal-runtime-eviction.test.ts Three new test cases cover exemption ordering, early-stop when only exempt entries remain, and exempt-slot semantics. All cases are mutation-verified per the PR description.
apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts New tryPersistRuntimeState export correctly gates eviction on a successful localStorage write. Dimensions are persisted outside the try block but persistDimensions swallows its own errors. Calling this before disposeEntry({clearPersistedState:false}) results in the buffer being serialized twice.
apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts Wires alt-screen exemption and persist guard into the eviction sweep. The !entry.runtime guard in the eviction loop is dead code (selectRuntimesToEvict already guarantees non-null runtime). Double persist path is a P2 efficiency issue.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts Adds hidden-webview LRU capped at 3. The eviction candidate adapter is correct. However, destroy() deletes the listenersByPaneId entry, silently severing any active React subscriptions; after evict+re-attach, state notifications are never delivered to live subscribers.
apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md Status row updated to reflect shipped state and CDP verification date. No code impact.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant React as React BrowserPane
    participant Reg as browserRuntimeRegistry
    participant Policy as selectRuntimesToEvict

    React->>Reg: attach(paneId, placeholder, url, onPersist)
    Reg->>Reg: "createEntry / set visible=true, lastUsedAt=++seq"
    React->>Reg: onStateChange(paneId, listener)

    Note over React,Reg: User switches away
    React->>Reg: "detach(paneId) - visible=false, lastUsedAt=++seq"
    Reg->>Reg: scheduleHiddenEviction() [setTimeout 0]

    Reg->>Policy: "selectRuntimesToEvict(candidates, cap=3)"
    Policy-->>Reg: [victim paneIds]

    Reg->>Reg: destroy(victim) - entries.delete + listenersByPaneId.delete

    Note over React,Reg: User re-opens evicted pane
    React->>Reg: attach(paneId, placeholder, url, onPersist)
    Reg->>Reg: createEntry (new webview, loads url)
    Reg->>Reg: setState - notify(paneId)
    Note over Reg: listenersByPaneId has no entry for paneId
    Note over React: listener never fires - stale state displayed
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant React as React BrowserPane
    participant Reg as browserRuntimeRegistry
    participant Policy as selectRuntimesToEvict

    React->>Reg: attach(paneId, placeholder, url, onPersist)
    Reg->>Reg: "createEntry / set visible=true, lastUsedAt=++seq"
    React->>Reg: onStateChange(paneId, listener)

    Note over React,Reg: User switches away
    React->>Reg: "detach(paneId) - visible=false, lastUsedAt=++seq"
    Reg->>Reg: scheduleHiddenEviction() [setTimeout 0]

    Reg->>Policy: "selectRuntimesToEvict(candidates, cap=3)"
    Policy-->>Reg: [victim paneIds]

    Reg->>Reg: destroy(victim) - entries.delete + listenersByPaneId.delete

    Note over React,Reg: User re-opens evicted pane
    React->>Reg: attach(paneId, placeholder, url, onPersist)
    Reg->>Reg: createEntry (new webview, loads url)
    Reg->>Reg: setState - notify(paneId)
    Note over Reg: listenersByPaneId has no entry for paneId
    Note over React: listener never fires - stale state displayed
Loading

Comments Outside Diff (2)

  1. apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts, line 449-458 (link)

    P1 Eviction severs existing React subscriptions

    destroy deletes the listenersByPaneId entry before any React component listening on that paneId has a chance to re-subscribe. When the evicted pane is later re-opened, attach creates a new RegistryEntry, and subsequent setState → notify calls find no Set for that paneId (because listenersByPaneId.get(paneId) returns undefined). Any component that subscribed via onStateChange before eviction — URL bar, loading indicator, favicon, nav-state — will never receive another notification, leaving the pane UI permanently stale after the first navigate on the rebuilt webview.

    The fix is to not delete the listener Set in destroy. Subscribers already hold a reference to the Set via their closure cleanup; when the component eventually unmounts, it calls listeners.delete(listener), draining the Set naturally. Not deleting in destroy means notify continues to reach live subscribers across the evict-and-rebuild cycle without any component having to re-subscribe.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts
    Line: 449-458
    
    Comment:
    **Eviction severs existing React subscriptions**
    
    `destroy` deletes the `listenersByPaneId` entry before any React component listening on that `paneId` has a chance to re-subscribe. When the evicted pane is later re-opened, `attach` creates a new `RegistryEntry`, and subsequent `setState` → `notify` calls find no Set for that `paneId` (because `listenersByPaneId.get(paneId)` returns `undefined`). Any component that subscribed via `onStateChange` before eviction — URL bar, loading indicator, favicon, nav-state — will never receive another notification, leaving the pane UI permanently stale after the first navigate on the rebuilt webview.
    
    The fix is to not delete the listener Set in `destroy`. Subscribers already hold a reference to the Set via their closure cleanup; when the component eventually unmounts, it calls `listeners.delete(listener)`, draining the Set naturally. Not deleting in `destroy` means `notify` continues to reach live subscribers across the evict-and-rebuild cycle without any component having to re-subscribe.
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts, line 288-302 (link)

    P2 Redundant double-serialize on every terminal eviction

    tryPersistRuntimeState already serializes the xterm buffer and writes it to localStorage. Immediately after, disposeEntry(entry, { clearPersistedState: false }) calls disposeRuntime which — when clearPersistedState is false — calls persistBuffer a second time (serializing the same unchanged buffer again). For a large scrollback this doubles both the CPU cost and the localStorage write. Since tryPersistRuntimeState has already guaranteed the state is on disk, consider passing a flag so disposeRuntime skips the second persist.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts
    Line: 288-302
    
    Comment:
    **Redundant double-serialize on every terminal eviction**
    
    `tryPersistRuntimeState` already serializes the xterm buffer and writes it to localStorage. Immediately after, `disposeEntry(entry, { clearPersistedState: false })` calls `disposeRuntime` which — when `clearPersistedState` is `false` — calls `persistBuffer` a second time (serializing the same unchanged buffer again). For a large scrollback this doubles both the CPU cost and the localStorage write. Since `tryPersistRuntimeState` has already guaranteed the state is on disk, consider passing a flag so `disposeRuntime` skips the second persist.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts:449-458
**Eviction severs existing React subscriptions**

`destroy` deletes the `listenersByPaneId` entry before any React component listening on that `paneId` has a chance to re-subscribe. When the evicted pane is later re-opened, `attach` creates a new `RegistryEntry`, and subsequent `setState` → `notify` calls find no Set for that `paneId` (because `listenersByPaneId.get(paneId)` returns `undefined`). Any component that subscribed via `onStateChange` before eviction — URL bar, loading indicator, favicon, nav-state — will never receive another notification, leaving the pane UI permanently stale after the first navigate on the rebuilt webview.

The fix is to not delete the listener Set in `destroy`. Subscribers already hold a reference to the Set via their closure cleanup; when the component eventually unmounts, it calls `listeners.delete(listener)`, draining the Set naturally. Not deleting in `destroy` means `notify` continues to reach live subscribers across the evict-and-rebuild cycle without any component having to re-subscribe.

### Issue 2 of 2
apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts:288-302
**Redundant double-serialize on every terminal eviction**

`tryPersistRuntimeState` already serializes the xterm buffer and writes it to localStorage. Immediately after, `disposeEntry(entry, { clearPersistedState: false })` calls `disposeRuntime` which — when `clearPersistedState` is `false` — calls `persistBuffer` a second time (serializing the same unchanged buffer again). For a large scrollback this doubles both the CPU cost and the localStorage write. Since `tryPersistRuntimeState` has already guaranteed the state is on disk, consider passing a flag so `disposeRuntime` skips the second persist.

```suggestion
	private evictExcessParkedRuntimes() {
		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) {
			if (!entry.runtime || !tryPersistRuntimeState(entry.runtime)) {
				warnPersistFailureOnce(entry.terminalId);
				continue;
			}
			// State was already persisted by tryPersistRuntimeState; skip the
			// second serialize+write that disposeRuntime would otherwise do.
			this.disposeEntry(entry, { clearPersistedState: false, skipPersist: true });
		}
	}
```

Reviews (1): Last reviewed commit: "docs(desktop): mark terminal eviction sh..." | Re-trigger Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts">

<violation number="1" location="apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts:296">
P2: A runtime can be evicted even when its complete persisted state was not saved: `tryPersistRuntimeState` treats a failed dimensions write as success. Returning failure when either buffer or dimensions persistence fails would keep the runtime alive until its state is safely restorable.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

(entry) => entry.runtime?.terminal.buffer.active.type === "alternate",
);
for (const entry of victims) {
if (!entry.runtime || !tryPersistRuntimeState(entry.runtime)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A runtime can be evicted even when its complete persisted state was not saved: tryPersistRuntimeState treats a failed dimensions write as success. Returning failure when either buffer or dimensions persistence fails would keep the runtime alive until its state is safely restorable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts, line 296:

<comment>A runtime can be evicted even when its complete persisted state was not saved: `tryPersistRuntimeState` treats a failed dimensions write as success. Returning failure when either buffer or dimensions persistence fails would keep the runtime alive until its state is safely restorable.</comment>

<file context>
@@ -288,8 +289,14 @@ class TerminalRuntimeRegistryImpl {
+			(entry) => entry.runtime?.terminal.buffer.active.type === "alternate",
 		);
 		for (const entry of victims) {
+			if (!entry.runtime || !tryPersistRuntimeState(entry.runtime)) {
+				warnPersistFailureOnce(entry.terminalId);
+				continue;
</file context>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts (1)

393-419: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

disposeRuntime's "persist" branch drops write failures silently.

The eviction path now checks tryPersistRuntimeState's boolean and keeps the runtime alive with a warning on failure (see terminal-runtime-registry.ts evictExcessParkedRuntimes), but here (used by release()) persistBuffer/persistDimensions failures are discarded with no fallback or signal — a quota-exceeded write during pane release silently loses scrollback/dimensions with no way to detect it later.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts` around lines 393
- 419, Update disposeRuntime’s "persist" branch to use tryPersistRuntimeState
and inspect its success result instead of discarding
persistBuffer/persistDimensions failures. On failure, preserve the runtime’s
state and emit the same warning or fallback signal used by
evictExcessParkedRuntimes, while keeping the existing disposal flow for
successful persistence and other persistedState values.
🧹 Nitpick comments (2)
apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts (1)

568-574: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

warnPersistFailureOnce only ever warns once per process lifetime, across all terminals.

Once any single terminal fails to persist, persistFailureWarned is permanently true, so later persist failures for different terminals — each of which remains pinned above the parked-runtime cap as a result — never surface a warning. This can silently mask a systemic quota problem that defeats the eviction cap's purpose.

Consider keying the warning per-terminal (e.g. a Set<string>) or resetting the flag on the next successful persist, so recurring failures across the fleet of parked terminals stay observable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts` around
lines 568 - 574, Update warnPersistFailureOnce to track warning state per
terminal rather than using the process-wide persistFailureWarned flag. Use a Set
keyed by terminalId (or reset the terminal’s warning state after a successful
persist) so each terminal’s first persist failure is reported while duplicate
warnings for that terminal remain suppressed.
apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts (1)

81-86: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Unify persistBuffer with the inline buffer-write in tryPersistRuntimeState.

persistDimensions was updated to return a boolean and is now shared by both call sites, but persistBuffer was left as a void, error-swallowing helper, so tryPersistRuntimeState had to re-implement the same serialize+localStorage.setItem logic inline instead of reusing it. This duplicates the write logic and leaves two divergent error-handling conventions for the same operation.

♻️ Suggested refactor: give `persistBuffer` a boolean return and reuse it
-function persistBuffer(terminalId: string, serializeAddon: SerializeAddon) {
+function persistBuffer(terminalId: string, serializeAddon: SerializeAddon): boolean {
 	try {
 		const data = serializeAddon.serialize({ scrollback: SERIALIZE_SCROLLBACK });
 		localStorage.setItem(`${STORAGE_KEY_PREFIX}${terminalId}`, data);
+		return true;
 	} catch {}
+	return false;
 }
 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;
-	}
+	if (!persistBuffer(runtime.terminalId, runtime.serializeAddon)) return false;
 	return persistDimensions(
 		runtime.terminalId,
 		runtime.lastCols,
 		runtime.lastRows,
 	);
 }

Also applies to: 99-113

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts` around lines 81 -
86, Update persistBuffer to return a boolean indicating whether serialization
and localStorage.setItem succeeded, returning false when either operation
throws. Replace the duplicated inline buffer serialization/write logic in
tryPersistRuntimeState with a call to persistBuffer, preserving its existing
success/failure handling alongside persistDimensions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts`:
- Around line 393-419: Update disposeRuntime’s "persist" branch to use
tryPersistRuntimeState and inspect its success result instead of discarding
persistBuffer/persistDimensions failures. On failure, preserve the runtime’s
state and emit the same warning or fallback signal used by
evictExcessParkedRuntimes, while keeping the existing disposal flow for
successful persistence and other persistedState values.

---

Nitpick comments:
In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts`:
- Around line 568-574: Update warnPersistFailureOnce to track warning state per
terminal rather than using the process-wide persistFailureWarned flag. Use a Set
keyed by terminalId (or reset the terminal’s warning state after a successful
persist) so each terminal’s first persist failure is reported while duplicate
warnings for that terminal remain suppressed.

In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts`:
- Around line 81-86: Update persistBuffer to return a boolean indicating whether
serialization and localStorage.setItem succeeded, returning false when either
operation throws. Replace the duplicated inline buffer serialization/write logic
in tryPersistRuntimeState with a call to persistBuffer, preserving its existing
success/failure handling alongside persistDimensions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0952c8b8-b641-42b0-a586-6f5ba92f9490

📥 Commits

Reviewing files that changed from the base of the PR and between 56255ba and cd09fdd.

📒 Files selected for processing (6)
  • apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.test.ts
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime-registry.ts
  • apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.test.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/desktop/docs/MEMORY_AND_WORKERS_REVIEW.md
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/BrowserPane/browserRuntimeRegistry.ts

@Kitenite
Kitenite merged commit 7fb5b1a into main Jul 19, 2026
11 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant