Repository navigation
Keep side-panel terminals alive across panel and thread switches without streaming to hidden ones - #7801
Open
lanjak wants to merge 8 commits into
Open
Keep side-panel terminals alive across panel and thread switches without streaming to hidden ones#7801lanjak wants to merge 8 commits into
lanjak wants to merge 8 commits into
Conversation
This was referenced Nov 18, 2026
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]>
…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
force-pushed
the
fix-7724-terminal-keepalive
branch
from
November 24, 2026 00:58
6d1907f to
44ed709
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
The secondary panel unmounts a terminal when the user selects another panel tab or another thread.
ThreadTerminalViewthen disposed its xterm instance and its WebSocket transport. On return, a new transport connected withsinceSeq=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:
visibility: false. The server uses visibility only to decide if a socket governs PTY flow control (terminal-output-flow-control.ts,isGoverning).forwardTerminalOutputinterminal-session-lifecycle.tsstill sends every output chunk to every attached socket. So each hidden terminal received all of its output. In a test, a hidden terminal that ranseq 1 300000received 56 output messages (2.29 MB) that nobody saw.terminal-cache-owner.ts(hooks) imported from@/components/..., andtakeParkedTerminalRuntimereturned an uncheckedas Rcast.What changed
packages/client-core/src/terminal/terminal-websocket-transport.ts: newsuspend(). It closes the socket and stops the heartbeat, drain and reconnect timers. It keepsnextOutputSeq, the last resize and queued input.start()aftersuspend()connects withsinceSeqset to the next output sequence. This is the same path that a reconnect uses.ThreadTerminalView.tsx: parking callstransport.suspend()instead ofsetVisible(false). Attaching a parked runtime callstransport.start(). Parking no longer clears the selection. The runtime is a smallTerminalRuntimeclass, so the view narrows a parked runtime withinstanceofand does not cast it.ThreadTerminalView.tsx: this change removes the check that disposed a parked runtime on anexitedmessage, 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 fromcomponents/thread/terminal/): storesParkedTerminalRuntimevalues (dispose()only) with no type parameter and no cast.terminal-cache-owner.tsimports 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.HOST_DAEMON_PROTOCOL_VERSIONdoes not change. No CLI, guide or doc change.ThreadTerminalView.tsx, replay: whenattachedannounces a replay (replayStartSeq < nextSeq) or the transport reports a sequence gap, the view hides.xterm-screenand 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 readdocument.fonts.readyagain, 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 arequestAnimationFramecallback, 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 aftersuspend(), thenstart()usessinceSeq=2and 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'.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 exceptUpdatePluginDialog.test.tsx"opens persisted failure details", which fails the same way on unchangedmainon 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, runseq 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.mainoutput, 339 KB, 5 screens drawn, final screen at 163 msoutput(441 bytes,attachedonly), final screen at 106 ms, first screen is the final screenoutput, 339 KB, 7 screens drawnoutput, 441 bytesoutput, 479 KB on returnoutput, 140 KB while hiddenoutput, 140 KB on return, first screen is the final screenoutput, 524 KB on returnoutput, 2.29 MB while hiddenoutput, 498 KB on return (sequence gap, same asmain)Also checked in the browser:
tput cols; tput linesprinted60 46on all three builds, and the xterm screen fits the panel.getSelection()returned an empty string.Replay and thread-switch return (production builds in headless Chromium, interleaved rounds against
main):mainmain(max 65 ms). These rounds ran on a loaded host (load average 5 to 19), wheremain's own switch task is just under 50 ms.ThreadTerminalView.replay.test.tsxandThreadTerminalView.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.readyis 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-core244 of 244, terminal tests 113 of 113. In the full@bb/apprun,UpdatePluginDialog.test.tsxfails on the date text with a non-US locale, as onmain, 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 26outputmessages and 339 KB onmain. 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:
attachedonly (455 bytes), and the first frame is the final screen at 33-44 ms.mainreplays 24-26outputmessages (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 (
tput78x52, as onmain), 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
attachedmessage arrives (36-44 ms in the desktop app). After a resize while parked, the first 1-2 frames show the old size.Fixes #7724