Skip to content

Build test databases from one template, share test setup, and move DOM-free tests out of jsdom - #5261

Merged
ymichael merged 10 commits into
mainfrom
bb/test-setup-consolidation-v1-thr_tiev9nbusz
Oct 14, 2026
Merged

ymichael merged 10 commits into
mainfrom
bb/test-setup-consolidation-v1-thr_tiev9nbusz

Conversation

@ymichael

@ymichael ymichael commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Test time went to repeated setup, not to the tests themselves. Server tests ran all migrations against a fresh :memory: database per test, even though a cached-template helper already existed: 607 migrate calls and about 58 s of CPU per @bb/server run, at about 80 ms each against 0.4 ms to deserialize a template. Small helpers were copied per file (makeTempDir ×45, initRepo ×9, LocationProbe ×12, deferred and jsonResponse copies), react-resizable-panels was mocked 9 times, and the two ThreadDetailPromptArea test files duplicated 21 module mocks. A handful of tests (listed below) asserted guide prose or restated the implementation.

In the app and plugins, every jsdom test file pays about 3.8 s of fixed cost (environment 1.7 s, imports 1.4 s, setup 0.3 s) before 0.44 s of tests. A mutation audit of all 496 jsdom files found most of them are the only guard on DOM behavior (keyboard, IME and focus paths, portals, observers, iframe sandboxes, stale-response races tied to fix commits), but about 100 ran in jsdom for logic that needs no DOM, 14 duplicated stronger tests, about 50 passed for the wrong reason, and about 110 restated inventories, class tokens or library behavior.

What changed

Eight original commits plus rebase integration fixes. Commits 1–6 touch test code and test support only. Commits 7–8 also change production code, but only to extract logic into functions the component or hook still calls (behavior-preserving, reviewed for parity below).

  1. One migrated template database. @bb/db/testing exports createMigratedConnection() and prepareMigratedConnectionTemplate(). The db and server globalSetup build the template once and hand it to workers through BB_TEST_MIGRATED_DB_TEMPLATE, so isolated files deserialize instead of re-migrating. Full-schema setup sites in apps/server and packages/scripts use it. A guard test in apps/server fails on new migrate( calls in its tests. Three files keep raw migrate on purpose: an empty pre-migration schema, child-process scripts, and a 0117 backfill replay that reads migrate's TEMP table. Still a real SQLite database built by the real migrations.

  2. Shared small helpers. @bb/test-helpers gains makeTempDir/makeTempDirSync (cleanup through onTestFinished, with the Windows retry budget from Run every test suite on Windows CI #4776) and initRepo. Local deferred copies use createDeferredPromise, and jsonResponse copies use Response.json. apps/app gets one LocationProbe, two shared react-resizable-panels modules (real browser build, layout stub) and one shared question-shortcut system-queries mock. plugins/theme-preview/server.test.ts uses the SDK fake host instead of 8 as unknown as BbPluginApi casts. @/lib/sdk and system-queries factories were not added: 57 of 61 and 31 of 35 blocks are distinct, so a factory would only move code. Plugins keep local copies (forkable rule).

  3. Shared ThreadDetailPromptArea harness (apps/app/src/test/thread-detail-prompt-area-harness.tsx). The two "every atom returns 40" jotai mocks became a store with secondaryPanelWidthPercentAtom set. Changing it to 33 fails 2 and 1 tests, so the store is load-bearing.

  4. Evidence-backed deletions, each checked against the test-audit skill and with mutation checks:

    • Deleted: prose-matching tests in plugin-authoring-docs.test.ts (4) and submit-a-plugin.test.ts (4), and create-via-prompt-examples.test.ts, which built its expectations with the same map the code uses (getCreateExamples is now un-exported).
    • Trimmed: colour and size class assertions in SecondaryPanelTabStrip.test.ts. Visibility, no-drag and touch-target assertions stay.
    • Replaced: MachineLabel.test.tsx now covers an ephemeral host whose provider is not loaded instead of the trivial persistent branch.
    • Kept after the mutation check showed they were the only guard: route-loading-skeleton.test.tsx, the release-approval/--ignore-scripts skill test, and the changelog footer colour pair.
  5. pnpm exec turbo run bench runs the three opt-in benchmarks (sidebar, composer paste, watcher recovery), documented in docs/debugging-and-qa.md. Per-file jsdom cost was measured; no config change (below).

  6. createMemoryStorage() in @bb/test-helpers, for node tests that only need localStorage/sessionStorage.

  7. Move DOM-free tests out of jsdom and delete duplicated ones. jsdom test files go from 496 to 403.

    • Pragma only: files that pass unchanged in node drop the jsdom line.
    • Storage only: node tests stub storage with createMemoryStorage() (plugins keep a local copy).
    • TanStack Query hooks with no DOM assertions: option factories are exported and driven with QueryObserver/MutationObserver on a QueryClient.
    • Pure logic inside components and hooks is extracted into functions the component still calls and table-tested in node; hooks that only need React render through renderHookStatically (renderToStaticMarkup).
    • Partial files are split; DOM-needing cases stay in jsdom.
    • 14 files deleted where every catch is also caught elsewhere, the test covers story-only code, or it passes for an unrelated reason; a single unique catch moves into the stronger owner's test.
    • sidebar.bench.test.tsx leaves the default include (bench still runs it). plugin-scaffold-external.test.ts declares the node environment, since a template literal containing the jsdom pragma was selecting jsdom. theme-preview declares the SDK test host's optional peers (better-sqlite3, cron-parser, hono) now that its server test uses the fake host, so its fork installs them.
    • Kept in jsdom on purpose: useThreadSecondaryPanelVisibility (moving it changed callback identities), root-compose-selection (atomWithStorage only hydrates on mount) and plugin-api-tester's smoke test (the plugin fork check runs npm test in every forkable plugin).
  8. Fix tests that passed for the wrong reason and trim junk. About 50 tests now fail when their named guard is removed. Examples: MarketplacesSettingsSection asserted no "Remove BB Official" button against a fixture named "BB Community", so nothing guarded removing the official marketplace. scheduled-send "stays closed in another composer" passed because the second composer's empty draft closed the dialog anyway. Others include clipboard "desktop clipboard first", detail-page-recipes' code-fence split, the plugin install/update "reports once" checks, ThreadDetailHeader's edit-time pane drag and SidebarVisibilityControls' Fix overlapping mobile thread list More menus #4245 overlap. Three tests whose guard cannot be observed at that boundary are deleted. About 110 junk tests are trimmed.

Net vs main after the October 14 rebase: 572 files, +13.6k / −19.0k.

How you verified

Local timings, one package at a time (turbo run test --filter=<pkg> --only --force -- --reporter=json), 16-core macOS shared with other threads (load 10–16):

Package Wall Vitest tests sum
@bb/server 106.6s → 91.6s 532.0s → 398.3s
@bb/app 63.5s → 67.4s 177.7s → 190.1s
@bb/db 5.0s → 6.7s 20.0s → 19.8s
@bb/host-daemon 30.8s → 31.0s 72.7s → 85.6s
@bb/cli 13.4s → 9.0s 40.4s → 35.4s
@bb/scripts 18.6s → 18.2s 31.0s → 31.8s

Only the server change is outside noise. migrate calls per server run went from 607 to 24, and migrate CPU from 58 s to about 2 s. The 51 converted server files went from 201 s to 109 s summed. Largest drops: plugin-catalog-service 13.1 → 1.6 s, third-party-marketplaces 6.3 → 1.2 s.

Per-file jsdom cost (402 isolated files, medians): environment 1.66 s, import 1.42 s, setup file 0.30 s, tests 0.44 s. vmForks was slower on an 80-file sample (13.2–14.3 s vs 10.8–11.1 s) and failed 6 tests. The Vite deps optimizer gave no gain and broke 2 importOriginal mocks. Neither was adopted.

Checks: pnpm exec turbo run lint typecheck test --filter='...[origin/main]' after rebasing onto current main: 246 of 247 tasks passed. The failure was PluginSettings.test.tsx "autosaves the latest text value on blur" at load ~22. That test body is unchanged; the file only swapped its local deferred for createDeferredPromise in other tests. It has failed once in each full parallel run, and a standalone turbo run test --filter=@bb/app --only --force rerun passed (594 files, 5568 tests). The same test passed 8/8 alone and 9/9 under parallel stress on the base commit.

jsdom audit and cleanup (commits 7–8). Audit method per file: read against the test-audit skill, 2–4 realistic mutations of the code under test, then which other test files fail on the same mutation; about 1,500 mutations over 496 files. For every moved file, each unique catch the audit recorded was re-applied: the moved test fails with it and passes without it. Every fix in commit 8 was proven the same way (fails with the mutation, passes after revert).

Behavior parity: three independent reviews read every production diff (82 files) against the old code. No user-visible change. Fixed from the review: an attachment-failure check that had moved one React tick earlier, two no-op state updates while a panel is closed or a folder chain is empty, merged panel-opener callbacks (reverted, see above), and test-only exports (moved into their own modules with production importers, or reached through public hooks). A dead useUiPreferencesReady/isUiPreferencesReady pair with no production caller is deleted.

Known coverage losses: thin hook wiring that now only forwards to extracted functions (thread-list held read status effect and reveal atom setters, a tasks scheduler null-check, the mobile recents collapsed-id filter, the timeline panel's background-agent count). One new React Compiler warning (not error) in plugins/tasks/shell/data.ts, next to five existing ones.

Timing, before (0da6f19) vs after, back to back, two rounds, load 15–19:

Package Wall Vitest file-time sum Files / tests
@bb/app 71 / 73 s → 61 / 66 s 202 / 204 s → 179 / 195 s 605 / 5711 → 602 / 5634
bb-plugin-tasks 6 / 7 s → 5 / 8 s 17 / 21 s → 15 / 21 s 40 / 412 → 37 / 409
bb-plugin-thread-list 4 / 5 s → 5 / 4 s 11 / 13 s → 11 / 12 s 37 / 451 → 35 / 444

Final checks: pnpm exec turbo run lint typecheck test --filter='...[origin/main]' passed every package except @bb/app, which failed on a fixup the rebase had dropped; after restoring it, turbo run lint typecheck test --filter=@bb/app passed (7/7).

PluginSettings.test.tsx "autosaves the latest text value on blur" fails occasionally under heavy parallel load. Its test and component are unchanged from main except the deferred helper swap in other tests of the file. Interleaved stress runs: 0/18 failures on main, 0/18 on this branch.

Windows shard timings were not measured locally; compare them on this PR's CI run.

October 14 rebase: updated onto origin/main at efb7d12f2f (#5494). Conflict resolutions preserve shared temp-directory cleanup retries, mobile queue defaults, project-specific model catalog caching, title-mention regressions, inline-vis preview helpers, and the Plugin Guide code-fence surface. The new HTML-preview routing regression stays in a separate jsdom file; Markdown image routing stays in Node. The new status-cap tests use the shared repository fixture, and WorkspaceChangesList retains main's server-provided total count and omitted-file coverage.

Rebase verification: pnpm exec turbo run lint typecheck test --filter=@bb/app --filter=@bb/host-workspace --filter=bb-plugin-inline-vis --filter=bb-plugin-plugin-api-docs passed lint/typechecks and the host-workspace (161 tests), inline-vis (50 tests), and Plugin Guide (72 tests) suites. The full app run passed 5,691 tests and exposed one HTML-preview static-render failure; after moving that test to jsdom, both preview files passed (6 tests), and app lint/typecheck passed. After including #5494, the workspace list/summary tests passed (10 tests), the host-workspace suite and typecheck passed again, and app typecheck passed. git diff --check passed.

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/test-setup-consolidation-v1-thr_tiev9nbusz branch from f3c9d4e to bf52844 Compare October 10, 2026 05:56
@ymichael ymichael changed the title Build test databases from one migrated template and share test setup Build test databases from one template, share test setup, and move DOM-free tests out of jsdom Oct 10, 2026
@ymichael
ymichael force-pushed the bb/test-setup-consolidation-v1-thr_tiev9nbusz branch 3 times, most recently from e417570 to 315ce26 Compare October 14, 2026 17:34
qa and others added 10 commits October 14, 2026 10:34
Most server tests ran all 143 migrations per test (607 migrate calls, ~58 s of CPU per
server run). `@bb/db/testing` now exposes `createMigratedConnection()`, which copies a
template built once per run in the server and db `globalSetup` and shared with workers
through a file, so isolated files deserialize it as well (0.4 ms instead of ~80 ms).

The server's `createTestDb` and 52 server/scripts call sites move onto it, plus the db
query-plan tests. A server test fails on any new `createConnection(":memory:")` outside
three files that need a fresh migrate. AGENTS.md and the test-audit skill point to the
helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`@bb/test-helpers` gains `makeTempDir`/`makeTempDirSync`, which register their own
cleanup with `onTestFinished`, and `initRepo`. 43 local `makeTempDir` copies and their
`tempDirs` arrays and `afterEach` cleanups go, along with `dispatch-helpers`'
`cleanupTempDirs` and 9 `initRepo` copies. The shared cleanup keeps the Windows retry
budget the host-daemon command tests used.

Local `deferred` helpers move to `createDeferredPromise`, and local `jsonResponse`
helpers to the platform `Response.json`. apps/app gets one `LocationProbe`, shared
`react-resizable-panels` modules (the real browser build and a layout stub), and one
question-shortcut `system-queries` mock. The theme-preview server tests use the SDK fake
host instead of hand-built `BbPluginApi` casts.

Kept local: `server-local.test.ts` (temp dirs from `beforeAll`), forkable plugins (no
`@bb/*` imports), the two `jsonResponse` helpers with different semantics, and the
per-test `@/lib/sdk` mocks (57 distinct shapes in 61 files).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two ThreadDetailPromptArea test files declared 18 of the same mocked modules, most
of the keystroke copies being weaker versions of the main file's. They now import one
harness module; the main file keeps only its `usePromptDraftStorage` mock, since the
keystroke tests drive the real draft storage.

SecondaryPanelLayout and RootComposeSecondaryContent tests mocked jotai so every
`useAtomValue` returned 40. They now render with a store that sets
`secondaryPanelWidthPercentAtom` to 40, and changing that value fails the layout
assertions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each removal was checked against the test-audit skill:

- create-via-prompt-examples: built its expected values with the same
  `BROWSE_ARCHETYPES.map(briefPrompt)` as the code; `getCreateExamples` loses its
  test-only export.
- MachineLabel: covered only the persistent-host branch. It now covers an ephemeral
  machine whose provider presentation is not loaded.
- plugin-authoring-docs (4) and submit-a-plugin (4): exact guide prose. The completeness
  checks stay, and so does the submit-a-plugin release-safety test (lifecycle scripts
  off, publish only after approval), which came from a security review.
- SecondaryPanelTabStrip and UpdatesSettingsSection: colour, border, radius, padding and
  font-weight class assertions. Visibility, layout, touch-target and reduced-motion
  assertions stay, as does the changelog footer's foreground/background pair, which
  keeps its link legible.

Mutation checks kept route-loading-skeleton: it is the only guard on the standalone
bleed margins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`pnpm exec turbo run bench` runs the three opt-in benchmarks that `turbo run test` skips:
the sidebar thread list and composer paste benchmarks in @bb/app, and the root watcher
recovery benchmark in @bb/host-watcher. Each package's bench script sets its own enable
variable. The task is uncached and passes the output and size variables through. Both
packages' benches ran through the task.

docs/ci-performance.md records the measured per-file costs. A median app jsdom file
spends about 0.76 s importing its own graph and 0.5 s loading jsdom in a fresh fork.
`vmForks` and Vite's dependency optimizer were both slower in wall time and broke
tests, so the config is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Node-environment tests that only need localStorage or sessionStorage can
stub it with createMemoryStorage() instead of loading jsdom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An audit of every jsdom test file (mutations of the code under test, then which
test files fail) found most of them guard behavior only a DOM shows, but about
100 run in jsdom for logic that needs none, paying ~1.7 s of environment setup
each. This moves that logic to node tests and deletes the files whose catches
are duplicated elsewhere. jsdom test files go from 496 to 403.

- Pragma only: files that pass unchanged in node drop the jsdom line.
- Storage only: node tests stub `localStorage`/`sessionStorage` with
  `createMemoryStorage()` (plugins keep a local copy).
- TanStack Query hooks with no DOM assertions: option factories are exported
  and driven with `QueryObserver`/`MutationObserver` on a `QueryClient`.
- Pure logic inside components and hooks is extracted into functions the
  component still calls, and table-tested in node. Hooks that only need React
  render through `renderHookStatically` (`renderToStaticMarkup`).
- Partial files are split; the DOM-needing cases stay in jsdom.
- Deleted where every catch is also caught elsewhere, the test covers story-only
  code, or it passes for an unrelated reason; a single unique catch moves into
  the stronger owner's test (e.g. ProviderIcon, openThreadInSplit).
- `sidebar.bench.test.tsx` leaves the default include (`bench` still runs it);
  the templates scaffold test declares the node environment, since a template
  literal containing the jsdom pragma was selecting jsdom.
- theme-preview declares the SDK test host's optional peers (better-sqlite3,
  cron-parser, hono) now that its server test uses the fake host.

Every unique catch the audit recorded for a moved file was re-applied as a
mutation: the moved test fails with it and passes without it. Known losses:
thin hook wiring that now only forwards to extracted functions (held read
status effect, sidebar reveal atom setters, a tasks scheduler null-check).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The same audit found tests that keep passing when the behavior they name is
removed, and tests that only restate inventories, class tokens or library
behavior.

About 50 tests are fixed so they fail when their named guard is removed, each
proven by applying that mutation and reverting it. Examples:
- MarketplacesSettingsSection asserted no "Remove BB Official" button against a
  fixture named "BB Community", so nothing guarded removing the official
  marketplace.
- scheduled-send's "stays closed in another composer" passed because the second
  composer's empty draft closed the dialog anyway.
- clipboard's "desktop clipboard first", detail-page-recipes' code-fence split,
  the plugin install/update "reports once" checks, ThreadDetailHeader's
  edit-time pane drag, TimelineSelectionMenu's flushSync focus, mobile-guide's
  vertical swipe and SidebarVisibilityControls' #4245 overlap.
Three whose guard cannot be observed at that boundary are deleted instead
(sidebar-navigation storage rejection, native-shell bridge version, theme
preview epoch).

About 110 junk tests are trimmed: registration and manifest inventories, class
assertions whose expected value is the constant under test, tests of TipTap,
shared-ui menus or React itself, and duplicates of a stronger owner. Every test
the audit found load-bearing stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/test-setup-consolidation-v1-thr_tiev9nbusz branch from 315ce26 to 6e46ab7 Compare October 14, 2026 17:35
@ymichael
ymichael merged commit 6852284 into main Oct 14, 2026
48 checks passed
@ymichael
ymichael deleted the bb/test-setup-consolidation-v1-thr_tiev9nbusz branch October 14, 2026 17:44
brsbl added a commit that referenced this pull request Oct 14, 2026
## Human comments

## What was wrong

Merging #4593 after #5261 combined a new regression test with an import
cleanup. The resulting test called `createNewTabFixedPanelTab` without
importing it, failing app tests and typechecking on main.

## What changed

- Restore the missing factory import used by the Browser replacement
regression.

## How you verified

- [Post-merge app tests
failed](https://github.com/get-bb/bb/actions/runs/38652452163/job/116154364883)
with `ReferenceError: createNewTabFixedPanelTab is not defined`.
- [Post-merge typechecking
failed](https://github.com/get-bb/bb/actions/runs/38652452163/job/116154364534)
on the same missing import.
- [Remote CI
passed](https://github.com/get-bb/bb/actions/runs/38652762434) at
`983b2bfa2777d3d60e99157e2b3c4912553034df`, including app tests and
typechecking.

BB-Thread-ID: thr_8f2nidvuyn

> AGENT GENERATED
ymichael added a commit that referenced this pull request Nov 3, 2026
## Human comments

## What was wrong

`@bb/app` had grown to 657 test files and 6,809 tests. Many tests
checked a contract that another test already covered more strongly.
Others only exercised wiring, tested a third-party library, or held
assertions that could not fail. A few production `export`s and one
parameter existed only for these tests. This made the suite slower to
run and maintain without catching any extra bugs.

## What changed

Test files only, apart from removing test-only exports. Net −1,077 test
lines across 58 files (+290 / −1,367), four whole files deleted, and
6,809 → 6,750 tests. Production changes are +8 / −11 across 7 files,
with no behaviour change.

**Removed**
- **Duplicates:** the raw-thread-id title tests that #5261 copied into
`ThreadTitleMentions.resources.test.ts` but never removed from the
original. Also sibling tests repeating the same setup and assertion, and
mocked copies of scenarios that already run through the real code:
`composer-submissions`, `app-toast-title-overflow`, OnboardingGate,
AddMachineDialog expiry, ToolsView banners, provider-icon, plugin-slots,
the cache-owner rename, pin acknowledgement, the CommandPalette settings
page, QuestionForm, and the PromptBox/composer-contract rejection.
- **Wiring and constant pins:** small helpers tested directly when their
only caller is tested (`resolveUrlOpenTarget`, `parseLifecycleError`,
`buildAudioInputConstraints`, `resolvePaneArrangementLabel`); realtime
registry rows that `satisfies Record<…>` already enforces at typecheck;
a snapshot-identity check covered by a stricter structural-sharing test.
- **Third-party only:** `src/test/virtualizer-scroll-lifecycle.test.tsx`
tested `@tanstack/virtual-core` and guarded a repo patch that #5951
removed. Upstream now cancels the timer itself.
- **Vacuous:** a lifecycle-error row varying `hasPath`, which no code
reads; BrowserTabDeck rows that pass either way; a FollowUpPromptBox
placeholder test whose two placeholders were the same string; a dead
`vi.mock` of a module the code under test never imports.
- **Test-only production seams:** dropped `export` from
`buildAudioInputConstraints`, `buildDevWebSocketUrl`,
`resolveUrlOpenTarget`, `parseLifecycleError`, `threadTitleTextSegments`
and `resolvePaneArrangementLabel`. Removed
`getSecondaryPanelChromeStackClassName`'s `hasGitDiffToolbar` parameter;
its only caller passed `false`.

**Repaired** (assertions that could not fail)
- `plugin-bound-sdk`: the test promised cache updates but only checked
call shape. It now asserts that a created section reaches the sidebar
cache before `create` resolves. That behaviour (#5045) had no test
before.
- `split-layout/ops`: `if (root.type === "split")` guards could skip
every resize-clamp assertion; they now throw on a non-split root.
- `provider-icon`: `toBeDefined()` on a non-optional return replaced
with real `ariaLabel` checks.
- `use-composers`: the test named "lock or paint" now also exercises
`setTextEffect`.
- `ThreadMetadataContent`: `path: null` let the "provisioning" test pass
without its status check.
- Terminal UTF-8 split glyph: this tested the browser's `TextDecoder`.
It now writes through `writeTerminalOutput` into a real xterm.
- Early `focusEnd`, the voice transition while hidden or under reduced
motion, and the model-picker cycle-chord exception could all pass with
the guarded code removed. They now fail when it is.
- `dev-websocket-url` now goes through `buildBrowserWebSocketUrl`, which
also covers the production fallback URL.

## How you verified

- **Mutation checks.** Three independent reviewers worked on dedicated
worktrees of `main` and of this branch. For every removed or merged
test, they wrote the bug it caught as a mutation of the production code.
They confirmed the old test fails on `main` and that a remaining test
fails on this branch, then restored the source.
- About 110 mutations were run. 18 removals turned out to be the only
guard on their contract; 16 of those were restored.
- The most important restoration: a known raw thread id must display as
its title through the synchronous `resolveThreadTitleDisplayText`. The
rendered pills hide this bug, but the AppLayout title, archived-threads
settings and the parent-thread picker show it.
- Other restorations: the Meta+Enter `aria-keyshortcuts` label,
QueuedMessagesList open/close reporting and overflow toggling, older
touch actions at the former width threshold, the touch-selection menu
side (#6567), the terminal-view unmount, the plugin update-action icon,
the marketplace icon in AddPluginDialog, the ReuseEnvironmentPicker
secondary text, the app chrome row-height token, the focused
notification on title Show more, the mapper's unread-error indicator,
the `useThreadStorageLocation` fetch, the thread invalidation `maxWait`
bounds, and the sidebar info-tab id.
- Two gaps were left out on purpose: the `hasPath` lifecycle row (no
code reads `hasPath`) and a single `shrink-0` class pin.
- Each repaired assertion was shown to fail under a mutation that the
old assertion let through.
- **Baseline** at 51d8ddc: `pnpm exec turbo run test
--filter=@bb/app` ran 6,809 tests, with 6 failures at machine load ~89.
All six pass when run alone or at normal load.
- **After rebasing onto origin/main:** `pnpm exec turbo run lint
typecheck test --filter=@bb/app` gave 0 lint errors, a clean typecheck,
and 6,740 of 6,750 tests passing (9 skipped).
- The one failure, `CommandPalette` "runs an available shortcut … after
closing and restoring focus", timed out opening the palette at load ~79.
It failed the same way in the baseline run on `main`.
  - It passes in five isolated reruns, two of them uncached (`--force`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
…ime limit (#7745)

## Human comments

## What was wrong

Most CI flakes logged this week came from one class: a test charges real
work (Git or Node subprocesses, cold transforms, or thousands of
instrumented queries) against a fixed per-test limit. On a slow, usually
Windows, runner that work occasionally overruns the limit. Each item
below was verified from the failing job log, then measured locally. The
cause was rarely what the test is about.

| Item | CI evidence | Cause found |
|---|---|---|
| `packages/db` `resolved-item-pruning-resume.test.ts` › seed 1 (15 s) |
File took 64 s
([job](https://github.com/get-bb/bb/actions/runs/44168611379/job/134341637967));
32–64 s in passing `main` runs; seed 1 failed twice | Two causes. (1)
The query-plan test guard costs ~1.1 s per seed of ~1.7 s: on every
`prepare` (Drizzle re-prepares each query) it captures a 40-frame stack
in CI's `BB_QUERY_PLAN_EXECUTED` mode and re-resolves every frame.
Without the guard, 16.6k prepares cost 124 ms. (2) 400-step runs grow
superlinearly. |
| `apps/server` `timeline-in-turn-window.test.ts:1140` (15 s) | Linux,
file 41.8 s
([job](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996736))
| The verification helper loaded 1,750 content-deferred rows one by one
(1,764 paged walks) to collect call ids those rows already carry. Only 7
delegation expansions were needed. |
| `apps/server` `plugin-update.test.ts` › nested git plugin (Windows, 15
s) |
[job](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996617)
| Production runs `npm install` on every git plugin materialization,
even when the plugin declares nothing npm would install. The test pays a
cold npm boot three times (170–270 ms locally, seconds on Windows).
Users pay it on every git plugin install and update. |
| `environment-provider-host` `workspace-git-fetch.test.ts:194`
(Windows, 15 s) | [job
1](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996813),
[job
2](https://github.com/get-bb/bb/actions/runs/44166034127/job/134332437148)
| Each case ran 9 Git commands (`remote add`/`fetch`/`push` per remote),
and local transports spawn more helpers, before the one fetch under
test. Every ref in the topology points at the same commit. |
| `environment-provider-host` `workspace-git.test.ts:215` `beforeAll`
(Windows, 10 s hook) |
[job](https://github.com/get-bb/bb/actions/runs/44163251565/job/134322720725)
| 9 Git spawns, including 2 `git config` calls per repo and a `fetch`
right after a `push -u` that had already updated `origin/main`. |
| `process-utils` `vcs-process-admission.test.ts:59` (Windows, 20 s) |
4.5 s / 8.1 s / 21.3 s (failed) on Windows
([job](https://github.com/get-bb/bb/actions/runs/44170133473/job/134346992616))
| Each timeout case started `git` → `sh` → a 30 s Node grandchild that
inherited stdout/stderr. If the Windows tree kill (`taskkill /T`, 2 s
cap) is slow under load, `execPortableFile` keeps waiting on pipes the
grandchild still holds. |
| `process-utils` `workload-priority.test.ts:38` (Windows, 5 s) | 0.45 s
/ 5.2 s / 7.1 s (failed)
([job](https://github.com/get-bb/bb/actions/runs/44152213676/job/134283643727))
| The child is lowered to below-normal priority, then must cold-boot a
second Node process only to print that priority. A starved low-priority
Node boot is the slow step. |
| `logger` `logger.test.ts:215` and `:243` (Windows, 15 s) |
[job](https://github.com/get-bb/bb/actions/runs/44168611379/job/134341637638)
| Each test spawns `node --import tsx`, which transforms `@bb/logger`
and `@bb/config` TypeScript, again inside pino's worker thread (it
inherits `--import tsx`). |
| `@bb/web` `oauth.test.ts:1137` (Windows, 5 s) | 5,048 ms; the
21-refresh sibling took 1,125 ms
([job](https://github.com/get-bb/bb/actions/runs/44156219534/job/134297803640))
| 72 sequential hourly refreshes, about 54 ms each on Windows PGlite, to
prove a 24 h retention bound. Locally they take 2 ms each. |
| macOS Package Smoke, first server start | Full stack timed out after
62.6 s
([job](https://github.com/get-bb/bb/actions/runs/44166147875/job/134333018710));
passing runs take 3.3–6.8 s | **Not a slow start; a hang.** The server
printed `Starting server` and never answered `/health`. The smoke
printed only stdout, so the log cannot show why. |
| `timeline-in-turn-window.test.ts:1357` | **Not found.** No failure at
that line in the last 60 CI runs. On `main` it falls inside the
image-generation test, which takes 65 ms locally. | — |

## What changed

**Fixes, at the cause:**
- **Query-plan test guard** (`packages/db/src/query-plan-guard.ts`):
memoizes located stack frames in nested maps keyed by script, line and
function, instead of re-parsing every frame on every `prepare`. The
audit dedupe key no longer concatenates the full SQL text on every
execution; it uses caller → SQL → plan-signature maps. Findings and the
executed-function report are unchanged. This benefits every `@bb/db` and
`@bb/server` test.
- **Pruning property test:** 16 seeds × 200 steps instead of 8 × 400, so
the same 3,200 steps are split into shorter runs. Every seed still
exercises 2–8 suffix-delete-and-compare cycles (81 in total).
- **Git plugin dependencies**
(`apps/server/src/services/plugins/git-plugin-dependencies.ts`): skip
`npm install` when `package.json` declares no `dependencies` or
`peerDependencies`. With `--omit=dev --omit=optional`, those are all npm
would install. `.npmrc`/`.yarnrc` are still removed. Tests pin the skip
(no `package-lock.json` written) and that a peer-only plugin still runs
npm.
- **Timeline helper:** `buildTimelineTurnSummaryDetails(…,
"keep-deferred")` expands delegations but leaves content deferred. The
two call-id-only tests use it; the 5 content-asserting callers still
load.
- **`workspace-git-fetch`:** `beforeAll` builds one final-state bare
remote. Each case copies it and writes the remote config and tracking
refs as files, so the only Git work per test is the fetch under test.
- **`workspace-git`:** test identity and the remote are written into
`.git/config` directly, as `@bb/test-helpers`' `initRepo` already does,
and the redundant post-push `fetch` is dropped. `beforeAll` goes from 9
Git spawns to 5, the clone helper from 6 to 4, and every repo the file
builds saves 2.
- **`vcs-process-admission`:** the timeout case's delayed command is
`exec sleep 30 </dev/null >/dev/null 2>&1`. That is no Node boot, and
the command can't hold the root's pipes after the root is killed. The
assertions (rejected with `killed: true, signal: SIGTERM`, then six
recoveries) are unchanged.
- **`workload-priority`:** the lowered child spawns the grandchild and
reports its PID. The test reads `getPriority(grandchild)` directly,
since Windows and POSIX fix the inherited priority at process creation.
The grandchild never has to boot Node at low priority.
- **`logger`:** `beforeAll` bundles `@bb/logger` once with esbuild's
in-process API, keeping `pino`/`pino-pretty`/`pino-roll` external; the
server ships it bundled too. The subprocess runs plain `node -e` with no
tsx, in the main thread or the transport worker. Adds `esbuild` as a
logger devDependency.
- **`oauth`:** the retention test refreshes every
`OAUTH_ROTATED_REFRESH_RETENTION_MS / 6` (4 h) over the same 72 h. That
is 18 refreshes instead of 72, and the bound is derived from the
constant instead of the literal 26. The reuse test spans the same 20 h
in 4 steps instead of 20. A temporary break in production pruning still
fails it.
- **Package smoke:** on timeout it appends the tail of every log in the
data directory's `logs/`, so the next hang shows what the server was
doing.

**Class policy:**
- **Reporter:** `vitest.test-durations.ts`, added by
`defineWorkspaceTestConfig` when `BB_TEST_DURATIONS_DIR` is set. It
records every test that used ≥25% of its effective timeout
(`testCase.options.timeout`, else the project's `testTimeout`).
- **CI:** the Linux tests, Windows tests and Windows foundation jobs set
the variable and upload the records with their `test-timings-*`
artifacts. Foundation gains an upload step.
- **Nightly report:** a new `CI Health` step downloads those artifacts
from the last 20 `main` push runs. `scripts/report-test-headroom.mjs`
(pure logic in `scripts/lib/test-headroom.mjs`, tested in
`packages/scripts/test/test-headroom.test.mjs`) lists, per platform,
every test that reached ≥50% of its timeout. Each row shows its worst
duration, the number of runs near the limit and the number of failed
runs. The list goes to the step summary and
`.ci-health/test-headroom.md`.
- **Docs:** `docs/ci-performance.md` gains "Tests near their time
limit".

## How you verified

Local numbers are on macOS (M-series), from interleaved before/after
runs. Other agents were running suites on the same machine, so CPU time
is shown where wall time was noisy.

| Test | Before | After |
|---|---|---|
| `resolved-item-pruning-resume` slowest test | 1,680 ms | 510 ms |
| `resolved-item-pruning-resume` file, CPU in CI's guard mode (3 rounds)
| 15.3–16.8 s | 12.9–14.3 s |
| `resolved-item-pruning-resume` file, test time (guard + split) |
10.1–13.6 s | 6.4 s |
| two-seed profile, guard frames in CI mode | 4,540 ms | 2,767 ms |
| `timeline` › delegated byte-budget slices | 1,542–1,651 ms | 106–115
ms |
| `timeline` › finished turn over byte budget | 1,069–1,123 ms | 77–78
ms |
| `timeline` file, test time | 4.2–4.4 s | 1.8 s |
| `plugin-update` › nested git plugin | 1,491–1,675 ms | 1,040–1,333 ms
|
| `plugin-update` file, test time (npm skipped for every git fixture) |
11.9–12.7 s | 7.5–9.6 s |
| `workspace-git-fetch` › prunes only origin (×2) | 414–549 ms | 111–147
ms |
| `workspace-git-fetch` › only remote / several remotes | 184–213 /
277–284 ms | 94–113 / 71–106 ms |
| `workspace-git` file, test time | 3.7–4.6 s | 3.3–4.0 s |
| `logger` › worker mode / plain file | 619–629 / 503–507 ms | 379–398 /
365–379 ms |
| `oauth` › bounded refresh rows / reuse in window | 143 / 65 ms | 49 /
29 ms |
| `workload-priority` › lowers a running process | 51–54 ms | 27–29 ms |
| `vcs-process-admission` › releases admission | 228–232 ms | 226–257 ms
|

`vcs-process-admission` shows no local difference because POSIX group
kills are immediate; its fix targets the Windows pipe hold.

**Windows CI, file durations.** "Before" is every sample in the failing
jobs and recent logs above; "after" is this PR's full-matrix [run
44212664696](https://github.com/get-bb/bb/actions/runs/44212664696).
This is one after sample, so the per-test check below is the stronger
evidence.

| File | Before | After |
|---|---|---|
| `vcs-process-admission` | 4.5 s, 8.1 s, 21.3 s (failed) | 1.5 s |
| `workload-priority` | 0.45 s, 5.2 s, 7.1 s (failed) | 0.19 s |
| `oauth` | 9.4–18.3 s (one failed) | 5.6 s |
| `logger` | 6.1–6.8 s, 34.2 s (failed) | 5.5 s |
| `workspace-git-fetch` | 21–47 s (two failed) | 20.8 s |
| `workspace-git` | 28–51 s | 29.0 s |
| `plugin-update` | 78.6 s (failed) | 52.3 s |
| `timeline-in-turn-window` (Linux) | 41.8 s (failed) | 5.4 s |

**Per-test check from the new reporter.** In that full run, across all
30 Linux and Windows test shards (37 record files, 87 tests at ≥25% of
their timeout), **no test from any file fixed here reached even 25% of
its timeout on any platform.**

The report over that one run already lists 7 tests at ≥50% of their
timeout. Several deliberately wait out a real timeout, for example
`disk-usage` › kills every running du when the timeout elapses (62%),
`desktop-browser-broker-client` › timed out broker (61–62%),
`actions-api` › bounds recovery for timeout (55–56%), and
`host-toolchain` › kills a shell that ignores SIGTERM (60%). They are
the next work list, not part of this PR.

- `@bb/db` full suite passes. Also passing: process-utils, logger, web,
environment-provider-host and scripts full suites, and the touched
`@bb/server` files (147 tests).
- `typecheck`, `lint` and `lint:type-aware` pass for the 8 changed
packages; root `lint:type-aware` passes; `actionlint` passes.
- **Reporter end to end:** locally, `BB_TEST_DURATIONS_DIR=/tmp/tdur
turbo run test --filter=@bb/db -- … --testTimeout=1000` writes one JSONL
record per qualifying test, with the resolved timeout. In CI, all 30
`test-timings-*` artifacts of run 44212664696, including
`windows-foundation`, contain records; `report-test-headroom.mjs` over
them produced the table above.
- **oauth mutation check:** with production pruning disabled, the
18-refresh test fails.

## Past fixes on these files

- `workspace-git-fetch` / `workspace-git`: #7687 (shared fixture
topology), #7145 (SSH wrapper independent of the fetch deadline).
- `query-plan-guard.ts`: #7323 (structured call sites), #7711 (no
reparsing of audit frames), #7535.
- `plugin-update.test.ts`: #7685 (shared native plugin startup), #7688
(open: proposes 60 s for native loading).
- `timeline-in-turn-window.test.ts`: #7541, #5261.
- `vcs-process-admission.test.ts`: #5630.
- `smoke-tarball.mjs`: #7202.

## Decisions for review

- **Git plugins with no runtime or peer dependencies no longer run `npm
install`** on install or update. It's faster, and no `package-lock.json`
or `node_modules` is created in that plugin's directory. Plugins that
declare dependencies are unchanged.
- **The policy reports; it does not block.** A per-PR duration budget
would itself fail on slow runners, the flake class this fixes. So
durations are recorded in every CI test job and aggregated nightly
across 20 `main` runs, which is a stable signal. The two numbers are
policy constants, not per-test budgets:
- 25% of timeout is the threshold for recording a test, which keeps
artifacts small;
  - 50% is the threshold for listing it.

Turbo cache hits replay results without running, so they add no records.
Hook timeouts (as in `workspace-git` `beforeAll`) are not covered:
Vitest does not expose hook durations to reporters.
- **The pruning property test now explores shorter histories** (200
steps) across twice as many seeds.
- **Not fixed: the macOS smoke hang.** The cause is unknown; the change
is the diagnostic that will name it.
- **Out of scope, noted:** on Windows, `stopWindowsProcessTree` caps
`taskkill /T` at 2 s, and a tree it fails to kill keeps inherited pipes
open. The `vcs-process-admission` fix stops the test from depending on
that, but the production behaviour under load deserves its own issue.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

1 participant