Reports · 2026-10-29

#6541 · Desktop restore scheduling and redundant native menus

BugPriority: MediumEffort: Lowdesktop · perf · confirmed-reproIssue

Verdict: REPRODUCED · Root-cause confidence: high (production-owner tests, not a macOS live-app reproduction).

1. TL;DR

Restoring multiple saved desktop windows waits for each page navigation before it starts creating the next window. A slow first page therefore delays every subsequent window, even though the windows can load independently. Separately, every accepted system-settings refresh asks Electron to build and replace the application menu, whether or not any displayed item or accelerator changed. Both mechanisms reproduce on trusted main in two separate checkouts using newly authored regression tests. No issue-provided code, commands, branches, or test files were executed.

2. Claims vs findings

ClaimFindingEvidence
Saved windows wait for the previous page navigation.VerifiedWith three real persisted window entries and unresolved fake page navigations, only one load starts. The other two cannot begin until it resolves.
Unchanged settings cause native-menu replacement.VerifiedTwo equivalent installations call both Electron build and installation twice. Trusted source routes every accepted config refresh to this installer.
Activation, reconnect, and polling trigger settings refresh.Source-verified; not exercised against a remote servermain.ts owns all three triggers, including a five-minute poll interval.
Exact five-window millisecond measurements and macOS presentation order.Unverified hereThe reproduction measures scheduling invariants rather than elapsed time. Native compositor/show order is not asserted; the repair preserves persisted result ordering.

3. Environment

4. Minimal reproduction

The attached patch changes only trusted-main desktop tests, reusing the repository's existing fake Electron-window fixture. Persistence and factory code run for real; the fake loadURL boundary merely holds navigation promises unresolved. The menu mock records the real installer's calls to Electron and invokes the handlers produced by the production template builder.

  1. Clone the trusted repository and select the recorded base:
    git clone https://github.com/get-bb/bb.git bb-6541
    cd bb-6541
    git checkout --detach 3bacfac9ed69d42392076e5b3da2815bec822cd8
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/desktop
  2. Save the regression patch from this report and apply it:
    git apply /path/to/regression.patch
    pnpm exec turbo run test --filter=@bb/desktop -- test/desktop-window-factory.test.ts test/menu.test.ts
  3. Expected: all saved loads begin while none is completed; equivalent menu inputs preserve one native menu. Actual baseline assertions:
    AssertionError: expected [ FakeDesktopWindow{ ... } ] to have a length of 3 but got 1
    AssertionError: expected "vi.fn()" to be called 1 times, but got 2 times
    These are intentionally failing bug assertions, not install or test-discovery failures.
Complete reproduction test patch (including callback and invalidation guards)
diff --git a/apps/desktop/test/desktop-window-factory.test.ts b/apps/desktop/test/desktop-window-factory.test.ts
index dfbee046e..d91df1a26 100644
--- a/apps/desktop/test/desktop-window-factory.test.ts
+++ b/apps/desktop/test/desktop-window-factory.test.ts
@@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
 import type { BrowserWindowConstructorOptions } from "electron";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
 import {
   MACOS_TRAFFIC_LIGHT_INSET_PX,
   MACOS_TRAFFIC_LIGHT_TOP_INSET_PX,
@@ -323,6 +323,59 @@ async function createFactoryHarness(
 }
 
 describe("desktop window factory", () => {
+  it("starts every saved page before any finishes and returns saved order", async () => {
+    const original = await createFactoryHarness();
+    for (const stateKey of ["primary", "window-second", "window-third"]) {
+      const browserWindow = await original.factory.createWindow({
+        initialUrl: null,
+        stateKey,
+      });
+      if (!(browserWindow instanceof FakeDesktopWindow))
+        throw new Error("Expected a fake window");
+      browserWindow.bounds.x = original.createdWindows.length * 100;
+    }
+    await original.factory.persistOpenWindows();
+    const releases: Array<() => void> = [];
+    const loads = Array.from(
+      { length: 3 },
+      () => new Promise<void>((resolve) => releases.push(resolve)),
+    );
+    const started: DesktopBrowserWindow[] = [];
+    const completed: DesktopBrowserWindow[] = [];
+    let releaseAll = false;
+    const restarted = await createFactoryHarness({
+      userDataPath: original.userDataPath,
+      onWindowCreated(browserWindow) {
+        const load = loads[started.length];
+        browserWindow.loadURL = async () => {
+          started.push(browserWindow);
+          if (!releaseAll) await load;
+          completed.push(browserWindow);
+        };
+      },
+    });
+    const restoring = restarted.factory.restoreSavedWindows({
+      initialUrl: "http://127.0.0.1:41234",
+    });
+    try {
+      await vi.waitFor(() => expect(started).toHaveLength(3));
+      expect(completed).toHaveLength(0);
+      releases[2]?.();
+      await vi.waitFor(() => expect(completed).toEqual([started[2]]));
+      releases[1]?.();
+      releases[0]?.();
+      expect(
+        (await restoring).map((window) => window.getNormalBounds()),
+      ).toEqual(
+        original.createdWindows.map((window) => window.getNormalBounds()),
+      );
+    } finally {
+      releaseAll = true;
+      for (const release of releases) release();
+      await restoring;
+    }
+  });
+
   it.each([
     [0.5, 4],
     [1.5, 26],
diff --git a/apps/desktop/test/menu.test.ts b/apps/desktop/test/menu.test.ts
index 25f1a1ad8..73d85ac48 100644
--- a/apps/desktop/test/menu.test.ts
+++ b/apps/desktop/test/menu.test.ts
@@ -1,15 +1,30 @@
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
 import type { BaseWindow, MenuItemConstructorOptions } from "electron";
 
-vi.mock("electron", () => ({
-  app: { name: "bb" },
-  Menu: { sendActionToFirstResponder: vi.fn() },
-}));
+vi.mock("electron", () => {
+  const buildFromTemplate = vi.fn((_template: MenuItemConstructorOptions[]) => {
+    const menuItem = { submenu: { on: vi.fn() } };
+    return { getMenuItemById: vi.fn(() => menuItem) };
+  });
+  let applicationMenu: ReturnType<typeof buildFromTemplate> | null = null;
+  return {
+    app: { name: "bb" },
+    Menu: {
+      buildFromTemplate,
+      getApplicationMenu: () => applicationMenu,
+      setApplicationMenu: vi.fn((menu: typeof applicationMenu) => {
+        applicationMenu = menu;
+      }),
+      sendActionToFirstResponder: vi.fn(),
+    },
+  };
+});
 
 import { Menu } from "electron";
 
 import {
   buildApplicationMenuTemplate,
+  installApplicationMenu,
   SET_SERVER_URL_MENU_LABEL,
   type InstallApplicationMenuArgs,
 } from "../src/menu.js";
@@ -56,7 +71,7 @@ function menuArgs(
 }
 
 function findServerSubmenu(
-  template: MenuItemConstructorOptions[],
+  template: Parameters<typeof Menu.buildFromTemplate>[0],
 ): MenuItemConstructorOptions[] {
   const windowMenu = template.find((item) => item.label === "Window");
   const windowSubmenu = windowMenu?.submenu as MenuItemConstructorOptions[];
@@ -80,6 +95,138 @@ function findDesktopSettingsServerSubmenu(
 }
 
 describe("application menu", () => {
+  beforeEach(() => {
+    Menu.setApplicationMenu(null);
+    vi.clearAllMocks();
+  });
+
+  it("keeps an unchanged native menu while using the latest callbacks", () => {
+    const oldOpenNewTab = vi.fn();
+    const newOpenNewTab = vi.fn();
+    const oldSelectServer = vi.fn();
+    const newSelectServer = vi.fn();
+    const onServerMenuWillShow = vi.fn();
+    installApplicationMenu(
+      menuArgs(() => {}, {
+        openNewTab: oldOpenNewTab,
+        selectServer: oldSelectServer,
+      }),
+    );
+    const template = vi.mocked(Menu.buildFromTemplate).mock.calls[0]?.[0];
+    if (!template) throw new Error("Expected an installed template");
+    installApplicationMenu(
+      menuArgs(() => {}, {
+        openNewTab: newOpenNewTab,
+        selectServer: newSelectServer,
+        onServerMenuWillShow,
+      }),
+    );
+    expect(Menu.buildFromTemplate).toHaveBeenCalledTimes(1);
+    expect(Menu.setApplicationMenu).toHaveBeenCalledTimes(1);
+    const fileItems = template.find((item) => item.label === "File")
+      ?.submenu as MenuItemConstructorOptions[];
+    fileItems
+      .find((item) => item.label === "New Tab")
+      ?.click?.({} as never, undefined, {} as never);
+    expect(oldOpenNewTab).not.toHaveBeenCalled();
+    expect(newOpenNewTab).toHaveBeenCalledOnce();
+    const menu = vi.mocked(Menu.buildFromTemplate).mock.results[0]?.value;
+    const submenu = menu?.getMenuItemById("bb-server-menu")?.submenu;
+    if (!submenu) throw new Error("Expected a server submenu");
+    const listener = vi.mocked(submenu.on).mock.calls[0]?.[1];
+    if (!listener) throw new Error("Expected a server menu listener");
+    listener();
+    expect(onServerMenuWillShow).toHaveBeenCalledOnce();
+    installApplicationMenu(
+      menuArgs(() => {}, { selectServer: newSelectServer }),
+    );
+    listener();
+    expect(onServerMenuWillShow).toHaveBeenCalledOnce();
+    findServerSubmenu(template)[0]?.click?.(
+      {} as never,
+      undefined,
+      {} as never,
+    );
+    expect(oldSelectServer).not.toHaveBeenCalled();
+    expect(newSelectServer).toHaveBeenCalledWith("builtin");
+  });
+
+  it.each<Partial<InstallApplicationMenuArgs>>([
+    { isMac: false },
+    { showBuiltinServer: false },
+    { connectServersSkipReason: "unauthorized" },
+    { servers: [{ checked: false, id: "builtin", name: BUILTIN_SERVER_NAME }] },
+    {
+      servers: [
+        { checked: true, id: "custom:other", name: BUILTIN_SERVER_NAME },
+      ],
+    },
+    { servers: [{ checked: true, id: "builtin", name: "Renamed" }] },
+    { servers: [] },
+    {
+      accelerators: {
+        closeWindowOrSideTab: undefined,
+        createNewWindow: undefined,
+        openNewTab: "CommandOrControl+T",
+        openNewThread: undefined,
+        openSettings: undefined,
+        reopenClosedTab: undefined,
+      },
+    },
+  ])("replaces the native menu when its contents change: %j", (overrides) => {
+    installApplicationMenu(menuArgs(() => {}));
+    const previousMenu = Menu.getApplicationMenu();
+    installApplicationMenu(menuArgs(() => {}, overrides));
+    expect(Menu.getApplicationMenu()).not.toBe(previousMenu);
+    expect(Menu.setApplicationMenu).toHaveBeenCalledTimes(2);
+  });
+
+  it("reinstalls the menu if another owner removes it", () => {
+    installApplicationMenu(menuArgs(() => {}));
+    Menu.setApplicationMenu(null);
+    installApplicationMenu(menuArgs(() => {}));
+    expect(Menu.getApplicationMenu()).not.toBeNull();
+    expect(Menu.buildFromTemplate).toHaveBeenCalledTimes(2);
+  });
+
+  it("updates server routing even when the displayed label stays the same", () => {
+    const selectServer = vi.fn();
+    for (const id of ["custom:first", "custom:second"]) {
+      installApplicationMenu(
+        menuArgs(() => {}, {
+          selectServer,
+          servers: [{ checked: true, id, name: "Remote" }],
+        }),
+      );
+    }
+    const template = vi.mocked(Menu.buildFromTemplate).mock.calls[1]?.[0];
+    if (!template) throw new Error("Expected an updated server template");
+    findServerSubmenu(template)[0]?.click?.(
+      {} as never,
+      undefined,
+      {} as never,
+    );
+    expect(selectServer).toHaveBeenCalledWith("custom:second");
+  });
+
+  it.each(["This Mac", BUILTIN_SERVER_NAME])(
+    "restores native checked state after an unsuccessful selection: %s",
+    (label) => {
+      const args = menuArgs(() => {});
+      installApplicationMenu(args);
+      const template = vi.mocked(Menu.buildFromTemplate).mock.calls[0]?.[0];
+      if (!template) throw new Error("Expected an installed template");
+      const serverItems = findServerSubmenu(template);
+      const item = serverItems.find(
+        (item) => item.label === label || item.label === `Show ${label}`,
+      );
+      if (!item?.click) throw new Error("Expected a server action");
+      item.click({} as never, undefined, {} as never);
+      installApplicationMenu(args);
+      expect(Menu.buildFromTemplate).toHaveBeenCalledTimes(2);
+    },
+  );
+
   it.each([true, false])(
     "opens local logs independently of runtime ownership (isMac=%s)",
     (isMac) => {

5. Root cause

apps/desktop/src/desktop-window-factory.ts:439 awaits each createWindow in a loop:

    const restoredWindows: DesktopBrowserWindow[] = [];
    for (const entry of entries) {
      restoredWindows.push(
        await createWindow({
          initialUrl: restoreArgs.initialUrl,
          stateKey: entry.stateKey,
        }),
      );
    }
    return restoredWindows;

That promise includes the initial navigation (apps/desktop/src/desktop-window-factory.ts:405); construction of the next saved window is therefore gated by completion of the previous page.

apps/desktop/src/main.ts:1046 resolves accelerators and calls refreshApplicationMenu unconditionally after a successful, current settings request. apps/desktop/src/menu.ts:359 then always builds and installs a native menu:

export function installApplicationMenu(args: InstallApplicationMenuArgs): void {
  const menu = Menu.buildFromTemplate(buildApplicationMenuTemplate(args));
  const onServerMenuWillShow = args.onServerMenuWillShow;
  if (onServerMenuWillShow !== undefined) {
    for (const id of SERVER_MENU_ITEM_IDS) {
      menu.getMenuItemById(id)?.submenu?.on("menu-will-show", () => {
        onServerMenuWillShow();
      });
    }
  }
  Menu.setApplicationMenu(menu);

There is no content-equivalence check. The activation hook at apps/desktop/src/main.ts:2885, the configuration-sync open/realtime callbacks at apps/desktop/src/main.ts:1005, and the polling setup at apps/desktop/src/main.ts:1070 all reach this path. Window registration already occurs before first navigation; this is a distinct scheduling defect, not late registration.

6. Proposed fix and safety

Use Promise.all over the saved entries, preserving the returned array's persisted order while allowing navigation to overlap. Reuse the installed native menu when its serialized template and ordered server IDs are unchanged and Electron still has that same menu installed. Refresh retained callback arguments even when skipping native replacement, and always dispatch the server-open hook through the latest arguments. Invalidate the cache before radio/checkbox actions because Electron may mutate checked state even if the action fails and application settings stay unchanged.

The implemented candidate changes four desktop-subsystem files, 271 text lines counting additions plus deletions. It adds no dependency, public API, protocol, schema, stored-data, packaging, migration, or release change. The unchanged empty-state fallback is retained. The fix does not promise native show/compositor order.

7. Verification

The same agent repeated the reproduction in a second newly created detached checkout at the exact base commit, with its own frozen install, dependency builds, and fresh test user-data directories. No owner data or existing development server was used. This is a second clean reproduction, not independent-agent verification.

git worktree add --detach /tmp/issue-6541-second 3bacfac9ed69d42392076e5b3da2815bec822cd8
cd /tmp/issue-6541-second
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/desktop
git apply /path/to/regression.patch
pnpm exec turbo run test --force --filter=@bb/desktop -- test/desktop-window-factory.test.ts test/menu.test.ts

During verification, the regression fixture was corrected to use ES2022-compatible deferred promises, stable fake submenu identity, and distinct saved geometries. Both intended baseline failures remain unchanged. The final fixture checks persisted result order, not construction callback timing or macOS show order.

8. Related issues and pull requests

GitHub linked metadata shows PR #6545 was closed without merge on 2026-10-29 at 09:20:51 UTC. No linked open pull request existed when checked. Its branch/code was not executed or used to design this patch. This report does not make a correctness verdict on that closed patch. The existing pre-navigation registration regression also passes.

9. Appendix

Issue content was treated as untrusted claims. Embedded checkout/install/test instructions and external branches were ignored. All executed application code came from recorded trusted main plus this agent's local changes.

pnpm exec turbo run test --filter=@bb/desktop -- test/desktop-window-factory.test.ts test/menu.test.ts test/desktop-menu-shortcuts.test.ts test/window-state.test.ts test/server-list.test.ts test/server-target.test.ts
pnpm exec turbo run lint typecheck --filter=@bb/desktop
git diff --check
git diff --numstat origin/main

The raw full-suite log also records an attempted CLI exclusion that Vitest's workspace projects did not honor; it is not described as a passing run. Logs have checkout/home paths removed.

> AGENT GENERATED