Repository navigation
perf: low-risk sweep fixes (F5, F3, F2, S3, D1, F4) - #2346
Merged
Merged
Conversation
pruneDestroyedEnvironments deleted every expired environment in one DELETE ... WHERE id IN (...), so SQLite ran the ON DELETE SET NULL cascade over every event/thread of every environment inside one synchronous call (5.6 s event-loop stall on a 481-id restart backlog). It now orders by updatedAt, takes a bounded batch (default 10/tick), and deletes one environment per statement; the server boundary supplies destroyedBefore. Verified: new sweeps.test.ts cases fail on the old implementation and pass on the new one; archive-pruned-environment.test.ts and turbo typecheck for @bb/db and @bb/server pass. Co-Authored-By: Claude <[email protected]>
detail-view.tsx imported AUTOMATION_PROMPT_MAX_LENGTH from src/rpc-types.ts, the only value import of that module from the frontend, so esbuild inlined zod and all 85 schemas into dist/app.js (served no-store and evaluated at every boot). Move the eleven limit constants into an import-free src/limits.ts, re-export the four public ones from rpc-types.ts so backend and package-export consumers are unchanged, and add a frontend import-graph guard test that fails if rpc-types or any zod module becomes reachable from app.tsx again. Verified: dist/app.js 441,461 -> 125,495 bytes (brotli 85,083 -> 32,734), zero 'zod' occurrences after; guard test fails with the old import and passes now; turbo typecheck + test for bb-plugin-automations pass. Co-Authored-By: Claude <[email protected]>
deactivateAfterFinalRelease removed a plugin's <link> in a microtask when its consumer count hit zero, so thread-to-thread navigation (old composer releases, new one retains 150-1,000 ms later) detached and re-attached the sheet and paid two full style recalcs. The final release now schedules a cancellable 1.5 s setTimeout (CSS_RELEASE_GRACE_MS); retainPluginCss, both applyPluginCss invalidation paths, and resetPluginCssForTest clear the timer as well as bumping the epoch. Verified with fake-timer tests in plugin-frontend-reload, PluginSlotMount, and plugin-slot-mounts (6 fail on the old code, all pass now). Co-Authored-By: Claude <[email protected]>
SidebarWindowedItems read the scroll container from the SidebarContent ref in its layout effect. When the list commits in the same pass as SidebarContent (warm boot, direct thread route, mobile deferred realization) that ref is not attached yet, so every row was realized and demoted hundreds of milliseconds later. Resolve the container from the first wrapper's closest [data-sidebar="content"] ancestor when the ref is still null; keep promote-all for a zero-height container or a missing IntersectionObserver. Verified with three new jsdom cases in SidebarWindowedItems.test.tsx (the same-commit case fails before and passes after) and the existing sidebar suites. Co-Authored-By: Claude <[email protected]>
requireSupportedProviderCliForThreadStart ran the bridge's full installation probe (six subprocesses, plus a maintenance-bridge respawn after 60 s idle and a re-hash of the bridge artifact) before every thread.start and thread.rewind.prepare, even though the answer almost never changes. The daemon now keeps a RuntimeManager-owned memo keyed by providerId, bridge launch process key, and requirement, with a 5 minute TTL. Only a supported answer is stored; an unsupported one or a rejected probe is re-probed on every attempt. Concurrent starts share the in-flight probe, and a probe that was running when the memo was cleared is discarded. The memo clears with invalidateProviderMaintenanceRuntime (after a verified bb-run install or update) and on a base shell env change, but not on the idle teardown of the maintenance runtime. bridgeLaunchProcessKey now takes the three fields it reads structurally so the key comes from the wire launch and a hit skips artifact resolution. The user-facing provider.installation.status RPC stays uncached. Daemon-internal only: no session payload, RPC command, or result changed, so no protocol bump. Verified: turbo typecheck for @bb/host-daemon and @bb/agent-runtime; new provider-installation-gate.test.ts (9 tests); command-dispatch.test.ts (37 tests, 6 new; probe reuse, in-flight sharing, and shell-env re-probe fail against the pre-fix handler); runtime-manager.test.ts (49 tests); bridge-launch-process-key.test.ts. Co-Authored-By: Claude <[email protected]>
createApiClient lived in public-api.ts, so the browser app and @bb/sdk pulled the whole publicApiRoutes table (and its schema imports) into the boot closure just to get the hc<PublicApiRoutes> type. Move the client into api-client.ts with a type-only import of PublicApiRoutes, re-export it from the barrel, and give build-bundled-dts its own stub so the bundled plugin .d.ts stays identical. Verified: turbo typecheck of server-contract/sdk/app/cli/plugin-sdk, the server-contract and plugin-sdk suites (bundled-types unchanged), and an app build where public-api.ts is no longer rendered into any boot chunk (before: 24,462 rendered bytes; boot payload 1,603,612 -> 1,601,241 raw bytes). Co-Authored-By: Claude <[email protected]>
Review found that the grace window made a previously unreachable onload branch live: a <link rel=stylesheet> whose load completed after the final release (consumers === 0) was removed from the document while record.pendingStylesheet still pointed at it, so every retainPluginCss inside the grace early-returned on the stale pending href and mounted plugin UI with no stylesheet; the live-reload variant left the old sheet attached and never applied the new URL. The onload handler no longer treats consumers === 0 as a discard: when the link is still the pending sheet for the current URL it is adopted as record.stylesheet regardless of consumers, and the grace timer, applyPluginCss(null), and the URL-change path (all of which call deactivateStylesheet) detach it when nobody retains. Verified in plugin-frontend-reload.test.ts: the grace-reuse test now fires load on the stylesheet link so the loaded-sheet branch is exercised, and two new cases (load completes during the grace then a consumer retains; changed URL loads during the grace then a consumer retains) fail against the previous plugin-css.ts and pass with this change. Co-Authored-By: Claude <[email protected]>
Review found the F2 source guard covered only half of the tree-shaking precondition: it regexed api-client.ts's import lines against a three-entry denylist, so a value import of a sibling zod module (./errors.js) or an 'export { publicApiRoutes } from "./public-api.js"' re-export slipped through, and nothing pinned the package's "sideEffects": false, which is the only reason bundlers drop the barrel's 'export * from "./public-api.js"' edge. The api-client stub header also justified the redirect with a duplicate-export clause that the F2 commit itself removed.
The contract test now collects every import/export-from specifier in api-client.ts and expects exactly ["hono/client", "./public-api.js"] plus the separate 'import type { PublicApiRoutes }' statement, and a sibling test asserts packages/server-contract/package.json declares sideEffects === false. The stub header states the real reason for the redirect: inside the rollup-plugin-dts program api-client.ts still resolves the real route table, so bundling it expands hc<PublicApiRoutes> into a ~540 KB declaration that drags sibling modules into the bundle graph and perturbs declaration order.
Verified: the new assertions fail against a value re-export of publicApiRoutes, an './errors.js' value import, and a package.json without sideEffects, while the HEAD test passed all three; contract.test.ts passes (35 tests); turbo typecheck of @bb/server-contract; turbo build:types of @get-bb/plugin-sdk reports all 15 bundled-types Unchanged and the bundled-types test passes.
Co-Authored-By: Claude <[email protected]>
…er test Review found that the same-commit windowing fix rests on SidebarContent keeping data-sidebar="content" on the element its context ref points at, and on React attaching that ref after the list's layout effect, but the test suite hand-built the container and mocked the whole sidebar module, so renaming or moving the attribute left every test green while every row was realized again. Export SIDEBAR_CONTENT_SELECTOR from sidebar.tsx next to the attribute and import it in SidebarWindowedItems instead of duplicating the string. The test mock now spreads the real module and only overrides useSidebarContentElementRef when a case supplies a stand-in ref; a new case renders the real SidebarContent around the list in one render and asserts the rows stay windowed. Dropped the misnamed detachedContainer variable and its afterEach removal, which RTL cleanup() already performs. Verified: the new case fails when the data-sidebar attribute is renamed in sidebar.tsx (the four existing cases stay green) and against the pre-F3 component; 5/5 pass at HEAD. Typecheck for @bb/app and the sidebar, AppLayoutSidebar, sidebar-resize, sidebarThreadShortcuts, and ProjectList.modes suites pass. Co-Authored-By: Claude <[email protected]>
…atedAt clock Review found that the per-tick limit bounded environments, not cascade work: pruneDestroyedEnvironments ran all ten DELETEs (each with its synchronous ON DELETE SET NULL cascade, ~756 ms measured for a 101k-event environment) inside one macrotask, so ten co-expiring large environments could stall the event loop for ~7.5 s, longer than the 5.6 s restart backlog the original fix targeted. runDestroyedEnvironmentPruneSweep is now async and prunes one environment per call (limit: 1) up to DEFAULT_DESTROYED_ENVIRONMENT_PRUNE_BATCH_SIZE, awaiting setImmediate between environments and stopping when nothing was deleted; the running guard in runPeriodicSweepJob already prevents overlapping ticks. The db function stays synchronous. Also renames PruneDestroyedEnvironmentsArgs.destroyedBefore to updatedBefore (it is compared against environments.updatedAt, which any metadata write moves; the table has no destroy timestamp), matching ListStaleDestroyingManagedEnvironmentsArgs, and rewords the sweeps.ts comment so the tick bound is credited to the SELECT limit while the per-row DELETE is credited only with transaction granularity and per-row notifications. Verified: new periodic-sweeps.test.ts case samples the destroyed-row count from a self-rescheduling setImmediate probe and fails on the previous synchronous sweep (observed [] because the whole batch ran inside one macrotask) and passes after; new sweeps.test.ts case pins that a metadata write on a destroyed row restarts its retention clock. vitest for packages/db test/data/sweeps.test.ts (16 passed) and apps/server test/services/periodic-sweeps.test.ts plus test/threads/archive-pruned-environment.test.ts (9 passed); turbo typecheck for @bb/db and @bb/server; oxlint and oxfmt clean. Co-Authored-By: Claude <[email protected]>
…et not-installed answers Review found that the thread-start memo from 9e3ab4f4a broke the PATH-change invalidation it advertised. The only thread-start caller of app.ts's refreshRuntimeShellEnv was the probe itself, so a memo hit never re-read the login shell: replaceBaseShellEnv (where the gate is cleared and idle runtimes evicted) was unreachable for up to five minutes, the environment runtime was created with the stale baseShellEnv, and a CLI installed into a new PATH directory was not found on retry. Two further consequences of the same placement: when the refresh did run inside the probe, its gate.clear() bumped the generation under the probe's feet and the fresh answer was discarded, costing a second full probe; and because first-party bridges report versionUnsupported: false for a CLI that is not installed, the gate remembered not-installed answers, so a too-old CLI installed out of band within the window slipped past the actionable version error. CommandDispatchOptions gains a daemon-internal refreshShellEnv hook, wired in app.ts to the existing refreshRuntimeShellEnv closure and passed through CommandRouter. requireSupportedProviderCliForThreadStart awaits it before consulting the gate, so a PATH change clears the memo before the lookup and before the gate samples its generation; the refresh's own 10 s TTL keeps back-to-back starts free. The gate now stores only answers with installed true and versionUnsupported false. The hook is optional in the dispatch options, like the interface's other host-local hooks, with omission meaning the process has no login shell to re-read (tests seed a fixed env). No wire field is added: packages/host-daemon-contract and packages/provider-bridge-protocol are untouched, so no HOST_DAEMON_PROTOCOL_VERSION bump. Verified: turbo typecheck for @bb/host-daemon; provider-installation-gate.test.ts (10 tests, 1 new: a not-installed status is never remembered); command-dispatch.test.ts (39 tests, 3 new/rewritten: the PATH change is driven through the hook with a createRuntime spy asserting the new runtime gets the new PATH and the probe re-runs, the first probe after a PATH change is remembered so the next start probes once, and a not-installed answer is re-probed so the next start rejects with provider_cli_unsupported_version); command-router.test.ts. All four new tests fail against HEAD's thread.ts and provider-installation-gate.ts and pass after. Co-Authored-By: Claude <[email protected]>
Review found the frontend import guard followed only relative and @/ specifiers, so zod re-entering dist/app.js through a bundled workspace module (a used @bb/domain/thread-status import, update-state.ts gaining a zod-bearing sibling import, or any @bb/shared-ui source) passed unnoticed; it also justified the split with a cache-control claim that is false for the URL the app loads (the bundle is content-hashed and served immutable, so the recurring cost is parse/evaluate, not download). The walker now resolves @bb/domain and @bb/shared-ui specifiers through each package's exports map under the source condition into packages/<pkg>/src and keeps walking, skipping only the host-provided icon module; a root-barrel @bb/domain import counts as reached by design, which the docblock states (import the leaf subpath). The anti-vacuity assertion now requires the realpath'd packages/domain/src/update-state.ts and shared-ui's button.tsx. Both no-store comments are reworded to the evaluate cost. Verified: the new anti-vacuity entries fail against HEAD's resolver (only 6 plugin files reached) and pass now; a scratch entry value-importing @bb/domain/thread-status and the @bb/domain barrel makes 'imports nothing from zod' fail naming packages/domain/src/thread-status.ts and the barrel's zod-backed re-exports; turbo typecheck and test for bb-plugin-automations pass; oxlint and oxfmt clean. No metafile test: esbuild resolves here only as the root's devDependency and every package whose tests import it declares it, and runtimeShimPlugin is a non-re-exported internal of @bb/plugin-build. Co-Authored-By: Claude <[email protected]>
Round-2 review found the guard's bundled-workspace matcher was hardcoded to @bb/domain and @bb/shared-ui, so any other @bb/* workspace import (e.g. @bb/plugin-interaction-contracts, which the plugin build also inlines from source because RUNTIME_SLOT_BY_SPECIFIER has no slot for it) fell through to the bare branch, was compared against the literal 'zod', and passed silently, reopening the blind spot the previous fix closed one package over. The matcher now covers every @bb/* specifier except the host-slotted legacy @bb/plugin-sdk/app alias (negative lookahead); @bb/shared-ui/icon is still dropped after resolution. An unknown workspace package therefore resolves through its exports 'source' condition and is walked, or throws: workspaceSourceFile now names the package when it has no node_modules link instead of surfacing a raw lstat ENOENT, and still throws when the package has no 'source' export. The docblock no longer claims only third-party deps are uncovered. Added a proving test that resolving @bb/plugin-interaction-contracts from the frontend entry throws naming the package. Verified: the proving test fails against HEAD's resolver (returns null, no throw) and passes now; all four tests pass; neither packages/shared-ui/src nor packages/domain/src imports another @bb/* package so the existing walk is unchanged; turbo typecheck for bb-plugin-automations passes; oxlint and oxfmt clean. Co-Authored-By: Claude <[email protected]>
…rk frame
Round-2 review found that each synchronous prune (SELECT + DELETE with its ON DELETE SET NULL cascade, ~756 ms measured for 101k events) ran bare inside the async sweep:destroyed-environment-prune frame. runEventLoopWork opens that frame with blocksEventLoop: false and selectSlowestWork skips such frames, so a prune crossing the 500 ms stall threshold was logged with slowestWork naming an unrelated sync unit (or null) and an operator would attribute the stall to the wrong code path. Pre-existing, not a regression from 5550d62a8.
runDestroyedEnvironmentPruneSweep now wraps each pruneDestroyedEnvironments call in runEventLoopWorkSync("sweep:destroyed-environment-prune:delete", ...). AsyncLocalStorage nests it under the async sweep frame, so currentWork still reads sweep:destroyed-environment-prune > sweep:destroyed-environment-prune:delete and the stall monitor can name the delete as slowestWork.
Verified: new periodic-sweeps.test.ts case seeds one expired destroyed environment, resets the work window, runs the sweeps, and expects takeEventLoopWorkWindowSnapshot().slowestWork to be the delete label; it fails with HEAD's periodic-sweeps.ts swapped in (received null) and passes with the change (6 passed). turbo typecheck @bb/server, oxlint and oxfmt clean.
Co-Authored-By: Claude <[email protected]>
…is discarded Round-2 review of 91a214f5a found that activateStylesheet's onload discard branch (record.url !== url) still removed the link without clearing record.pendingStylesheet, unlike onerror. Under bb plugin dev with a slot mounted, publishing v2, republishing v1 before v2 lands (the loaded v1 sheet is reused, leaving v2 pending), and then republishing v2 after its load fired left pendingStylesheet pointing at the detached v2 link; linkUrl() reads the href of a detached node, so every later activateStylesheet(v2) early-returned with v1 still attached and v2 never applied until a null publish, a third URL, or the zero-consumer grace. The discard branch now mirrors onerror and nulls pendingStylesheet when it is the discarded link. Verified with a new fake-timer case in plugin-frontend-reload.test.ts (flip-flop aaa -> bbb -> aaa, discard bbb's load, republish bbb): fails against the previous plugin-css.ts with only aaa attached and passes with this change; the three plugin-css suites (81 tests) and a forced @bb/app typecheck pass. Co-Authored-By: Claude <[email protected]>
… selector Round-2 review found two gaps in SidebarWindowedItems.test.tsx. The real-render case claimed to guard that SidebarContent keeps data-sidebar="content" on the element its context ref points at, but both geometry spies key off the selector, so a SidebarContent that keeps the ref on its outer overflow-auto div and moves the attribute to an inner wrapper still passed 5/5 while in a browser it would realize every row against the wrapper's content height and then demote them from the observer rooted at the real scroller. Separately, the hand-built container and the getBoundingClientRect spy still spelled the attribute out by hand, so a consistent rename of SIDEBAR_CONTENT_SELECTOR and the JSX attribute made the same-commit hand-built case fail against a component that still works. Forward a createRef into the real SidebarContent and assert the element resolved through SIDEBAR_CONTENT_SELECTOR is contentRef.current; setContentRef writes the same node to the forwarded ref and the context ref, so this is the coupling the comment describes. Parse the attribute name and value out of the exported selector once and use them for the hand-built container, and use matches(SIDEBAR_CONTENT_SELECTOR) in the rect spy like the clientHeight spy already does. Verified with a throwaway /tmp harness running the HEAD test and the fixed test against the real sidebar module, a moved-attribute variant, and a consistently renamed variant: HEAD passes 5/5 on the moved variant and the fixed test fails there at the new toBe assertion; HEAD fails the same-commit hand-built case on the renamed variant and the fixed test passes 5/5; both pass 5/5 on the real module. In-repo suite 5/5, turbo typecheck for @bb/app, oxlint, and oxfmt clean. Co-Authored-By: Claude <[email protected]>
Round-2 review found the F2 source guard's statement regex (^(?:import|export)\b[^;]*?\bfrom ...;) still let real edges through: a ';' inside a comment in a multi-line import block stopped the scan before 'from', and a bare side-effect import has no 'from' at all, so a value import of ./errors.js hidden behind a line comment, a comment-hidden re-export of publicApiRoutes, or a bare 'import "./public-api.js"' all left the matched specifier list unchanged and the test green. The same rewrite was also order-sensitive and anchored the import-type check with ';$', so a benign reorder of the two imports or a trailing line comment failed the guard even though the module graph was unchanged.
The test now parses api-client.ts with ts.createSourceFile (typescript is already a devDependency of @bb/server-contract) and collects every ImportDeclaration/ExportDeclaration module specifier with whether it is type-only (importClause.phaseModifier === TypeKeyword, the TS 6 replacement for the deprecated isTypeOnly; ExportDeclaration.isTypeOnly). It asserts the set of value edges is exactly {"hono/client"} and the only ./public-api.js edge is type-only, so a bare import, a comment-hidden statement, an inline 'import { type X }' clause, or a value re-export all fail, while statement order and trailing comments do not matter. The sideEffects === false assertion is unchanged.
Verified: with the rewritten test, the real api-client.ts plus swapped-import-order and trailing-comment variants pass, and ten injected edges fail (value import of ./errors.js, line- and block-comment ';' imports of ./errors.js, bare import of ./errors.js, 'export { publicApiRoutes } from "./public-api.js"', comment-hidden re-export, bare import of ./public-api.js, comment-hidden value import of publicApiRoutes, 'import { type PublicApiRoutes }', bare import of zod); the HEAD test passed seven of those ten and failed both benign variants. api-client.ts was restored byte-identically after each mutation. contract.test.ts passes (35 tests), turbo typecheck of @bb/server-contract passes, oxlint and oxfmt are clean.
Co-Authored-By: Claude <[email protected]>
…um version and require the shell env refresh hook Round-2 review of d7dabdcce found three problems. (1) The gate's store predicate (status.installed && !status.versionUnsupported) forgot every not-installed answer, but only bridges that enforce a minimum version (codex, pi) can turn an out-of-band install into versionUnsupported: true. Claude Code and ACP hard-code versionUnsupported: false and minimumSupportedVersion: null, and the Claude Code launcher falls back to well-known install paths the PATH probe misses, so 'not installed' is a working steady state for them; re-probing it on every thread.start and thread.rewind.prepare re-ran the five-subprocess probe (including an npm view network call and claude doctor) plus the maintenance-bridge respawn for a verdict that could never change. The predicate is now (status.installed || status.minimumSupportedVersion === null) && !status.versionUnsupported, so only a not-installed answer from a bridge with a minimum version is forgotten. (2) refreshShellEnv was optional on CommandDispatchOptions and CommandRouterOptions to hide a test-only no-op default, which AGENTS.md forbids, and thread.ts awaited it with ?. so a dropped app.ts wiring would silently reinstate the stale-PATH regression the review had just confirmed. The field is now required on both interfaces, thread.ts awaits it unconditionally, and the test fixture unexpectedProviderMaintenance (spread by every CommandDispatchOptions literal in the host-daemon tests) supplies an explicit no-op, documented as the one member that does not throw. (3) docs/provider-bridge-protocol.md still described the pre-change policy; it now states exactly which answers are remembered and which are forgotten. Verified: turbo typecheck for @bb/host-daemon; provider-installation-gate.test.ts (11 tests, 1 new: a Claude-Code-shaped not-installed status with minimumSupportedVersion: null is served from memory; it fails against the previous predicate with the probe called twice); the existing codex-shaped not-installed test and command-dispatch.test.ts 'does not remember a not-installed provider that enforces a minimum version' still pass; command-dispatch.test.ts, command-router.test.ts, thread-stop-races.test.ts, thread-dispatch.test.ts (95 tests across the five files); removing the refreshShellEnv entry from app.ts now fails tsc with TS2741 on CommandRouterOptions; oxlint and oxfmt clean. Co-Authored-By: Claude <[email protected]>
…t probe isProcessRunning reads /proc/<pid>/stat after a signal-0 probe. A child that exits between the two calls makes the read fail with ESRCH, which the helper rethrew, so 'terminates descendant processes when a script times out' failed once under load on this branch. Map ESRCH to 'not running' like ENOENT. Co-Authored-By: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 24, 2026
## What was wrong The parity self-test `pi/compaction reproduces its recording` fails on `main` (CI for #2346 and #2349, job `Tests (packages, ubuntu-latest, Node 22.x)`). The recording contains a steer. After the steer, pi writes the `prompt` response and then the `tool_execution_end` for `sleep 2`. One pipe read can carry both lines. The pi bridge handled a chunk in one synchronous loop: the event's delivery (`deliverInOrder`) runs one microtask hop after its line, but the steer's `input.accepted` runs several `await` hops after the response. So `item.close` went out before `input.accepted`, and the bridge's output order depended on pipe chunking. The parity replay child keeps a 50 ms gap after a response, but a starved CI runner can stall the bridge past that gap. The diff in CI shows this exactly: `turn/input/accepted` moved, and the `sleep 2` row spans seq 9–11 instead of 9–12. The other red test on `main` (`bridge.lifecycle.test.ts > a failed construction leaves no child`, #2346 only) is the pi lifecycle budget flake that #2353 addresses. ## What changed - `plugins/provider-pi/src/bridge/rpc-child.ts`: `PiRpcChild` queues stdout lines and handles one line per event-loop turn (`setImmediate`). A request's continuation finishes before the next line, which is the order a line-at-a-time read gives. - `plugins/provider-pi/src/bridge/fake-pi-rpc.mjs`: new knob `FAKE_PI_BATCH_STEER_REPLY=1` writes a steer's `prompt` response and the resumed run's first event in one stdout write. - `plugins/provider-pi/src/bridge/bridge.round2.test.ts`: regression test that pins the ack before the same-chunk event. No wire change. `HOST_DAEMON_PROTOCOL_VERSION` stays the same: only the bridge's ordering became deterministic. ## How you verified - The new round2 test fails before the change (ack at index 5, event at index 4) and passes after it. - Deterministic repro of the parity failure: a replay child patched to write the post-response line in the same write failed the `pi/compaction` cell 3/3 before the change and passed 3/3 after it. The patch was a local experiment and is not part of this PR. - `pnpm exec turbo run test typecheck --filter=./plugins/provider-pi --filter=@bb/provider-parity --force`: pi plugin 105/105, parity 56/56, typecheck clean. - Off-pipeline: real `pi` (0.84.3) slice of `@bb/agent-runtime#test:integration` (`integration.provider-basic.test.ts -t "pi provider"`): 8/8, including "steers an active turn". Fixes the `pi/compaction` parity failure on `main` (no issue filed). > AGENT GENERATED Co-authored-by: Claude <[email protected]>
ymichael
added a commit
that referenced
this pull request
Aug 24, 2026
## What was wrong `preload-browser-api.test.ts` reset Vitest's module registry and dynamically imported the preload inside every test body. Under contention, that import crossed the first test's 10-second timeout. Vitest reported the timeout but did not cancel the pending async body, so it resumed later and appended its 14 IPC sends to the shared `electronMock` after the following zoom test had reset it. That produced the observed 16 calls instead of 2. The failing [packages job](https://github.com/get-bb/bb/actions/runs/32773408314/job/97578795580) and the successful same-SHA rerun show this is timing-dependent rather than a regression from PR #2346. ## What changed Moved the per-test preload reset/import into a `beforeEach` hook with a setup-specific 30-second timeout. Test command bodies now begin only after preload setup completes, so a slow transform cannot release stale commands into a later test. Module state is still reset for every test, and all production behavior and assertions are unchanged. ## How you verified - Reproduced the exact failure on merge-base with a temporary Vitest transform that delayed `preload.ts` by 10.5 seconds: the first test timed out at 10 seconds and the next test received 16 sends. - Re-ran the same delayed transform after the change: all 5 tests passed in 10.92 seconds. - `pnpm exec vitest run --config vitest.config.ts test/preload-browser-api.test.ts` — 5 tests passed. - `pnpm exec turbo run test typecheck build lint --filter=@bb/desktop --force` — 15/15 Turbo tasks passed; desktop test suite 35 files / 230 tests passed. > AGENT GENERATED: by GPT-5.6-Sol
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.
What was wrong
Six cheap-to-fix bottlenecks from an internal performance sweep (findings F5, F3, F2, S3, D1, F4), each a small local defect:
plugins/automations/detail-view.tsximported one number fromsrc/rpc-types.ts; that value edge dragged zod and 85 schemas into the plugin's frontend bundle (441 KB, evaluated on every boot).SidebarWindowedItemsread the scroll container from theSidebarContentref inside its layout effect. When the list mounts in the same commit asSidebarContent(warm boot, direct thread route, mobile deferred realization) the ref is not attached yet, so every row was realized and demoted a few hundred ms later.apps/app/src/lib/api-server.tsimportedcreateApiClientfrompublic-api.ts, which keeps the whole route table and its schema modules in the boot closure although the client only needs the route types.pruneDestroyedEnvironmentsdeleted every expired environment in oneDELETE … WHERE id IN (…); SQLite ran theON DELETE SET NULLcascade over all of their events inside one synchronous better-sqlite3 call (5.6 s event-loop stall on a 481-row backlog).thread.start/thread.rewind.prepare, although Claude Code can never fail that gate (1.6–1.8 s per start).What changed
plugins/automations/src/limits.ts;rpc-types.tsimports and re-exports them, so every existing import keeps working. A guard test walks the frontend import graph (following every@bb/*workspace package through itssourceexport) and fails if zod orrpc-types.tsbecomes reachable again.dist/app.js441,461 → 125,495 B (brotli 85 → 33 KB); zod occurrences 475 → 0.closest(SIDEBAR_CONTENT_SELECTOR)when the ref is still null; promote-all is kept for a zero-height container or a missingIntersectionObserver. The selector constant is exported fromcomponents/ui/sidebar.tsxnext to the attribute.createPublicApiClient/createApiClient/ApiClientmoved topackages/server-contract/src/api-client.tswithimport type { PublicApiRoutes }and are re-exported from the barrel; a second bundled-dts redirect (packages/plugin-sdk/scripts/api-client-stub.d.ts) keepsbundled-types/byte-identical. An AST-based test pins the import graph and the package'ssideEffects: false. The route table androute-descriptor.tsleave every boot chunk. Step two (lazy route schemas) is not in this PR.DEFAULT_DESTROYED_ENVIRONMENT_PRUNE_BATCH_SIZE(10) per 10 s tick, oneDELETEper environment with an event-loop yield between environments, each wrapped in a blocking work frame so the stall monitor attributes a long cascade.destroyedBeforeis namedupdatedBeforebecause it comparesupdatedAt. Constants exported from@bb/db; the server boundary supplies the cutoff.provider-installation-gate.ts: the gate remembers an answer per provider + bridge launch + requirement for 5 min, cleared byinvalidateProviderMaintenanceRuntime()and by a base shell-env change; the shell env is refreshed before the gate (new requiredrefreshShellEnvdispatch option) so a PATH change is a guaranteed miss. Unsupported answers are never remembered; not-installed answers are forgotten only for bridges that enforce a minimum version (codex, pi). No wire change — nothing inpackages/host-daemon-contractorprovider-bridge-protocolchanged, so noHOST_DAEMON_PROTOCOL_VERSIONbump.docs/provider-bridge-protocol.mddocuments the policy.deactivateAfterFinalReleaseuses a cancellable 1.5 ssetTimeout(cleared on retain,applyPluginCss(null), URL change, and test reset). A sheet that finishes loading inside the grace is adopted, and a discarded pending link no longer blocks later activations.ESRCHfrom/proc/<pid>/statto "not running" (it threw once under load).How you verified
Tests added or extended; each was run against the pre-fix code first and fails there:
plugins/automations/src/frontend-imports.test.ts,SidebarWindowedItems.test.tsx(same-commit mount, realSidebarContentrender),packages/server-contract/test/contract.test.ts,packages/db/test/data/sweeps.test.ts,apps/server/test/services/periodic-sweeps.test.ts(per-environment yield observed by asetImmediateprobe; stall-monitor attribution),apps/host-daemon/src/provider-installation-gate.test.ts,command-dispatch.test.ts(reuse, in-flight dedupe, PATH change, TTL, rewind requirement),plugin-frontend-reload.test.ts(grace reuse, load-during-grace, URL flip-flop),PluginSlotMount.test.tsx,plugin-slot-mounts.test.tsx.On this branch:
pnpm exec turbo run typecheck(76/76),pnpm exec turbo run lint,pnpm exec turbo run test(all packages green). Bundle-size numbers measured with the plugin build pipeline (F5) and a same-tree Vite build (F2).Fixes: no issue — source is an internal performance sweep (findings F5, F3, F2, S3, D1, F4).