Skip to content

Stop blocking thread start on shell-env and CLI version probes - #4022

Merged
ymichael merged 2 commits into
mainfrom
bb/new-thread-startup-latency-and-warm-stack-propos-thr_pqwwmk7q5s
Sep 22, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/new-thread-startup-latency-and-warm-stack-propos-thr_pqwwmk7q5s

Conversation

@ymichael

@ymichael ymichael commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Starting a thread awaited an expired login-shell environment cache and then an expired provider CLI version cache before provisioning or provider work could begin. Threads created minutes apart repeatedly paid for both probes even when their previous results were usable. Moving refreshes into the background also requires tracking stale environment runtimes: a runtime created before a refresh finishes can be busy when eviction runs and otherwise retain its old PATH indefinitely.

What changed

  • Thread start and rewind preparation use the last resolved shell environment while refreshing it in the background. Initial resolution still blocks, and failed background refreshes log the error while retaining the last environment.
  • The provider installation gate serves an expired supported status while revalidating. Failed or unsupported revalidation drops that status so subsequent starts probe again.
  • Maintenance requests await shell refreshes when the cache expires.
  • Runtime entries record the shell-environment generation used at creation. When an outdated runtime is next requested while idle, it is shut down and recreated with the current environment. Live threads, terminals, background work, and other in-flight thread commands defer replacement; the requesting thread's own command does not prevent it. The generation is captured alongside the environment snapshot after provisioning.

All changes are daemon-internal. No wire fields, protocol version, CLI commands, or settings change.

How you verified

  • Added five runtime regression cases covering a background refresh during an active turn, replacement after that turn ends, protection for background tasks, terminals and other thread commands, and refresh during provisioning.
  • pnpm exec turbo run test --filter=@bb/host-daemon -- runtime-manager.test.ts runtime-shell-env-cache.test.ts provider-installation-gate.test.ts command-dispatch.test.ts app.test.ts — 123 tests passed.
  • pnpm exec turbo run typecheck --filter=@bb/host-daemon — passed.
  • Formatting and git diff --check passed.

Earlier measurements on this branch used five thread starts per series, approximately five-minute gaps, a small repo, fresh worktrees, and Codex. Submit-to-provider median fell from 2801 ms to 1361 ms; shell-environment and version probes fell from 1340 ms to 1 ms. These measurements preceded the runtime-generation fix and were not repeated for this update. Initial starts after daemon restart still require an uncached version probe.

Earlier full integration-suite runs hit wall-clock timeouts under concurrent local test load; they did not provide a conclusive result. The targeted regression tests above exercise the environment-change path directly.

AGENT GENERATED

ymichael and others added 2 commits September 21, 2026 15:20
Starting a thread serialized two revalidation probes in the host daemon
before any provisioning or provider work began: the login-shell PATH
probe ($SHELL -ilc env, 10s TTL, 0.5-1.9s here) and the provider
installation version gate (5min TTL, 0.4-1.5s, spawning a second bridge
process on the maintenance runtime). Both revalidate results that were
already known-good, and neither is needed to dispatch the first prompt,
so a user creating threads minutes apart paid both every time.

Both caches now serve the last known-good value to thread start and
revalidate in the background, dropping the cached value when the
revalidation fails or reports a missing or unsupported CLI, so the next
start blocks and re-probes. UI-driven maintenance work (provider health,
model listing) still forces a real probe.

Measured on a small repo with a fresh worktree and codex, n=5 with
5-minute idle gaps so both TTLs were cold: submit-to-provider median
2801ms (2299-6275) before, 1361ms (1287-5280) after; the two probes fell
from a 1340ms median to 1ms. The remaining outlier is the first start
after a daemon restart, where the gate has no cached status yet.

Co-Authored-By: Claude Opus 5 <[email protected]>
@ymichael
ymichael merged commit cb0bdbc into main Sep 22, 2026
16 checks passed
@ymichael
ymichael deleted the bb/new-thread-startup-latency-and-warm-stack-propos-thr_pqwwmk7q5s branch September 22, 2026 17:28
ymichael added a commit that referenced this pull request Oct 26, 2026
…he (#6210)

## Human comments

## What was wrong

`GET /api/v1/projects/:id/commands` took 1.0–1.3s on cold calls (10
times in an hour on a real server, once per thread view), which delayed
the composer. The route ran four lookups in parallel. I timed each one
with temporary logs on a dev server: the native-root scan, workspace and
shared skills, and the skill catalog took under 25ms combined. All the
remaining time went to the `provider.list_commands` host RPC. That RPC
uses the daemon's maintenance runtime, which (since #4022) waits for a
fresh login-shell environment once its 10s cache expires. It also
restarts the provider bridge after 60s idle, and Claude Code re-probes
its initialization. The server cached none of this, so every view
outside those short windows paid the full cost again.

Measured on a dev server, personal project, Claude Code:

| Call | Shell env refresh | Bridge start | Request | Route total |
| --- | --- | --- | --- | --- |
| cold | 2152ms | 0 | 1ms | 2.18s |
| +12s | 1723ms | 0 | 1ms | 1.75s |
| +70s | 695ms | 477ms | 190ms | 1.38s |
| +130s | 619ms | 492ms | 184ms | 1.32s |
| immediate repeat | 0 | 0 | 0 | 15–25ms |

## What changed

- New `apps/server/src/services/providers/provider-live-commands.ts`: a
cache of live provider commands keyed by host, provider and cwd, held in
`AppDeps.providerLiveCommands` next to `providerNativeRoots`.
  - A cached answer is served as is for 60s.
- After 60s it is still served immediately, while one background refresh
runs.
- If the refreshed list differs, the server sends a new
`provider-commands-changed` host change. The app's realtime registry
maps it to the project command queries, so an open composer refetches.
- A failed refresh keeps the previous list and is retried on the next
read. A failed first load is not cached and falls back to scanned
commands only, as before.
- Concurrent reads share one in-flight load. At most 256 entries are
kept.
- The route calls `listProviderLiveCommands` in place of the removed
`listProviderLiveCommandsBestEffort`.
- The native-root scan and skill catalog are still read on every
request, so commands and skills added or edited on disk appear on the
next request. Live commands only add names the scan doesn't already
list, so a stale live list can only miss provider extras (for example a
newly installed Claude plugin) until its refresh lands.
- `HOST_CHANGE_KINDS` gains `provider-commands-changed`. Clients parse
change kinds leniently, so older clients ignore it. This is a server/app
change only: the daemon wire is untouched, so there is no
`HOST_DAEMON_PROTOCOL_VERSION` bump.
- `docs/provider-bridge-protocol.md` (Command catalog) describes the
caching.

The first view of a new cwd still waits for the live answer (about
0.7–2s, as before), so `bb project commands` and the SDK still get a
complete list on first call. Making that miss faster means letting
maintenance requests use a stale shell environment in the daemon, which
#4022 chose not to do. I left that for a separate change.

## How you verified

- `test/services/providers/provider-live-commands.test.ts` covers four
cases: a failed refresh keeps the old list and the next read retries; a
failed first load is not cached; concurrent first reads share one load;
one refresh per stale window, with no change signal when the list is
unchanged. The last test first failed on a real race: the in-flight
marker was cleared before the refreshed list was stored, which allowed a
duplicate refresh. The implementation now stores before clearing.
- `test/public/public-project-commands.test.ts` has a new route-level
case. A second request inside the window makes no
`provider.list_commands` RPC but still shows a newly scanned skill.
After the window, the cached list is served, one refresh runs,
`provider-commands-changed` is pushed, and the next request returns the
new command.
- Dev server re-measurement after the fix, same sequence: cold 1.36s
(nothing cached yet), then 15ms, +12s 83ms, +70s 20ms, +130s 28ms.
- `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/app
--filter=@bb/integration-tests` passed.
- `pnpm exec turbo run lint --filter=@bb/app` passed.
- `pnpm exec turbo run test --filter=@bb/domain` passed. Targeted
`@bb/app` (`realtime-cache-effects.test.ts`) and `@bb/server`
(`hub.test.ts`, `public-project-*`) tests passed.
- Full `pnpm exec turbo run test --filter=@bb/server`: 3684 passed and 1
failed. The failure was `public-thread-timeline-scrollback.test.ts`
under parallel load; it passes when run alone.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Oct 26, 2026
…tch (#6219)

## Human comments

## What was wrong

Every new thread gets its own worktree, so the first command-list lookup
for a thread always reaches the machine, even with the server-side cache
in #6210. On the machine, `provider.list_commands` ran through
`withMaintenanceRuntime`, which waited for a fresh login-shell
environment whenever the cached one was more than 10s old. That wait is
0.6–2.2s depending on the shell. #4022 made thread start use the last
resolved environment and refresh it in the background, but kept every
maintenance request blocking, so command listing still paid for the
login shell. Separately, `shouldPrefetchCommandCatalog` prefetched the
catalog whenever focus entered a composer on a coarse pointer. Opening a
thread focuses its composer, so every thread open on a phone sent this
request, even when nobody typed a command.

## What changed

**Daemon (`apps/host-daemon/src/app.ts`).** `withMaintenanceRuntime` now
takes the shell-environment refresh mode explicitly at each call site:

| Request | Shell env | Why |
| --- | --- | --- |
| `provider.list_commands` | last resolved, refreshed in background |
Command names don't depend on a just-changed PATH, and the thread that
uses them already starts on the last resolved environment (#4022). |
| `provider.usage` | last resolved, refreshed in background | Quota/plan
display, polled and cached for 10s on the server. Errors aren't cached
there, so if a stale PATH ever causes one, the next poll runs on the
refreshed environment. |
| `provider.list_models` | fresh | The server clears the model-catalog
failure right after a successful CLI install and fetches again. A stale
PATH there would record a failure that sticks for the catalog's failure
TTL. The catalog is persisted, prewarmed and served
stale-while-revalidate on the server, so the wait rarely reaches a user.
|
| `provider.health` | fresh | This is the "is the CLI installed and
signed in" answer shown after install/login. It must see the current
PATH. |
| `provider.installation.status` / `.run` | fresh | Unchanged from
#4022: they must see a just-installed CLI on PATH. |

The first resolution after daemon start still blocks for every request.
The cache only serves a stale environment once one has been resolved. No
wire fields change, so there is no `HOST_DAEMON_PROTOCOL_VERSION` bump.

**App.** The coarse-pointer focus prefetch is gone, along with
everything that existed only for it:
- the `focusin` listener in `composer-root.tsx`;
- `prefetchCommands` / `useComposerCommandPrefetch` in
`composer-search.tsx`;
- `composerFocused`, `shouldPrefetchCommandCatalog` and
`prefetchCommandCatalog` in `useCommandSuggestions.ts`;
- `projectCommandsQueryOptions`, now inlined back into
`useProjectCommands`.

The catalog loads on the first `/` or `$` query. On first open the menu
shows what it already has (prompt-action commands such as `plan` and
`goal`) with the refreshing spinner, then fills in the catalog. With
nothing to show yet, it shows the existing "Searching commands…" row.
`docs/api_to_audit.md` (composer search contract) now says that commands
load on the first command query rather than when focus enters the
composer.

This is independent of #6210 and based on main. The two together make
the first lookup in a new worktree cheap: #6210 serves repeat lookups
from the server, and this change removes the login-shell wait from the
misses.

Remaining cost on a miss: the maintenance runtime still restarts after
60s idle, plus Claude Code's startup check (about 350ms total in the
measurements below). One race existed before this change and is
unchanged: if a background refresh finds a *different* PATH while a
listing request is in flight, `replaceBaseShellEnv` shuts down the
maintenance runtime under that request. The shell env holds only PATH
and bb's own variables, so this only happens when PATH actually changes.

## How you verified

- `apps/host-daemon/src/app.test.ts`: a table test runs each of the six
maintenance RPCs with an expired shell env and a pending login-shell
resolution. `list_commands` and `usage` answer on the last resolved env
without waiting. `list_models`, `health`, `installation.status` and
`installation.run` don't reach the runtime until the fresh env resolves,
and then run on it. A second test checks that `list_commands` still
waits for the first resolution after daemon start. Flipping
`listCommands` to blocking, or `providerHealth` to stale, fails the
matching case.
- `apps/app/src/hooks/useCommandSuggestions.dom.test.tsx`: the real hook
makes no catalog request before a trigger, reports `isLoading` while the
first request is pending, then returns the catalog.
- `pnpm exec turbo run test --filter=@bb/host-daemon`: 823 passed, 12
skipped.
- `pnpm exec turbo run test --filter=@bb/app --
src/hooks/useCommandSuggestions src/components/promptbox
src/components/plugin/PluginNewThreadComposer`: 599 passed.
- `pnpm exec turbo run typecheck --filter=@bb/app
--filter=@bb/host-daemon` and `pnpm exec turbo run lint
--filter=@bb/app` (0 errors) passed.
- Phone-width check on a `pnpm start:worktree` build: Chrome at 390×844
with `pointer: coarse` emulated. Tapping into the new-thread composer
sent no `/commands` request. Typing `/` sent one request; the menu
showed the prompt-action commands with the spinner, then the full
catalog when the (artificially delayed 1.5s) response landed.

**Measurements.** `GET
/api/v1/projects/:id/commands?provider=claude-code` on a `pnpm
start:worktree` instance (main without #6210, so every call reaches the
daemon). This machine's login-shell resolution takes about 570ms. Before
= this branch with `listCommands` switched back to `allowStale: false`,
otherwise identical build.

| Call | Before | After |
| --- | --- | --- |
| +15s (env stale, runtime warm) | 602ms, 603ms | 32ms, 34ms |
| +70s (env stale, runtime idle-restarted) | 936ms, 913ms | 357ms, 342ms
|

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant