Reports

#6261 · Repeated host discovery work

Bug Priority: Low Effort: Low host · 2026-10-25 · GitHub issue

Verdict: REPRODUCED · Root-cause confidence: high for the repeated discovery mechanism; native macOS timing and process counts remain unverified.

Trusted base: a6fff60f53c615a109103075328bf7017431e792 on origin/main. The issue text was treated only as untrusted claims. No issue commands, linked code, or external issue links were executed or fetched.

1. TL;DR

Each identical request to the host's workspace-open-target endpoint performs application discovery again. The route invokes the enumerator on every request without retaining a result or an in-flight promise. Running the real HTTP route and macOS enumeration code with only the operating-system command boundary substituted produced three complete enumerations for three requests. The regression expects one enumeration and fails on unchanged main in two clean checkouts. This demonstrates repeated command dispatch, not the reported native latency, CPU consumption, or machine-pressure effects.

2. Claims vs findings

ClaimFindingEvidence
Identical calls repeat editor and terminal detection and icon work.Verified at the real HTTP and enumeration boundaryOne fixture request dispatches 27 mdfind, 2 plutil, 2 qlmanage and 4 which calls. Three requests dispatch 81, 6, 6 and 12 respectively. Installed-app and icon results remain identical.
The daemon has no cache or in-flight sharing for this route.VerifiedThe route calls its discovery handler anew for every request; no retained target result exists.
Native requests take roughly one to two seconds and spawn about 35 processes.Unverified hereThis runner is Linux. Command dispatch is counted using a substituted execFile; no real mdfind, plutil or qlmanage processes are launched. Counts depend on installed applications, so the fixture is not a measurement of the reporter's machine.
Reconnects and configuration updates explain background requests, with much worse behavior under memory pressure.UnverifiedNo user runtime, real configuration, provider, or machine-pressure workload was accessed.

3. Environment

4. Minimal reproduction

  1. Check out the trusted commit in a fresh clone:
    git clone https://github.com/get-bb/bb.git bb-repro-6261
    cd bb-repro-6261
    git checkout --detach a6fff60f53c615a109103075328bf7017431e792
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
  2. Save the authored regression artifact as apps/host-daemon/src/workspace-open-target-cache.test.ts.
  3. Run the regression:
    pnpm exec turbo run test --filter=@bb/host-daemon --force -- --run src/workspace-open-target-cache.test.ts

Expected: three HTTP 200 responses with identical targets and one set of discovery commands. Actual: three HTTP 200 responses with identical targets, but three sets of commands and a failing cache assertion.

@bb/host-daemon:test: {"firstCommands":{"mdfind":27,"plutil":2,"qlmanage":2,"which":4},"totalCommands":{"mdfind":81,"plutil":6,"qlmanage":6,"which":12},"discoveryRuns":3}
@bb/host-daemon:test: AssertionError: expected { mdfind: 81, plutil: 6, …(2) } to deeply equal { mdfind: 27, plutil: 2, …(2) }
@bb/host-daemon:test:      76|     console.log(JSON.stringify({ firstCommands, totalCommands: command…
@bb/host-daemon:test:  Test Files  1 failed (1)
@bb/host-daemon:test:       Tests  1 failed (1)
@bb/host-daemon:test:    Duration  4.71s (transform 3.64s, setup 0ms, import 4.04s, tests 107ms, environment 0ms)
  Time:    7.567s

The first discovery must find VS Code with a data-url icon and dispatch all three system tools before the cache assertion runs. Thus an empty target fixture or a failure before enumeration cannot masquerade as this reproduction.

Complete regression test
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createHostDaemonLocalClient } from "@bb/host-daemon-contract";
import {
  listWorkspaceOpenTargetsWithRuntime,
  type WorkspaceOpenTargetRuntime,
} from "@bb/local-open-targets";
import { startLocalApiServer, type LocalApiServer } from "./local-api.js";

describe("workspace open-target discovery cache", () => {
  let server: LocalApiServer | null = null;

  afterEach(async () => {
    await server?.close();
    server = null;
    vi.restoreAllMocks();
  });

  it("reuses macOS discovery and extracted icons across identical HTTP requests", async () => {
    const commands: Record<string, number> = {};
    const runtime: WorkspaceOpenTargetRuntime = {
      platform: "darwin",
      applicationDirectories: [],
      execFile: async (file, args) => {
        commands[file] = (commands[file] ?? 0) + 1;
        if (file === "mdfind") {
          return {
            stdout: args.join(" ").includes("com.microsoft.VSCode")
              ? "/test/Code.app\n"
              : "",
          };
        }
        if (file === "plutil") {
          return { stdout: "Code.icns" };
        }
        if (file === "qlmanage") {
          await writeFile(
            path.join(args[4]!, "Code.icns.png"),
            Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/2ioAAAAASUVORK5CYII=", "base64"),
          );
        }
        return { stdout: "" };
      },
    };
    const discover = vi.fn(() => listWorkspaceOpenTargetsWithRuntime(runtime));
    server = await startLocalApiServer({
      hostId: "cache-test",
      localApiConfig: {
        bindHost: "localhost",
        healthPath: "/health",
        healthValue: "ok",
        port: 0,
      },
      serverUrl: "http://server.test",
      serverPort: 0,
      getConnected: () => true,
      listWorkspaceOpenTargets: discover,
    });
    const client = createHostDaemonLocalClient(`http://localhost:${server.port}`);
    const first = await client["workspace-open-targets"].$get({ query: {} });
    const firstBody = await first.json();
    const firstCommands = { ...commands };
    expect(first.status).toBe(200);
    expect(firstBody.targets).toEqual(expect.arrayContaining([
      expect.objectContaining({ id: "vscode", icon: expect.objectContaining({ kind: "data-url" }) }),
    ]));
    expect(firstCommands.mdfind).toBeGreaterThan(0);
    expect(firstCommands.plutil).toBeGreaterThan(0);
    expect(firstCommands.qlmanage).toBeGreaterThan(0);
    for (let request = 0; request < 2; request += 1) {
      const response = await client["workspace-open-targets"].$get({ query: {} });
      expect(response.status).toBe(200);
      expect(await response.json()).toEqual(firstBody);
    }
    console.log(JSON.stringify({ firstCommands, totalCommands: commands, discoveryRuns: discover.mock.calls.length }));
    expect(commands).toEqual(firstCommands);
    expect(discover).toHaveBeenCalledTimes(1);
  });
});

5. Root cause

The HTTP route constructs a new runtime and calls the target-list handler per request:

  get(
    "/workspace-open-targets",
    workspaceOpenTargetsQuerySchema,
    async (c, query) =>
      c.json({
        targets: await (
          options.listWorkspaceOpenTargets ??
          ((query) =>
            listWorkspaceOpenTargetsWithRuntime(
              workspaceOpenTargetRuntime(options),
              query,
            ))
        )(query),
      }),
  );

listWorkspaceOpenTargetsWithRuntime calls listKnownMacWorkspaceOpenTargets, which iterates every launch adapter. Each application lookup can dispatch mdfind; available applications additionally perform icon extraction using plutil and qlmanage. The only cache in the local API module is for client configuration, unrelated to target discovery. Therefore identical successful requests repeat the entire discovery chain.

The query can include a file path, which affects associated applications. The runtime also consumes a resolved shell PATH. Any result cache must distinguish these inputs rather than share an arbitrary first result with all callers.

6. Proposed fix

Retain a bounded, short-lived discovery-promise cache inside each local API server. Key by file-path query and effective executable PATH, share unresolved promises, start the TTL after successful completion and remove rejected entries. A bounded cache prevents file-path cardinality from growing memory indefinitely. Keep target-opening requests uncached and keep existing wire schemas and authentication unchanged. Add regression coverage for concurrent requests, expiry, failure recovery, input changes and server isolation. A short TTL is a contained alternative to a new filesystem watcher.

7. Verification

The same agent repeated the test in a second clean, detached worktree at a6fff60f53c615a109103075328bf7017431e792, with its own frozen install, build, fresh ephemeral HTTP listener and production icon temporary directories. The second run used --force so Turbo could not replay the first failure. It again dispatched 27/2/2/4 commands for the first response and 81/6/6/12 total for three responses, with three discovery invocations and the same expected assertion failure. This is a repeat by the same agent, not independent verification.

Artifacts: first selected output · second selected output. No correction to the repeated-discovery finding was required. Native macOS measurements are explicitly left unverified.

8. Pull requests and related issues

No open pull request linked to #6261 was present in the issue cross-reference metadata or open-PR search at investigation time. No related issue was needed to establish this mechanism.

Fix safety gate

A local candidate cache passed all five new focused tests, all 63 existing local-open-targets tests, and the host-daemon typecheck. The broader host-daemon suite did not pass: 73 files passed, three files failed; 822 tests passed, three failed and eight were skipped. The failures were a teardown timeout, a server-move unit-file permission expectation, and a server-move disk-space expectation. These failures were not repaired as part of this issue. The conservative automatic-fix gate therefore stopped the candidate: no fix commit or branch was pushed, and no pull request was opened. This does not change the two clean baseline reproductions.

Selected candidate verification output. The attempted change was 290 added/deleted text lines across three files, with no binary, wire-schema, dependency or stored-data changes; diff whitespace validation passed.

9. Appendix

Both checkouts ran the normal frozen install and Turbo build. The first unrestricted build hit an existing plugin-SDK build-order race; explicitly building the existing SDK first and retrying yielded 71 successful build tasks in each checkout. No dependency or build-source changes were made. Baseline commands were:

pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
pnpm exec turbo run test --filter=@bb/host-daemon -- --run src/workspace-open-target-cache.test.ts
pnpm exec turbo run test --filter=@bb/host-daemon --force -- --run src/workspace-open-target-cache.test.ts

Selected outputs are genuine test logs, not fabricated timing measurements. The icon bytes in the test are a deterministic one-pixel PNG fixture, not a screenshot.

> AGENT GENERATED