Skip to content

Latest commit

 

History

History
1480 lines (1283 loc) · 88 KB

debugging-and-qa.md

File metadata and controls

1480 lines (1283 loc) · 88 KB

Debugging And QA

  • pnpm dev and pnpm start:worktree save the absolute source checkout path in <data dir>/bb-dev-instance.json. Storage reports use this record to identify development data even after the checkout is removed. Older instances can be identified from bb-app-runtime.json or hash-verified path matches; unknown source paths are reported explicitly.
  • pnpm dev prints the active frontend URL, server API URL, host daemon port, data dir, and logs dir. Do not assume fixed dev ports.
  • pnpm mobile:apk:dev builds a standalone ARM64 Android APK at apps/mobile/build-output/bb-dev.apk, named bb dev with an orange icon and separate package/data from the installed app. Append -- x86_64 for an Intel emulator. See the mobile build instructions for prerequisites, installation, and per-thread delivery.
  • pnpm start:worktree builds production artifacts and serves the optimized app bundle from the checkout-specific dev server URL, while keeping the same dev data directory and deterministic server/host-daemon ports. It has no Vite dev server or hot reload.
  • pnpm start:worktree-remote is the trusted-network variant of pnpm start:worktree; it binds that server to all IPv4 interfaces.
  • pnpm desktop packages the Electron app and launches it against the installed data directory, ports and Electron user-data directory, the same targets a released build uses. It shares the single-instance lock with an installed bb: quit that first, or the launch focuses it instead of starting your build.
  • pnpm desktop:worktree packages and launches it against this checkout's data directory and deterministic ports, the same instance pnpm start:worktree uses, with Electron's user-data directory at $BB_DATA_DIR/desktop (override with BB_DESKTOP_USER_DATA_DIR). Like pnpm start:worktree, it skips first-run setup unless BB_SKIP_ONBOARDING=0. It refuses to start when the server or host-daemon port is busy, so a stale server cannot answer for your build. It shows the dev Dock icon while running (BB_DESKTOP_DEV_ICON=1). Set BB_DESKTOP_OPEN_DEVTOOLS=1 to open DevTools. Both desktop commands always repackage first; machines without a Developer ID identity produce unsigned artifacts.
  • The packaged app defaults to server/frontend :38886, host daemon :38887, data dir ~/.bb/, and logs under ~/.bb/logs/.
  • bb-app (including pnpm start), bb-server, and bb-host-daemon capture service stdout and stderr in logs/server-stdio.log and logs/host-daemon-stdio.log under the selected data directory. These append across restarts; a file over 10 MB is renamed to <name>-stdio.1.log (replacing the previous one) when its service starts. They hold early startup errors, crashes, and other output that bypasses the logger. Application log lines go only to the rotating <component>.N.log files, which keep the five newest per component; the logger skips its pretty console copy when stdout is a plain file, so pnpm dev terminals still show it. Service output is not forwarded to the launcher's terminal.
  • Entity IDs in URLs (proj_*, thr_*) are primary keys. Query them directly against the active data dir: sqlite3 <data>/bb.db "SELECT * FROM threads WHERE id = 'thr_xxx';".
  • API routes are under /api/v1/, for example GET /api/v1/threads/:id. Use curl against the server API to isolate frontend issues from server behavior.
  • Use the CLI to inspect state: pnpm bb thread show <id>, pnpm bb project list, pnpm bb status. From source, use pnpm bb:dev.

The desktop main process also writes rotating logs/desktop.log immediately, including updater, Connect, and startup errors. View → Local Logs is available on every desktop platform and when attached to an existing server; it follows local desktop, server, and daemon files in the selected data directory.

When the renderer of any desktop window (app windows, dialogs, Local Logs, bb Connect sign-in, browser popups) goes away, desktop.log records renderer gone (reason …, exit code …) with the window title. The desktop reloads the page after 500 ms, 2 s and 8 s; a fourth crash within five minutes, or a renderer that cannot launch, shows a "This window stopped working" page whose Reload button (or Cmd+R in app windows) restores the crashed URL with a fresh retry budget. A crashed find bar is dropped and recreated on the next find. To reproduce, attach to the main process with BB_DESKTOP_ELECTRON_ARGS="--inspect=<port>" and call webContents.forcefullyCrashRenderer() on a window.

Desktop Browser Tab Recovery

When the desktop app connects to a BB Connect server, it installs and renews the Connect desktop session in both the app and embedded browser cookie stores. This also authenticates shared-port links under the same Connect domain. The browser keeps its separate profile; unrelated site cookies are not copied.

Desktop browser registration first uses a private local broker descriptor whose recorded server URL matches the selected server's origin. Otherwise it discovers the other private local broker descriptors and sends a fresh random challenge to the selected server's /api/v1/desktop-browsers/broker-proof endpoint. The server routes it to the descriptor's enrolled host, whose broker returns an HMAC using its local authentication token. The desktop verifies that proof against the private descriptor before registering; the token never leaves the machine. This works for alternate domains and proxies without hostname rules or plugin dependencies. Redirects and invalid proofs are rejected. This internal desktop handshake adds desktop.broker.prove in daemon protocol 248. Older protocol-246/247 daemons remain compatible for existing operations; the server rejects proof requests for those daemons with an upgrade-required error before sending any RPC. Failed lookups retry with exponential backoff from 2 seconds up to 1 minute.

Saved desktop browser tabs keep their URL and owning host/window. Opening one in the desktop app attaches the existing view when that window still owns it, including after its connection generation changes. While the desktop or host is reconnecting, the panel retries for about a minute, then offers Try again.

The desktop keeps at most four hidden user browser pages resident across windows and servers, and evicts the renderer of any page hidden or unused for five minutes. A sweep runs every 30 seconds while hidden user pages exist; the least recently hidden or used pages are evicted first. Visible pages, agent-created tabs, downloads (including paused ones), control leases, attached debuggers, in-flight evaluations and captures, and pages with open popups are never evicted. An evicted (cold) tab keeps its identity in native tab lists and broker snapshots. Showing it, navigating it, evaluating, capturing, or leasing it restores its navigation history in the same browser session; in-page JavaScript state is lost. Hiding, moving, stopping, focusing, searching, or closing a cold tab does not restore it. CDP targets cover only resident pages, so a cold tab leaves the target list until it is restored.

Archiving a thread evicts its hidden pages in each desktop window at once, including agent-created tabs and pages with downloads; a page on screen is evicted once it is hidden. Control leases, attached debuggers, open popups, and in-flight evaluations or captures still keep a page until they end. Evicted tabs keep their saved tabs and restore like any cold tab. Unarchiving stops the immediate eviction and leaves the thread's pages to the idle rules above. Archive state reaches the window as realtime thread changes, so each time the window's realtime connection opens, including after a reconnect or a server switch, it re-reads the archive state of every thread with pages in that window. An archive or unarchive made while the window was disconnected applies then.

Switching servers hides each server's native pages and popups, pauses media, and revokes automation leases. Returning to the same server origin reattaches resident pages with their unsaved state; cold pages restore from history when shown. Native tab lookup, page events, and broker snapshots stay scoped to the active server. Closing the window or quitting the desktop app still releases its pages across all servers.

After a window closes or the app relaunches, the panel reopens the saved URL in the current window on the same host once the host confirms the old window is gone. Native history and unsaved page state are not restored. The desktop broker suppresses teardown snapshots from destroyed windows so closing a window does not delete its saved tabs before another window can recover them. The server adopts the restored tab from the window's browser snapshot and closes competing restored views if two windows reopen it concurrently. Snapshots from a stale restoring generation cannot adopt the tab. A newer snapshot from the same window and thread cancels a pending adoption, including when the newer snapshot is empty.

Web clients, other hosts, and other live windows show the saved URL and its availability instead of attaching a native view. Copy link remains available; Open in browser accepts only HTTP(S) URLs. The panel's tab close control also works in this state. Selecting another saved tab rechecks its owning window; Try again also rechecks a window previously reported as live after it closes. Inspect the persisted owner with bb thread tabs show <threadId> --json or sdk.threads.tabs.get, and compare it with bb browser instances --host <hostId> --json or sdk.experimental_desktopBrowsers.listInstances. Recovery uses the existing native snapshot and browser APIs; no daemon wire fields change.

Browser tab favicons retain their candidates across same-origin navigation. The native desktop manager caches candidates for the 40 most recently used HTTP(S) origins per connected server; returning to an origin or reopening its tab can reuse those candidates. Same-origin candidate updates retain earlier candidates as fallbacks, and empty updates leave the known icon intact. Crossing to an uncached origin clears the previous icon. The cache is in memory and ends with the desktop process.

The preload browser onState subscription immediately replays the latest validated state for up to 100 recently updated tabs before forwarding live updates. This lets remounted tab headers recover without waiting for a new favicon event. Renderer image-size measurements are also bounded and reused so remounts retain the appropriate Retina candidate. Image bytes still load through the renderer's browser cache; authenticated icon fetching through the embedded browser session is not implemented by this cache.

Log Fields

  • Slow DB query is logged when a prepared statement, exec batch, or complete transaction takes at least 100 ms. durationMs is elapsed time and cpuDurationMs is CPU time on the calling thread; a large gap means waiting or descheduling (filesystem I/O, lock waits, or scheduler contention), not necessarily slow SQL. operation: "transaction" covers the callback, commit, and rollback, and its SQL label is the transaction mode; statements inside it may log separately, so do not add their durations. Commits can include SQLite's automatic WAL checkpoint. SQL string literals are redacted and parameter values are never logged.
  • Connect's tunnel closed warnings include the last transport error's message and code, connectedDurationMs, and lastHeartbeatAckAgeMs. A null duration means the opening handshake never completed; a null acknowledgement age means no heartbeat acknowledgement arrived on that connection. They also carry the Cloudflare colo and ray, and traffic: open HTTP and WebSocket streams, bytes each way, how long each direction had been quiet, and bytes still buffered. tunnel connected and handshake timed out lines carry dial timings in milliseconds since dialing: lookupMs, connectMs, tlsMs, and upgradeMs (the gate's 101). A timed-out dial with tlsMs but no upgradeMs reached Cloudflare and was waiting on the gate. They appear in the server logs and <dataDir>/plugins/connect/logs/plugin.log.

bb Connect Gate Events

The gate answers every proxied request within the response-head timeout (30 s) from when the Worker receives it; a miss gets a 504 naming the stuck stage: routing, tunnel-object, request-body, response-head, or finishing. A relayed request still waiting in response-head at the deadline gets another 30 s while the tunnel object reports a heartbeat under 45 s old, up to 10 minutes from arrival. Workers Logs keeps only about 1% of gate requests, so the gate also writes these to the Analytics Engine dataset bb_connect_gate_events (bb_connect_gate_events_staging on staging):

  • blob1 stall (a 504) or slow (a tunnel dial unanswered after 3 s, or a relayed request first extended past the response-head timeout); blob2 stage, blob3 method, blob4 host, blob5 path; double1 elapsed ms; double2 tunnel-object attempts (above 1 means the object restarted and the dial was replayed).
  • For a stall that reached the tunnel object, blob6 is the tunnel state (connected, disconnected, or unknown when the object did not answer within 2 s) and double3 the age in ms of the last answered heartbeat, or -1. A bb heartbeats every 20 s, so an age of minutes means a dead tunnel the object still holds; a recent age means the bb's server did not answer. Routing stalls and slow events leave blob6 empty and double3 at -1.
  • blob1 tunnel-gap is written when a server's tunnel opens after a period with none: blob2 is how the previous tunnel ended (closed, lost, or unreported), blob3 is replaced-live when that tunnel had replaced a working one, blob4 host, double1 ms without a tunnel, and double2 the previous tunnel's lifetime (-1 when unreported). replaced-live with a short or unreported previous tunnel is a bb whose abandoned dial replaced its working tunnel; double1 + double2 near 300,000 means it then waited out the five-minute takeover backoff.

Query with the Analytics Engine SQL API and an Account Analytics Read token, for example SELECT timestamp, blob1, blob2, blob5, double2 FROM bb_connect_gate_events WHERE blob4 = '<handle>.getbb.app' ORDER BY timestamp DESC.

Observing Processes in Tests

A test must not learn about a process from its PID alone. The operating system reuses PIDs (Windows quickly), so a remembered PID can name an unrelated process. node scripts/check-test-process-identity.mjs, run in CI's plan job, rejects these in test code:

  • signal 0 (kill(pid, 0), shell kill -0);
  • liveness helpers given a PID (…Alive(pid), …Running(pid), …Exists(pid));
  • /proc/<pid> reads and ps -p <pid> probes;
  • PID comparisons (.not.toBe(oldPid), a.pid === b.pid, .not.toContain(oldPid));
  • process.kill(<remembered pid>, signal), including group signals. A failed spawn's child.pid ?? 0 would signal the runner's whole process group.

The process's own process.pid is allowed, and so is a ps call that reads a start time (lstart, etime) to compare a recorded identity. Use the fixtures in @bb/test-helpers/child-processes, the module that owns guarded signalling; forkable plugins get the same ones as experimental_ exports of @get-bb/plugin-sdk/testing.

  • Direct children: trackChildProcesses() records every ChildProcess spawned in the test process, including ones production code spawns internally. Use running(), waitForExit(), waitForClose() and killRunning(). Signal an owned child with child.kill() or killProcessGroup({ child }) from @bb/process-utils.
  • Node descendants and fake daemons: createProcessLifeline() gives a socket they join with holdSource(label, onHeld?). Await holder.exited; holder.kill() never signals a reused PID.
  • Shell descendants on POSIX: redirect into createDescendantPipe()'s path and await opened, then closed. Shell code that must wait for a process compares its recorded ps -o lstart= -p start time.
  • Real processes found through PID files or listings: compare readProcessIdentity() from @bb/process-utils, or stop them with stopVerifiedProcess() from @bb/config.
  • Restarted processes: compare an identity the process reports itself, such as a boot id.

Waits are event-driven and bounded by the test's own timeout, not by a separate deadline.

Reproducing Test Order Failures

CI's test shards shuffle test files and tests within each file. Vitest prints the seed for runs that execute; unchanged Turbo tasks can still reuse cached results. Reproduce a failing package with its logged seed:

pnpm exec turbo run test --filter=@bb/app -- --sequence.shuffle --sequence.seed=4721 --maxWorkers=2

For a repository-wide order audit, omit the filter and use --concurrency=4 before Turbo's -- separator. CI caps each Vitest process at two workers so package concurrency does not multiply into unbounded worker contention. Use a second seed after repairing order dependencies. Reset test-owned mock implementations, fixture arrays, persisted preferences, and databases before each test. Await background work and close streams, workers, and subprocesses before removing their files or tearing down their environment. Worker isolation does not restore built-in process objects or cancel resources that a test leaves running.

ACP Steer Cancellation Failures

ACP steering cancels the active prompt before submitting the follow-up. If that prompt returns an error during cancellation, BB marks the session for rebuilding before the next turn. The replacement process attempts session/load; providers without working session restoration start fresh and report the loss of in-agent history. The failed turn stays failed, and an unsent steer is not acknowledged as accepted.

Older Hermes adapters can throw NoneType.startswith during cancellation and leave their internal session marked running. Update Hermes to include the null-response fix and the running-state cleanup, then restart its retained process with bb thread stop <thread-id> before sending a new message. BB's recovery prevents reuse after a cancellation error; it does not repair the older adapter's failing turn.

Machine Authentication Cache

Successful verification of an unlimited daemon host key is cached in server memory for 30 seconds, capped at the key's expiry. The cache holds at most 1,024 entries and retains only token hashes. Hits neither read nor write the authentication database and do not extend the cache lifetime. The next request after expiry uses the existing verifier and updates usage timestamps, so lastRequest and updatedAt describe the last full verification rather than every request. A burst of concurrent cold requests can still perform separate verifications before the first result is cached.

Revocation and reenrollment invalidate that host's cached keys and prevent already-running verifications from returning or caching invalidated credentials. Restarting the server discards the cache. Enrollment keys and keys with quotas, refills, or enabled rate limiting always use the existing verifier. Direct edits to authentication rows outside the machine-auth service are observed when the cache expires; QA that changes a warmed key's database fields must account for that window. Expiry known when caching is enforced on every hit.

Slow Database Operations

The server logs Slow DB query when a prepared statement, exec batch, or complete transaction takes at least 100 ms. durationMs measures elapsed time; cpuDurationMs measures CPU time on the calling thread. A large gap indicates waiting or descheduling, not necessarily inefficient SQL. It does not by itself distinguish filesystem I/O, lock waits, and scheduler contention.

operation: "transaction" includes the callback, commit, and rollback; its SQL label identifies the transaction mode rather than containing callback SQL. Statements inside it may also log, so do not add their durations to the transaction duration. Commit timing matters because SQLite's automatic WAL checkpoint can perform filesystem writes and synchronization on the server thread. operation: "exec" also covers maintenance batches. SQL string literals are redacted and parameter values are never logged.

Only while performance diagnostics are enabled, slow-DB records also include diagnostics.resourceUsage: process-wide deltas for minorPageFault, majorPageFault, fsRead, fsWrite, voluntaryContextSwitches, and involuntaryContextSwitches. These are counts, not bytes or durations, from Node's resourceUsage. They can include activity on other process threads. Unsupported OS counters remain zero; in particular, zero filesystem counters do not rule out I/O or fsync waits. Page faults do not identify whether the fault was on the SQLite mmap, the server heap, or another mapping, and these counters do not measure swap-in bytes.

diagnostics.wal.sizeBytes is the most recent asynchronous sample of the WAL's physical file size. A slow log with diagnostics enabled requests a refresh at most once per second per connection, with at most one refresh in flight. diagnostics.wal.sampledAt is the sample's UTC completion time; the log uses the previous sample, which may be older after an idle period. Both fields are null before the first sample and for in-memory databases. Missing or inaccessible WAL files report a null size with a sample timestamp. WAL size can include space reused by earlier generations; it does not measure uncheckpointed backlog or identify checkpoint progress. Resource sampling is also disabled with the live gate.

Slow SQLite query plans

With BB_QUERY_PLAN_AUDIT=1 (the default for pnpm dev, pnpm start:worktree, and pnpm desktop:worktree) or the performanceDiagnostics experiment on, the server runs EXPLAIN QUERY PLAN once for each distinct statement and parameter shape it executes, after the statement returns, against a read-only connection to the same database. It logs a Slow SQLite query plan warning, once per process for each rule, table, and caller, when the plan:

  • walks events, thread_search_segments, prompt_history_entries, or terminal_sessions through an index that matches fewer equality terms than another index on that table (weaker-index);
  • scans one of those tables in full (full-scan);
  • builds an automatic index (automatic-index);
  • searches one of those tables once per outer row, from a correlated subquery or an EXISTS subquery SQLite turned into a join, through a key that grows with history (correlated-subquery). A search that pins a unique key, or an events column whose rows are bounded per value (turn_id, item_id, parent_tool_call_id), is accepted; a search on thread_id and type alone is not, because it rereads the thread's history for every outer row; or
  • loops over a CTE or subquery result, without an index, once for each row of a search on one of those tables through a key that grows with history (nested-loop). json_each and other virtual tables over the row's own JSON are not counted.

caller is the src/ file and function that ran the query; in the built server, the file comes from the module comments esbuild writes into apps/server/dist bundles, so it needs an unminified bundle. Callers are read from POSIX stack paths, so the audit logs nothing on Windows. Findings listed in packages/db/src/query-plan-allowlist.ts are not logged. The tests apply the same rules and fail on findings missing from the allowlist; see packages/db/src/query-plan-guard.ts. On pull requests, the Linux test shards set BB_QUERY_PLAN_EXECUTED, so @bb/db and @bb/server record the query functions they run in .query-plan/executed.jsonl (a Turbo test output, so cached runs restore it). The Query functions run in tests job then fails when an exported query function in a packages/db/src/data file the PR changed never ran. The Query Plan Audit workflow (.github/workflows/query-plan-audit.yml) runs nightly on main, on pull requests that change packages/db, and by hand. Its audit job checks for allowlist entries no test reports and for exported query functions in packages/db/src/data that no @bb/db or @bb/server test runs; reproduce it with BB_QUERY_PLAN_REPORT=<file> pnpm exec turbo run test --filter=@bb/db --filter=@bb/server followed by pnpm --filter @bb/db check:query-plan-report <file>.

Plans cannot show what a query costs once data grows, so the workflow's cost job runs pnpm exec turbo run check:query-costs --filter=@bb/db. It builds worlds through the real write paths and compares them along two axes:

  • Thread history: a thread with 625 or 10,000 turns (about 250,000 events in the full-scale world), plus what each case group in packages/db/scripts/query-costs/ seeds for its tables at about twice the size of the largest real user (for example 10,000 threads with title and message search segments, 4,000 environments, 50,000 prompt history entries and 15,000 terminal sessions at full scale).
  • Turn size: a 500-turn thread whose first and last turns, and the open turn of a second, running thread, have 94 or 1,500 steps (about 1,100 or 18,000 events each: reasoning, commands with streamed output, file edits, commentary, plan and usage updates, and delegations).

HistoryFixture.liveTurn names the open turn, and the open long turn cases in events-cases.ts time the reads and appends a running thread makes against it. The check calls every exported query function in packages/db/src/data and in the plugin database modules (below) against the smaller and larger world of each axis, interleaved, each call inside a rolled-back savepoint. Each call is timed by CPU time, not by the wall clock, so other work on a busy runner does not count against it: the thread's CPU time on macOS, and the process's on Linux, where a thread's CPU time only advances at scheduler ticks and reads near zero for short calls. The check keeps the fastest of at least three calls per world. The larger world is 16 times the smaller, so a bounded cost measures about 1x, a linear one about 16x (size^1, up to about size^1.5 on shared CI runners, where memory-heavy queries scale worse under neighbouring load), and a quadratic one about 256x (size^2).

A query function is expected to stay bounded: its cost must not grow faster than size^0.5 (4x) on either axis once its larger-world time reaches the growth floor. A full-history read that keeps a few rows, such as filtering every request event of a thread by a JSON field, measures about size^1 and fails. A case whose cost must grow, because it returns or modifies rows the larger world has more of, declares the axis with the reason: growsWith: { history: "Lists every thread on the host, and the seed grows the thread count" } (history or turnSize). A declaration that measures within size^0.125 (1.4x) is reported as a warning so it can be removed once the query is bounded; the gap between size^0.125 and size^0.5 keeps runner noise from either failing an undeclared case or flagging a declared one that only partly grows.

The growth floor is 2 ms on the reference machine, scaled by how long a fixed SQLite calibration workload takes on the current one, measured after the worlds are built (packages/db/scripts/query-costs/calibration.ts), so a slower CI runner checks roughly the cases a laptop does. The floor only screens out calls too small to time reliably; every case that grows with data declares it, so a case crossing the floor on one runner and not another does not change the result. The check prints the calibration, and for each axis the five undeclared functions closest to the limit. The check fails when:

  • an undeclared function grows faster than size^0.5 (4x);
  • a declared function grows faster than size^2 (256x);
  • a function takes longer than its ceiling in the larger world of either axis, whether or not it declares growth: 100 ms on the reference machine, scaled by the calibration like the growth floor, unless its case sets a higher ceilingMs with a reason. Every query runs synchronously on the server's main thread, request path or sweep alike, so a declaration explains why a cost grows but never lets it grow without bound; or
  • a single call runs for more than 5 seconds of wall time, when it is killed, or a case throws.

It reports a GitHub Actions warning, without failing, when a declared function grows faster than size^1.5 (64x), or when a case raises ceilingMs but measures within a third of the default ceiling on every axis, so the raise can be removed. A case that crosses size^0.5 or its ceiling is measured up to eight times before it is reported. The default sits at about twice the slowest bounded case on CI, where heavy reads run up to 4 times slower than on the reference machine while the calibration moves about 1.5 times. The request-path statement-count test below is exact, so it stays blocking.

The check also fails when an exported query function in packages/db/src/data has no case. A query function is an exported function that builds a query itself or calls a function in the same file that does, so wrappers around a private query helper count too (pnpm --filter @bb/db list:query-functions lists them; the same list drives the "query functions run in tests" checks). --group <name>[,<name>] runs only those case groups and skips the coverage check.

Server code runs SQL only through those query functions: apps/server/test/sql-in-data-modules.test.ts fails when a file in apps/server/src imports drizzle-orm at runtime or builds a query on a db, tx or $client receiver. The server may still open a transaction and pass it to query functions, and pass $client to connection-level helpers (backup, checkpointing, vacuum).

Plugins that keep their own SQLite file run it on the same main thread, but a forkable plugin cannot load @bb/db, so its test guard never sees them. The check therefore also covers the plugin database modules listed in PLUGIN_QUERY_MODULES (packages/db/scripts/query-functions.ts): the account-pool, automations and workflows stores. Their cases live in packages/db/scripts/query-costs/plugin-databases-cases.ts. Each of these groups sets pluginDatabase, so every world gets a separate database per plugin, opened as the server opens plugin databases (better-sqlite3 enforces foreign keys by default), which the group's seed migrates with the plugin's own statements and fills at both sizes; exported functions and public methods of exported classes count as query functions. The check also explains every statement those cases run against the larger history world's plugin databases and fails on the query-plan guard's rules for the tables the group lists in pluginDatabase.auditedTables, unless the group's pluginDatabase.allowedFindings lists the finding with the case name as its caller and a reason; an allowed finding no case reports is a warning. The workflow runs on pull requests that change these modules as well as packages/db. To time the cases against real data shapes, make a copy with sqlite3 ~/.bb/bb.db "VACUUM INTO '/tmp/bb-copy.db'" and run pnpm --filter @bb/db check:query-costs --db /tmp/bb-copy.db: it migrates the copy, seeds a world with 10,000 turns and 1,500-step long turns into it, and fails only on the ceiling, the plugin plan audit and the 5-second kill, since there is no second size to compare. The copy is written to; never point --db at ~/.bb/bb.db (the check refuses), and never start a bb server on the copy.

Both checks time single functions, so neither sees a request that calls a cheap query once per turn. apps/server/test/perf/request-path-statements.test.ts covers that: it builds the same fixture (@bb/db/history-fixture) in pairs of test servers, one pair per axis. On the history axis one server has 100 turns and 20 other threads and the other twice both; on the turn-size axis both have 100 turns, with 750-step or 1,500-step long turns, large enough that the timeline window cuts inside the open turn. It runs hot request paths against each pair (thread list, search and count, timeline, conversation outline, turn details, events, prompt history, send with a queued retry, edit, stop, fork, and the running thread's timeline, head state, a streamed timeline delta, daemon ingestion, send and stop), and fails when a path executes any statement more often in the larger server, or when its response bytes grow more than 1.5 times. Statements are counted at the better-sqlite3 layer, with parameter lists collapsed so a longer IN (...) list counts as the same statement. The counts are exact, so the test does not depend on machine speed. A path that grows by design, such as fork copying history or turn details returning the whole turn, declares it per axis and may grow at most linearly.

bb lowers agent CPU priority so it stays responsive when agents saturate the CPU:

  • The host daemon sets nice 10 (the below-normal priority class on Windows) on provider processes and environment lifecycle scripts as they start, and the builds and tests they launch inherit it. Terminals keep normal priority.
  • On macOS, where the scheduler ignores nice between processes, the launcher spawns the server and daemon through /usr/sbin/taskpolicy -a (application scheduling, not inherited by their children). Check with ps -axo pid,ppid,pri,ni,command: the server and daemon show PRI 46, their children 31.

A slow-DB record whose cpuDurationMs is a small fraction of durationMs with many involuntaryContextSwitches means the server thread was waiting for a CPU rather than working; on Linux check that agent processes show NI 10 in ps -o pid,ni,command.

Pending Question Drafts

Native provider questions and Ask User Question plugin forms save partial selections, free text, and the current question in browser-local storage under bb.question-draft.v1:<threadId>:<interactionId>. These drafts survive thread navigation and page reloads on the same browser/device. They are cleared after successful submission or cancellation and retained if either request fails. When local storage is unavailable, an in-memory fallback preserves drafts across navigation until the page reloads. Drafts are not sent to the agent until submitted, and CLI/SDK answers do not read the browser's draft. There is no time-based expiry. If an interaction is resolved elsewhere, its draft can remain in local storage but is never rendered as an active question; the server's pending interaction list controls that. Clearing browser site data removes these drafts. Older clients ignore this new storage namespace. Only the native question form and Ask User Question plugin opt in; secret-request forms do not use this storage.

Native Draft Rollback

Migration 0132_thread_drafts now only adds the temporary threads.draft column. Its original pre-release SQL merged Drafts plugin queue entries into that column and deleted the held rows and built-in plugin installation. The original hash remains accepted by migration-history.ts for databases that already ran it; it is not replayed.

Migration 0133_remove_thread_drafts drops the column without converting its contents back into queued messages. Databases upgrading through the revised 0132 retain their existing queue rows and Drafts plugin installation. Databases that ran the original 0132 lose the stored core draft contents, retaining their thread rows and any remaining queued messages. The restored built-in plugin is installed through normal server startup. Reintroducing native drafts requires a new migration after 0133.

Archive Confirmation Counts

GET /api/v1/threads/:id/child-summary and sdk.threads.childSummary return nonDeletedChildCount for deletion (direct children, including archived rows) and unarchivedDescendantCount for archive confirmation. The latter follows the same hierarchy, lifecycle-owner, and hidden source-fork edges as archive-all, deduplicates threads, traverses archived intermediaries, and excludes hidden, already archived, or deleted candidates and the requested root. Hidden threads still participate in the archive cascade, and visible descendants beneath hidden threads still count toward confirmation. The UI adds the root to the displayed total and skips confirmation when no unarchived descendants remain or the General setting confirmThreadArchive is disabled. The summary is a preview; concurrent changes can alter the eventual archive result. CLI and SDK archive calls remain non-interactive.

File Content Routes

Clients read file bytes through path-shaped GET routes, so relative URLs in HTML and markdown resolve against the same route:

  • /api/v1/threads/:id/thread-storage/files/:path reads the thread's storage folder.
  • /api/v1/threads/:id/host-files/:absolutePath and /api/v1/hosts/:id/files/:absolutePath read the thread environment's host or the named host from its filesystem root. The path omits the leading /; a first segment such as C: selects that Windows drive root.
  • /api/v1/environments/:id/files/:path reads the environment workspace, and /api/v1/environments/:id/revisions/:ref/files/:path reads HEAD or a 4-40 character hex commit from it.
  • /api/v1/projects/:id/files/:path and /api/v1/projects/:id/hosts/:hostId/files/:path read the project's local-path source on the primary or named host.

Media elements, HTML iframes, markdown images, and Download links use these URLs directly. The server resolves the root on every request, so they need no setup and do not expire.

Plugins that preview an arbitrary host directory instead mint a lease: POST /api/v1/files/previews with { hostId?, rootPath, ttlMs? } returns { baseUrl, expiresAtMs }, and GET /api/v1/file-previews/:lease/:path reads that root. Minting the same root again returns the same baseUrl and extends its expiry. Leases live in server memory and do not survive a server restart.

File content reads support a single HTTP byte range for media playback, seeking, and file preview sampling. Responses advertise Accept-Ranges: bytes; bounded, open-ended, and suffix ranges return 206 with Content-Range and the selected bytes. Unsatisfiable ranges return 416 with Content-Range: bytes */<size>. Malformed ranges, unsupported units, and multipart ranges fall back to the full 200 response. HEAD ignores Range. Revision routes read the file with one whole-file daemon read, so those responses ignore Range, keep the daemon's 25 MB non-image limit, and revalidate with a strong SHA-256 ETag.

File previews request the first 64 KiB. A complete sample becomes the preview directly. Otherwise the sample, its MIME type, and the Content-Range size classify the file: images and videos render from the file URL, binaries show their size and a Download link, and text is fetched in full only when it is at most 25 MB. The Download link is the file URL with the anchor download attribute, so the browser streams it to disk without the 25 MB limit.

If-None-Match revalidation takes precedence over Range. Streamed responses use weak metadata ETags (W/"file-<revision>"), not content SHA-256 hashes. This avoids reading an entire large file just to validate it. Because the validator is weak, any If-Range header falls back to a full 200 response, including a matching weak tag or date. All raw file responses carry Content-Security-Policy: sandbox allow-scripts, including SVG and XHTML, so directly opened documents cannot acquire the app's origin privileges. HTML also carries the no-store policy, at any size; the app renders an HTML iframe only for files up to 5 MiB and shows larger HTML as source or, past 25 MB, as a Download.

The server's first host.read_file_chunk returns the file's metadata together with its first 64 KiB, so a file up to 64 KiB takes one daemon round trip. That read sends the revisions named in If-None-Match as knownRevisions; when the file still has one of them, the daemon returns no bytes and the server answers 304. HEAD, If-None-Match: *, and ranges that do not start at byte 0 make the first read metadata-only (length: 0). Later reads take at most 64 KiB per RPC, keeping up to 16 RPCs in flight ahead of the HTTP consumer. The daemon returns each chunk's bytes as a binary WebSocket frame (a 4-byte header length, the JSON frame, then the raw bytes) instead of base64 inside JSON. HEAD, 304, and 416 responses read no contents. Cancelling, aborting, or a failed chunk stops subsequent reads and aborts the RPCs still in flight. Each RPC opens and closes its file handle, so no remote read session needs cleanup. Offsets and lengths are validated at the daemon boundary, and paths remain confined to the route's root.

The daemon's session socket keeps small messages ahead of bulk data. Terminal output and file chunks queue per terminal or per chunk RPC and take turns; everything else (RPC replies, heartbeats, events, and terminal output under 4 KiB such as keystroke echo whose terminal has nothing queued) is written at once. Bulk is written only while the socket buffers at most 64 KiB and the bulk the server has not yet acknowledged fits a send window; the server acknowledges every 32 KiB it receives. The window starts at 256 KiB and adapts between 64 KiB and 4 MiB by 64 KiB per round trip: it grows while acknowledgement round trips stay near the lowest seen in the last 10–20 seconds, and shrinks while its own bulk keeps more than about 144 KiB and 10 ms queued on the path. A terminal's exit, error, and replay messages stay behind its queued output. Without the window, bulk bytes sat in kernel and network buffers and a reply waited behind them: on a 45 ms, 3.6 MB/s link, replies took about 400 ms during a file download.

The daemon returns a revision based on device, inode, size, and nanosecond mtime/ctime. Every content read checks the expected revision before and after reading from its open descriptor. A mismatch before response headers produces retryable 409 file_changed; a change or error after streaming starts aborts the HTTP body. The server also rejects short/misaligned chunks. This detects ordinary writes, truncation, and replacement; it is not an immutable filesystem snapshot or a cryptographic guarantee against changes hidden by filesystem metadata granularity.

Streamed reads bypass the whole-file size caps (including the 25 MiB non-image cap); each chunk stays bounded regardless of file size. host.read_file consumers such as POST /files/read and revision routes keep their whole-file limits and SHA-256 validators. sdk.projects.fileContent (and bb project content) reads through the project file routes and decides utf8 versus base64 from the returned bytes. Host-daemon protocol 219 introduced the chunk RPC; older enrolled daemons cannot serve streamed reads until updated.

Stale Workspace Claims

Failed thread provisioning immediately requests environment cleanup. If a previous failure left a claim behind, sends, environment admission, and provider path claims repair it when they encounter it; restarting the server is not required.

Claims owned by threads that are still starting or stopping remain blocked. A stale claim on a ready or shared checkout is released locally, preserving the workspace. A partially created environment retains its claim and is scheduled for the existing background lifecycle cleanup. Sends report workspace_busy with “Workspace cleanup is pending. Try again shortly.” until removal completes. Provider cleanup is never awaited by this admission repair, and startup does not scan for abandoned claims.

A thread create that finds the path claimed by another create whose thread is still starting or stopping waits for that create to settle instead of failing. A provisioning thread that hits the same claim while attaching stays starting and resumes its provisioning when the claim settles, without holding up the command result that drove it. Both wake on changes to the claiming thread or its environment and re-run admission. After 15 minutes (the setup hook bound, which matches the checkout provider's own wait for a claimed path) they fail with the usual workspace_busy "Cannot checkout branch while another thread is using this workspace". Explicit reuse requests, sends, thread commands and directory changes still fail immediately. A create that adopts a workspace whose setup is still running joins that setup instead of running it again.

Local Dev QA

Run pnpm dev from this checkout and keep it running in a terminal. It prints the checkout-specific URLs, data directory, and logs directory. Stop it with Ctrl-C. For desktop-only changes, start pnpm exec turbo run dev --filter=@bb/desktop in a second terminal.

Use the Node version in .nvmrc (22.19.0). Desktop development requires Node 22.19 or newer in the Node 22 release line.

A bb connect shared-port URL is a different browser origin from localhost. If QA through that URL needs the browser-local host daemon, restart the dev app with the share origin configured after exposing its app port:

BB_APP_URL=https://<handle>--<app-port>.getbb.app pnpm dev

The port remains stable for the checkout, so the existing share continues to work after the restart. The host daemon intentionally rejects remote origins that are not configured; otherwise any webpage could drive its local editor API.

For CLI QA, pnpm bb:dev derives this checkout's server and daemon endpoints. In the test shell, clear inherited endpoint and thread context overrides first so commands target the dev instance. Keep these changes inside that shell.

Test agents with:

unset BB_SERVER_URL BB_HOST_DAEMON_PORT BB_THREAD_ID BB_ENVIRONMENT_ID BB_THREAD_STORAGE BB_PROJECT_ID BB_CLI BB_CLI_REEXEC
pnpm bb:dev thread spawn --project proj_personal --provider codex --permission-mode accept-edits --title "Smoke test" --prompt "Reply only with ok." --json

Local Cloud

Run the Cloud dashboard, the Connect worker, and the AI gateway against one local Postgres database:

pnpm cloud:dev

Nothing needs to be installed first. The command opens a PGlite database in connect-db-pglite under the state directory (.wrangler/cloud-dev, or BB_CLOUD_DEV_STATE_DIR), applies the migrations, serves it over the Postgres wire protocol on a loopback port derived from the worktree's dev ports, and points the three workers' HYPERDRIVE binding at it. The startup log prints the connection string, so psql or a pg script can inspect the data while it runs. The PGlite server runs one statement batch at a time; a client's open transaction holds the database until it commits, rolls back, disconnects, or idles for 60 seconds.

BB_CLOUD_DEV_DATABASE_URL uses another Postgres instead, for example a container:

docker run -d --name bb-connect-pg -p 5432:5432 \
  -e POSTGRES_USER=bb -e POSTGRES_PASSWORD=bb -e POSTGRES_DB=bb_connect \
  postgres:17
BB_CLOUD_DEV_DATABASE_URL=postgresql://bb:bb@localhost:5432/bb_connect pnpm cloud:dev

The command prints the dashboard URL when it is ready. Create a local email/password account, claim a handle, create a pairing code, and run the displayed bb account login --code command against a bb started with pnpm dev (bb connect --code does the same and also turns remote access back on). A browser sign-in started with bb account login opens <local origin>/link?code=… on the same origin. The same worktree-specific local origin serves the dashboard at bb.localhost, sends bb.localhost/api/ai/* to the AI gateway worker, and routes <handle>.bb.localhost through the Connect worker. Email/password auth is enabled only for this loopback workflow; production remains GitHub-only. pnpm dev automatically sets BB_DEV_CONNECT_BASE_URL to that worktree's local Cloud origin. While the bb is signed out, Settings → bb account and Settings → Installed plugins → Connect therefore sign in against the local Cloud, and a pasted code redeems locally. An explicit --base-url ... (or bb connect --server ...) still wins, so the dev bb can still sign in to getbb.app. Local machine enrollment follows the same origin: local http: server URLs produce ws: machine tunnels and http: share URLs, while non-local machine enrollment remains HTTPS-only.

BB_CLOUD_DEV_STATE_DIR moves the local Durable Object state away from .wrangler/cloud-dev.

The AI gateway answers 503 unavailable until an OpenRouter key is present. Export OPENROUTER_API_KEY in the shell before pnpm cloud:dev to pass it through to the local worker; the startup banner says which mode is active. To exercise the whole chain without OpenRouter, export BB_CLOUD_DEV_AI_UPSTREAM_BASE_URL (for example http://127.0.0.1:4599/api/v1) pointing at a local OpenAI-compatible fake, plus any non-empty OPENROUTER_API_KEY. The production gateway gets the key from the repository's OPENROUTER_API_KEY Actions secret, which deploy-ai-gateway.yml uploads with each deploy. Set the staging key with wrangler secret put OPENROUTER_API_KEY --env staging from apps/ai-gateway. Use a dedicated OpenRouter key with account-wide zero data retention and a daily credit limit.

Ctrl-C stops the local services. Account data and Durable Object state are kept under .wrangler/cloud-dev (or BB_CLOUD_DEV_STATE_DIR); delete that directory to start over. With BB_CLOUD_DEV_DATABASE_URL, account data stays in that database.

To test a source bb against the deployed staging Cloud instead, start it with pnpm dev --staging. bb account and Connect then sign in, redeem codes, open tunnels, and call the AI gateway at https://vibecodethis.site; no pnpm cloud:dev is needed. The flag only changes the default origin, so a dev data dir already signed in elsewhere keeps its account until bb account logout.

Record Provider Bridge Traffic

Export BB_PROVIDER_BRIDGE_RECORD_DIR before you start the dev app and every provider bridge records its runtime and provider wires as NDJSON:

BB_PROVIDER_BRIDGE_RECORD_DIR=$HOME/.bb/provider-recordings/raw pnpm dev

In a second terminal, run:

unset BB_SERVER_URL BB_HOST_DAEMON_PORT BB_THREAD_ID BB_ENVIRONMENT_ID BB_THREAD_STORAGE BB_PROJECT_ID BB_CLI BB_CLI_REEXEC
pnpm bb:dev thread spawn --project proj_personal --provider codex --prompt "Run git status." --json
ls ~/.bb/provider-recordings/raw/codex/

The layout is <dir>/<providerId>/<threadId>/<direction>.ndjson, plus a _process scope for lines that belong to no thread. See provider-bridge-protocol.md, "Record mode", for the entry format. Raw recordings can contain secrets and absolute paths. Run node scripts/provider-recordings/redact.mjs <raw-dir> <out-dir> before you share one, and never commit a raw recording.

To compare two checkouts' bridges on the committed recordings, run pnpm parity --old <checkout> --new . [--provider <id>] [--cell <name>]. Each leg replays every cell through its own bridge, assembler, and timeline projection; the run prints a PASS/FAIL line per cell with event and row counts and exits non-zero on any diff outside packages/provider-bridge-protocol/recordings/parity-allowlist.json.

Performance Fixture Database

Use pnpm seed:perf to fill a dev database with a large, realistic fixture: many projects, ~1,200 threads, and ~400k event rows with production-like payloads. Use it to reproduce performance problems that only appear at scale.

  • Start the dev app once first (pnpm dev), then stop it and seed. The fixture then attaches to the real local host, so agents still run.
  • By default the command seeds this checkout's dev data dir. Pass --data-dir <path> for another target. The command refuses to touch ~/.bb.
  • Scale flags: --projects, --threads, --events, --seed. --reset deletes the database file first. Without --reset the fixture appends.
  • Example: pnpm seed:perf -- --reset --events 400000.

Opt-in Benchmarks

pnpm exec turbo run bench runs the benchmarks that turbo run test skips. The task is uncached, and each package's bench script turns its benchmark on:

  • @bb/app: the sidebar thread list mount and update benchmark (sidebar.bench.test.tsx). BB_SIDEBAR_BENCH_THREADS sets the thread count (default 3000) and BB_SIDEBAR_BENCH_OUT writes the results as JSON.
  • bb-plugin-bb--composer: the composer large-paste benchmark (prompt-paste-performance.test.ts). PROMPTBOX_PERF_FIXTURE_OUT saves the paste fixture.
  • @bb/host-watcher: the root watcher recovery benchmark (root-recovery-benchmark.test.ts). BB_WATCHER_BENCHMARK_OUTPUT writes its report.

Filter to one package, e.g. BB_SIDEBAR_BENCH_OUT=/tmp/sidebar.json pnpm exec turbo run bench --filter=@bb/app. Compare runs on an idle machine; the numbers are wall-clock timings.

Provider Corpus

The provider corpus is a private set of real production threads extracted from a personal ~/.bb/bb.db. It is the regression oracle for timeline projection: every change must project the same rows and build timelines at the same speed. The corpus contains real prompts, code, and paths, so it is never committed; .gitignore blocks every provider-corpus/ directory except the in-repo harness and scripts.

  • Location: ~/.bb/provider-corpus/ by default. Tests read it through BB_PROVIDER_CORPUS_DIR and skip when the variable is unset or the directory has no manifest.json, so CI and fresh checkouts stay green.
  • Layout: manifest.json (thread selection and reasons), profile.json, threads/<provider>/<threadId>/{meta.json,events.ndjson}, and the generated snapshots/ directory described below.
  • Reader: @bb/test-helpers exports corpusAvailable(), listCorpusThreads({ provider?, reasons? }), and loadCorpusThread(id). Event rows decode through the same parseStoredThreadEvent the server uses.

Gates under apps/server/test/provider-corpus/:

  • row-snapshots.test.ts loads each thread into in-memory SQLite and projects every timeline page the way GET /threads/:id/timeline does (default and nested variants), then compares the rows with snapshots/rows/<provider>/<threadId>.json.
  • timeline-perf.test.ts measures cold builds of the 10 largest threads per provider (latest page and full page walk) and compares with snapshots/perf-baseline.json. The CI micro-benchmark in the same file needs no corpus.
  • timeline-streaming-memo.test.ts appends streaming rows to each thread's latest turn and requires every latest-page build to equal a build on a fresh connection with empty caches.

Run them:

scripts/provider-corpus/snapshot-rows.sh compare   # default mode, fails on diffs
scripts/provider-corpus/snapshot-rows.sh write     # refresh the baseline

The script wraps pnpm exec turbo run test:provider-corpus --filter=@bb/server with BB_PROVIDER_CORPUS_SNAPSHOT=write|compare. Turbo strips undeclared variables, so use that task (not the package test task) when you set the corpus variables. Each run writes snapshots/rows-last-run.json and snapshots/perf-last-run.md with totals and the perf table.

Compare mode fails on any row diff that snapshots/allowlist.json does not cover. An entry names a scope, a path, and the PR that made the change:

[
  {
    "threadId": "thr_abc123",
    "path": "/variants/*/pages/*/rows/*/output",
    "pr": "#1234",
    "reason": "…"
  },
  {
    "provider": "codex",
    "path": "/variants/default/pages/**/planSteps",
    "pr": "#1235",
    "reason": "…"
  },
  { "*": true, "path": "/variants/**/maxSeq", "pr": "#1236", "reason": "…" }
]

path is a JSON pointer over the snapshot, or a glob where * matches one segment and ** any number. The run prints the entries it used; an entry that covers nothing fails the run because it is stale.

snapshots/rows is the baseline minted on main and shared by every workstream, so never run write against it from a feature branch. A PR that intentionally changes rows carries its own allowlist in the repository (apps/server/test/provider-corpus/allowlists/<ws>.json, same schema, merged after the shared file) and compares with BB_PROVIDER_CORPUS_ALLOWLIST=<that file>. A snapshot of the branch's own rows goes to a shadow directory: BB_PROVIDER_CORPUS_SNAPSHOT_DIR=<dir> redirects both write and compare. Re-mint snapshots/rows from main after such a PR merges and delete the allowlist file it carried.

A pointer allowlist cannot describe a change that adds or removes rows: every later sibling shifts and the diff reports the whole turn. For such a change, carry a row-class file instead (apps/server/test/provider-corpus/allowlists/<ws>-row-classes.json) and set BB_PROVIDER_CORPUS_ROW_CLASSES=<that file> on the compare run. The gate then matches rows by identity (callId, itemId, interactionId, turn id, or row id), buckets every change into the first class whose matcher fits, and fails on a change no class claims or an entry that claims nothing (judged per entry, so a dead matcher cannot hide behind a sibling with the same name). A class names a reason and one matcher: added, removed, moved (the row left one nesting level for another), resegmented (a turn shows a different number of visible segments), reshaped (from/to kinds, optionally the other fields the reshape may touch), or changed with the fields it may touch; each narrows by kind, workKind, role, and nested. Turn bounds that follow a changed child fall into the built-in container-bounds class. The run prints the count per class and records them in rows-last-run.json. To iterate on the classes without re-projecting the corpus, mint the branch's rows once into a shadow directory and classify the two directories offline:

pnpm exec tsx scripts/provider-corpus/classify-row-diff.ts \
  ~/.bb/provider-corpus/snapshots/rows ~/.bb/provider-corpus/snapshots/rows.<ws> \
  --classes apps/server/test/provider-corpus/allowlists/<ws>-row-classes.json --verbose

Perf compare mode passes when each thread's normalized cost (minimum build time divided by a fixed CPU calibration workload run alongside it) is within 10% of the baseline, or within 5 ms for small latest-page builds, and the median event size is within 15%. Compare mode refuses a baseline written with different gate settings. Run the gate on a machine whose load average is below its core count; the table header warns when the machine is oversubscribed.

Timeline History Walk

apps/server/test/timeline-history/paged-walk.test.ts checks the paging contract in docs/timeline-pagination.md against a whole real database. It copies the database named by BB_TIMELINE_HISTORY_DB with VACUUM INTO (opening the source read-only, so a running server is unaffected), migrates the copy, and for every thread compares a paged walk at the default window budget and at 120 events with one full build. It fails with the threads and budgets that differ and deletes the copy afterwards. It starts no server, so it cannot take over the bb Connect tunnel. Without the variable the suite skips.

BB_TIMELINE_HISTORY_DB=~/.bb/bb.db pnpm exec turbo run test:timeline-history --filter=@bb/server
BB_TIMELINE_HISTORY_DB=~/.bb/bb.db BB_TIMELINE_HISTORY_THREADS=thr_a,thr_b \
  pnpm exec turbo run test:timeline-history --filter=@bb/server

Run it on changes to timeline selection, ownership, or projection. A full run over about 4,500 threads takes about ten minutes, most of it the copy and the full builds. The synthetic equivalence tests in apps/server/test/services/threads/timeline-read-equivalence-*.test.ts cover only the event kinds the generator produces; timeline-guard-coverage.test.ts lists the kinds it does not.

Desktop Browser Smoke Tests

pnpm exec turbo run smoke:browser-cdp --filter=@bb/desktop > /tmp/browser-cdp-smoke.log 2>&1
pnpm exec turbo run smoke:browser-cdp --filter=@bb/desktop -- --dev-browser /absolute/path/to/dev-browser > /tmp/browser-cdp-local-smoke.log 2>&1
pnpm exec turbo run smoke:browser-broker --filter=@bb/desktop -- --dev-browser /absolute/path/to/dev-browser > /tmp/browser-broker-smoke.log 2>&1

smoke:browser-cdp drives real Electron WebContentsView tabs through the production CDP bridge with checksum-pinned DevBrowser and agent-browser releases, a local fixture site, and a separate Electron profile; it starts no BB core and reads no existing store. It requires Linux x64, xvfb-run, and network access to GitHub releases. The command prints its artifact directory (screenshots, protocol traces, result summary); credentials are redacted. --dev-browser tests a local DevBrowser build instead, records its SHA256, and adds cross-origin iframe snapshot-reference checks that the pinned release cannot pass. Run the task with -- --help for usage. Popup control is untested. A result with forcedExit: true means Electron did not quit within five seconds and its process group was killed: the browser checks passed, but graceful shutdown was not proven.

smoke:browser-broker runs the actual SDK and CLI against an in-memory migrated test server, an authenticated host broker, the desktop broker client, and real Electron tabs. The harness supplies the server-to-host RPC responder, so it does not prove remote-machine transport. It uses no existing BB store or browser profile.

Provider-literal ratchet (G1)

node scripts/check-provider-literal-ratchet.mjs counts provider-id literals ("codex", "claude-code", "acp-…", providerId === "…", isAcpProviderId, …) in core (everything outside plugins/provider-* and examples/) and compares a per-file count against scripts/provider-literal-baseline.json. The count may only go down, so adding a provider-id branch to core fails CI. After removing literals, regenerate the baseline with --write and commit it. --list prints every hit. When the baseline reaches zero, delete it and the guard. See provider-plugin-api.md.

Branch ref owner

node scripts/check-branch-ref-owner.mjs keeps the choice between a local branch and origin/<name> in one place: resolveBranchRef, readDefaultBranchRefs().baseBranch and branchRefCandidates in packages/environment-provider-host/src/workspace-git.ts. It fails CI when source outside that file builds refs/remotes/origin/${…} or `origin/${…}` refs, or runs merge-base --is-ancestor. Tests and fixtures are exempt. The few sites that do this for another reason are listed in the script's allowlist with the reason. Every caller of the resolver also runs the shared case table in packages/environment-provider-host/src/testing/branch-ref-cases.ts.

File Content Routes

Clients read file bytes through path-shaped GET routes, which you can curl directly:

  • /api/v1/threads/:id/thread-storage/files/:path: the thread's storage folder.
  • /api/v1/threads/:id/host-files/:absolutePath and /api/v1/hosts/:id/files/:absolutePath: the thread environment's host or the named host, from its filesystem root. The path omits the leading /; a first segment such as C: selects that Windows drive root.
  • /api/v1/environments/:id/files/:path reads the environment workspace, and /api/v1/environments/:id/revisions/:ref/files/:path reads HEAD or a 4-40 character hex commit from it.
  • /api/v1/projects/:id/files/:path and /api/v1/projects/:id/hosts/:hostId/files/:path: the project's local-path source on the primary or named host.
  • GET /api/v1/file-previews/:lease/:path reads a root leased through POST /api/v1/files/previews ({ hostId?, rootPath, ttlMs? }); leases live in server memory and do not survive a restart.

Responses support a single HTTP byte range and carry Content-Security-Policy: sandbox allow-scripts. A file that changes before response headers are sent returns retryable 409 file_changed; a change after streaming starts aborts the body. Revision routes ignore Range and keep the daemon's 25 MB non-image limit.

Working-tree, host, thread-storage, leased-preview, and uploaded-attachment responses share services/files/file-stream-response.ts. It owns ranges, conditional requests, HEAD, bounded streaming, backpressure, and cancellation. The local reader opens a file handle only when bytes are needed and closes it on completion, cancellation, or failure. The daemon reader uses the existing chunk RPC and passes cancellation through to pending calls. Both readers validate file consistency; failures before headers return an error and failures after streaming begins terminate the body.

Routes explicitly choose content type, cache policy, and security headers. Daemon files retain weak revision ETags and their sandbox/nosniff policy; HTML remains no-store. Attachments retain their immutable private cache policy and strong ETags. Weak validators never authorize If-Range; attachment ranges can use an exact strong ETag or Last-Modified match. Git revision reads remain on the separate whole-file path described above.

Uploaded attachments use GET /api/v1/projects/:id/attachments/content?path=<stored-path>. This route streams single byte ranges from disk, including open-ended and suffix ranges, with 206, Accept-Ranges: bytes, and Content-Range. Unsatisfiable ranges return 416; malformed or multipart ranges fall back to the full 200 response. If-None-Match takes precedence over ranges. If-Range must match the strong ETag or Last-Modified value exactly; otherwise the full file is returned. HEAD returns full-file headers without reading the body. To check partial reads, use curl -D - -H 'Range: bytes=0-1023' '<attachment-url>' -o /tmp/attachment-part.

Skill detail reads and file listings resolve symlinked skill directories on their owning host. The server opts into followRootSymlink for host.read_file and host.list_files; other callers pass false. The server rejects absolute, .., and dotfile skill paths before reading, the host confines reads to the resolved directory, and listings skip nested symlinks. Linked skills remain read-only in bb.

Prepared Worktree Restarts

pnpm start and pnpm start:worktree always run Turbo-backed preparation before launching: Turbo rebuilds what changed and restores unchanged artifacts from cache, and native modules are repaired when necessary. Add --dryrun to prepare, print the resolved ports, bind host, paths, and runtime entrypoints as JSON, and exit without launching services, migrating data, or requiring free ports. Dry runs still write build outputs; run pnpm install --frozen-lockfile first when needed.

Preparation writes build outputs in the checkout, so it is not an atomic release switch for an instance serving those files. Do not prepare concurrently with another preparation or against files a live instance serves. To restart with minimal downtime, warm the shared Turbo cache from a separate staging checkout, then stop the instance, update and prepare its checkout, and launch. Moving the serving checkout changes the instance's default data directory and ports.

Cache hits restore cached files but can leave extra files from an earlier build. Built source servers load bundled plugins from packages/bundled-plugins/dist; see official-plugin-release-process.md for adding a bundled plugin. The launcher sets BB_BUILD_TOOLCHAIN (Node, OS, and architecture) to partition Turbo cache entries; do not set it yourself.

App production builds cache React Compiler transforms under <git-common-dir>/bb-cache/react-compiler, shared across worktrees; delete it while no build runs to clear it. BABEL_SHOW_CONFIG_FOR and ENABLE_REACT_COMPILER_TIMINGS=1 bypass that cache. Use pnpm exec turbo run build --filter=@bb/app --force to rebuild without Turbo's whole-task cache.

Reviewing UI Code Splits

See UI code splitting for the app's defineSplit contract, explicit preload scopes, bundle-boundary guards, and parallel worker handoff requirements. Use an isolated production build with browser request interception to review loading and failure states and verify cold-download behavior. Keep temporary review stories and fixtures out of the final diff.

Server Move Markers

A server move or bb server import leaves JSON markers in the data directory; check them when a server refuses to start or keeps redirecting:

  • server-import-journal.json: an import is installing files. Without a matching server-import.json the import was interrupted, and the server refuses to start; rerunning bb server import into that directory rolls it back from server-import-backup/.
  • server-import.json: the imported server on the target is waiting for activation (no plugins, sweeps, or daemon sessions run).
  • server-moved.json: the old computer after the switch. The launcher refuses to start a server from that data and answers the old port with 410 server_moved.
  • server-move-run.json: the old server's durable move state, reconciled at boot.
  • last-server-move.json: the new server's record of the move.
  • server-connect-hold.json: an imported server starts without bb connect until bb server allow-connect.

During a move, /health on the new server reports serverMove: { moveId, state } with pending, activating, or ready. Usage is in bb guide machines.

Daemon Protocol Mismatch

The server checks the daemon's protocol version before parsing session payloads. A daemon on another HOST_DAEMON_PROTOCOL_VERSION is rejected with protocol_version_mismatch and cannot serve workspace RPCs until it updates and reconnects. Auto-update-enabled daemons install the server's matching bb-app artifact; disabled or failed updates leave the machine disconnected until a manual update succeeds. The commit that bumps the version records what changed.

Terminal Output Streaming

A daemon sends a terminal's output to the server only while the server has asked for it with terminal.stream (enabled: true). The server asks just before it attaches a terminal client, or before it catches clients up after a daemon reconnect, and stops the stream when the last client detaches. While a terminal is not streamed, its output stays in the daemon's scrollback ring (4 MiB per terminal) and reaches clients through the attach replay. A dropped daemon session stops every stream.

A streamed terminal never has more than 1 MiB of output that the server has not acknowledged; past that, the daemon pauses the PTY until terminal.ack arrives. The server acknowledges up to what the fastest visible, acknowledging client has parsed. With no such client (hidden, stalled, or not sending acks), it acknowledges output as it arrives, so the PTY runs at the link rate.

Opt-in server performance diagnostics

Collection needs both startup permission and the Server performance diagnostics experiment; see configuration.md for the flag, environment variable, and experiment. It covers the server only, not the daemon. Leave it off for routine operation: profiling and extra logging add overhead.

While on, the server logs database operations of at least 25 ms, API requests of at least 100 ms, event-loop stalls of at least 100 ms, and slow SQLite query plans. Every five seconds Server performance sample records process and main-thread CPU, loop utilization and delay, GC, and memory; CPU values are interval totals, not per-request attribution. Its maxDelayMs and p99DelayMs are gaps of the shared 50 ms event-loop timer (delayResolutionMs), so an idle loop reports about 50 ms. A V8 CPU profile sampled every 10 ms is saved every 30 seconds to $BB_DATA_DIR/logs/performance/ (Server CPU profile saved logs its path, PID, and UTC window). Profiles are kept for up to 12 hours and 1 GB total, oldest first, so copy the ones you need. They use private permissions and contain local paths and function names; inspect before sharing.

A worker connects to the main-thread inspector and processes completed profiles, serializes JSON, and writes files. Captures overlap at rotation to preserve coverage without restarting V8's sampler. Native V8 sampling and profile completion still have some main-thread cost. Retention scans existing files once at startup, then tracks this recorder's writes incrementally; use one server per data directory. Rotation does not queue more captures while a previous capture is being saved. Shutdown awaits the active save and writes the final capture.

Turn traces

While both gates are on, every message sent through the send API also writes one Turn trace info line once its first streamed output is stored and broadcast. turnTrace.spans holds milliseconds since the server received the send: dispatch.checkpoint.done, runtimeConfig.* (runtime configuration assembly, including the daemon reads it waits on), command.sent, send.responded, command.settled, and firstOutput.batchReceived, firstOutput.committed, firstOutput.notified for the first event batch that carries an agent message, reasoning, or plan delta. turnTrace.rpcs lists every daemon RPC the send awaited with its start offset and duration. turnTrace.daemon.spans are the daemon's own offsets from receiving turn.submit: lanes.entered, skills.staged, runtime.ready, input.staged, bridge.turnStarted, and events.flushed. Server and daemon offsets use different clocks, so compare durations rather than offsets: command.settled - command.sent - daemon events.flushed is the round trip spent on the network. outcome is output, not-sent (queued or refused), command-failed, completed-without-output, superseded by a newer traced send on the thread, or no-output after two minutes. Queue drains, retries, and other server-initiated dispatches are not traced.

Stream traces

While both gates are on, every ingested daemon event batch that carries agent message, reasoning, or plan text writes one Stream trace info line per thread. streamTrace.receivedAt, committedAt, and notifiedAt are epoch milliseconds; events, textEvents, and textChars size the batch; served is push when a thread view is subscribed to timeline pushes and refetch otherwise. The intervals between consecutive lines for a thread are the chunk cadence the server sees. The host daemon logs Posted daemon event batch at debug level (BB_LOG_LEVEL=debug) for every POST: eventBatch.events, textChars, oldestQueuedMs (how long the oldest event waited), sincePreviousPostMs, postMs, and postedAt. Each timeline push to a subscribed thread view writes a Timeline push trace line: timelinePushTrace.maxSeq, withDelta (false when the subscriber had no base and received the full window), bytes, buildMs, and sentAt. In the browser, the same gates add performance.mark entries: bb:timeline-applied (threadId, maxSeq, source: fetch, fetch-delta, push, or push-delta) when timeline data is applied, and bb:stream-row-commit (rowId, threadId, textLength) when a streaming assistant row commits. Read them with performance.getEntriesByType("mark"). Streaming assistant text is revealed a complete line at a time, so row commits follow line completion, not every applied chunk.

Diagnose a captured stall

  1. Note the request path and UTC time. Find its Slow API request and nearby Event loop stalled records; for timelines, also Thread timeline build blocked the event loop and its stage timings. inFlightWorkAtObservation can name an unrelated long poll; compare longestSynchronousWork and its wall/CPU times with the profile instead. Measured synchronous work includes daemon WebSocket messages, timeline builds, sweep steps, every transaction on bb.db (db:transaction <mode>: followed by the first write statement, or the first statement when it only reads), single statements that take at least 1 ms (db:all, db:get, db:run, db:exec with redacted SQL), and the synchronous part of each API request, plugin RPC or HTTP handler, plugin event handler, plugin load, and plugin background service before its first await (<label> (until first await)). When a measured child took at least half of its parent's time, longestSynchronousWork names the chain, for example ws:daemon heartbeat > db:transaction deferred: update "host_daemon_sessions" .... longestSynchronousWorkCaller names the request, plugin invocation, sweep, or plugin load or service that was running the work, including callbacks and timers a plugin scheduled while it loaded. Code a plugin runs after an await is not measured here; it is only named by plugin id in the sampled records below. longestSynchronousWorkCpuMs is main-thread CPU, and longestSynchronousWorkVoluntaryContextSwitches and longestSynchronousWorkInvoluntaryContextSwitches are process-wide counts for the same interval: CPU far below wall time with many involuntary switches means the thread was waiting for a core, and with many voluntary switches it was waiting on a lock, disk, or another thread. Thread timeline build blocked the event loop carries the same split as cpuDurationMs, voluntaryContextSwitches, and involuntaryContextSwitches. stallAttribution is candidate, with the operation in stallCauseCandidate, when a measured synchronous operation is long enough (within one 50 ms timer interval) to explain the maximum delay, and unattributed otherwise. A candidate is not a confirmed cause: both fall somewhere in the five-second window. Profile processing runs in a worker and no longer emits the historical cpu-profile:* synchronous-work labels.
  2. With performance diagnostics enabled, look for Event loop stall attribution records for the same PID and UTC window. They are emitted at the next CPU profile rotation (normally within 30 seconds), or on diagnostics shutdown, even if the profile file is discarded for exceeding its size limit. The same 50 ms timer that feeds the stall monitor records individual gaps of at least 100 ms, so every stall of 100 ms or more is caught; the five-second histogram's observation time is not the stall's end time. stacks ranks the top five sampled leaf stacks in each gap, with up to 12 caller frames, including GC, plugin functions, native writes, and database callers. owners totals the window's sampled time per plugin (plugin:<id>), counting a sample when any frame on its stack belongs to that plugin's server code, and each ranked stack carries the same owner (or null). Frame coordinates are one-based; cached Node source maps are used in the profile worker when available, otherwise coordinates refer to the generated code. Profile scanning and stack formatting run in that worker; the main thread only collects and transfers bounded timing windows. clockCalibration reports the profiler-to-stall clock offset bounds in milliseconds. Status calibrated includes the applied offsetUs; disjoint means the start and end bounds disagree, and uncertain means their intersection exceeds 10 ms. Rejected calibration leaves attribution empty rather than assigning samples to the wrong window. The saved raw profile retains its samples and original V8 timestamps; its save record includes the same calibration diagnostic. sampledMs is elapsed sampling coverage, not CPU time; native frames can include waiting. Each sample contributes at most 20 ms so a long sampling gap cannot be blamed on one frame. unobservedMs reports missing coverage, including profile boundaries. The window includes up to one timer interval of ordinary work; ranked stacks are evidence, not proof of a single cause. Up to 128 windows are retained per rotation, with overflow reported as droppedWindows; gaps of 60 seconds or more are treated as suspension. These records require the existing profiling gates. Without profiling, the immediate stall record can only report explicitly measured candidates.
  3. Load the .cpuprofile covering that time and PID in Chrome DevTools' JavaScript profiler, select the window, and read the bottom-up view. Match function names against the exact source revision of the build.
  4. Compare stacks with mainThreadCpuMs, GC totals, and SQL cpuDurationMs. A slow SQL operation with little CPU indicates waiting but does not identify the lock owner or prove disk I/O.
  5. Repeat with a small control workload. Expected long polls log slow requests without blocking the loop; require corroborating loop delay, stage timings, or sampled execution before calling them stalls.

Workspace Context Read Limits

The server passes host.read_workspace_agent_context its project skill read policy: at most 1,000 non-hidden, non-excluded directories, 10 MiB per SKILL.md, and 4 MiB of JSON-encoded frontmatter in total (directory metadata, shared skill discovery, and workspace instructions do not count). The daemon returns each SKILL.md only through its closing --- delimiter, never the body; the server parses that block exactly as it would the whole file, because injected project skills reach the provider by path. These are a starting policy, not a measured requirement or transport ceiling. Files over a limit are skipped with server warnings; smaller later files can still fit, and count truncation is reported separately. Only exact-case SKILL.md files are read; symlinked skill directories or files and roots escaping the workspace are skipped before reading. Command lookup sets includeAgentInstructions: false, so an invalid .bb/AGENTS.md cannot break the command catalog; turn preparation sets it to true and reports instruction-read errors.

Interrupted Optimistic Query Refreshes

Optimistic cache owners use cancelOptimisticQueries instead of calling queryClient.cancelQueries directly. During a mutation it records interrupted reads and the mutations pending at cancellation. It invalidates those queries after those mutations finish, including success, error, and settled callbacks. A later optimistic cancellation of the same query extends that wait even if the query is already idle. Active queries refresh; inactive queries become stale for their next mount. Removed queries are discarded from recovery.

This deliberately waits for every mutation pending at cancellation because a cache owner does not have the identity of its calling mutation. Later unrelated mutations do not delay recovery. Queries without an interrupted read are not refetched. Calling cache-owner helpers outside a mutation retains ordinary cancellation behavior. Browser suspension and realtime replacement reads have their own recovery paths and continue to use ordinary cancellation.

For a stale drawer or sidebar, check whether an optimistic mutation canceled the last realtime refresh, then whether its recovery ran after the mutation callbacks. Cover this ordering with real Query and Mutation observers; an isolated rollback helper test does not exercise mutation settlement.

Shared Async Caches

The server and daemon share createAsyncTtlMemo from @bb/async-cache for keyed asynchronous reads. It shares pending work, starts TTLs at completion, retries rejected reads, and prevents invalidated work from repopulating the cache. Callers own keys, lifetimes, invalidation, and stale-result policy; set maxEntries when keys can grow. Invalidation does not cancel existing readers or replace their results.

The daemon also uses this helper for client configuration and shell-environment refresh. Client configuration keeps its one-second TTL and retries failed reads on the next request. Shell refresh preserves startup values and optional stale reads, shares even slow pending refreshes, and starts its ten-second TTL after the resolved environment is applied.

Workspace Open-Target Discovery

The host daemon's GET /workspace-open-targets shares the installed-app list, including icons, between general and file-specific discovery. It stays fresh for 60 seconds after discovery completes. After expiry, requests return the previous list immediately and share one background refresh. The first request after daemon startup or an effective executable search PATH change waits for a fresh scan. The cache belongs to the local API server instance.

Failed initial scans are retried on the next call. Failed background scans keep the previous list and retry on the next request. Discovery's existing per-app fallbacks can still produce a successful partial list, which is cached for the same TTL. Installing or removing an application appears after the next successful refresh; the request that triggers an expired refresh still sees the old list.

Requests with a path query reuse that same base list, then check file existence and macOS file associations fresh. File-associated apps do not enter the shared list, and already-listed apps reuse their cached icons. File discovery still waits for its native association lookup and any additional apps' icon extraction.

Environment Status Loading

Merge-base status is cached per host daemon process at two levels, each a least-recently-used cache capped by estimated size. Full comparisons (16 MiB) are keyed by checkout path, shell path, resolved HEAD and base commits, base label, and file limit; working-tree status is always read fresh. Per-commit changed files (64 MiB, skipping any commit over 1 MiB) and patch IDs (8 MiB per diff mode) are keyed by commit SHA and shared by every checkout on the host, so a new commit or a fetched base commit only needs its own diff. Comparisons where a Git command failed or squash detection timed out are not cached. A daemon restart clears both levels.

Ahead/behind counts exclude commits whose patch appears on the other side, as git rev-list --cherry-pick does: only commits touching the same set of paths as a commit on the other side are patch-hashed, without rename detection. Squash detection reuses the per-commit changed files for the newest 1,000 base commits and hashes its candidate patches with Git's rename detection, cached separately, within 8 MiB of patch output and a 1-second deadline per attempt. When it cannot finish, mergeBase.squashMergeCheckComplete is false and the counts may include already squash-merged commits; the next refresh retries with the cached work. Daemons older than this field report true.

Plugin Stylesheet Version Skew

Plugin CSS URLs in bundle metadata always identify the complete stylesheet. The app adds host-tailwind=<HOST_TAILWIND_VERSION> when prefetching, preloading, or attaching that stylesheet. The version is generated from the host's Tailwind registrations, fallback declarations, and theme values. Both plugin asset routes strip matching host-provided rules only when that query value matches the server's generated version. Missing or mismatched values receive the original CSS, so a tab retained across a server update keeps working with its old host styles. Compressed responses are cached separately for the original and stripped variants.

The app also adds css-scope=plugin-attribute-v1. When a plugin's app.js never sets data-bb-plugin-root without a nearby data-bb-plugin, both routes drop the [data-bb-plugin-root]:not([data-bb-plugin]) alternative from that plugin's utility selectors and key them on [data-bb-plugin-scope-<id>] instead of [data-bb-plugin=<id>]; otherwise the plugin keeps the original CSS, and bb plugin build warns. Authored CSS is never rewritten. Browsers' ancestor filters hash attribute names but not values, so only a per-plugin attribute name lets the browser skip another plugin's copy of .flex without walking every ancestor of each element inside the sidebar, composer, or any other plugin root. Plugin roots the host renders (slot mounts, panel header content, and portaled overlays) carry data-bb-plugin-scope-<id>="" next to data-bb-plugin. For elements a plugin labels itself, including old portal-scope copies and element.dataset.bbPlugin = id, the app watches the document (apps/app/src/lib/plugin-scope-attributes.ts) and adds the attribute before the element is styled. Older tabs that send css-scope=owned-root-v1 get the same selectors without the scope attribute, and tabs that send no scope get the original CSS.

To reproduce version skew, load the production main app in Chrome, restart the same isolated server on the branch without reloading the tab, and open Automations and Plugin Guide. Normal revision detection reloads the app automatically. To isolate a client that has not received that update status yet, retain the old immutable app assets and hold the update-status response at the old revision in a test proxy. Compare against a fresh tab and confirm the old tab's performance.timeOrigin and host stylesheet URL stay unchanged. Inspect Plugin Guide's .font-bold elements: they must still compute to weight 700.