Reports

#6534 · Delayed preference broadcasts restore superseded sidebar state

BugPriority: LowEffort: LowuiIssue #65342026-10-29

Trusted base: 3bacfac9ed69d42392076e5b3da2815bec822cd8 (origin/main fetched directly from get-bb/bb).

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

1. TL;DR

A quick collapse and expand should leave a sidebar project expanded. The preference synchronization layer instead accepts an old broadcast after the corresponding save request has finished, briefly restoring the collapsed state before accepting the newer broadcast. A focused test against the real production preference atoms and synchronization code reproduces the extra state pair in two clean trusted checkouts. A separate test also demonstrates two simultaneous writes for the same preference key. These tests reproduce the underlying state regression; browser animation and relayed-network frequency were not directly verified.

2. Claims vs findings

ClaimFindingEvidence
Delayed broadcasts can replay an earlier collapse choice.Verified at the preference-state boundary.Two clean runs produce five states instead of three, with a 400 ms signal delay and a 250 ms input gap.
The server publishes a preference update without distinguishing the writer.Verified.The store publishes only key and value after persisting; the client signal schema has no origin field.
The pending guard ends before a delayed broadcast arrives.Verified.RPC completion deletes the pending entry; a later valid signal is applied.
Writes for a single key can overlap.Verified.The deferred-response test records two outstanding saves before the first response.
Server persistence actually finishes out of order.Not directly verified.Concurrent requests are proven; no real server write-reordering experiment was run.
This is a CSS-only or background-thread reveal problem.Not needed to produce the failure.Production preference atoms change with no CSS, threads, providers, or reveal state machine in the test.
Visible animation replay is common on remote connections.Not directly verified.No usable local browser runtime; real connection frequency and rendered animation are outside this evidence.

3. Environment

4. Minimal reproduction

  1. Prepare a clean trusted checkout, pin the recorded base, and install existing dependencies:
    git clone https://github.com/get-bb/bb.git bb-6534
    cd bb-6534
    git checkout 3bacfac9ed69d42392076e5b3da2815bec822cd8
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
    
    If the SDK dist build-order race occurs on the first full build, rerun the same build after its SDK build has completed.
  2. Save the test below as plugins/thread-list/app/preferences/issue-6534.test.ts. It uses the real production synchronization module and Jotai store. Its small RPC double returns the save response immediately and independently delivers the corresponding signal 400 ms later; it does not mock a database.
  3. Run:
    pnpm exec turbo run test --filter=bb-plugin-thread-list -- app/preferences/issue-6534.test.ts
  4. Compare the observable state history and outstanding request count:
    Expected collapsed-project states:
    [[],["project-fixture"],[]]
    Actual console output, verbatim in both clean runs:
    Observed collapsed-project states: [[],["project-fixture"],[],["project-fixture"],[]]
    Outstanding saves before first response: 2
    
    Expected outstanding saves: 1
    Actual assertions:
    AssertionError: expected [ [], [ 'project-fixture' ], [], …(2) ] to deeply equal [ [], [ 'project-fixture' ], [] ]
    AssertionError: expected 2 to be 1 // Object.is equality
    Tests  2 failed (2)
    Process exit: 1

The first choice is written at 150 ms; the second choice is made at 250 ms and written at 400 ms. The first signal arrives at 550 ms, after both save responses, and restores the old collapsed value. The second arrives at 800 ms and restores the expanded value.

Complete investigator-authored regression test
import { createStore } from "jotai";
import { afterEach, expect, it, vi } from "vitest";
import {
  applyRemotePreferenceSignal,
  attachPreferencesStore,
  hydratePreferences,
  resetPreferencesSyncForTest,
  setPreferencesMirrorStorageForTest,
  type PreferencesRpc,
} from "./preferences-sync.js";
import { createSyncedPreferenceAtom } from "./synced-preference-atom.js";
import { defaultPreferences } from "../../shared/preferences.js";

afterEach(() => {
  resetPreferencesSyncForTest();
  setPreferencesMirrorStorageForTest(undefined);
  vi.useRealTimers();
});

it("keeps the last local selection when acknowledged writes echo later", async () => {
  vi.useFakeTimers();
  setPreferencesMirrorStorageForTest(null);
  const store = createStore();
  attachPreferencesStore(store, "thread-list");
  const rpc: PreferencesRpc = {
    async call(method: string, input: unknown) {
      if (method === "listPreferences") {
        return { preferences: defaultPreferences() };
      }
      setTimeout(() => applyRemotePreferenceSignal(input), 400);
      return input;
    },
  };
  await hydratePreferences(rpc);
  const collapsed = createSyncedPreferenceAtom("collapsedProjects");
  const history: string[][] = [store.get(collapsed)];
  const unsubscribe = store.sub(collapsed, () => {
    history.push(store.get(collapsed));
  });
  store.set(collapsed, ["project-fixture"]);
  await vi.advanceTimersByTimeAsync(250);
  store.set(collapsed, []);
  await vi.advanceTimersByTimeAsync(700);
  unsubscribe();
  console.log("Observed collapsed-project states:", JSON.stringify(history));
  expect(history).toEqual([[], ["project-fixture"], []]);
});

it("keeps each key serialized while its first save is unresolved", async () => {
  vi.useFakeTimers();
  setPreferencesMirrorStorageForTest(null);
  const store = createStore();
  attachPreferencesStore(store, "thread-list");
  const saves: unknown[] = [];
  const settle: Array<() => void> = [];
  const rpc: PreferencesRpc = {
    async call(method: string, input: unknown) {
      if (method === "listPreferences") {
        return { preferences: defaultPreferences() };
      }
      saves.push(input);
      await new Promise<void>((resolve) => settle.push(resolve));
      return input;
    },
  };
  await hydratePreferences(rpc);
  const collapsed = createSyncedPreferenceAtom("collapsedProjects");
  store.set(collapsed, ["project-fixture"]);
  await vi.advanceTimersByTimeAsync(250);
  store.set(collapsed, []);
  await vi.advanceTimersByTimeAsync(250);
  const outstanding = saves.length;
  for (const resolve of settle) resolve();
  await vi.advanceTimersByTimeAsync(0);
  for (const resolve of settle) resolve();
  await vi.advanceTimersByTimeAsync(0);
  console.log("Outstanding saves before first response:", outstanding);
  expect(outstanding).toBe(1);
});

The complete test is embedded here for reproducibility. Raw tests and logs are retained outside the public reports repository, whose policy forbids separate test/log artifacts.

5. Root cause

The pending-write guard ends at RPC completion, allowing delayed self-broadcasts to overwrite newer local preferences; per-key writes can also overlap.

  1. Preference persistence and publish: every successful write stores the parsed value and publishes the key/value pair. There is no writer correlation in the signal.
  2. Production realtime subscription: the live plugin connects its preference channel directly to applyRemotePreferenceSignal.
  3. Remote-value pending guard: applyValues skips a key only while it is present in pendingWrites.
  4. Signal application and save completion: a valid remote signal applies its value; the request completion deletes the pending key as soon as no debounce timer remains. HTTP completion does not establish delivery of the corresponding realtime signal.
  5. Per-key flush and scheduling: inFlight is assigned but never checked before issuing a new request. Two request completions therefore share one mutable pending entry.
  6. Project collapse preference consumer and Project row collapsed prop: project collapse is derived from that preference, so stale preference transitions reach the row's collapsed state.
if (state.pendingWrites.has(key)) continue;
store.set(valueAtomFor(key), value);

pending.inFlight = true;
void rpc.call("setPreference", { key, value })
  ...
  state.pendingWrites.delete(key);

The excerpt is abbreviated; the linked source includes validation, error handling and timer checks. The issue is ordering and correlation, not an invalid payload or a CSS transition. A finite post-save timeout would only move the race rather than identify obsolete self-echoes.

6. Proposed fix

Correlate writes with their originating window, ignore that window's own echoes, and serialize writes per preference key while retaining the latest queued value. Keep other windows' changes flowing once no local write owns the key. Ensure a first request's completion cannot discard a newer queued value. Cover late self-echoes, overlapping saves, failed saves, other-window changes, and originless CLI writes. A correlation field changes the plugin RPC/realtime contract, so it is not merely a CSS repair.

7. Linked PR review

PR #6535 — static review only

The open PR links this issue. Its metadata and diff were read as untrusted evidence; its branch was never checked out, built, or executed. Reviewed head: 0e9deb92c1f27208fbf228bc1bfe72d95a66ec35.

The diff tags writes with a window origin, forwards that origin in the server broadcast, filters matching-origin signals, and guards per-key in-flight writes with a latest-value follow-up. It also updates the shared schema, tests and skill documentation. Static verdict: directionally addresses both reproduced mechanisms. No runtime correctness or passing-test claim is made for the PR; the tests in this report ran only on trusted main.

Review limits: cross-window convergence, failed-save follow-ups and mixed/old signal payload behavior still warrant runtime checks. No duplicate fix branch or pull request was created because #6535 is already open. The proposed PR also changes six files and a plugin signal schema; this report does not treat it as satisfying this automation's simple-fix gate.

8. Verification — second clean checkout

The same investigator created a second new detached worktree at 3bacfac9ed69d42392076e5b3da2815bec822cd8, installed the existing lockfile, and first ran the existing preference-sync suite. That control passed. The authored test was then copied into the otherwise unchanged second checkout and run with the identical Turbo command from section 4. Both intended assertions failed with the same state history and outstanding count. This is a repeat clean reproduction by the same investigator, not an independent review.

Verification supports the final state-ordering report without correction. It does not upgrade the unobserved browser animation or real server write reordering into verified claims.

Second checkout:
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run test --filter=bb-plugin-thread-list -- app/preferences/preferences-sync.test.ts
pnpm exec turbo run test --filter=bb-plugin-thread-list -- app/preferences/issue-6534.test.ts

Existing full-suite control, first checkout:
pnpm exec turbo run test --filter=bb-plugin-thread-list -- --exclude '**/issue-6534.test.ts'
Test Files  37 passed (37)
Tests  482 passed (482)

Full build retry:
Tasks: 72 successful, 72 total

9. Related issues

#6306 and #6302 concern preserving collapse choices during background activity. They are closed. Their changes were not needed to reproduce this distinct synchronization-layer failure; the test has no background-thread activity.

10. Appendix and boundaries

Repository visibility was checked as public before publication. Issue text and linked PR content were treated as untrusted claims; no issue-supplied command, script, test, branch or external URL was executed or fetched. Only the trusted repository base and this investigator-authored test were run. GitHub metadata was used to discover the open PR. The test's two assertions protect distinct invariants: no post-acknowledgement stale-state replay, and at most one in-flight save per key. Existing tests covered remote changes while a write remained pending but did not exercise delayed post-response echoes or an unresolved first request.

Raw local evidence consists of the two reproduction logs, second-checkout preference control, 482-test full-suite control, build logs, and isolated-instance health checks. No raw log, private path, credential, runtime data or screenshot containing personal data is published. Browser verification was attempted but blocked by the runtime prerequisites described above. The public report therefore deliberately supplies no fabricated visual evidence.