Skip to content

Keep side-panel terminals alive across panel and thread switches without streaming to hidden ones - #7801

Open
lanjak wants to merge 8 commits into
get-bb:mainfrom
lanjak:fix-7724-terminal-keepalive
Open

lanjak wants to merge 8 commits into
get-bb:mainfrom
lanjak:fix-7724-terminal-keepalive

Conversation

@lanjak

@lanjak lanjak commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

The secondary panel unmounts a terminal when the user selects another panel tab or another thread. ThreadTerminalView then disposed its xterm instance and its WebSocket transport. On return, a new transport connected with sinceSeq=0, and the server replayed up to 512 KB of history. The user saw the terminal scroll through that history. Details are in #7724.

This change starts from #7726 by Dante Regis. That PR parks up to 8 terminal runtimes and attaches them again on return. The first commit of this change is that commit, with its original author. Review of that commit found three problems:

  • A parked terminal kept its socket open and sent only visibility: false. The server uses visibility only to decide if a socket governs PTY flow control (terminal-output-flow-control.ts, isGoverning). forwardTerminalOutput in terminal-session-lifecycle.ts still sends every output chunk to every attached socket. So each hidden terminal received all of its output. In a test, a hidden terminal that ran seq 1 300000 received 56 output messages (2.29 MB) that nobody saw.
  • Parking cleared the xterm selection. The xterm DOM renderer does not update its selection render model when the selection is cleared. The next resize then drew the old highlight again, with no text selected. Copy and the selection menu ignored that highlight.
  • terminal-cache-owner.ts (hooks) imported from @/components/..., and takeParkedTerminalRuntime returned an unchecked as R cast.

What changed

  • packages/client-core/src/terminal/terminal-websocket-transport.ts: new suspend(). It closes the socket and stops the heartbeat, drain and reconnect timers. It keeps nextOutputSeq, the last resize and queued input. start() after suspend() connects with sinceSeq set to the next output sequence. This is the same path that a reconnect uses.
  • Result: the server sends only the output that the parked terminal did not get. If that output is more than the 512 KB replay limit, the existing sequence-gap path resets the terminal and writes the existing notice.
  • ThreadTerminalView.tsx: parking calls transport.suspend() instead of setVisible(false). Attaching a parked runtime calls transport.start(). Parking no longer clears the selection. The runtime is a small TerminalRuntime class, so the view narrows a parked runtime with instanceof and does not cast it.
  • ThreadTerminalView.tsx: this change removes the check that disposed a parked runtime on an exited message, because a parked runtime has no socket. The cache owner still evicts a parked runtime when its session closes as exited or is missing.
  • apps/app/src/lib/terminal-runtime-cache.ts (moved from components/thread/terminal/): stores ParkedTerminalRuntime values (dispose() only) with no type parameter and no cast. terminal-cache-owner.ts imports it from @/lib.
  • ThreadTerminalView.tsx, app command keys (after the rebase onto Let bound commands through a focused terminal, keeping shell keys #7888): the key handler that Let bound commands through a focused terminal, keeping shell keys #7888 added reads its dispatcher through the runtime's live bindings, which each remount replaces. Thus a reattached terminal sends command keys to the view that shows it, not to the view that created it. Test: ThreadTerminalView.keepalive.test.tsx "sends app command keys of a remounted parked terminal to the new view" fails when the handler keeps the first view's ref.
  • No server or daemon change. No wire change, so HOST_DAEMON_PROTOCOL_VERSION does not change. No CLI, guide or doc change.
  • ThreadTerminalView.tsx, replay: when attached announces a replay (replayStartSeq < nextSeq) or the transport reports a sequence gap, the view hides .xterm-screen and shows it again in the render after the write callback of the last replayed chunk. Each chunk is still a separate xterm write, so xterm keeps its 12 ms budget per task. Live output, an error or an exit also shows the screen. A version counter keeps a callback from an older replay from showing a newer one. The sequence-gap reset is an RIS in the write stream, so it runs after the writes that are already queued. This covers the replays that parking cannot avoid: output of more than 512 KB while hidden, and every reload.
  • ThreadTerminalView.tsx, replay suppression: only replies to terminal queries found while replay output is parsed are dropped (DA, DSR, XTVERSION, DECRQM, window reports, kitty keyboard query, DECRQSS, OSC color queries). Before, all terminal data was dropped while a replay write was queued, including keyboard, paste and IME input.
  • ThreadTerminalView.tsx, thread-switch return: profiles of an unminified build named three costs in the React commit of a thread switch to a parked terminal. The theme effect rebuilt the terminal theme on every remount (22 CSS variable reads, each a forced style recalculation), because the reattach sets the terminal synchronously. The font observer read document.fonts.ready again, which makes Chromium update style and layout synchronously. The reattach appended, fitted and refreshed the terminal in the commit. The runtime now records the theme key it was built for and rebuilds the theme only when the key changes. It observes font loading once for its whole life and measures again on return if fonts loaded while it was parked. It attaches in a requestAnimationFrame callback, which runs before the next frame paints; if the view unmounts first, the runtime goes back to the parked cache.

How you verified

Tests added. Each one fails before the change and passes after it:

  • packages/client-core/test/terminal-websocket-transport.test.ts "closes the socket on suspend and resumes from the next output sequence": no reconnect after suspend(), then start() uses sinceSeq=2 and sends the last resize again. Before: TypeError: harness.transport.suspend is not a function.
  • ThreadTerminalView.keepalive.test.tsx "closes the socket of a parked terminal and resumes it when the same session remounts". Against the fix(app): keep side panel terminals alive across panel and thread switches #7726 view: expected "vi.fn()" to be called 1 times, but got 0 times (suspend).
  • ThreadTerminalView.keepalive.test.tsx "keeps the selection of a parked terminal when the same session remounts". Before: expected '' to be 'hello'.
  • Also added: "disposes a parked terminal that closes as exited" (eviction through applyTerminalSessionClose) and "does not park a terminal that exited while it was shown".

Commands:

  • pnpm exec turbo run typecheck test lint --filter=@bb/app --filter=@bb/client-core: typecheck and lint pass. @bb/client-core: 244 tests pass. @bb/app: all tests pass except UpdatePluginDialog.test.tsx "opens persisted failure details", which fails the same way on unchanged main on this machine (date text).

Real browser check. Headless Chromium with CDP, each build on a scratch instance (pnpm start:worktree, own data dir and ports). Steps: open a thread, open a terminal in the side panel, run seq 1 50000, select the Diff tab and return, select another thread and return. Measured from the return click. xterm used its DOM renderer, because WebGL was off in the headless browser.

Return main #7726 only This change
Panel tab, nothing printed while hidden new socket, 15 output, 339 KB, 5 screens drawn, final screen at 163 ms no new socket, 0 messages, final screen at 95 ms new socket, 0 output (441 bytes, attached only), final screen at 106 ms, first screen is the final screen
Thread switch, nothing printed while hidden new socket, 15 output, 339 KB, 7 screens drawn 0 messages 0 output, 441 bytes
20,000 lines printed while hidden 34 output, 479 KB on return 4 output, 140 KB while hidden 0 while hidden, 5 output, 140 KB on return, first screen is the final screen
300,000 lines printed while hidden 16 output, 524 KB on return 56 output, 2.29 MB while hidden 0 while hidden, 16 output, 498 KB on return (sequence gap, same as main)
Open terminal sockets while hidden 0 1 0

Also checked in the browser:

  • The panel was made smaller while the terminal was hidden. After return, tput cols; tput lines printed 60 46 on all three builds, and the xterm screen fits the panel.
  • After return the terminal has focus for panel tab switches. After a thread switch it does not have focus on any of the three builds.
  • With this change, a selection made before a panel-tab switch is still selected after return, copy returns the text, and a click clears it. On fix(app): keep side panel terminals alive across panel and thread switches #7726 the highlight stayed but getSelection() returned an empty string.

Replay and thread-switch return (production builds in headless Chromium, interleaved rounds against main):

Return main This change
300,000 lines printed while hidden (8 runs) median 215 ms to the final screen, 4-5 partial screens median 166 ms, 0 partial screens
Reload with a 512 KB replay (32 runs) median 731 ms, 2-6 partial screens median 697 ms, 0 partial screens
Thread switch to a parked terminal (22 runs) median 269 ms to the final screen median 148 ms
  • No replay write is a long task in either build (CDP traces).
  • Long tasks on a thread-switch return: before the three thread-switch fixes, 22 of 22 returns had one (median 78.5 ms). After them, 11 of 22 (median 26 ms, max 67-92 ms), against 8 of 22 on main (max 65 ms). These rounds ran on a loaded host (load average 5 to 19), where main's own switch task is just under 50 ms.
  • Tests in ThreadTerminalView.replay.test.tsx and ThreadTerminalView.keepalive.test.tsx, each shown to fail without its fix: the replay stays hidden until its last chunk has rendered, also after a sequence gap; the theme is not rebuilt on a remount with the same theme, and a theme change made while parked is applied on return; document.fonts.ready is not read again on remount, and a font load while parked is measured on return; the reattach happens in the next animation frame, and an unmount before that frame keeps the terminal parked.
  • pnpm exec turbo run typecheck test lint --filter=@bb/app --filter=@bb/client-core: typecheck and lint pass, @bb/client-core 244 of 244, terminal tests 113 of 113. In the full @bb/app run, UpdatePluginDialog.test.tsx fails on the date text with a non-US locale, as on main, and two lazy-import tests timed out under load and pass alone.

Not changed here:

  • If a hidden terminal prints more than the 512 KB replay limit, the return still resets the terminal and transfers the last 512 KB, as on main, but the screen stays hidden until the replay is complete.

  • After a resize while parked, the first frame of the return shows the old row count, and the correct size follows 30-60 ms later. xterm pauses rendering while the screen is detached and applies the resize when it resumes.
    WebKit on macOS (Playwright WebKit 26.0, WebGL renderer) and iOS 27 Simulator Safari on iPad:

  • 0 open terminal sockets while hidden. A return opens one socket that receives only attached (452 bytes), against 26 output messages and 339 KB on main. The first frame after the return is the final screen. After a resize while hidden the size is correct, and input works.

  • A selection survives a panel-tab switch. It does not survive a thread switch with a real mouse click: the pointer-down dismisses the "Add to chat" selection menu, and its dismiss handler clears the terminal selection before the terminal parks. On iPad the on-screen keyboard closes and opens again on a return, which changes the row count and clears the selection. Both also happen on main.
    macOS desktop app (packaged with pnpm desktop:worktree, Electron 44.10.2, Chromium 152, Apple M4 Pro, 120 Hz), WebGL renderer, every frame captured from the return click:

  • Panel-tab return: attached only (455 bytes), and the first frame is the final screen at 33-44 ms. main replays 24-26 output messages (339 KB) and shows 6-8 frames before the final screen at 112-142 ms.

  • Thread-switch return: the first terminal frame is the final screen at 90-103 ms (main: 192-194 ms).

  • 20,000 lines printed while hidden: 0 messages while hidden, 140 KB on return, final screen at 45-48 ms (main: 481 KB, 139-158 ms).

  • After a resize while hidden, the size is correct (tput 78x52, as on main), but the first frame shows the old-size image cut to the new size for one frame (about 9 ms at 120 Hz).

macOS verification: On macOS (Apple M4 Pro, macOS 27.0.1), main and this change were compared in Playwright WebKit 26.0, iOS 27 Simulator Safari on iPad, and the packaged desktop app (Electron 44.10.2, WebGL renderer). Rounds were interleaved and started only at 94% CPU idle or more. A reload with a 512 KB replay drew 0 partial screens in 30 of 30 runs (main: 1-9 per run). Input typed during a replay reached the shell in 22 of 22 runs (main: 0 of 22, the input was dropped). A thread-switch return showed the final screen in the first frame in 60 of 60 runs, at a median of 82 ms (desktop app), 152 ms (WebKit) and 121 ms (iPad), against 163, 252 and 331 ms on main. No long task occurred on a return in the desktop app (24 runs per build). A theme change made while the terminal was parked was applied on return in 16 of 16 runs. Known limits: if output is still printing when the terminal parks, the return first shows the parked screen until the attached message arrives (36-44 ms in the desktop app). After a resize while parked, the first 1-2 frames show the old size.

Fixes #7724

AGENT GENERATED

ymichael added a commit that referenced this pull request Nov 20, 2026
## Human comments

## What was wrong

`ThreadSecondaryPanel` only mounted `SidebarSplitContainer` once the
thread's fixed tabs were ready (`areFixedTabsReady`). Until then it
rendered the flat panel surface. On a thread switch, readiness is false
on the first render: plugin tabs report visibility from layout effects,
and since #7878 a thread also waits for its saved thread tabs
(`useThreadTabs`) to load. When readiness arrived, the panel replaced
the flat surface with the split container, and React mounted all panel
content a second time. The same swap ran whenever readiness dropped
mid-session, for example while a plugin that owns a saved tab reloads.
The gate came from #6013. It keeps a saved split layout from being
parsed, and overwritten, against an incomplete tab list.

## What changed

- `ThreadSecondaryPanel` mounts `SidebarSplitContainer` right away and
passes readiness down as `isTabListReady`. There is no flat-to-split
swap, so content mounts once on a switch and stays mounted through
plugin reloads.
- `SidebarSplitContainer` (new required `isTabListReady` prop): if it
mounts before the tab list is ready and a saved layout exists, it
renders a best-effort layout from the available tabs, skips persistence
so the saved value stays intact, and restores the saved layout once the
list is ready. With no saved layout it uses the deterministic default
layout, so nothing remounts when tabs arrive.
- No skeleton is shown on a switch. The first version of this PR held
the panel behind `SecondaryPanelContentSkeleton`. After #7878 that
skeleton painted for one thread-tabs fetch on every first visit to a
thread: 33 ms locally and 333 ms with 150 ms of added latency, with no
tab bar or close button.
- The drawer path is unchanged.

## How you verified

- `ThreadSecondaryPanel.threadSwitch.test.tsx` uses the real
`useThreadFixedTabs`, a real plugin tab registration and a stubbed
`sdk.threads.tabs.get`. Content mounts once per switch for Info and an
open file. Content stays mounted with no skeleton while a saved tab's
owning plugin reloads, for Info, an open file and a plugin tab. These
five tests fail with main's `ThreadSecondaryPanel.tsx` and
`SidebarSplitContainer.tsx` (`expected [ 'info:thr_b', 'info:thr_b' ] to
deeply equal [ 'info:thr_b' ]`). Further tests check that panel content
shows while saved tabs load and that a reloaded plugin tab stays
selected.
- The existing saved-split test in
`ThreadSecondaryPanel.collapseControl.test.tsx` passes: the stored split
survives while visibility resolves and is restored afterwards. It now
seeds the thread's `lastUsedAt`, because the container mounts earlier
and `pruneSidebarSplitStorage` drops splits for threads without one.
- `pnpm exec turbo run typecheck lint --filter=@bb/app` passes. The
`secondary-panel/`, `plugin/` and `thread-detail/` suites pass, apart
from two failures unrelated to this change: a lazy-loading test that
times out under load and passes alone, and a `branding.icon` test that
reads leftover untracked plugin directories in this checkout.
- Live, headless Chromium at 1600x1000 on `pnpm start:worktree`:
- Repeated switches, Info or Diff active, 30 each: 1 panel chrome
insertion per switch (main: 2). Click-to-paint median 16 ms both ways.
- First visit to a thread after a reload, 4 runs each at 0 ms and 150 ms
added latency: 1 insertion, 0 skeleton frames.
- Saved Info | Diff split, first visit after a reload, at 0 ms and 150
ms: the panel shows Info, then restores both panes. The stored layout is
unchanged and no skeleton frames paint.
- Disabling and re-enabling the Git plugin and another plugin with the
panel open: 0 panel remounts, 0 skeleton frames.
- Main-thread CPU per switch, measured on the pre-#7878 base (main: 1
run, branch: 2 runs): Info 50 ms on main vs 45–47 ms on the branch, Diff
92 ms vs 80–84 ms.

Related: #7801. With that change, the duplicate mount opened one extra
short-lived terminal socket per thread switch.

Fixes #7802

> AGENT GENERATED

---------

Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
danteregis and others added 8 commits November 24, 2026 11:49
…put sequence

A parked terminal kept its WebSocket open and only sent visibility false.
The server uses visibility only to stop that socket from governing PTY flow
control. It still forwarded every output chunk, so each hidden terminal
streamed output that nobody saw.

TerminalWebSocketTransport.suspend() now closes the socket, stops the
heartbeat and reconnect timers, and keeps nextOutputSeq and the last
resize. A remount calls start(), which connects with sinceSeq set to that
sequence through the same path a reconnect uses. The server then sends only
the output the parked terminal missed. A gap above the 512 KB replay cap
goes through the existing sequence-gap path.

The parked runtime cache moves to apps/app/src/lib, so the terminal cache
owner no longer imports from components. The cache stores a disposable
runtime, and the view narrows it with instanceof TerminalRuntime instead
of an unchecked cast.
Parking cleared the xterm selection. The xterm DOM renderer does not update
its selection render model when the selection is cleared, so the next resize
drew the old highlight again with no text selected. After a return the user
saw a highlight that copy and the selection menu ignored.

Parking no longer clears the selection. The terminal comes back with the
selection the user left, and the highlight matches the selected text.
Each return to a parked terminal had one long task. A CPU profile of an
unminified build showed that the theme effect ran buildTerminalTheme on
every remount: it reads 22 CSS variables, and each read forces a style
recalculation. The effect then set terminal.options.theme again, with
values that had not changed. On main this effect ran before the
asynchronous terminal creation and found no terminal. A parked terminal
attaches synchronously in the mount effect, so the theme effect found it
every time.

The runtime now records the theme key (preferred theme and app theme
epoch) that its theme was built for. The effect rebuilds the theme only
when the current key is different. A theme change while the terminal is
parked is applied when it remounts.
After the theme fix, a trace of the unminified build still showed two
forced style and layout passes in each thread switch to a parked terminal.
Both came from observeTerminalFontLoading, which attachRuntime called on
every attach. Reading document.fonts.ready after the promise has resolved
makes Chromium update style and layout synchronously. The resolved promise
then called forceTerminalFontMeasurement in the same task, so each return
measured fonts that were already measured.

The runtime now observes font loading from creation until it is disposed.
A font load while the terminal is attached measures and fits it, as before.
A font load while the terminal is parked sets fontsLoadedWhileParked, and
the next attach measures the font and schedules a fit.
After the theme and font fixes, each thread switch to a parked terminal
still had a long task. The reattach ran inside the React commit of the
thread switch: it appended the terminal element, forced a style and layout
pass to fit it, refreshed all rows, and started the socket. On main this
work does not happen in that task, because the new terminal is created
after its modules load.

The mount effect now takes the parked runtime and attaches it in a
requestAnimationFrame callback. The callback runs before the first frame
after the commit paints, so the terminal is in that frame, and its style
and layout are part of the layout that the frame does anyway. If the view
unmounts before the frame, the frame is cancelled and the runtime goes back
to the parked cache. attachRuntime now also applies a theme change made
while the terminal was parked, because the theme effect runs before the
attach.
When a terminal attaches with history, the server sends the replay as many
output messages. The view wrote each message to the visible terminal, so the
user saw several partial screens scroll past before the final screen. A gap
above the 512 KB replay cap also reset the terminal and showed the
unavailable-output notice as one more screen.

The view now hides .xterm-screen when an attached message announces a
replay (replayStartSeq < nextSeq) or when the transport reports a sequence
gap. Each replay chunk is still a separate xterm write, so no parse task is
larger than before. After the write callback of the chunk before nextSeq,
the view forces a render and shows the screen in that render. Later live
output, an error, or an exit also shows the screen. A version counter stops
a callback from an older replay from showing a newer hidden replay.

The sequence-gap reset is now an RIS in the write stream, so it runs after
writes that are already queued.

Replay suppression used to drop all terminal data while a replay write was
queued, which also dropped keyboard, paste, and IME input. The view now
registers parser handlers for the terminal queries that make xterm send a
reply (DA, DSR, XTVERSION, DECRQM, window reports, kitty keyboard query,
DECRQSS, and OSC color queries). Only a reply that one of these queries
makes while it parses replay output is dropped. User input during a replay
goes to the PTY.
get-bb#7888 added an app command key handler to the terminal that reads the
dispatcher through a ref of the view that created the terminal. A
parked terminal outlives that view, so the handler is wired through the
runtime's live bindings, which each remounted view replaces. This test
fails when the handler keeps the dispatcher ref of the first view.
@lanjak
lanjak force-pushed the fix-7724-terminal-keepalive branch from 6d1907f to 44ed709 Compare November 24, 2026 00:58

This branch has not been deployed

No deployments
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.

Terminal reconnects and replays its history every time you return to its side-panel tab

2 participants