← reports

#5399 · Read-state events leave observed caches stale

Bug · Priority: Medium · Effort: Low · Area: ui · 2026-10-12
Trusted origin/main: 406c009502ad0f961fc6ce9c75c1d262cb3e3e7c · GitHub issue

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

1. Summary

A read-state notification reaches the client cache owner, but observed thread-list and sidebar queries keep their previous read timestamp. The handler invalidates these queries with refetch disabled and does not patch their rows. A real TanStack Query observer therefore continues receiving old data even though the next fetch would return the new timestamp. A focused regression fails twice on unchanged production code in separate clean clones. This reproduces the backing-cache defect, not a macOS desktop or cross-device screenshot journey.

2. Claims vs findings

ClaimFindingEvidence
Remote read-state changes leave lists unchanged.Verified at the client cache boundary.Two clean runs retain lastReadAt: 200 when authoritative fetch data changes to 0.
The read-state handler suppresses list refreshes.Verified.The trusted registry calls stale-only invalidation, with no row patch.
The event does not include the new timestamp.Verified in the trusted writer.The update emits a change kind and project ID, not lastReadAt.
Both desktop windows and other devices show the symptom.Not separately verified.No macOS device or second device used. Browser Automation could not open because Chrome is absent.
The plugin and core share the underlying sidebar data.Verified by source inspection, not visual execution.The sidebar query and plugin sidebar-data hook consume the shared sidebar thread data.

3. Environment and isolation

4. Minimal reproduction

Download the investigator-authored regression patch. From a new clone of the trusted repository:

git clone https://github.com/get-bb/bb.git bb-5399-repro
cd bb-5399-repro
git checkout --detach 406c009502ad0f961fc6ce9c75c1d262cb3e3e7c
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
git apply /path/to/regression.patch
pnpm exec turbo run test --filter=@bb/app -- \
  src/hooks/realtime-cache-effects.test.ts -t 'refreshes observed read state'
  1. The test seeds the real app QueryClient with a read timestamp of 200 and subscribes real QueryObservers to thread detail, the project list, and sidebar navigation.
  2. The authoritative fetch fixture changes to 0; the test feeds a read-state-changed event through createRealtimeCacheEffects.handleChanged.
  3. Advance the real debounce using fake timers, then inspect observer data. Repeat with and without project metadata; the fixed test also verifies the reverse transition to 300.
Expected observed row: { id: 'thr_1', lastReadAt: 0 }
Actual observed row:   { id: 'thr_1', lastReadAt: 200 }
First run:  2 failed, 80 skipped; exit 1
Second run: 2 failed, 80 skipped; exit 1

Artifacts: first-run output, second-run output, post-fix suite output. These are actual captured test results with local checkout paths replaced by neutral identifiers.

Standalone sidebar reproduction source and results

This additional minimal test directly inspects sidebar data rather than failing first at the project-list assertion. Download the tested source, place it at apps/app/src/hooks/sidebar-read-state.test.ts, then run pnpm exec turbo run test --filter=@bb/app -- src/hooks/sidebar-read-state.test.ts. It fails both metadata cases on the unchanged second checkout and passes both on the fixed checkout: baseline output / fixed output. The temporary copy is removed afterwards; the permanent PR regression remains in the existing owner test file.

import { QueryObserver } from "@tanstack/react-query";
import { afterEach, expect, it, vi } from "vitest";
import { createAppQueryClient } from "@/lib/query-client";
import { sidebarNavigationQueryKey } from "./queries/query-keys";
import { createRealtimeCacheEffects } from "./realtime-cache-effects";

afterEach(() => vi.useRealTimers());

it.each(["project-1", undefined])(
  "updates the observed sidebar timestamp after a read-state event (%s)",
  async (projectId) => {
    vi.useFakeTimers();
    const queryClient = createAppQueryClient({
      defaultOptions: { queries: { retry: false, staleTime: Infinity } },
      showMutationErrorToasts: false,
    });
    let lastReadAt = 200;
    const response = () => ({
      projects: [{ threads: [{ id: "thr_1", lastReadAt }] }],
      personalProject: { threads: [] },
    });
    const queryKey = sidebarNavigationQueryKey();
    queryClient.setQueryData(queryKey, response());
    const observer = new QueryObserver(queryClient, {
      queryKey,
      queryFn: async () => response(),
    });
    const unsubscribe = observer.subscribe(() => {});
    const effects = createRealtimeCacheEffects({ queryClient });
    try {
      lastReadAt = 0;
      effects.handleChanged({
        type: "changed",
        entity: "thread",
        id: "thr_1",
        metadata: { projectId },
        changes: ["read-state-changed"],
      });
      await vi.advanceTimersByTimeAsync(50);
      expect(observer.getCurrentResult().data?.projects[0]?.threads[0]?.lastReadAt).toBe(0);
    } finally {
      effects.dispose();
      unsubscribe();
      queryClient.clear();
    }
  },
);

5. Root cause

At the trusted base, the read-state rule runs markThreadDetailQueryStale and markThreadListQueriesStale. The latter invalidates sidebar, project, and global list queries with refetchType: "none". No read-state patch handler updates cached rows.

The sidebar bootstrap query uses an infinite stale-time policy and has no periodic polling. Suppressing the notification's refetch leaves its active observer with old data until another action triggers a load. The read-state calculation compares the cached read timestamp with the latest attention timestamp, making stale data directly relevant to the unread indicator.

"read-state-changed": {
  flush: "debounced",
  dirty: [markThreadDetailQueryStale, markThreadListQueriesStale],
}

queryClient.invalidateQueries({
  queryKey: sidebarNavigationQueryKey(),
  refetchType: "none",
});

The trusted thread writer persists lastReadAt and emits the change plus project metadata, but does not transmit the timestamp. Refreshing observed queries is therefore the smallest repair that needs no wire-format change. Existing tests explicitly preserved stale-only read notifications; one is replaced with the behavioral regression and the project-scoping expectation is updated.

6. Fix and safety assessment

Reuse the existing dirtyActiveThreadListQueries handler for read-state events and delete the now-unused stale-only list helper. This refreshes subscribed sidebar, list, and search queries, retains project scoping, and keeps archived lists stale without fetching them. Thread detail remains stale-only to avoid needless active-conversation refreshes.

The change stays in the app realtime-cache subsystem: 2 text files, 95 additions + 113 deletions = 208 changed lines. No dependency, lockfile, generated file, data migration, stored-data shape, public protocol, authentication, authorization, or release change. The relevant existing tests and the new regression pass: 13 files / 185 tests. Turbo app lint and typecheck pass; lint reports 248 existing warnings and no errors. git diff --check passes. The warning baseline also reports 248 warnings with zero errors.

7. Verification

The same investigator repeated the reproduction, not an independent agent. The second clean clone was detached at 406c009502ad0f961fc6ce9c75c1d262cb3e3e7c and clean before copying the investigator-authored test-only change. The exact focused Turbo command in section 4 produced the same two failures and stale timestamp. No report correction was needed.

pnpm exec turbo run test --filter=@bb/app -- \
  src/hooks/realtime-cache-effects.test.ts \
  src/hooks/realtime-cache-effects.coarse-pointer.test.ts \
  src/hooks/cache-owners \
  src/hooks/queries/thread-queries.test.tsx \
  src/hooks/queries/query-helpers.test.ts
pnpm exec turbo run lint typecheck --filter=@bb/app
git diff --check
git diff --numstat origin/main

The fixed suite covers both read directions, both metadata cases, no detail refetch, unrelated-project isolation, and archived-list no-refetch behavior. It does not prove native macOS rendering, a real WebSocket connection between two windows, or a device-to-device journey. The verification inventory also has pre-existing drift (unmapped browser CLI family); no unrelated documentation was rewritten.

8. Pull requests and trust boundary

Before fixing, GitHub issue timeline metadata contained no linked open pull request and the open-PR search for issue 5399 returned none. No pull-request code was checked out. Issue contents were treated solely as untrusted claims; commands and tests were derived from trusted repository source and authored by the investigator. The final SlopCop issue comment contains the ready fix pull request if its final safety checks pass.

Generated report; evidence links are pinned to the recorded trusted base.