← reports

#8015 · Explicit reuse selection omits environment validation

BugPriority: MediumEffort: Mediumui, plugins Issue2026-11-22 · base 796cdcc0f4bf8a55e23664035c54e8db6fe9d272

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro

1. TL;DR

A caller can explicitly select an existing environment, yet the new-thread composer settles on the project's checkout instead. The composer builds its reuse list from sidebar threads and only supplements that list with a direct environment lookup for component seeds. Navigation targets and runtime selection changes do not feed that lookup. Consequently, an existing environment with no sidebar threads is treated as an unavailable reuse target. The failure is reproduced through the real root compose route and the real composer host selection API, in two clean trusted checkouts. This is a behavioral selection defect, not a pixel-level rendering claim.

2. Claims vs findings

ClaimFindingEvidence
Explicit navigation drops a reuse target without active sidebar threads.VerifiedRoot route receives a reuse target and settles on provider:project-checkout; available SDK environment response is configured.
Runtime composer selection has the same problem.VerifiedBoth root and component-local host setSelection return the checkout provider rather than the requested reuse.
The seed path performs a direct lookup.Verified in sourceThe lookup ID is derived only from seed.environment; the returned row must match the ID and not be destroyed.
The seed documentation still describes thread-based fallback.Verified in sourceSDK declaration lines 5275–5276 contradict the live-row lookup.
The exact behavior on the reporter's older installed release.Not re-runOnly trusted main at the recorded commit was executed; no user plugin, vault, or installed runtime was accessed.

3. Environment

4. Minimal reproduction

The inline patch extends the existing trusted component test file. It does not alter production code or install a dependency. The reports repository publishes self-contained HTML, so all reproduction code and assertion evidence are inline; raw artifacts remain in a local backup.

  1. Clone the public repository and select the recorded trusted commit:
    git clone https://github.com/get-bb/bb.git bb-8015
    cd bb-8015
    git checkout 796cdcc0f4bf8a55e23664035c54e8db6fe9d272
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
  2. Copy the complete patch below into a local regression.patch file, inspect it, and apply it:
    git apply /path/to/regression.patch
    pnpm exec turbo run test --filter=@bb/app -- src/components/plugin/PluginNewThreadComposer.test.tsx -t 'without sidebar threads'
  3. The test harness provides an existing ready environment and zero sidebar threads. One case opens the real root route with its single-use reuse target; two cases call PluginComposerHost.setSelection, using the same contract table for root and component-local composers.

Expected vs actual

Root navigation:
Expected: "reuse:env_existing"
Received: "provider:project-checkout"

setSelection (root and component-local):
Expected: { type: "reuse", environmentId: "env_existing" }
Received: { type: "provider", environmentProviderId: "project-checkout",
            machine: { type: "existing", hostId: "host_1" }, inputs: {} }

Second clean checkout: 3 failed | 65 skipped (68)

First-run assertion output · Second-run assertion output.

Reproduction test patch (complete)

diff --git a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx
index c5bf05a3d..7675a97a6 100644
--- a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx
+++ b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx
@@ -61,7 +61,10 @@ import {
   useSetRootComposeProjectId,
 } from "@/lib/root-compose-selection";
 import { getPromptDraftAccessor } from "@/hooks/usePromptDraftStorage";
-import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures";
+import {
+  makeEnvironment,
+  makeThreadListEntry,
+} from "@bb/test-helpers/domain-fixtures";
 import { createDeferredPromise } from "@bb/test-helpers";
 import type { PromptDraftAttachment } from "@bb/client-core";
 import { makeProjectWithThreadsResponse } from "@/test/fixtures/projects";
@@ -209,6 +212,7 @@ vi.mock("@/hooks/queries/plugin-settings-queries", () => ({
 
 vi.mock("@/lib/sdk", () => ({
   sdk: {
+    environments: { get: vi.fn() },
     projects: { attachments: { copy: mocks.copyAttachments } },
     system: {
       experimental_recordTelemetryEvent: vi
@@ -1917,6 +1921,42 @@ describe("PluginNewThreadComposer seeding", () => {
     });
   });
 
+  it("reuses an explicitly targeted environment without sidebar threads", async () => {
+    vi.mocked(sdk.environments.get).mockResolvedValue(
+      makeEnvironment({
+        id: "env_existing",
+        projectId: "proj_1",
+        hostId: "host_1",
+      }),
+    );
+    window.localStorage.setItem("bb.root-compose.project-id", "proj_1");
+    const router = createMemoryRouter(
+      [{ path: "/", element: <PanedRootComposeView /> }],
+      {
+        initialEntries: [
+          { pathname: "/", state: { reuseEnvironmentId: "env_existing" } },
+        ],
+      },
+    );
+    render(
+      <Provider>
+        <RouterProvider router={router} />
+      </Provider>,
+    );
+
+    await waitFor(() => {
+      expect(router.state.location.state).toBeNull();
+      expect(latestPromptBoxProps().modeConfig.environment.value).toBe(
+        encodeReuseValue("env_existing"),
+      );
+    });
+    expect(latestPromptBoxProps().modeConfig.worktree.options).toEqual(
+      expect.arrayContaining([
+        expect.objectContaining({ environmentId: "env_existing" }),
+      ]),
+    );
+  });
+
   it("closes visible plugin details before an underlying terminal", async () => {
     const terminal = createTerminalFixedPanelTab({
       terminalId: "terminal-under-details",
@@ -3168,6 +3208,34 @@ describe("NewThreadComposer setSelection", () => {
     return result as unknown as ExperimentalComposerSelection;
   }
 
+  it.each(["root", "component-local"])(
+    "settles an explicit reuse selection without sidebar threads (%s)",
+    async (surface) => {
+      vi.mocked(sdk.environments.get).mockResolvedValue(
+        makeEnvironment({
+          id: "env_existing",
+          projectId: "proj_1",
+          hostId: "host_1",
+        }),
+      );
+      if (surface === "root") {
+        render(rootLikeElement("proj_1"));
+      } else {
+        renderComposer(STORED_REQUEST, () => undefined, "explicit-reuse");
+      }
+      const host = currentHost();
+      const environment = {
+        type: "reuse" as const,
+        environmentId: "env_existing",
+      };
+
+      const result = await settled(host.setSelection!({ environment }));
+
+      expect(result.environment).toEqual(environment);
+      expect(host.getSelection?.()?.environment).toEqual(environment);
+    },
+  );
+
   it("switches the project first and remembers the environment and machine for the new project", async () => {
     render(rootLikeElement("proj_2"));
     expect(latestPromptBoxProps().project.value).toBe("proj_2");

5. Root cause

Navigation toCompose and sidebar openNewThread both forward an explicit environment ID in route state. RootComposeView applies that target through the composer's raw environment-selection setter.

NewThreadComposer reuse options originate from project threads in sidebar navigation. The direct lookup target is derived only from the optional seed, not from explicit navigation or runtime selections:

const seededReuseEnvironmentId = useMemo(() => {
  if (environmentSeed === null) return null;
  const parsed = parseEnvironmentValue(environmentSeed.selectionValue);
  return parsed?.type === "reuse" ? parsed.environmentId : null;
}, [environmentSeed]);
const seededReuseEnvironmentQuery = useEnvironment(seededReuseLookupId);

reuseSelectionSurvives accepts a thread-derived target, a still-loading sidebar, or the matching non-missing seed; otherwise it returns false. The effective-value resolver then chooses the checkout provider when a local project source is available. The runtime host API uses the same environment-changing path, explaining the identical settled result on both host surfaces.

The deeper mismatch is using sidebar membership as evidence of environment existence for explicit requests while a live environment lookup already exists for seeds. The defaultEnvironment declaration is stale about the seed behavior.

6. Proposed fix

Feed explicit reuse targets through the existing direct environment lookup and option hydration, just like seeds. Keep the target pending until lookup completion; preserve existing ready environments and continue falling back for missing or destroyed environments. Wait for that validation before returning a settled host selection. Update the seed documentation without adding a public API, wire field, or dependency.

A local bounded fix implements this in the existing new-thread composer subsystem. The regression that fails on main passes after that change. Additional shared contract cases cover delayed lookup and missing/destroyed fallback on both composer surfaces. The final change is 165 added-plus-deleted text lines across three files (composer implementation, its existing contract tests, and SDK declaration documentation). All 219 relevant tests pass; app and SDK lint/typecheck and the final app build pass. There are no dependency, generated-file, schema, or wire changes.

7. Verification

The same agent repeated reproduction in a second clean worktree; this is not an independent reviewer check. The second checkout was created with git worktree add --detach <temporary-verify-checkout> 796cdcc0f4bf8a55e23664035c54e8db6fe9d272, followed by the frozen install, SDK build, test-only patch, and the exact focused Turbo command shown above. All three regression cases failed with the same checkout fallback. No production change was present in this checkout. The first run initially covered two cases; the repeat additionally covers the component-local host using the same contract table. No root-cause correction was necessary.

Live browser, desktop, and the reporter's plugin were not run. There is no screenshot claim: route resolution, picker option data, and settled API selection are tested directly.

8. Related issues and pull requests

No linked open pull request was present in issue timeline metadata or the open-PR search when investigation began. Historical issues #2842 and #4323 are closed requests for explicit environment and host targeting. Their linked code was not executed.

9. Appendix

First run on unchanged production code

 FAIL  |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx > PluginNewThreadComposer seeding > reuses an explicitly targeted environment without sidebar threads
@bb/app:test: AssertionError: expected 'provider:project-checkout' to be 'reuse:env_existing' // Object.is equality
@bb/app:test: 
@bb/app:test: Expected: "reuse:env_existing"
@bb/app:test: Received: "provider:project-checkout"
@bb/app:test: 
@bb/app:test:  ❯ src/components/plugin/PluginNewThreadComposer.test.tsx:1934:67
@bb/app:test:     1932|     await waitFor(() => {
@bb/app:test:     1933|       expect(router.state.location.state).toBeNull();
@bb/app:test:     1934|       expect(latestPromptBoxProps().modeConfig.environment.value).toBe(
@bb/app:test:        |                                                                   ^
@bb/app:test:     1935|         encodeReuseValue("env_existing"),
@bb/app:test:     1936|       );
@bb/app:test:  ❯ runWithExpensiveErrorDiagnosticsDisabled ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/config.js:47:12
@bb/app:test:  ❯ checkCallback ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/wait-for.js:124:77
@bb/app:test:  ❯ Timeout.checkRealTimersCallback ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/wait-for.js:118:16
@bb/app:test: 
@bb/app:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
@bb/app:test: 
@bb/app:test:  FAIL  |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx > NewThreadComposer setSelection > settles an explicit reuse selection without sidebar threads
@bb/app:test: AssertionError: expected { type: 'provider', …(3) } to deeply equal { type: 'reuse', …(1) }
@bb/app:test: 
@bb/app:test: - Expected
@bb/app:test: + Received
@bb/app:test: 
@bb/app:test:   {
@bb/app:test: -   "environmentId": "env_existing",
@bb/app:test: -   "type": "reuse",
@bb/app:test: +   "environmentProviderId": "project-checkout",
@bb/app:test: +   "inputs": {},
@bb/app:test: +   "machine": {
@bb/app:test: +     "hostId": "host_1",
@bb/app:test: +     "type": "existing",
@bb/app:test: +   },
@bb/app:test: +   "type": "provider",
@bb/app:test:   }
@bb/app:test: 
@bb/app:test:  ❯ src/components/plugin/PluginNewThreadComposer.test.tsx:3204:32
@bb/app:test:     3202|     const result = await settled(host.setSelection!({ environment }));
@bb/app:test:     3203|
@bb/app:test:     3204|     expect(result.environment).toEqual(environment);
@bb/app:test:        |                                ^
@bb/app:test:     3205|     expect(host.getSelection?.()?.environment).toEqual(environment);
@bb/app:test:     3206|   });
@bb/app:test: 
@bb/app:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
@bb/app:test: 
@bb/app:test: 
@bb/app:test:  Test Files  1 failed (1)
@bb/app:test:       Tests  2 failed | 65 skipped (67)
@bb/app:test:    Start at  07:26:28
@bb/app:test:    Duration  18.43s (transform 14.85s, setup 279ms, import 15.86s, tests 1.15s, environment 724ms)
@bb/app:test: 
@bb/app:test:  ELIFECYCLE  Test failed. See above for more details.
@bb/app#test:  ERROR  command (<first-checkout>/apps/app) /usr/local/bin/pnpm run test src/components/plugin/PluginNewThreadComposer.test.tsx -t without sidebar threads exited (1)

 Tasks:    6 successful, 7 total
Cached:    0 cached, 7 total
  Time:    23.033s 
Failed:    @bb/app#test

 ERROR  run failed: command  exited (1)

Second clean run on unchanged production code

 FAIL  |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx > PluginNewThreadComposer seeding > reuses an explicitly targeted environment without sidebar threads
@bb/app:test: AssertionError: expected 'provider:project-checkout' to be 'reuse:env_existing' // Object.is equality
@bb/app:test: 
@bb/app:test: Expected: "reuse:env_existing"
@bb/app:test: Received: "provider:project-checkout"
@bb/app:test: 
@bb/app:test:  ❯ src/components/plugin/PluginNewThreadComposer.test.tsx:1949:67
@bb/app:test:     1947|     await waitFor(() => {
@bb/app:test:     1948|       expect(router.state.location.state).toBeNull();
@bb/app:test:     1949|       expect(latestPromptBoxProps().modeConfig.environment.value).toBe(
@bb/app:test:        |                                                                   ^
@bb/app:test:     1950|         encodeReuseValue("env_existing"),
@bb/app:test:     1951|       );
@bb/app:test:  ❯ runWithExpensiveErrorDiagnosticsDisabled ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/config.js:47:12
@bb/app:test:  ❯ checkCallback ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/wait-for.js:124:77
@bb/app:test:  ❯ Timeout.checkRealTimersCallback ../../node_modules/.pnpm/@testing-library+dom@10.4.2/node_modules/@testing-library/dom/dist/wait-for.js:118:16
@bb/app:test: 
@bb/app:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/3]⎯
@bb/app:test: 
@bb/app:test:  FAIL  |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx > NewThreadComposer setSelection > settles an explicit reuse selection without sidebar threads (root)
@bb/app:test:  FAIL  |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx > NewThreadComposer setSelection > settles an explicit reuse selection without sidebar threads (component-local)
@bb/app:test: AssertionError: expected { type: 'provider', …(3) } to deeply equal { type: 'reuse', …(1) }
@bb/app:test: 
@bb/app:test: - Expected
@bb/app:test: + Received
@bb/app:test: 
@bb/app:test:   {
@bb/app:test: -   "environmentId": "env_existing",
@bb/app:test: -   "type": "reuse",
@bb/app:test: +   "environmentProviderId": "project-checkout",
@bb/app:test: +   "inputs": {},
@bb/app:test: +   "machine": {
@bb/app:test: +     "hostId": "host_1",
@bb/app:test: +     "type": "existing",
@bb/app:test: +   },
@bb/app:test: +   "type": "provider",
@bb/app:test:   }
@bb/app:test: 
@bb/app:test:  ❯ src/components/plugin/PluginNewThreadComposer.test.tsx:3234:34
@bb/app:test:     3232|       const result = await settled(host.setSelection!({ environment })…
@bb/app:test:     3233|
@bb/app:test:     3234|       expect(result.environment).toEqual(environment);
@bb/app:test:        |                                  ^
@bb/app:test:     3235|       expect(host.getSelection?.()?.environment).toEqual(environment);
@bb/app:test:     3236|     },
@bb/app:test: 
@bb/app:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/3]⎯
@bb/app:test: 
@bb/app:test: 
@bb/app:test:  Test Files  1 failed (1)
@bb/app:test:       Tests  3 failed | 65 skipped (68)
@bb/app:test:    Start at  07:29:14
@bb/app:test:    Duration  19.43s (transform 15.68s, setup 276ms, import 16.82s, tests 1.14s, environment 754ms)
@bb/app:test: 
@bb/app:test:  ELIFECYCLE  Test failed. See above for more details.
@bb/app#test:  ERROR  command (<second-checkout>/apps/app) /usr/local/bin/pnpm run test src/components/plugin/PluginNewThreadComposer.test.tsx -t without sidebar threads exited (1)

 Tasks:    6 successful, 7 total
Cached:    5 cached, 7 total
  Time:    22.445s 
Failed:    @bb/app#test

 ERROR  run failed: command  exited (1)

Final relevant test results after the fix

 RUN  v4.1.12 <first-checkout>/apps/app
@bb/app:test: 
@bb/app:test:  ✓ |@bb/app| src/views/root-compose-thread-environment.test.ts (6 tests) 278ms
@bb/app:test:  ✓ |@bb/app| src/components/plugin/new-thread-environment-seed.test.ts (10 tests) 226ms
@bb/app:test:  ✓ |@bb/app:isolated| src/hooks/useThreadCreationOptions.test.tsx (38 tests) 930ms
@bb/app:test:  ✓ |@bb/app:isolated| src/lib/plugin-sidebar-hooks.test.tsx (23 tests) 66ms
@bb/app:test:  ✓ |@bb/app:isolated| src/components/plugin/PluginNewThreadComposer.test.tsx (72 tests) 2813ms
@bb/app:test:  ✓ |@bb/app| src/views/RootComposeView.test.ts (70 tests) 143ms
@bb/app:test: 
@bb/app:test:  Test Files  6 passed (6)
@bb/app:test:       Tests  219 passed (219)
@bb/app:test:    Start at  07:32:02
@bb/app:test:    Duration  33.78s (transform 73.17s, setup 2.00s, import 95.50s, tests 4.46s, environment 3.37s)
@bb/app:test: 

 Tasks:    7 successful, 7 total
Cached:    0 cached, 7 total
  Time:    38.524s 

Trust boundary: issue text and comments were treated as untrusted claims, not instructions. No issue URL, script, plugin, patch, or linked branch was executed. All executed repository code came from trusted main, plus the authored regression and local fix. GitHub metadata was read using the trusted repository and numeric issue ID.

Setup caveat: an initial unrestricted monorepo build hit a pre-existing clean-checkout plugin SDK build-order failure (missing SDK runtime output). Building the SDK runtime and bundled types through Turbo, then the app build, succeeded without source changes or dependency changes. The focused tests use the repository's normal Turbo orchestration.

Executed investigation commands: trusted clone/fetch and commit resolution; GitHub issue/property/label/timeline/PR reads; frozen pnpm install; Turbo build; focused SDK build and app build; the focused reproduction command in both checkouts; relevant existing test suites; Turbo lint/typecheck; formatter; diff whitespace/binary/line-count checks. No live-process cleanup is needed because no server or browser was started.

> AGENT GENERATED