Repository navigation
Conversation
…torage Persisted terminal-buffer:* entries were only deleted on an explicit terminal kill, so terminals that disappeared any other way (workspace deleted, host reset, crash) leaked their snapshot forever - measured at 945 entries / 23.7 MB after two months, enough to wedge the renderer on the synchronous localStorage load. Stamp each buffer with a last persist/restore time and prune at renderer boot: unstamped (legacy) entries immediately, stamped entries after a 14-day TTL, and oldest-first once total buffer size exceeds a 2M-char budget.
|
Ready to review this PR? Stage has broken it down into 6 individual chapters for you: Chapters generated by Stage for commit 67df6f6 on Jul 29, 2026 2:50am UTC. |
📝 WalkthroughWalkthroughAdds renderer-side garbage collection for persisted terminal state and tracks terminal session termination across the host service, WebSocket transport, and runtime registry. Persisted snapshots receive timestamps, startup pruning removes stale or oversized entries, and ended sessions clear saved state. ChangesTerminal state garbage collection
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant HostService
participant WebSocketTransport
participant RuntimeRegistry
participant TerminalRuntime
participant LocalStorage
HostService->>WebSocketTransport: send session-gone error
WebSocketTransport->>RuntimeRegistry: invoke onSessionEnded
RuntimeRegistry->>TerminalRuntime: clear persisted runtime state
TerminalRuntime->>LocalStorage: remove terminal buffer, dims, and persisted-at entry
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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.
Inline comments:
In `@apps/desktop/src/renderer/lib/terminal/terminal-buffer-gc.test.ts`:
- Around line 98-107: Update the “drops index rows whose storage keys are gone”
test to delete the ghost terminal’s dimensions key from the fake storage before
calling pruneExpiredTerminalState, while preserving the existing removal of its
buffer key and the expected index assertion.
In `@apps/desktop/src/renderer/lib/terminal/terminal-runtime.ts`:
- Around line 115-119: Update the persisted-buffer check in the terminal
restoration flow to test explicitly for null rather than truthiness, so an
existing empty string is restored and touchTerminalStatePersistedAt is called.
Preserve the current behavior for a missing localStorage entry.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: fb8fa01f-93bd-438c-962c-31a7545d360b
📒 Files selected for processing (4)
apps/desktop/src/renderer/index.tsxapps/desktop/src/renderer/lib/terminal/terminal-buffer-gc.test.tsapps/desktop/src/renderer/lib/terminal/terminal-buffer-gc.tsapps/desktop/src/renderer/lib/terminal/terminal-runtime.ts
| test("drops index rows whose storage keys are gone", () => { | ||
| const { values, storage } = createFakeStorage(); | ||
| seedTerminal(values, "live"); | ||
| touchTerminalStatePersistedAt("live", storage, NOW); | ||
| touchTerminalStatePersistedAt("ghost", storage, NOW); | ||
| values.delete(`${TERMINAL_BUFFER_KEY_PREFIX}ghost`); | ||
|
|
||
| pruneExpiredTerminalState(storage, NOW); | ||
|
|
||
| expect(Object.keys(readIndex(values))).toEqual(["live"]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Delete the remaining dimensions key before asserting index cleanup.
Line 103 leaves terminal-dims:ghost present, so GC correctly retains the fresh ghost index row and the assertion at Line 107 fails.
Proposed fix
touchTerminalStatePersistedAt("live", storage, NOW);
touchTerminalStatePersistedAt("ghost", storage, NOW);
values.delete(`${TERMINAL_BUFFER_KEY_PREFIX}ghost`);
+ values.delete(`${TERMINAL_DIMS_KEY_PREFIX}ghost`);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| test("drops index rows whose storage keys are gone", () => { | |
| const { values, storage } = createFakeStorage(); | |
| seedTerminal(values, "live"); | |
| touchTerminalStatePersistedAt("live", storage, NOW); | |
| touchTerminalStatePersistedAt("ghost", storage, NOW); | |
| values.delete(`${TERMINAL_BUFFER_KEY_PREFIX}ghost`); | |
| pruneExpiredTerminalState(storage, NOW); | |
| expect(Object.keys(readIndex(values))).toEqual(["live"]); | |
| test("drops index rows whose storage keys are gone", () => { | |
| const { values, storage } = createFakeStorage(); | |
| seedTerminal(values, "live"); | |
| touchTerminalStatePersistedAt("live", storage, NOW); | |
| touchTerminalStatePersistedAt("ghost", storage, NOW); | |
| values.delete(`${TERMINAL_BUFFER_KEY_PREFIX}ghost`); | |
| values.delete(`${TERMINAL_DIMS_KEY_PREFIX}ghost`); | |
| pruneExpiredTerminalState(storage, NOW); | |
| expect(Object.keys(readIndex(values))).toEqual(["live"]); |
🤖 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-buffer-gc.test.ts` around
lines 98 - 107, Update the “drops index rows whose storage keys are gone” test
to delete the ghost terminal’s dimensions key from the fake storage before
calling pruneExpiredTerminalState, while preserving the existing removal of its
buffer key and the expected index assertion.
| if (data) { | ||
| terminal.write(data); | ||
| // Restored-but-never-detached terminals must stay fresh for boot GC. | ||
| touchTerminalStatePersistedAt(terminalId); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Treat an empty persisted buffer as present.
localStorage.getItem() returns "" for an existing empty snapshot. The truthiness check skips restoration/timestamp refresh, so that active state can expire after 14 days. Check explicitly for null.
Proposed fix
- if (data) {
+ if (data !== null) {
terminal.write(data);
// Restored-but-never-detached terminals must stay fresh for boot GC.
touchTerminalStatePersistedAt(terminalId);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (data) { | |
| terminal.write(data); | |
| // Restored-but-never-detached terminals must stay fresh for boot GC. | |
| touchTerminalStatePersistedAt(terminalId); | |
| } | |
| if (data !== null) { | |
| terminal.write(data); | |
| // Restored-but-never-detached terminals must stay fresh for boot GC. | |
| touchTerminalStatePersistedAt(terminalId); | |
| } |
🤖 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 115
- 119, Update the persisted-buffer check in the terminal restoration flow to
test explicitly for null rather than truthiness, so an existing empty string is
restored and touchTerminalStatePersistedAt is called. Preserve the current
behavior for a missing localStorage entry.
The server now tags attach errors for permanently-destroyed sessions (not found / disposed / exited) with code: "session-gone". The renderer transport tracks that signal plus live exit messages as sessionEnded, clears the persisted snapshot immediately, and every persistence path (detach, release, parked eviction) clears instead of re-persisting a dead session's buffer.
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
CDP before/after verification (dev app, this worktree)Drove the real dev instance (
Method notes: terminals were driven through the real registry/transport ( |
Problem
Terminal scrollback is persisted to renderer localStorage (
terminal-buffer:<id>+terminal-dims:<id>) so panes can restore across remounts and relaunches. Those entries were only deleted on an explicit terminal kill (terminalRuntimeRegistry.dispose()). Terminals that disappear any other way — PTY exit, workspace deleted, host reset, crash, org switch — leaked their snapshot forever.Measured on a real install after ~2 months: 945 orphaned buffers / 23.7 MB, enough that Chromium's synchronous localStorage load wedged the renderer (652% CPU, 6.31 GB RSS, unresponsive AX queries).
Fix (two layers)
1. Destroyed PTY ⇒ scrollback deleted, immediately.
code: "session-gone"on the existing error message (additive, version-skew safe).exitmessages assessionEnded, distinct from_terminated(which also covers access denials where the PTY may still be alive). The signal clears the persisted snapshot on the spot, and every persistence path — detach, release, parked eviction — clears instead of re-persisting a dead session's buffer. A successful re-attach resets the flag (session re-created under the same id).2. Boot-time GC bounds the store no matter how a terminal dies.
terminal-buffer-persisted-atindex.pruneExpiredTerminalState()removes: unstamped entries (all pre-existing bloat, cleaned on first launch after this ships — a one-time scrollback-restore loss), entries older than a 14-day TTL (covers deaths the renderer never observes, e.g. workspace deleted while the app is closed), and oldest entries beyond a 2M-char (~4 MB) total budget.Pruning deliberately does not cross-reference pane layouts:
v2WorkspaceLocalStateis org-scoped and cache-first, so reading it for GC could delete valid buffers for evicted orgs / not-ready collections.Relationship to #5965
Complementary, not overlapping fixes: #5965 guards the TanStack-DB localStorage collections write path against the QuotaExceededError rollback→retry loop once the store is already full, and reclaims orphaned snapshots only reactively on that quota path. This PR stops the terminal-snapshot store from growing unbounded in the first place and ties snapshot lifetime to PTY lifetime. Both touch
terminal-runtime(-registry).ts, so whichever lands second needs a small rebase.Testing
terminal-buffer-gc.test.ts: legacy pruning, TTL, size-budget eviction order, index hygiene, dims-only orphans, corrupt-index recovery. Core tests verified to fail when their behavior is mutated out.terminal-ws-transport.test.ts: exit ⇒sessionEnded+ callback fired once;session-goneattach error ⇒ same; plain error ⇒ untouched; re-attach resets.terminal-runtime-registry.test.ts: release of an ended session disposes withclearand never serializes.bun run typecheck --filter=desktop --filter=@superset/host-serviceandbun run lintclean.Summary by CodeRabbit