Skip to content

Stop stale tab fetches and fresh devices from rewriting a thread's tabs - #6611

Merged
ymichael merged 2 commits into
mainfrom
bb/fix-thread-tab-sync-stale-fetch-and-diff-info-re-thr_iasxxtysqp
Oct 29, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/fix-thread-tab-sync-stale-fetch-and-diff-info-re-thr_iasxxtysqp

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Two races in the client's thread-tab sync (apps/app), both on main, found while testing #6594:

  1. A new terminal jumps back to Info. Closing a terminal saves the thread's tabs, and the realtime "tabs changed" event starts a fetch of the saved list. Starting a new terminal then saves a newer list (higher revision). If that earlier fetch lands last, React Query writes the older list into the cache, hydration drops the new terminal's tab, selection falls back to Info, and the terminal sync re-adds the tab unselected. Nothing compared revisions: neither setCachedThreadTabs nor the useThreadTabs fetch. Network latency (bb Connect) makes the late landing likelier.
  2. Pinned tabs get reordered (Diff saved before Info). A device that has never opened a thread's panel starts with an empty local list and seeds it with the pinned tabs available at that moment, often just Info (the Git plugin's Diff tab isn't available yet). On save, mergeThreadTabChanges(server=[info, diff], previous=[], next=[info]) treated Info as newly added and appended it after the server's tabs, saving [diff, info] for every device, permanently.

What changed

  • Keep the newer tab list (hooks/cache-owners/thread-tabs-cache-owner.ts, hooks/queries/thread-tabs-query.ts): setCachedThreadTabs and the useThreadTabs fetch (via resolveFetchedThreadTabs) keep whichever list has the higher revision. Both are needed because React Query writes fetch results straight into the cache. Revisions only increase on the server (replaceStoredThreadTabs checks the expected revision and stores revision + 1), so a real change from another device always wins.
  • Keep server positions for tabs a device "adds" that the server already has (lib/thread-tabs-sync.ts, mergeThreadTabChanges), unless the local list deliberately places the tab before another server tab. That exception keeps the existing case where a registered Browser tab replaces a New tab placeholder.

No server, wire or SDK changes.

How you verified

  • New tests, each failing before its fix and passing after:
    • fixed-panel-tabs-sync.test.ts "keeps a newer saved tab list when an older tab fetch lands last": real hooks and query cache; a terminal close saved as rev 2, the triggered fetch hangs, a new terminal saved as rev 3, then the fetch returns rev 2. Before: cache rolled back to rev 2 without the terminal. After: rev 3 with the terminal selected.
    • thread-tabs-sync.test.ts "keeps a server tab in place when a device that never loaded the list adds it": server [info, diff] + previous [] + next [info] → [info, diff] (was [diff, info]).
  • pnpm exec turbo run typecheck lint test --filter=@bb/app: 8 tasks green (6,501 tests).
  • Live repro on start:worktree servers with the same data, main vs this branch:
Repro main This branch
Close a terminal, immediately start another, with tab fetch responses held 1.5 s in the browser (forces the late landing) 5/5 bad: terminal dropped, Info active, terminal re-added unselected ~2.5 s later 5/5 ok: terminal stays selected
Fresh browser profile, open the Pull request thread's panel and start a terminal right after load, server order reset to [info, diff] each time Flipped to [diff, info] in 2 of 3 0 of 3

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits October 29, 2026 16:26
Closing a terminal saves the tab list and the realtime tabs-changed event
starts a GET. Starting a terminal right after saves a newer revision. When
the earlier GET resolved last it replaced the cache with the older list,
hydration dropped the new terminal tab and selection fell back to Info.

Revisions only increase, so the tabs query and setCachedThreadTabs now keep
whichever list has the higher revision.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A device that had never opened a thread's panel starts with an empty local
list and seeds it with Info. Its first save merged server [Info, Diff] with
previous [] and next [Info], treated Info as a new tab, moved it to the end,
and permanently saved [Diff, Info].

A tab the device adds that already exists on the server now keeps its server
position unless the local list places it before a tab the server also has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 8a63c6c into main Oct 29, 2026
30 checks passed
@ymichael
ymichael deleted the bb/fix-thread-tab-sync-stale-fetch-and-diff-info-re-thr_iasxxtysqp branch October 29, 2026 23:47
ymichael added a commit that referenced this pull request Oct 30, 2026
## Human comments

## What was wrong

Several cache owners wrote a server reply or the thread-detail bootstrap
straight into the React Query cache with `setQueryData` while a fetch of
the same key could still be in flight. React Query writes fetch results
without checking whether they're older than what's cached (query-core
`query.ts`), so the older fetch landed last and put stale data back.
Effects included: an environment or host status that stayed stale after
opening a thread, a plugin settings form resetting its draft to the old
value, a cancelled plugin install flipping back to running, new plugin
update jobs dropping out of the list, an `idle` app update phase
switching off the progress poll, and the AI service selection flickering
back. These are items #2–#10 from the direct cache write audit
(@thread:thr_fjr5x8dzaz). #1 (thread tabs) is fixed separately in #6611.

## What changed

Two fixes, depending on whether the data has a version field:

- **Environment and Host keep the newer copy by `updatedAt`** (#2, #3,
#10). The bootstrap ingest (`thread-detail-cache-owner.ts`), the rename
reply (`applyEnvironmentUpdateResult`), and the
`useEnvironment`/`useHosts` fetches all compare `updatedAt`. The
fetch-side check is what catches a fetch that started before the write
and lands after it. To make it testable, those fetches now live in
`environmentQueryOptions` and `hostsQueryOptions`. Host `status` comes
from live daemon sessions and a disconnect doesn't change `updatedAt`,
so on a tie the cached copy wins over the bootstrap. The bootstrap only
fills an empty cache or replaces strictly older data. Rename replies and
fetch results still win ties.
- **`setQueryDataOverInFlightFetch`** (`cache-effect-utils.ts`) for data
with no version (#4–#9): it writes the value, and if a fetch of the key
is in flight it cancels that fetch (the cache keeps the written value)
and refetches. With nothing in flight it's a plain write. Used by
`applyPluginSettingsView`, `applyPluginInstallJob`,
`applyPluginUpdateJob`, `hydrateAppUpdateStatus`,
`hydrateSystemVersionCache` and `writeCachedAiServices`, so every caller
gets the fix. Where the audit suggested an unconditional
cancel-write-invalidate (#7) or a cancel before the write (#8, #9), this
helper refetches only when a fetch was actually in flight. That avoids
an extra request on every write. Forced version and app-update checks
update the server's cache, so the trailing unforced refetch returns the
forced result.

No wire, CLI or plugin API changes.

Not covered here: audit items #11 (plugin safe mode) and #12 (prompt
history), both low risk. Also not covered: a lint rule restricting
direct `setQueryData` calls to the helper, which would stop new call
sites from bringing the race back.

## How you verified

- New tests use real `QueryClient`/`QueryObserver` instances: start a
fetch that resolves late with older data, do the write, let the fetch
land, then check that the newer value survives (and, for the helper,
that the trailing refetch runs).
- `thread-detail-cache-owner.test.ts` (new): late environment and
host-list fetches after a bootstrap, an older bootstrap over a newer
cache, and the equal-`updatedAt` host status case.
- `environment-workspace-cache-owner.test.ts`: a late environment fetch
after a rename, and an older rename reply over a newer cache.
- `in-flight-fetch-writes.test.ts` (new): one row per cache-owner write
for #4–#9, plus helper tests for the no-fetch case (no extra request)
and a fetch of an unobserved query.
- With each source change reverted, every race test failed on the stale
data and passed once the fix was restored.
- `pnpm exec turbo run typecheck lint test --filter=@bb/app`: passed
(647 files, 6515 tests; 0 lint errors, no new warnings). After rebasing
onto `0472409243` I re-ran the three changed test files (21 tests
passed).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant