← reports

#7534 · Cleanup retries against a retired desktop generation

Bug Priority: Medium Effort: Medium desktop partial-repro · GitHub issue · 2026-11-13

Trusted origin/main: f024a372f0e1e0670f6fd7452ebcd1341f639c95

PARTIALLY REPRODUCED · Root-cause confidence: high

1. TL;DR

The server-side retry loop is reproduced in two clean checkouts: closing an old desktop session twice targets its saved generation both times, fails both times, and keeps telling the caller to retry. A replacement session using the new generation opens and closes successfully in the same fixture. The real host-broker test suite separately confirms that refreshed instances reject old generations. This is a partial reproduction because desktop RPCs in the plugin reproduction are simulated; no live Electron reconnect, original incident resources, or HTTP transport was exercised.

No production fix or pull request is included. A generation change revokes leases without necessarily removing the old tabs, so blindly rebinding cleanup or silently treating a stale generation as successful cleanup would choose ownership/retirement policy without enough evidence.

2. Claims vs findings

ClaimFindingEvidence
Repeated close cannot recover after generation rotation.Verified at plugin RPC boundary.Both runs fail the terminal-outcome assertion after two stale-generation cleanup failures.
A fresh session can work while the old session cannot clean up.Verified with simulated desktop RPCs.Replacement close resolves as closed; only its distinct tab is closed.
The host rejects requests to retired generations.Verified in the actual host broker.All 8 desktop-browser-broker tests pass in both checkouts, including refreshed-generation rejection.
A desktop reconnect naturally produced this exact incident and HTTP 502.Unverified end to end.No desktop hardware was driven; no HTTP 502 was generated by the plugin harness.
The old owned tab still exists or was removed.Unverified for the incident.The test uses synthetic tabs and cannot determine the original resources' final state.

3. Environment

4. Minimal reproduction

The test extends the repository's existing plugins/browser-automation/server.test.ts fixture. The plugin implementation is unchanged. Save the complete patch below as generation-retry.patch, outside the checkout; this HTML intentionally embeds evidence instead of publishing raw artifact directories.

  1. Clone trusted main and select the recorded base:
    git clone --single-branch --branch main https://github.com/get-bb/bb.git bb-7534
    cd bb-7534
    git switch --detach f024a372f0e1e0670f6fd7452ebcd1341f639c95
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
  2. Before inserting the reproduction, the existing session tests pass:
    pnpm exec turbo run test --filter=bb-plugin-browser-automation -- server.test.ts
    Test Files  1 passed (1)
    Tests       39 passed (39)
  3. Apply the reproduction-only patch, then run its failing contract:
    git apply ../generation-retry.patch
    pnpm exec turbo run test --filter=bb-plugin-browser-automation -- server.test.ts -t 'reaches a terminal cleanup outcome'
    git diff --check
  4. Expected: the second close reaches an explicit terminal cleanup outcome rather than repeating the same retry instruction. This expectation does not authorize deleting tabs or leases in a new generation.
  5. Actual in both clean runs (exit code 1):
    FAIL server session cleanup > reaches a terminal cleanup outcome after desktop generation rotation
    AssertionError: expected 'experimental_PluginRpcCallError: Brow…' not to contain 'Run close to retry'
    Received: "experimental_PluginRpcCallError: Browser session closed, but cleanup on host desktop-host failed: Desktop browser instance is unavailable or generation is stale; Desktop browser instance is unavailable or generation is stale. Run close to retry."
    Test Files  1 failed (1)
    Tests       1 failed | 39 skipped (40)
    The duplicate stale-generation reason comes from the separately rejected release-control and tab-list operations in this fixture; it is not a claim about the incident's exact error aggregation.

Complete reproduction-only patch

diff --git a/plugins/browser-automation/server.test.ts b/plugins/browser-automation/server.test.ts
index bd02b9a03..5c3f927a3 100644
--- a/plugins/browser-automation/server.test.ts
+++ b/plugins/browser-automation/server.test.ts
@@ -528,6 +528,97 @@ describe("server session ownership", () => {
   });
 });
 describe("server session cleanup", () => {
+  it("reaches a terminal cleanup outcome after desktop generation rotation", async () => {
+    const h = await setup();
+    let generation = "generation";
+    const requireGeneration = (input: { generation: string }) => {
+      if (input.generation !== generation)
+        throw new Error(
+          "Desktop browser instance is unavailable or generation is stale",
+        );
+    };
+    h.harness.sdk.stub(
+      "experimental_desktopBrowsers.listInstances",
+      async () => ({
+        instances: [
+          {
+            hostId: "desktop-host",
+            instanceId: "desktop",
+            generation,
+            label: "Desktop",
+          },
+        ],
+      }),
+    );
+    h.harness.sdk.stub(
+      "experimental_desktopBrowsers.createTab",
+      async () => ({
+        tab: {
+          tabId: generation === "generation" ? "created" : "replacement",
+          threadId: "thread-test",
+          url: "about:blank",
+          title: "",
+          control: null,
+          presentation: "hidden",
+        },
+      }),
+    );
+    h.harness.sdk.stub(
+      "experimental_desktopBrowsers.listTabs",
+      async (input: { generation: string }) => {
+        requireGeneration(input);
+        return {
+          tabs: [
+            { tabId: "created", control: null },
+            { tabId: "replacement", control: null },
+          ],
+        };
+      },
+    );
+    h.harness.sdk.stub(
+      "experimental_desktopBrowsers.releaseControl",
+      async (input: { generation: string }) => {
+        requireGeneration(input);
+        return { ok: true };
+      },
+    );
+    const close = (sessionId: string) =>
+      h.harness.behavior.callRpc("close", {
+        threadId: "thread-test",
+        sessionId,
+      });
+    try {
+      const original = await h.open();
+      generation = "replacement-generation";
+      const replacement = await h.open();
+      const outcomes: string[] = [];
+      for (let attempt = 0; attempt < 2; attempt++) {
+        const outcome = await close(original.id).then(
+          () => "closed",
+          (error: unknown) => String(error),
+        );
+        outcomes.push(outcome);
+      }
+      await expect(close(replacement.id)).resolves.toMatchObject({
+        state: "closed",
+      });
+      expect(h.closedTabIds()).toEqual(["replacement"]);
+      console.log(
+        JSON.stringify({
+          originalCloseAttempts: outcomes,
+          replacementClose: "closed",
+          closedTabIds: h.closedTabIds(),
+          releaseScopes: h.harness.sdk
+            .callsTo("experimental_desktopBrowsers.releaseControl")
+            .map(([input]) => input),
+        }),
+      );
+      expect(outcomes[1]).not.toContain("Run close to retry");
+    } finally {
+      await h.harness.lifecycle.dispose();
+    }
+  });
+
   const ready = { status: "ready", version: "1.0.0-test", source: "release" };
   const ownedBy = (sessionId: string) => ({
     threadId: "thread-test",

Observed sequence

Both runs print the same meaningful sequence. The identifiers below belong only to the test fixture, not to any user session:

Original close attempt 1: stale generation; Run close to retry.
Original close attempt 2: stale generation; Run close to retry.
Replacement close: closed
Closed tab IDs: ["replacement"]
Release-control request generations:
  original attempt 1: generation
  original attempt 2: generation
  replacement close: replacement-generation

The assertion fails only after the replacement close and ownership-isolation assertion succeed. The failure therefore demonstrates the retry-loop contract, not an unrelated opening or fixture error. The desktop generation guard is intentionally simulated from the real host-broker behavior; actual browser process cleanup is outside this test.

5. Root cause

  1. releaseDesktop, lines 96–129, builds every cleanup request from the saved desktop target, including its old generation. It does not rediscover an instance or classify retirement separately:
    const scope = {
      hostId: target.hostId,
      instanceId: target.instanceId,
      generation: target.generation,
      threadId: target.threadId,
    };
  2. Host broker, lines 282–294, correctly requires a matching instance and generation for scoped commands. A request carrying the retired generation is rejected before dispatch. Its existing refreshed-generation test exercises this behavior against the real broker and passes.
  3. finish, lines 130–205, records the session as closed but leaves cleanup pending after any rejected cleanup operation. Every failure receives the same retry instruction:
    record.cleanupPending = failures.length > 0;
    await save(record);
    ...
    throw new Error(
      `Browser session ${state}, but cleanup on host ${session.hostId} failed: ${reasons}. Run close to retry.`,
    );
    The next close reloads the persisted record and repeats the same unreachable generation. Local host-close success does not remove the desktop cleanup failure.
  4. The safety constraint is deeper than the retry text. Desktop generation rotation, lines 323–342, revokes leases and can clear thread association. revoke, lines 132–148, removes lease state and unmarks leased tabs; it is not tab cleanup. release_control, lines 510–520, rejects an unavailable lease. Merely substituting the new generation would not recreate the original lease and is not a proven ownership-safe repair.

Confidence: high for this saved-generation/retry mechanism, supported by two executed plugin reproductions, actual broker tests, and the recorded source. Confidence does not extend to the original desktop's tab state or the precise reconnect trigger.

6. Proposed fix and simple-fix gate

Define an explicit terminal disposition for retired desktop generations and communicate whether cleanup was completed, the resource is known gone, or cleanup cannot safely continue. Preserve strict thread, generation, lease, and owned-tab boundaries. Treat temporary host disconnection separately from confirmed retirement. Do not convert stale-generation failures into silent cleanup success or replay the old tab IDs against a replacement generation.

No production repair was attempted: choosing when ownership may transfer or when an owned-resource obligation may be retired needs a product/lifecycle decision that the available evidence does not resolve. That fails the automation's no-product-decision/no-security-boundary simple-fix gate. The reproduction patch adds 91 text lines in one existing test file and changes no production source; it is retained locally only. There was no fix branch, commit, push, or pull request. No open pull request linked to issue 7534 was found by search or issue timeline metadata.

Next test after that policy is chosen: drive the actual desktop broker through generation rotation while an owned tab and an attached shared tab coexist; verify that only resources with provable ownership can be closed and that the caller receives a final cleanup disposition. Re-run the focused failing contract against that implementation.

7. Verification

The same agent repeated the reproduction in a second clean detached checkout at the same trusted commit, using a separate install and the same reproduction-only patch. This is a repeated check, not an independent review. No development instance was needed; the broker suite allocated fresh temporary directories and loopback ports on each run.

CheckCheckout ACheckout B
Frozen dependency installPassPass
SDK build:types through TurboPassPass
Existing unmodified server.test.ts39 passed before patchNot repeated separately
Generation-rotation cleanup contract, unchanged production1 expected failure; retry text on attempt 21 expected failure; same reason
Replacement session closes, only replacement tab is closedPass before failing retry assertionPass before failing retry assertion
Actual host desktop-browser-broker suite8 passed8 passed
git diff --checkPassPass
Broad trusted source build73/73 tasks after SDK preparationNot repeated; irrelevant to the narrow reproduction

Checkout B commands were the same frozen install, SDK build, git apply, focused Turbo test, and host-broker test command listed here. Its actual result was exit 1 with exactly one failing terminal-outcome assertion and 39 skipped sibling tests. The verification did not require changing the causal finding. The report conservatively retains PARTIALLY REPRODUCED because neither run includes a live Electron desktop or HTTP error mapping.

8. Related issues

Repository metadata identifies #5418 as an earlier closed cleanup-reporting issue and #4261 as a closed desktop-tab recovery issue. Neither was treated as a verified fix for this retry loop. No linked open PR required review.

9. Appendix

Additional verification commands and results

pnpm exec turbo run build
Initial attempt: failed resolving generated SDK exports.

pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
Result: 4 successful tasks.

pnpm exec turbo run build
Result after SDK preparation: 73 successful tasks.

pnpm exec turbo run test --filter=@bb/host-daemon -- src/desktop-browser-broker.test.ts
Checkout A: Test Files 1 passed (1); Tests 8 passed (8).
Checkout B: Test Files 1 passed (1); Tests 8 passed (8).

git diff --check
Result in both checkouts: no output; exit 0.

git diff --numstat origin/main
91  0  plugins/browser-automation/server.test.ts

The broad build regenerated an unrelated route-tree file; it was restored before the final diff count. No generated output is part of the reproduction patch. Full logs, the test patch, and the working brief remain outside the public reports Git tree; the report embeds the complete test patch and decisive output, in accordance with the reports repository's publication rules.

Trust boundary: issue text, comments, links, and examples were treated only as untrusted claims. No issue-supplied command, script, URL, patch, branch, or test was run. All executed repository code came from the recorded public origin/main commit, plus the reproduction test authored from trusted source evidence. No user instance or unrelated runtime data was inspected.

> AGENT GENERATED