Repository navigation
Environment providers: plugins own where threads run - #3227
Conversation
|
🚨 SLOP COP 🚨 · I’m reviewing this now. I’ll check security, general code quality and architecture, performance, and the affected environment/thread-creation journey end to end before posting a consolidated review. |
| ); | ||
| } | ||
| try { | ||
| await validateProviderSelection(deps, record, { |
There was a problem hiding this comment.
🚨 slopcop/review — Provider validation runs twice, so the second refusal occurs after the thread exists
completeProviderSelection already invokes validateProviderSelection before insertion, but provisioning calls it again here even when selectionResolved is true. A capacity-sensitive or otherwise stateful validator can accept the request first and refuse this duplicate call, leaving a visible errored thread despite the SDK contract promising that refusal happens before a thread or environment row exists. Validate exactly once during selection completion; if recovery needs revalidation, model that state separately and add exact-once coverage.
| baseBranch: { kind: "named", name: baseBranch }, | ||
| }, | ||
| type: "provider", | ||
| environmentProviderId: DEFAULT_ENVIRONMENT_PROVIDER_ID.gitWorktree, |
There was a problem hiding this comment.
🚨 slopcop/review — Project defaults can select a disabled provider and park every new thread forever
This path hardcodes git-worktree without consulting the live provider registry. Built-in plugins can be disabled, and the later missing-provider path persists the request and retries indefinitely. Disabling this plugin therefore makes normal Git-project thread creation produce permanently waiting rows instead of choosing an available provider or failing before insertion. Resolve defaults against registered/available providers and define an explicit fallback or error; reserve indefinite waiting for an explicitly named provider or recovery of an existing intent.
| row.teardownStatus !== "running" | ||
| ) | ||
| return; | ||
| const record = getEnvironmentProvider(row.environmentProviderId); |
There was a problem hiding this comment.
🚨 slopcop/review — Destructive provider lookup loses the plugin owner across restarts and replacements
Environment and launch rows persist only the flat provider ID, while this lookup selects whichever running plugin currently registers that ID. If plugin A creates an environment and is later disabled or uninstalled, plugin B can register the same ID and receive the private resource, path, and removal context from A. Persist the owning pluginId with launch/environment provenance and require both IDs to match before create/remove; mismatches need an explicit adoption or migration flow.
| row.resource = result.resource ?? null; | ||
| }); | ||
| controller.signal.throwIfAborted(); | ||
| if (result.ownsPath) { |
There was a problem hiding this comment.
🚨 slopcop/review — Setup code runs before the provider-returned path passes core admission
The setup hook executes against the raw returned path before resolveProducedEnvironmentPlacement canonicalizes it and checks foreign project ownership. A confused provider can therefore return another workspace and cause core to execute its .bb-env-setup.sh before the placement is rejected; failure cleanup can then act on the same unadmitted path. Canonicalize and atomically claim/admit the result, including foreign-owned-path checks, before running any lifecycle hook.
| selectionResolved: true, | ||
| produced: { | ||
| hostId: args.hostId, | ||
| path: args.path, |
There was a problem hiding this comment.
🚨 slopcop/review — Admission checks one path identity but execution keeps the mutable alias
This function canonicalizes args.path for ownership and overlap checks, then persists the original alias here. A symlink can be retargeted after admission so later attach, hook, terminal, or thread commands execute elsewhere while database claims remain tied to the old canonical identity. Bind execution to the admitted canonical path, or reverify identity on the daemon immediately before each attach/hook instead of using the display alias as cwd.
| ): PluginEnvironmentProviderProgress { | ||
| const update = (change: (row: EnvironmentLaunchRow) => void): void => { | ||
| if (mutateLaunch(deps, launch, ["creating"], change)) | ||
| requestEnvironmentProviderRecheck(record.pluginId); |
There was a problem hiding this comment.
🚨 slopcop/review — Every progress chunk triggers a global provider and client refetch storm
Each changed report.step or report.log synchronously rewrites SQLite and calls this recheck. The handler invalidates all provider availability and broadcasts config-changed, which makes connected clients invalidate system config, timelines, execution options, and environment-provider queries. A verbose setup script can multiply database writes, broadcasts, HTTP refetches, and host Git inspections. Coalesce progress persistence, wake only the affected launch, and reserve global config invalidation for actual provider configuration or availability changes.
|
|
||
| const { providers: registeredEnvironmentProviders } = | ||
| useSystemEnvironmentProviders({ projectId }); | ||
| const environmentProvidersByHostId = useSystemEnvironmentProvidersByHost( |
There was a problem hiding this comment.
🚨 slopcop/review — The composer performs aggregate plus per-host provider fanout
The project-wide query already evaluates every provider across every persistent host, then this hook adds another request for each host. With H hosts the composer makes H+1 HTTP requests and roughly 2H host evaluations per provider; Git-checkout availability can perform about 2H daemon Git inspections on a cold or invalidated pass. Return one provider/host availability matrix, reuse the aggregate evaluation for host-specific rows, and dedupe Git inspection by host and path.
| request: text("request", { mode: "json" }).$type<JsonValue>(), | ||
| cancelPending: integer("cancel_pending", { mode: "boolean" }).notNull(), | ||
| }, | ||
| (table) => [index("environment_launches_phase_idx").on(table.phase)], |
There was a problem hiding this comment.
🚨 slopcop/review — Active path-claim admission scans a table that grows with thread history
The only index is on phase, but claim lookup filters by host_id, claim_path, environment_id, and phase/cancellation state. EXPLAIN QUERY PLAN reports a full environment_launches scan. Attached launch rows remain until their threads are deleted, so archived thread history progressively slows synchronous admission checks and the ten-second cleanup sweep. Remove attached launch state when safe or separate active claims from history; at minimum add an appropriate partial composite index and a query-plan regression test.
| deps.db, | ||
| record.provider.id, | ||
| )) { | ||
| void sweepProviderEnvironment(deps, row.id).catch((error) => { |
There was a problem hiding this comment.
🚨 slopcop/review — Lifecycle cleanup removes all backpressure during mass teardown
The periodic sweep starts every eligible removal with void and returns without awaiting a bounded batch. When many archive grace periods or migrated rows become eligible together, this can launch hundreds of teardown hooks, process kills, Git removals, filesystem deletes, and host RPCs simultaneously. The previous cleanup loop was sequential. Add explicit global and per-host concurrency limits and await the bounded batch before completing the periodic job.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
Plain-English summary: this PR turns “where a thread runs” into a plugin-owned capability. BB core still decides placement, retries, cancellation, recovery, and cleanup timing, while environment plugins create or reuse the actual project checkout, Git worktree, or personal workspace and expose their controls in the composer.
I found nine actionable issues and left each on the relevant line:
- Correctness: provider validation runs twice, violating the documented pre-insertion refusal contract; and built-in defaults can select a disabled provider, leaving ordinary new threads waiting forever.
- Security and isolation: durable rows do not preserve the owning plugin identity; setup hooks run before the returned path passes core admission; and canonical admission is followed by execution through the original mutable path alias.
- Performance: progress output triggers global cache invalidation and client refetches; the composer duplicates aggregate and per-host availability work; path claims scan a lifetime-growing launch table; and lifecycle cleanup launches every eligible teardown without backpressure.
The duplication/architecture scan also found that environment-directory switching still manufactures a project-checkout environment directly in core instead of invoking that provider. That is not a separate inline blocker, but it leaves false provider provenance and duplicates plugin-owned attach behavior; routing it through normal provider orchestration, or marking it explicitly core-owned, would keep the ownership model coherent.
Verification at b738452c:
- GitHub CI is green, and
git diff --checkpassed. - Focused Turbo tests passed for the three environment plugins: 74 tests total (Worktree 36, Project checkout 28, Personal workspace 10).
- In a fresh isolated dev database, doobie drove the real UI through project selection → Worktree provider → named
feature-reviewbase branch → thread creation. The environment persisted asgit-worktree,ready, andisWorktree: true; a real Codex turn returned the expected text; reload preserved it; and “New thread in this environment” reopened in Reuse mode. - Archiving moved the environment into retirement; deletion completed provider teardown, marked it
destroyed, removed the managed worktree, and left the source checkout intact. - The verification inventory check itself was blocked by an existing unmapped
browserCLI family, so I did not count that catalog check as a PR failure.
I would address the inline findings before merging, especially the duplicate validation, disabled-default hang, provider-owner provenance, pre-admission hook execution, and unbounded/refetch-heavy hot paths. This review is posted with comment disposition only.
2b320f5 to
78fec24
Compare
c9b64f0 to
f9ecb9a
Compare
## Human comments ## What was wrong Docs could not load any vault when the host list was nonempty: `listNotes` returned `rpc output validation failed`. PR #3227 removed `type` from Docs' strict host schema, while the SDK continued returning that field. Existing Docs fixtures returned empty host lists, hiding the regression. ## What changed Strip additional host properties from the Docs RPC response while continuing to validate its declared fields. Add regression coverage using the complete SDK host fixture for both successful file listing and the unavailable-vault fallback. ## How you verified - Both new regression cases failed before the fix with `Unrecognized key: "type"`; all 68 Docs tests pass afterward. - `pnpm exec turbo run test typecheck build --filter=bb-plugin-simple-notes` passed. - Verified in an isolated source dev app with a connected host and synthetic vault. Temporarily restoring the original validator reproduced the exact error in both the browser and real RPC. Rebuilding/reloading the fixed plugin loaded the vault and opened its Markdown note through browser input. Captured before/after screenshots and RPC responses. - Secret-model scan clean for the working tree, HEAD, added lines, and commit messages in the push range. - SlopCop skipped as requested. > AGENT GENERATED
…#3436) ## Human comments ## What was wrong The prompt-box environment picker offered every environment provider on every machine, so CoW copy showed up under Macs where its reflink probe can never succeed. Per-machine plugin availability existed briefly (#3227), but #3393 removed it from discovery because the app's per-machine fan-out blocked the picker on the slowest machine's Git inspection and plugin probe. That fix removed the information rather than making it non-blocking: discovery became structural only, availability is always null, and an unsupported choice now fails only at thread creation. ## What changed Server (`apps/server/src/services/environments/provider-machine-availability.ts`, new): a background per-machine availability probe. When a project's providers are listed, each structurally eligible provider and connected persistent machine is probed in the background (Git inspection when `requires.gitCheckout`, then the plugin's `availability` hook), keyed by provider, project, and machine. Listing never awaits a probe: it returns the cached answer or null. Results are cached for ten minutes, cleared when a plugin rechecks, and disconnected machines are never probed. When an answer changes, the server emits a new `environment-availability-changed` system change so clients refetch. Contract (`packages/server-contract/src/api/system.ts`): each provider now carries `machineAvailability`, a map from host id to `available`, `setup-required`, `unavailable`, or null while unknown. `availability` is filled from that map when `hostId` is given. Thread creation still checks the selected provider and machine afresh, exactly as #3393 left it. App: `NewThreadComposer` lists providers for the current project and derives each machine's rows from `machineAvailability`. The picker hides providers a machine reports as unavailable, except the currently selected one, which stays visible and disabled with its reason so the selection never disappears; setup-required rows stay selectable with their message; unknown rows show as before. The provider list is remembered per project in localStorage through the existing last-known cache and served as placeholder data, so the picker is already trimmed on the first open after a reload. The realtime registry maps the new system change to the provider query. CLI: `bb environment providers --project <id> --machine <id>` prints each provider's availability on that machine, and `--json` includes `machineAvailability`. Guide template, bb-cli skill, `docs/api_to_audit.md`, the Plugin Guide surface text, and the SDK doc comment were updated to describe background probing. No server/daemon wire fields changed, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. ## How you verified - Server tests in `apps/server/test/threads/environment-providers.test.ts` rewritten for the new contract: listing answers null first, the background answer is served on the next listing and `environment-availability-changed` fires once; Git inspection runs in the background and a missing branch is reported as unavailable; disconnected machines are not probed; unmet structural requirements never probe; a plugin recheck invalidates the cache and probes again; a throwing hook is reported as unavailable without failing the listing; creation still checks afresh. 43 passed. - App tests: picker hides unavailable rows, keeps the selected unavailable row disabled with its reason, keeps setup-required selectable with its message, hides per machine in the grouped menu; provider query writes and serves the last-known cache and rejects a corrupt entry; realtime registry covers the new system change. - CLI test for the availability column with available, unavailable, and unknown rows. - `pnpm exec turbo run typecheck` for server, app, cli, domain, server-contract, sdk, plugin-sdk, plugin-api-map, and templates passes. - `pnpm exec turbo run test` for cli, server-contract, sdk, domain, templates, plugin-api-map, and plugin-sdk passes. Full server and app Vitest suites pass (the app's turbo test task fails before tests on this machine because its PWA icon check needs a libvips module that isn't installed, so the app suite was run with vitest directly). - Manual, on the earlier client-only version of this change: a dev server with the btrfs-cow plugin and two projects on one machine, one on btrfs and one on tmpfs; the tmpfs picker omitted CoW copy and was already trimmed on first open after a reload. > AGENT GENERATED Co-authored-by: Claude Fable 5.1 <[email protected]>
## Human comments ## What was wrong A thread in the personal project runs in a `personal-workspace` environment, which has neither a name nor a branch. `resolveEnvironmentDisplayName` therefore fell through to the workspace folder's basename — and that basename is the environment provider's instance key, which the server sets to the thread ID (`thread-environment-placement.ts`, `environmentProviderInstanceKey: context.thread.id`). So every personal thread was labelled with a raw `thr_…` ID in mobile Recents and in the reuse-environment picker. The folder-name step was introduced in #3227; before that the label was `branchName ?? name`, which was simply empty for these rows. ## What changed `resolveEnvironmentDisplayName` in `packages/core-ui/src/environment-display.ts` now names a provider-backed environment by its provider display name and uses the workspace folder only for environments with no provider: name ?? branchName ?? (providerId === null ? basename(path) : providerDisplayName) A personal thread now reads `Personal workspace` instead of `thr_5b9tupt9ej`. `resolveWorkspaceFolderName` is no longer exported; it is reachable only through the resolver. Deleting the folder step outright was the simpler change, but it regressed provider-less environments (legacy rows predating #3227, which exist in real installs): with no provider label to fall back to, they degraded to the generic "Environment". Gating the step keeps them named by their folder. Two deliberate consequences: - A branchless worktree environment now shows its provider name (`Worktree`) instead of the checkout folder name (`bb`) in the sidebar environment group header. - While the provider list is still loading, a branchless provider-backed environment renders no name instead of briefly showing the folder — which is what stops `thr_…` flashing during that window. No wire, schema or CLI changes; `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. ## How you verified - `packages/core-ui/test/environment-display.test.ts`: the case that asserted `thr_k72wqg7tcs` now asserts `Personal workspace`, plus new cases for the loading window and for provider-less directory attachments. They fail against the previous resolver. - `pnpm exec turbo run typecheck lint test --filter='...[origin/main]'`: 118 of 121 tasks pass (`@bb/app` lint reports only pre-existing react-compiler warnings, 0 errors). `@bb/integration-tests` failed with ~10 suites hitting their 60s timeout; a `pnpm start:worktree` instance was running in the same checkout during the run, and this change is a pure display-string helper with no server, daemon or provider surface, so the timeouts are contention rather than a regression. Worth confirming from CI. - Manual, in an isolated dev instance driven through the browser, with the same seeded data on both builds — the fix reverted, then restored: - Mobile Recents: `thr_zymfj7m9z6 · 4m ago` → `Personal workspace · just now`. - Reuse-environment picker: chip and menu rows `thr_hxbeuzp4r9` / `thr_zymfj7m9z6` → `Personal workspace`. - Sidebar environment group header, branchless worktree row: `scratch-notes` → `Worktree`. - Provider-less directory attachment: `scratch-notes` on both builds, confirming parity. 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…3929) ## Human comments <!-- Agents: Do not fill in this section. This is for human users to fill in. --> ## What was wrong The environments-into-plugins migration (#3227) replaced the composer's fixed workspace rows with plugin-provided environment provider rows, and the "Existing worktree" row was dropped along with them. `ReuseEnvironmentPicker` only renders once the selection is *already* a reuse value, so `reuse:<id>` became unreachable from the root composer — reuse mode could only be entered when a thread seeded it (the thread "+" button or the workspace header). Choosing an existing environment for a new thread from the root composer was impossible. This PR is the reuse-restoration half of a branch split; the external Git worktree adoption work ships separately. ## What changed App-only, seven files under `apps/app/src`, no SDK/server/daemon/wire changes. - `components/pickers/EnvironmentPicker.tsx` — adds an optional `onSelectReuse` prop and a `ReuseEnvironmentOption` row ("Reuse existing", `REUSE_ENVIRONMENT_ICON_NAME`) rendered in its own `CommandGroup` below the provider rows, separated by a `CommandSeparator`. The row is omitted entirely when `onSelectReuse` is not wired, and marked selected while the active value parses as `type: "reuse"`. The label shares its verb with the selected-state pill ("Reuse") and the reuse dropdown heading ("Reuse an existing environment") so the three surfaces read as one option. The row is always offered rather than disabled-when-empty: the reuse dropdown already explains an empty project, and a disabled row is a dead end. - `components/pickers/EnvironmentPicker.tsx` (menu width) — the popover was pinned to `w-80` for every variant. Every variant now sizes to content between `min-w-52` and `max-w-80`, including the machine-search menu: the search input stretches to whatever width the menu has, so there was no reason to pin it. Measured across the picker stories the searching menu settles at 208–309px instead of a flat 320px, and holds its width while results filter because the floor covers the search placeholder. This matches `ModelReasoningPicker`, which already sizes to content. With the floor unconditional, the `isLoading` arm that re-applied `min-w-52` became dead and was removed. - `components/promptbox/NewThreadComposer.tsx` — `handleSelectReuse` sets `REUSE_VALUE_WITHOUT_ENVIRONMENT` through the existing `changeEnvironment` path. - `components/promptbox/NewThreadPromptBox.tsx` — threads `onSelectReuse` through `NewThreadEnvironmentConfig` to `EnvironmentSlot`. - `views/root-compose-environment-selection.ts` — `resolveRootComposeEffectiveEnvironmentValue` no longer rewrites a pending `reuse` (null environment id) selection to the fallback value when the project has nothing to reuse. Selecting "Reuse existing" now holds reuse mode and shows the "Pick an environment" dropdown instead of silently snapping back to the default provider. - `components/promptbox/NewThreadEnvironmentOptions.stories.tsx` — wires `onSelectReuse` into the strip and drops the now-obsolete "reuse unavailable" story row. - `components/pickers/EnvironmentPicker.stories.tsx` — no fixture drove the machine-grouped menu with `onSelectReuse`, the combination the real composer always produces, so the row's placement below every machine group, its selected state, and its behaviour beside a disabled offline machine had no visual coverage. Adds four stories over the existing machine fixtures: reuse offered, reuse selected, offline machine, and the machine-search variant. - Tests: `EnvironmentPicker.test.tsx` and `RootComposeView.test.ts` (see below). - `components/pickers/ReuseEnvironmentPicker.tsx` — the reuse dropdown rendered every option in a plain `DropdownMenu` with no filter. Replaced with the cmdk `Command` the other pickers use: a search input appears once the list reaches seven entries, and each whitespace-separated term is matched against the environment label, name, branch, path, machine name, and the titles of the threads living in it. - `views/root-compose-environment-selection.ts` + `NewThreadComposer.tsx` — "New thread in environment" seeds `reuse:<id>` directly, but the resolver only kept such a value when the id appeared in the thread-derived option list. That list comes from the sidebar's non-archived threads, so a seeded environment that no live thread points at was silently replaced by the default provider, and knowing the exact id saved no work. The composer now resolves that id through the existing `GET /environments/:id` query (no new route), only when it is absent from the thread-derived list: the selection is held while the lookup is pending, kept once the environment returns, and dropped only when it is gone or destroyed. The resolved environment is appended to the picker options so the trigger shows its real label instead of "Pick an environment". - `components/pickers/ReuseEnvironmentPicker.stories.tsx` — new stories for the empty, short, selected, disabled, and searchable states. ## How you verified Tests added, all failing before these changes and passing after: - `EnvironmentPicker.test.tsx` — the row is offered alongside the providers and invokes `onSelectReuse`; the row reports `aria-current="true"` while a `reuse:<id>` value is active; the row is omitted when `onSelectReuse` is not supplied. - `RootComposeView.test.ts` — `resolveRootComposeEffectiveEnvironmentValue` holds `"reuse"` both with an empty `reuseThreadOptions` list and with one available, rather than falling back. Four more cover the seeded path: a seeded environment absent from the thread-derived list is kept, a pending lookup holds the selection, a missing environment falls back, and a lookup for a different id does not rescue an unrelated reuse value. - `ReuseEnvironmentPicker.test.ts` — `filterReuseThreadOptions` returns everything for a blank query, matches branch/thread-title/machine-name, ignores case, requires every whitespace-separated term to match, and returns nothing when no option matches. Commands run from the worktree: - `pnpm exec turbo run typecheck lint --filter=@bb/app` — 5/5 tasks successful, `Found 191 warnings and 0 errors`. Warning count and the per-file `NewThreadComposer.tsx` warning count (4) are identical to `origin/main` with these files reverted, so no new lint warnings are introduced. The `preserve-manual-memoization` warning on that hook is pre-existing (inferred `setCommandState`, unrelated to the added dependency). - `pnpm exec turbo run test --filter=@bb/app -- --run src/components/pickers/EnvironmentPicker.test.tsx src/views/RootComposeView.test.ts src/components/pickers/ReuseEnvironmentPicker.test.ts` — 3 files, 110 tests passed. Visual check via Ladle (`promptbox--environment-options--overview`) in headless Chrome: - Opening the project checkout picker lists `Project checkout` (current), `Worktree`, then `Reuse existing` below a separator, with `aria-disabled="false"` on the reuse row. - The menu measures 208px wide instead of the former fixed 320px. - Swept every picker story and measured the popover: grouped menu 208px, grouped menu with reuse 253px, offline machine 309px, machine-search 208px — all previously a flat 320px. Typing into the machine search and clearing it again held 208px at every step, so content sizing does not make the menu jitter while filtering. The loading menu still measures 208px with the `isLoading` width arm removed. - The "project · reuse empty" row renders `Reuse` + `Pick an environment` rather than reverting to a provider, confirming reuse mode is held before an environment is chosen. Reuse-picker search driven in headless Chrome against its new story: with eight environments the search input appears; `payment` narrows to the one matching on branch and thread title; `build-box` narrows to the two on that machine; `zzzz` renders the "No environments match." empty state. With three environments no search input renders, selecting a row closes the menu, and the empty-options variant shows only "Nothing to reuse yet.". > AGENT GENERATED --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Before environments moved into plugins, bb wrote managed workspaces to `<dataDir>/worktrees` and `<dataDir>/personal-workspaces`, and `isBbManagedWorkspacePath` tested exactly those two roots. Since #3227 each environment plugin writes under `<dataDir>/plugins/<id>/host-data`, so the test has matched nothing for ten days. The guard it feeds refuses a user-supplied path that sits inside bb's own storage without being a recorded workspace of the asking project — the case where another project is mid-provision at that path, or where the directory is an orphan of an environment that was destroyed. Both `update_environment_directory` and thread creation with an unmanaged path accept arbitrary paths from a user, and both silently stopped refusing these. Match any plugin's process data directory, using the `host-data` / `bridge-data` convention that `ensurePluginProcessDataDir` already owns, alongside the pre-plugin roots so existing workspaces keep their protection. Repairing the path test alone would have broken every worktree creation. The provider-create path in the engine runs the same guard against the path the provider just produced, before that path is bound to its environment row, so a correct test would refuse bb's own fresh workspaces. Split the two uses: `foreignProjectOwnedPathRefusal` for a provider-produced path, which only asks whether another project owns it, and `suppliedWorkspacePathRefusal` for a path a user chose, which asks that and the storage question. Clause two also claimed the path was "owned by another project" when the orphan case has no owner at all; it now reports what the check actually knows. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The composer could only ask the worktree provider for a fresh worktree. A worktree made by hand outside bb was invisible, even though the provider contract has been able to attach an unowned path since #3227. Discovery lives in the plugin. A `listWorktrees` host method parses `git worktree list --porcelain -z` in the project checkout and drops the main checkout, bare repositories and anything under the plugin's own worktrees root, so what is left is what bb did not create. A plugin RPC exposes that list to the plugin's own composer control, which now offers "New worktree" alongside each discovered worktree. No core change, no new daemon RPC, no HOST_DAEMON_PROTOCOL_VERSION bump. The inputs schema becomes a union so `{ kind: "existing", path }` joins the existing `{ branch }` shape. The branch member keeps its exact old form, so selections persisted on existing environments still parse. Creating on an existing path re-resolves it against the repository, refuses a prunable worktree, claims the path through core, and returns it with `ownsPath: false` and an `{ adopted: true }` resource. Removal returns early for that resource, so archiving a thread never deletes a directory the user made. That early return is the whole safety property of this change and is tested from both sides. Verified in the app with a hand-made worktree: it appeared in the composer, a thread created on it landed on the existing path with `managed: false`, and archiving that thread left both the directory and its git registration intact. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ugin branch pickers (#4062) ## Human comments ## What was wrong When environment selection moved into plugins (#3227 for project checkout, #3932 for worktrees), both branch pickers stopped rendering through `BranchPicker` and silently dropped behavior that component still implements. Three regressions followed, all confirmed by driving the pickers in a dev app at 1440×900, 470×844 and 390×844: 1. **Compact drawer height.** `plugins/environment-git-worktree/app.tsx` pinned the option list with an unconditional `h-80`, so the compact drawer measured a flat 390 × 399 in every state — 399 px of sheet for two rows. Every other branch picker uses `min-h-0 max-h-[60vh] … md:max-h-80`, which sizes to content below `md`. 2. **Search debounce.** Both plugins pass `useDeferredValue(query)` straight into `experimental_useBranches`, which is not a debounce. Typing `feature` issued 7 `GET /api/v1/projects/:id/branch-options` requests — 7 host round trips running `git branch`. `BranchPicker` debounces the same query at 120 ms. 3. **Trigger label.** The worktree chip rendered `Branch from: main` in one span instead of marking the prefix `data-promptbox-hide-compact`. In a promptbox under 30 rem the prefix is supposed to disappear; instead it consumed the chip, which read `Branch from: ...` at 470 px and `Branc...` at 390 px, hiding the branch entirely. ## What changed - `plugins/environment-git-worktree/app.tsx` — option list `h-80` → `md:h-80`, so the compact drawer sizes to content while the desktop popover keeps the stable 288 × 367 dimensions #3932 introduced. The trigger renders prefix and value as separate spans, the prefix carrying `data-promptbox-hide-compact` and the value the usual emphasis, matching the project-checkout chip. - `apps/app/src/hooks/queries/branch-search-debounce.ts` (new), `project-queries.ts`, `environment-queries.ts` — the debounce now lives in the two hooks that own branch requests, `useProjectSourceBranches` and `useEnvironmentMergeBaseBranches`, behind a shared `useDebouncedBranchSearchQuery`. A component holding this policy is what let the regression happen: callers that stopped rendering `BranchPicker` silently started hitting the host per keystroke. At the query boundary no caller can forget it, and the first render is still immediate — only changes wait. - `apps/app/src/components/pickers/BranchPicker.tsx` — drops its own debounce and reports search queries to consumers as they are typed; both consumers feed them back into the hooks above. Callers keep filtering cached results off the immediate query, so lists still narrow on each keystroke. - `packages/plugin-sdk/src/app-contract.ts`, `docs/api_to_audit.md` — record that `experimental_useBranches` debounces `query`, since that decides whether a plugin should debounce its own search input. No plugin source changed: the plugins never held the debounce, they call `experimental_useBranches` and the implementation is app-side, so nothing needs rebuilding against a new SDK. No wire, CLI, or configuration changes, and no new public plugin API members. ## How you verified Measured in an isolated source dev app (fixture repo: 6 branches, 2 existing worktrees), driven through headless Chromium: | Check | Before | After | | --- | --- | --- | | Worktree drawer, no search match | 390 × 399 | 390 × 266 | | Worktree drawer, branches listed | 390 × 399 | 390 × 382 | | Worktree drawer, 2 existing worktrees | 390 × 399 | 390 × 284 | | Worktree popover, desktop | 288 × 367 | 288 × 367 | | `branch-options` requests for 7 keystrokes, worktree | 7 | 1 | | `branch-options` requests for 6 keystrokes, project checkout | 6 | 1 | | Worktree chip at 470 px | `Branch from: ...` | `main` | The after values match the project-checkout picker in the same states (266 px empty, 382 px listed), and the pre-#3932 worktree picker also issued 1 request for 7 keystrokes. Tests: - `usePluginBranchPickerState.test.tsx` and `environment-queries.test.tsx` — new debounce tests for both request paths; with the debounce removed they fail with 8 and 5 requests instead of 2. - `plugins/environment-git-worktree/app.test.tsx` — new compact-prefix test asserting the prefix span carries `data-promptbox-hide-compact` and the value does not; the existing chip assertions move to the split-span text. - `pnpm exec turbo run test typecheck --filter=bb-plugin-environment-git-worktree` — 96 tests, 5 files, typecheck clean. - `pnpm exec turbo run test --filter=@bb/app -- src/components/plugin src/components/pickers src/components/secondary-panel/git-diff src/hooks/queries` — 850 tests across the pickers, plugin bridge, git-diff panel, and query hooks. - `pnpm exec turbo run typecheck lint --filter=@bb/app` — clean. Not covered: headless Chromium only, so the WebKit/iOS-Simulator drawer checks the UI guidance asks for were not run, and the full repository suite was not run. The merge-base picker's debounce is covered by the new `environment-queries` test rather than a live measurement. Unrelated and untouched: branch-picker drawers have no bottom safe-area inset because `BRANCH_PICKER_CONTENT_CLASS_NAME`'s `p-0` overrides the drawer padding, which has been true since #325 for all three pickers. > AGENT GENERATED --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
🚨 **SLOP COP** 🚨 · `new-issue-autopilot` ## Human comments ## What was wrong When the project-checkout provider created a new branch, it did not tell core which ref the branch was based on. Core then recorded no merge base and compared the thread against the default branch, so commits inherited from the base showed up as the thread's own changes (#5850). The first commit made the provider report the base. That only worked for the first environment created at a checkout path. Project-checkout environments are never retired. Every later thread at the same path reuses that environment row, and core skipped merge-base writes on reused rows owned by the same provider (`environment-engine.ts`, the `adoptedExistingEnvironment && existingProviderOwnsLifecycle` guard). This had two effects: - A checkout that already had an environment (the usual case) still recorded no base. - A checkout whose first thread branched from `topic-base` kept `topic-base` for every later thread. A later thread branched from `main` then showed commits `main` gained after `topic-base` as its own changes. On `main` today, that later diff is correct. The first commit alone caused this regression. Reproduction and root-cause report for the original bug: https://get-bb.github.io/reports/issues/5850.html ## What changed - **Provider result contract (Plugin SDK, experimental environment providers):** `PluginEnvironmentProviderCreateResult.mergeBaseBranch` now accepts `null`. A string records the base, `null` clears it, and omitting the field keeps it. This only matters when core reuses an environment row the provider already owns at that path. The result schema accepts `null`. Plugin SDK patch bumped to 0.6.60, because the published declaration types change. - **Core** (`apps/server/src/services/environments/environment-engine.ts`): on a reused row owned by the same provider, a reported `mergeBaseBranch` (string or `null`) is now applied, and an omitted one leaves the row unchanged. New rows behave as before. - **Project-checkout plugin** (`server.ts`): - A new branch reports its base ref. - Switching to an existing branch reports `null`, so the diff falls back to the default branch. Core did the same before #3227. - Attaching without a branch switch omits the field, so the current base is kept. - Restoring a removed environment re-reports that environment's recorded merge base. Previously the restore dropped it. - **Docs:** the plugin README and the plugin-authoring backend reference describe the three cases. - No host/daemon wire change, migration, or CLI change. ## How you verified - **Regression tests:** each one fails on the previous head of this PR and passes after the fix. - `apps/server/test/threads/environment-providers.test.ts`, "on a reused host row it …": three cases (reported, `null`, omitted). - Before the fix, the reported case fails with `expected 'origin/old' to be 'origin/dev'`. - The `null` case fails because the old schema rejects `null`. - The omitted case passes on both versions, as a control. - `plugins/environment-project-checkout/server.test.ts`: - "checkout provider merge base": existing branch reports `null`; attach-only omits the field. - The restore test asserts that the recorded base is re-reported. - The original real-git test `server-merge-base.test.ts` is kept. It fails on `main` and passes here. - **End-to-end check** (temporary probe in the `tests/integration` harness: real server, host daemon and plugin, fake agent; not committed). It reads the diff through `GET /environments/:id/diff`: - A checkout that already had an environment, then a thread on a new branch from `topic-base`: before, the merge base was `null` and the diff included `base-only.txt`. After, the merge base is `topic-base` and the diff is empty. - A thread from `topic-base`, then a later thread from `main` after `main` gained `main-only.txt`: with this PR's first commit alone, the merge base stays `topic-base` and the diff shows `A main-only.txt`. After the fix, the merge base is `main` and the diff is empty. - **Commands:** - `pnpm exec turbo run test --filter=bb-plugin-environment-project-checkout`: 45 passed. - `pnpm exec turbo run test --filter=@bb/server -- test/threads/environment-providers.test.ts`: 68 passed. - `pnpm exec turbo run typecheck lint --filter='...[origin/main]' --continue`: 139 of 139 tasks passed. - `node .github/workflows/check-plugin-sdk-version.mjs` and `node packages/plugin-sdk/scripts/check-npm-version-guard.mjs`: both pass. Fixes #5850 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- slopcop:rule=new-issue-autopilot run=run_f48tdnxrmvgsveyn sha=issue-5850 kind=summary --> --------- Co-authored-by: SawyerHood <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Remove the reuse rule that required Personal threads to share only bb-created personal workspaces. It predates update_environment_directory, which made a Personal thread in an attached folder a normal state; since then every flow that shares that folder (forks, then children) hit a 409. The project half of the rule is unreachable since #3227 because the different-project check rejects it first. Drop the fork-only exception and the PR's fresh-workspace fallback with it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
## Human comments ## What was wrong A Personal thread that moved into an attached folder with `update_environment_directory` could not spawn Personal children: every variant returned `409 Personal project threads must reuse a personal workspace` (#7256). The cause is a reuse rule from c35a710 (May 27) that let Personal threads share only bb-created personal workspaces. It was written before threads could move (79f409a, June 24); moving made "a Personal thread in an attached folder" a normal state, but the rule was never revisited. Forks hit the same 409 and got a fork-only exception in #1212 (`allowUnmanagedPersonalProjectReuseEnvironmentId`); children of moved parents hit it now. The rule's other half, "standard project threads cannot reuse personal workspaces", has been unreachable since #3227: personal workspaces always belong to the Personal project, so the earlier "Environment belongs to a different project" check rejects that case first. ## What changed - Delete the reuse rule (`assertReuseWorkspaceProjectCompatibility`) and the fork-only exception plumbing in `thread-request-eligibility.ts`, `thread-environment-placement.ts` and `thread-create.ts`. - Children of a moved Personal parent now share the parent's folder, the same way forks already did. A parent still in its personal workspace keeps sharing it as before, and `--machine` on another host still gets a fresh workspace (#5207). - Deviation from the issue's proposed fix and this PR's first commit: instead of falling back to a fresh, empty personal workspace when the parent has moved, the child follows the parent. That keeps children and forks consistent and removes an exception rather than adding one. It also makes `--environment <parent env id>` work. The first commit's guard is reverted. - Still blocked: starting a new Personal thread at an arbitrary path (`--environment <path>`, a separate 400 check), and a standard project thread sharing a personal workspace (different-project check, now covered by a test). - No wire, schema, CLI or doc changes. ## How you verified - Tests: - The three `environment-providers.test.ts` cases now expect the child to share the attached parent's environment. They fail on main with the 409. - A new case asserts that a standard project thread reusing a personal workspace still gets 409 "Environment belongs to a different project". - The fork test that asserted the exception's narrowness is removed along with the exception. - `pnpm exec turbo run test --filter=@bb/server -- test/threads test/public`: 117 files, 1275 tests pass. `turbo run typecheck --filter=@bb/server` passes; oxlint and prettier are clean on the changed files. - Live, on a `pnpm start:worktree` server, a claude-code Personal thread moved itself to `/tmp/bb7258-scratch`: | From the moved parent | main | this PR | |---|---|---| | child, no env flag | 409 | shares `/tmp/bb7258-scratch` | | child, `--new-environment personal` | 409 | shares `/tmp/bb7258-scratch` | | child, `--environment-provider personal-workspace` | 409 | shares `/tmp/bb7258-scratch` | | child, `--environment <parent env id>` | 409 | shares `/tmp/bb7258-scratch` | | fork (no flags / `--environment <parent env id>`) | shares | shares `/tmp/bb7258-scratch` | | fork `--new-environment personal` | fresh workspace | fresh workspace | A running child and a running fork each replied `/private/tmp/bb7258-scratch` to `pwd`. Fixes #7256 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- slopcop:rule=new-issue-autopilot run=run_wgn1lcuqmw71ng1k sha=issue-7256 kind=summary --> --------- Co-authored-by: SawyerHood <[email protected]> Co-authored-by: Michael Yong <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Human comments
What was wrong
Main implements three workspace kinds directly in core server and host-daemon provisioning code: the project's checkout, a managed Git worktree, and a personal directory. Adding another environment requires extending those switches and their cleanup paths. Plugins cannot supply workspace creation/removal, validate inputs, report availability, or render the associated composer controls through a common environment contract.
What changed
Reviewer report — overview, API, review fixes, and before/after screenshots
Environment plugins own resource operations; core owns placement, durable launches, cancellation, recovery, retries, retirement, and teardown. The three existing behaviors are bundled, auto-installed plugins. Main's fixed defaults remain: a Git project defaults to a fresh worktree, a non-Git project uses its checkout, and a projectless root gets a personal workspace. A project child gets a fresh worktree; a projectless child shares its parent's environment.
The request shape already names an enrolled machine inside the provider selection:
bb.experimental_environments.register(...)acceptscreateandremoveoperations withAbortSignal, plus availability, validation, input schemas, and lifecycle policy. The type-only@get-bb/plugin-sdk/environment-providerentry exports unprefixed types. New runtime values remain experimental. Creation returns a path and ownership flag; removal receives the persisted provider resource and stable path key. Core persists launch progress and settles interrupted attempts inapps/server/src/services/environments/provider-orchestration.ts.environment-project-checkoutenvironment-git-worktreeenvironment-personal-workspacepackages/environment-provider-hostsupplies shared host-side primitives. The daemon now attaches resolved paths withenvironment.attach/environment.attach.cancel; it no longer provisions or destroys environments. Git inspection reportsisWorktree.HOST_DAEMON_PROTOCOL_VERSIONincreases from 183 to 193, and the SDK patch-bump script advances 0.4.49 to 0.4.50.Migration 0113 is the single migration from main: it converts legacy environment kinds and pending intents to provider records, records owning plugin IDs, indexes active path claims, remaps lifecycle statuses, and drops the old managed/provision-type/cleanup columns. It creates neither canonical-path storage nor a hook-operation table. The implementation uses stored paths without host-wide canonicalization or backfills. Published environments expose provider fields and lifecycle; deprecated
managed,workspaceProvisionType, and display kind are derived compatibility fields.Provider policy exposes only retirement grace and path-key strategy. Core uses fixed retry defaults (60 seconds for removal; three transient creation retries 30 seconds apart) with no overall provider-create timeout. Setup/teardown scripts retain their separate 15-minute timeout.
Hooks use IDs derived from existing launch/environment identity and are tracked only in daemon memory. A server restart can join a known daemon operation. If a daemon restart loses hook state, core reports an unknown outcome and blocks automatic cleanup rather than rerunning the script or deleting its workspace. Recovery then requires manual inspection; there are no persisted hook files, PID reconciliation, or separate hook ledger.
API and CLI additions include environment provider discovery, environment list/show/delete,
bb thread spawn --environment-provider/--environment-inputs, andbb thread list --environment. Existing path shorthand and legacy request forms normalize at the server boundary. Hooks expose onlyenvironmentorproviderenvironment intents, and addthread.unarchivedandmessage.cancelled. SDK areas, host helpers, Plugin Guide/API map, audit documentation, built-in authoring and CLI skills, guide chapters, and READMEs are updated together.User-facing changes:
experimental_useBranches,experimental_useCheckoutState, and the seven-propexperimental_BranchPicker. The checkout plugin preserves main's chip interactions.isWorktree; the plugin catalog gains Environments; General uses New branch prefix.This change includes no machine-provider API, machine launch table, host lifecycle columns, installer behavior changes, machine controls, new-machine selection, Modal plugin, or SSH plugin. Two existing test fixtures were made portable: README-directory copy errors accept macOS
ENOTSUP, and the nested-ignore watcher test accounts for native event coalescing and checks nested paths specifically. Production installer and watcher behavior are unchanged.How you verified
git diff --checkpasses. The local worktree app is rebuilt and restarted with the latest migrations.