#7724 · Panel selection tears down terminal client sessions
Trusted base: 7889bd2b5d960b6a414d0708e8bae06ddc9d95a2 (origin/main, fetched and compared with the target repository).
Verdict: PARTIALLY REPRODUCED · Root-cause confidence: high · Reproduction label: partial-repro
1. TL;DR
Selecting another side-panel tab unmounts the terminal content instead of retaining its client session. A behavioral regression against the real secondary-panel component starts the same content twice and cleans it up once after a round trip; this fails the expected single-mount assertion in two separate trusted checkouts. Separately, two fresh instances of the production WebSocket transport each request sinceSeq=0 and receive the same roughly 518 KB of actual retained terminal output, verified against two fresh local server/daemon instances. The source connects these observations: terminal cleanup disposes xterm and its transport, and the next mount recreates both. The exact visible scrolling, elapsed return delay, and macOS desktop/thread-navigation journey were not driven, so this is deliberately a partial rather than full end-to-end reproduction.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Inactive terminal tabs lose their mounted client content. | Verified | The real panel rendered with two terminal tabs produces two mount effects and one cleanup after selecting the other tab and returning. Both clean-main runs fail identically. |
| Recreating the transport causes retained output to be replayed. | Verified | Both live server runs send identical retained bytes to two successive new production transports. Both socket requests start at sequence zero. |
| The terminal process itself restarts. | Not established; not required | The live checks attach twice to one still-running terminal ID. The server-side shell survives; the client renderer and connection are the objects recreated. |
| The desktop visibly scrolls while returning to the terminal. | Unverified visually | No Chrome/Chromium executable was available on the isolated execution host. The production writer queues each replay chunk into xterm, but no timing claim or screenshot is inferred from this alone. |
| Switching to another thread has the same effect. | Source-supported; not driven end to end | The terminal effect cleans up on unmount or changed session identity. The desktop thread-navigation journey was not exercised. |
| Hiding replay alone makes returning instant. | Not supported | Hiding pixels would not avoid creating a new transport or receiving its replay. No proposed patch from issue data was executed. |
3. Environment
- Public repository
get-bb/bb; trusted base above, unchanged by the final main fetch. - Linux, kernel
4.19.0-gvisor; Nodev22.19.0; pnpm9.15.0; Vitest4.1.12; jsdom for panel behavior. The panel harness uses its compact/drawer presentation, not a complete desktop window; selected-content rendering is shared. - Two separate source checkouts at the same commit. The second was created detached from
origin/mainbefore installing dependencies or adding the reproduction test. Only investigator-authored reproduction files were added to the relevant application sources. - Frozen dependency installation and full Turbo build succeeded in each checkout. The plugin SDK runtime/types had to be built first after the initial build exposed missing SDK output.
- First isolated server/daemon: loopback ports
47124/47125, fresh$QA_WORK/data-first. Second:47224/47225, fresh$QA_WORK/data-second.$QA_WORKdenotes an investigator-created temporary directory, not production data. - No provider turn was executed. One future-scheduled synthetic thread was created for a browser attempt, then removed during cleanup; wire checks used host-scoped terminals in a fresh scratch repository.
- The reported macOS release/environment was not separately installed or verified. No user instance, production data, issue-supplied script, or linked-PR code was used.
4. Minimal reproduction
A. Panel lifecycle regression
- Use the trusted base commit, install frozen dependencies, and build the existing SDK artifacts and repository:
git clone https://github.com/get-bb/bb.git bb-7724 cd bb-7724 git checkout --detach 7889bd2b5d960b6a414d0708e8bae06ddc9d95a2 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build
- Save the complete test below as
apps/app/src/components/secondary-panel/ThreadSecondaryPanel.terminal-lifecycle.test.tsx. The probe observes mount/cleanup at the real panel boundary; it is not an xterm mock and does not claim to verify raster output. No production export or test-only seam is introduced. - Run:
pnpm exec turbo run test --filter=@bb/app -- src/components/secondary-panel/ThreadSecondaryPanel.terminal-lifecycle.test.tsx
Expected versus actual, identical in both checkouts:
Expected: { starts: 1, stops: 0 }
Received: { starts: 2, stops: 1 }
AssertionError: expected { starts: 2, stops: 1 } to deeply equal { starts: 1, stops: +0 }
Test Files 1 failed (1)
Tests 1 failed (1)
Complete behavioral regression test
// @vitest-environment jsdom
import { cleanup, render, screen } from "@testing-library/react";
import { useEffect, useState } from "react";
import { afterEach, expect, it } from "vitest";
import { Panel, PanelGroup } from "react-resizable-panels";
import { TooltipProvider } from "@bb/shared-ui/tooltip";
import { createTerminalFixedPanelTab } from "@/lib/fixed-panel-tabs-state";
import { createQueryClientTestHarness } from "@/test/queryClientTestHarness";
import { ThreadSecondaryPanel } from "./ThreadSecondaryPanel";
import type { SecondaryPanelRenderableTab } from "./secondaryPanelTab";
afterEach(() => {
cleanup();
window.localStorage.clear();
});
const noop = () => {};
const { wrapper: Wrapper } = createQueryClientTestHarness();
it("preserves a terminal session when another panel tab is selected", () => {
let starts = 0;
let stops = 0;
function SessionProbe() {
const [screenText] = useState("last screen before switching tabs");
useEffect(() => {
starts += 1;
return () => {
stops += 1;
};
}, []);
return <output aria-label="Terminal screen">{screenText}</output>;
}
const terminals: SecondaryPanelRenderableTab[] = ["first", "second"].map(
(terminalId) => ({
tab: createTerminalFixedPanelTab({ terminalId }),
label: terminalId,
leadingVisual: null,
statusLabel: null,
onSelect: noop,
onClose: noop,
renderContent: () =>
terminalId === "first" ? <SessionProbe /> : <div>other tab</div>,
}),
);
function panel(activeIndex: number) {
return (
<Wrapper>
<TooltipProvider>
<PanelGroup direction="horizontal">
<Panel id="main" order={1}>main</Panel>
<ThreadSecondaryPanel
activeTab={terminals[activeIndex].tab}
fixedTabs={[]}
tabs={terminals}
isConversationCollapsed={false}
isOpen
metadataContent={null}
onClose={noop}
onCollapse={noop}
onTabReorder={noop}
onOpenNewTab={noop}
onPanelFocus={noop}
onToggleConversationCollapse={noop}
renderAsDrawer
/>
</PanelGroup>
</TooltipProvider>
</Wrapper>
);
}
const view = render(panel(0));
expect(screen.getByLabelText("Terminal screen").textContent).toBe(
"last screen before switching tabs",
);
view.rerender(panel(1));
view.rerender(panel(0));
expect(screen.getByLabelText("Terminal screen").textContent).toBe(
"last screen before switching tabs",
);
expect({ starts, stops }).toEqual({ starts: 1, stops: 0 });
});B. Actual transport replay, without a browser renderer
Save the complete wire-repro.mjs below outside the source tree. Run it from the trusted repository root, which is where it resolves the production transport module. Node's own WebSocket connects to the real isolated server; there is no fake socket or database.
- Choose free loopback ports, set
QA_WORKto a newly created temporary directory, and start the built trusted application. Do not point these commands at a real instance:QA_WORK=$(mktemp -d) BB_SKIP_ONBOARDING=1 node packages/bb-app/dist/bb-app.js --bundled --no-in-app-updates --data-dir "$QA_WORK/data-first" --server-port 47124 --host-daemon-port 47125
- In another shell at the same source root, clear inherited thread/CLI context, point the source CLI explicitly to this instance, and list its host:
unset BB_THREAD_ID BB_ENVIRONMENT_ID BB_THREAD_STORAGE BB_PROJECT_ID BB_CLI BB_CLI_REEXEC export BB_SERVER_URL=http://127.0.0.1:47124 BB_HOST_DAEMON_PORT=47125 node apps/cli/dist/index.js machine list --json git init "$QA_WORK/scratch" node apps/cli/dist/index.js terminal create --machine "$QA_HOST_ID" --cwd "$QA_WORK/scratch" --title 'QA retained stream' --json
SetQA_HOST_IDfrom the host listing before creating the terminal, andQA_TERMINAL_IDfrom the creation response. Keep the sameQA_WORKvalue in both shells. - Generate controlled output once and wait for the prompt:
node apps/cli/dist/index.js terminal send "$QA_TERMINAL_ID" --text "node -e 'for (let row = 0; row < 20000; row += 1) console.log(\"terminal lifecycle sample \" + row);'" --enter --json node apps/cli/dist/index.js terminal wait "$QA_TERMINAL_ID" --help node --conditions=source --import tsx /path/to/wire-repro.mjs 47124 "$QA_TERMINAL_ID"
The helper finishes only after the attached replay's last sequence has arrived. Its assertions require nonempty substantial output and matching byte hashes across successive attachments.
Observed wire results:
First isolated instance, attachment 1 and attachment 2: sinceSeq = 0; outputMessages = 23; replayBytes = 518405 firstSeq = 14; nextSeq = 37 sha256 = 0f22af23e16b0b61c9604de60a0239b08e694c049ed3335807980722568de910 Second isolated instance, attachment 1 and attachment 2: sinceSeq = 0; outputMessages = 25; replayBytes = 517989 firstSeq = 14; nextSeq = 39 sha256 = 85444ea6b8f27390d7807a704356690d5608c553ca52a4a1091db77ca850f3d8 Two fresh transports replayed the identical retained output from sinceSeq=0.
Chunk counts and hashes can vary between fresh terminal sessions because PTY chunk boundaries vary. Within each run, both attachments received byte-for-byte identical retained output. A retained client should not need a second attach at all; this helper intentionally recreates the transport to isolate what the real unmount would trigger.
Complete real-transport replay helper
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
const { TerminalWebSocketTransport } = await import(pathToFileURL(resolve(
process.cwd(),
"packages/client-core/src/terminal/terminal-websocket-transport.ts",
)).href);
const [port, terminalId] = process.argv.slice(2, 4);
const url = "ws://127.0.0.1:" + port + "/ws/terminals/" + terminalId;
const attachments = [];
async function attach() {
const socketUrls = [];
const chunks = [];
let replayEnd = null;
let complete;
let fail;
const finished = new Promise((resolve, reject) => {
complete = resolve;
fail = reject;
});
const timeout = setTimeout(() => fail(new Error("Replay did not finish")), 10000);
const transport = new TerminalWebSocketTransport({
url,
shouldReconnect: () => false,
createSocket: (socketUrl) => {
socketUrls.push(socketUrl);
return new WebSocket(socketUrl);
},
onMessage: (message) => {
if (message.type === "error") fail(new Error(message.message));
if (message.type === "attached") {
replayEnd = message.nextSeq;
if (message.replayStartSeq === replayEnd) complete();
}
if (message.type === "output") {
chunks.push({ seq: message.chunk.seq, bytes: Buffer.from(message.chunk.dataBase64, "base64") });
transport.acknowledgeOutput(message.chunk.seq + 1);
if (message.chunk.seq + 1 === replayEnd) complete();
}
},
});
try {
transport.start();
await finished;
const output = Buffer.concat(chunks.map((chunk) => chunk.bytes));
assert.ok(output.length > 0, "terminal must have output to replay");
return {
sinceSeq: new URL(socketUrls[0]).searchParams.get("sinceSeq"),
outputMessages: chunks.length,
replayBytes: output.length,
firstSeq: chunks[0].seq,
nextSeq: replayEnd,
sha256: createHash("sha256").update(output).digest("hex"),
};
} finally {
clearTimeout(timeout);
transport.dispose();
}
}
attachments.push(await attach(), await attach());
console.log(JSON.stringify({ attachments }, null, 2));
assert.equal(attachments[0].sinceSeq, "0");
assert.equal(attachments[1].sinceSeq, "0");
assert.equal(attachments[0].sha256, attachments[1].sha256);
assert.ok(attachments[1].replayBytes > 100000);
console.log("Two fresh transports replayed the identical retained output from sinceSeq=0.");Visual limit: the local Browser Automation plugin could not open a browser: Install Chrome/Chromium on this host or link its executable at the plugin data runtime/chrome path. An existing browser on a different host could not reach this isolated loopback server. No browser dependency was added and no simulated screenshot was substituted. Consequently the visible animation and exact return latency remain unverified.
5. Root cause
The client lifetime is incorrectly tied to selected panel content. The session and retained output exist on the server/daemon, but the xterm screen buffer and browser transport are local to one mounted terminal view.
- The panel renders only its active non-browser tab:
const surfaceContent = activeSurfaceTab === null || isBrowserSurfaceActive || holdsPanelContent ? null : activeSurfaceTab.renderContent(paneRenderContext);Changing to another tab therefore removes the terminal content from that surface. This is what the behavioral test observes. - The terminal effect cleanup destroys both client resources:
transport?.dispose(); terminal?.dispose(); terminalRef.current = null;
The effect returns that cleanup and is keyed by session identity. Thread changes that replace the owning view or session consequently cannot retain this client through the existing effect. - A mount creates a new xterm terminal and a new transport. Each transport starts at output sequence zero; connect builds its socket URL from that sequence. Both live checks confirm the zero-offset reattach.
- Browser attachment asks the daemon for a bounded tail. The limit is 512 × 1024 bytes. Completion sends attached metadata followed by output chunks. This is an ordinary attach/replay, not evidence that the PTY restarted.
- Replay still calls xterm's writer, and each received output message is decoded and written. That explains why a newly visible empty renderer can paint history while the replay arrives, though this run does not measure its paint timing.
The browser deck has a separate retained rendering path. Adding keepMounted to a child loader alone cannot prevent unmount when its parent stops rendering that loader.
6. Proposed fix and simple-fix gate
Separate terminal client ownership from the currently selected panel/thread view. Retain xterm and its active transport by terminal identity while hiding or reparenting presentation; notify the transport of visibility changes, re-fit on show, and avoid stale focus/selection/link callbacks when another thread owns the visible surface. Dispose on terminal closure and define bounded eviction/cleanup for hidden sessions so repeated thread navigation cannot accumulate renderers, sockets, or WebGL contexts indefinitely. Saving only the sequence cursor is insufficient because a newly created xterm would lack the prior screen buffer.
No production fix or PR was attempted. A tab-only retention change cannot address thread-navigation lifetime. Selecting the cross-thread owner and its eviction/cleanup policy is an architecture/lifecycle decision, which fails this rule's simple-fix condition even if a small patch could hide one symptom. The exact desktop journey is also unverified. The failing test is preserved inline as evidence, not landed as a failing repository test.
No linked open PR or matching open PR was found in the issue timeline and GitHub search. A closed, unmerged proposal appeared during the final metadata check; its diff was read only, as described below. No PR branch was checked out or executed.
7. Linked proposal: static review only
PR #7726 was closed, unmerged, on November 17, 2026. GitHub metadata reports 591 additions, 214 deletions, and seven changed files. This PR was discovered after the trusted-main reproduction and read as untrusted metadata/diff only; none of its code or tests were run.
The diff moves xterm and its transport into a reusable runtime, parks it when the view unmounts, reattaches it on remount, and adds close/missing-session cleanup. Its proposed cache limits parked runtimes to eight. That direction addresses client lifetime rather than simply hiding replay, which matches the independently observed root cause. It also illustrates the additional ownership, callback, visibility, eviction, and cleanup contracts that make this more than a loader flag.
Assessment: directionally relevant, not a verified fix or approval. The added view test shown in the diff mocks the transport, so it does not by itself establish the reported desktop route/tab journey or real-socket safety; no severity-rated implementation defect is asserted from this limited review. End-to-end navigation, stale callbacks, hidden-session output/flow control, terminal restart, and eviction disposal remain verification requirements. The closed proposal was not copied into a new fix.
8. Verification
The same investigator repeated both checks, not an independent verifier. A second temporary detached checkout was created at the exact base commit with fresh dependencies/build outputs. It received only the same authored behavioral test; unchanged production code failed with the same {starts: 2, stops: 1} result. A new server/daemon and new temporary data directory at ports 47224/47225 reproduced zero-offset attachment and identical retained output across two fresh transports. This supports the final lifecycle/replay findings; no findings were upgraded to a desktop visual reproduction.
Relevant existing tests also passed on the first trusted checkout:
pnpm exec turbo run test --filter=@bb/app -- src/components/secondary-panel/ThreadSecondaryPanel.tabVisible.test.tsx src/components/secondary-panel/ThreadSecondaryPanel.markdown-scroll.test.tsx src/components/secondary-panel/split-demand.test.tsx src/components/thread/terminal/ThreadTerminalView.test.ts Test Files 4 passed (4) Tests 40 passed (40) pnpm exec turbo run test --filter=@bb/client-core -- test/terminal-websocket-transport.test.ts Test Files 1 passed (1) Tests 11 passed (11)
These existing suites do not cover keeping a terminal client alive across inactive-tab selection; the new regression is a distinct panel-lifetime assertion. Both wire helpers passed against real SQLite-backed fresh instances.
9. Related issues
- #1075 is closed and concerns terminal reopen/sustained-output behavior. The current bounded replay limits bytes but does not stop the remount observed here.
- #6162 remains open and concerns diff-panel scroll retention. It shares a selected-content lifetime boundary but is not itself a terminal session regression.
10. Appendix and safety
Issue text and links were treated as untrusted claims. Only trusted-main code, existing build tools, and investigator-authored reproduction files were executed. Source evidence was read locally and links were constructed from verified repository paths at the recorded commit. No issue-proposed patch or command was run, and no linked PR was executed. The report is public and intentionally excludes machine identities, actual temporary-directory identifiers, runtime session IDs, credentials, API dumps, and raw logs. Repository report policy requires reproduction sources inline rather than committed artifact directories.
The initial all-package build failed on missing SDK artifacts; explicitly building the existing SDK resolved that setup failure, and both complete builds then passed. An initial transport-suite command used the wrong test directory and discovered no tests; the corrected test/terminal-websocket-transport.test.ts command passed all 11 cases. Neither setup issue was counted as product evidence. Source history/blame confirmed selected-content rendering and terminal cleanup are existing main behavior, not changes introduced by the reproduction.
All started isolated processes and terminals were stopped after evidence collection. No production code change, dependency addition, GitHub fix branch, or pull request is part of this report.