Hibernate idle background terminal surfaces and cap live surfaces (LRU)

Closed
AU
2mo ago
+3518-205

Part of https://github.com/manaflow-ai/cmux/issues/5731 (P0: surface hibernation + LRU cap)

Problem

The issue's live audit found 112 live Ghostty surfaces while one workspace was visible — ~3.3 GB of IOSurface across 850 regions, ~1 GB of scrollback malloc, and four threads per surface. Unmounting a workspace only hides portal views (hideAllTerminalPortalViews); ghostty_surface_free runs solely on panel close. The only reclaim path that exists today — agent hibernation — covers restorable-agent panels only, is opt-in (default off), and its cap counts only those panels. Plain-shell surfaces are immortal, and surfaces force-created by bypass paths (background workspace priming, queued socket input on surface-less panels) never create eviction pressure.

What this adds

One pure selection policy, SurfaceHibernationPlanner, over all terminal panels. Three rules compose (union):

  1. Agent cap — the pre-existing agent-hibernation cap, preserved exactly (the old AgentHibernationPlanner is replaced by this rule; its tests were migrated 1:1).
  2. Global LRU cap (maxLiveSurfaces, default 12) — the census counts every live surface, including exempt ones and bypass-path materializations, so they still create pressure; only idle, non-busy, non-visible, mechanism-capable surfaces are evicted, oldest first.
  3. Unmounted-idle — surfaces whose workspace has been unmounted (and quiet) longer than unmountedIdleSeconds (default 30 min) hibernate even without cap pressure.

A shellRestart hibernation mechanism for plain shells: capture scrollback (session-persistence truncation policy) and the panel's working directory, free the runtime surface (ghostty_surface_free → Metal/IOSurface buffers, the four surface threads, PTY), and on the next visit start a fresh shell in the captured directory with the scrollback replayed through the existing CMUX_RESTORE_SCROLLBACK_FILE plumbing.

Restore triggers mirror agent-hibernation auto-resume: workspace selection / visibility reconcile, panel focus, focus-intent restore, and every input path (keyboard, socket, CLI — including the two observer-wait paths that would otherwise wedge on a panel whose surface can never materialize while suspended).

Safety exemptions (all planner-level and unit-tested): busy surfaces (needs_confirm_quit, i.e. not safely at a prompt — conservatively true when shell integration is absent), visible panels of the visible workspace, unconfirmed terminal input, deferred startup work (initial command, tmux attach, initial input, queued input bytes), remote terminals, and agent panels (which hibernate only through their own opt-in agent mechanism). On top of eligibility, the existing 60-second output-stability confirmation window must pass before anything is reclaimed.

Settings (default ON) — terminal.surfaceHibernation.{enabled, idleSeconds, unmountedIdleSeconds, maxLiveSurfaces} in cmux.json, settings search row, command-palette toggle, cmux surface-hibernation <on|off> CLI, surface_hibernation socket command, JSON schema, and docs. Defaulting on is the point of the P0: it only ever reclaims surfaces that are off-screen, at a prompt, quiet, and output-stable, and the visible state (scrollback + cwd) is restored on return.

Persistence — the autosave fingerprint tracks hibernation transitions, and the session snapshot uses the captured scrollback for hibernated panels, so after an app relaunch they restore as normal (surface-less) panels with replay staged.

Red/green structure

  • Commit 1 adds SurfaceHibernationPolicyTests against a planner scaffold that faithfully reproduces the shipped agent-only policy — the new policy tests fail (CI red), proving the gap.
  • Commit 2 implements the real policy and mechanics — CI green.

Commit 1 also adds a dedicated Run surface hibernation policy regression CI step (-only-testing:cmuxTests/SurfaceHibernationPolicyTests, mirroring the existing split-theme step). This was forced by a pre-existing hole in the tests job discovered while proving the red: the full unit pass intermittently crashes inside BrowserDeveloperToolsVisibilityPersistenceTests (Signal 11), every suite that sorts after the crash is skipped, and the job's expected-failure classifier then reports "All failures are expected, treating as pass" — so new suites late in the alphabet can silently never execute (two consecutive runs reproduced this). The dedicated step makes the policy tests a real gate regardless. The crash/soft-pass hole itself is worth a separate issue — it affects every suite from C to Z on crashy runs, not just this one.

Unit-tested vs. verified by inspection

  • Unit-tested: LRU eviction order and tie-breaks, idle gates, busy/protected/unconfirmed-input/deferred-startup/remote exemptions, census including bypass materializations, unmounted-idle rule (both clocks), agent-rule parity with surface hibernation disabled, settings defaults/sanitization/change notification, and the hibernate→restore round trip (state capture, replay-file staging, working-directory override, input queueing on restore, focus/visibility-driven restore, cross-guards with agent hibernation, session-snapshot fallback, autosave fingerprint, workspace unmount clock).
  • Code-inspection only (not cleanly unit-testable): the Metal/IOSurface/render-thread teardown itself happens inside ghostty_surface_free; suspendRuntimeSurfaceForHibernation reaches it on the next main-actor turn — the same already-shipping path agent hibernation uses. End-to-end memory reclamation was not measured in this PR.

Localization audit

  • New user-facing Swift string: settings.terminal.surfaceHibernation — added to Resources/Localizable.xcstrings with en + ja translations; the palette toggle and settings row reuse it, and enable/disable wrappers use existing localized formats.
  • JSON-schema descriptions, docs/configuration.md, and the web docs example follow the agentHibernation precedent exactly (plain description strings; that section has no entries in web/messages/en.json/ja.json to mirror).
  • CLI and socket help text is English-only by existing convention (agent-hibernation likewise).

Not in this PR

The third P0 item (stop mass agent auto-resume at launch) is a separate workstream item of #5731.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Surface hibernation for terminal panels: suspend idle panels to free runtime surfaces and later restore scrollback/working directory or restart shells.
  • Settings

    • User-configurable surface hibernation (enable, idle/unmounted timeouts, max live terminals, confirmation); persisted, clamped, and emits single-change notifications.
  • CLI & UI

    • Added surface-hibernation CLI command, command-palette toggle, settings entry, localized label, and JSON/OK CLI output.
  • Behavior

    • Input/focus now queues and restores for hibernated panels; autosave fingerprint includes hibernation state.
  • Docs & Tests

    • Docs, JSON schema, template updates, CI step, and extensive tests for policy, restore, and settings.