Skip to content

Remove timing and shared-state assumptions from UI test fixtures - #7684

Merged
ymichael merged 6 commits into
mainfrom
bb/flake-ui-followups
Nov 17, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/flake-ui-followups

Conversation

@ymichael

@ymichael ymichael commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Several UI fixtures retained assumptions already implicated in previous flakes: reconnect requests had to land on different clock ticks, browser mocks survived teardown, and a functional panel test spent its assertion deadline loading the real lazy module. Three settings fixtures also reused consumed Response bodies; a real query invalidation produced Body is unusable: Body has already been read. The PostHog comparison serialized hundreds of independent WebCrypto operations and repeatedly exceeded its existing Windows deadline.

What changed

Give reconnect tests explicit timestamps, restore animation-frame and visibility spies, await the real panel preload in setup, and construct fresh responses for repeatable settings fetches. Run PostHog comparisons in batches of 16 while preserving all 1,500 identity/variant comparisons, real crypto, and the real reference implementation. No production changes, CI jobs, retries, or timeout increases.

The sidebar row-isolation fixture also scopes answer-field queries to its question form. A global button lookup previously computed accessible styles for all 60 sidebar rows; the production components and render-count assertions stay intact.

Server-move fixtures now hold running, activating, stale-history, and recovery phases until the corresponding UI/query state is observed. Previously their 20 ms poll could consume every response before the test found the intermediate dialog.

How you verified

  • Frozen clock: all eight old reconnect cases fail; all 28 cases pass with explicit timestamps.

  • Temporary teardown probes detect both leaked browser mocks before restoration and pass afterward; probes are not retained.

  • A 5.5-second module delay reproduces the panel skeleton failure; all eight panel tests pass with the same delay after awaiting preload.

  • The existing machine reconnection test leaves a consumed-body query error before the response fix and none afterward.

  • Adding 20 ms around each real digest times out the old serial comparison; all five batched cases pass under the same fault, each within its original deadline.

  • Clean shuffled runs: 99 affected app tests and all 558 web tests pass with seed 8821. Turbo lint and typecheck pass (9 tasks).

  • A call-through 6 ms delay on actual style reads reproduces the row test’s 15-second timeout: 2,803 reads / 17.94 seconds before versus 49 reads / 362 ms for the scoped lookup. The corrected case passes in 1.17 seconds under the same delay. Cloning every row in the production cache still fails both versions (59 rendered rows instead of one). 28 owner/sibling cases and 7 static-check tasks pass.

  • A 150 ms observer delay reproduces three server-move failures before stable phases and passes afterward. Mutations accepting an activating server, accepting stale move history, or suppressing restart recovery still fail at the intended guards. All 32 component/sibling tests and 7 static-check tasks pass. The polling interval is unchanged.

  • A later native run passed all 832 assertions but failed with three uncaught Sonner callbacks after DOM teardown. The notification test now waits for actual toast removal; the same repair covers the adjacent rapid-swipe test, and notification cleanup/restoration runs after each case. Delaying the real removal callback and destroying the DOM reproduces window is not defined before; all 15 controlled cases pass after. Six related files pass all 28 tests, and 7 static-check tasks pass. Real toast behavior and existing timer budgets remain unchanged.

  • The combined Windows run exposed a second row-isolation cause: cold plugin-module loading could consume the first test's 15-second budget; its unfinished body then overlapped the next test and corrupted row order. Loading the same real plugin during collection fixes both the row-isolation and hidden-row functional suites. A 15.5-second real import delay reproduces the exact timeout, overlapping React act calls, and wrong order before; all three cases pass afterward under the same delay. The render-isolation mutation still fails, and all 32 related tests plus 7 static-check tasks pass. The existing settle waits and behavior assertions are unchanged.

The complete integration branch containing this and the related flake repairs passed the unchanged native CI workflow: 47 successful jobs and one skipped job. This uses normal Turbo cache reuse; it is not a claim that every task reran from scratch.

AGENT GENERATED

@ymichael
ymichael merged commit 8ce9400 into main Nov 17, 2026
33 checks passed
@ymichael
ymichael deleted the bb/flake-ui-followups branch November 17, 2026 17:44
ymichael added a commit that referenced this pull request Nov 18, 2026
## Human comments

## What was wrong

App tests had no shared way to wait for a lazy module. Each test that
rendered a `defineSplit`, `React.lazy` or dynamic-import loader made up
its own wait: `await import("./X")` inside `act`, deferred gates in
`vi.mock` factories, a `findBy` with its 1 s deadline, counted
`setTimeout(0)` loops, `vi.dynamicImportSettled()`, a `{ timeout: 5_000
}` bump, or a collection-time raw import. On a cold runner the transform
beat whichever deadline the copy had. Tests also passed only because a
sibling test had already loaded the module. Each flake was fixed again
in the file where it appeared.

Past fixes for this root cause:

- #4911: FilePreview and SplitThreadArea assertions relied on sibling
tests warming the lazy renderer and panel.
- #6851: FilePreview asserted before the lazy code renderer loaded.
- #6938: a cold Vite transform counted against `findByText`'s 1 s
deadline (lazy plugin renderers).
- #7673: a 1 s readiness wait raced the real import (voice preferences,
KaTeX clipboard, model picker and palette cold-open).
- #7678: cold transforms raced short deadlines across functional UI
suites (palette, thread search, sidebar retry, KaTeX, cold HTML, queued
messages, terminal clipboard, prompt paste). Its body lists four rounds
of follow-ups in the same PR.
- #7684: the lazy panel preload in ServerMoveOverlay.

Each was a per-file patch. None stops the next test from making the same
mistake.

## What changed

**Guard (`apps/app/vite-test-lazy-imports.ts`, `src/test/setup.ts`).** A
test-only Vite transform wraps every dynamic `import()` in app source.
Production code is unchanged. During each test the setup holds every
such import until the test settles it. A test that asserts lazy content
without waiting now fails deterministically, on every machine and in
every order. Its error names the held or loading module:

> Lazy imports had not settled when this test failed:
"./MicrophonePreferences" (held). …

**One signal (`src/test/lazy-modules.ts`).**
- `await settleLazyModules()` resolves once every import has loaded,
including imports that loading starts, and React has committed.
- `await settleLazyModules(operation)` covers tests that await a
production promise whose chain loads code, such as
`bootPluginFrontends()`.
- Testing Library `findBy*` and `waitFor` settle pending imports before
they poll, so the ordinary idiom is correct for lazy content without
per-test code. `vi.waitFor` does not settle, so cold-load tests use it
to poll while an import is still pending.

**Copies deleted.**
- Module-specific `await import()` waits in VoiceInputButton,
SelectableMessageProse (×2), FilePreview and thread search.
- Raw `beforeAll`/top-level preloads in CommandPalette,
PromptBoxInternal paste and ServerMoveOverlay.
- `ready`/`loaded`/`release` deferred gates in the CommandPalette and
ModelReasoningPicker cold-open tests, KaTeX loader, cold HTML, lazy
plugin renderers, CodeHosts cold-load, sidebar retry and queued
messages. The hold now does their job.
- `vi.importActual` preloads in lazy-plugin-renderers (#6938) and
`vi.dynamicImportSettled()` in useCodeRendererPreloads.
- The `flushLoad` (`setTimeout(0)` in `act`) helper in
ThreadDetailWorkerPoolProvider.
- The "5 ticks" loops in SplitThreadArea.environment-archive.
- The `{ timeout: 5_000 }` waits in AppFileExternalNavigationHost.
- The `await act(async () => { await opened })` wait in the terminal
clipboard fixture.

**Migrated callers.** The guard also found tests that passed only by
order or timing: timeline row isolation, sender metadata and plugin-slot
render counts, which asserted before a lazy row view committed. It also
found the new `plugin-frontend-boot-catch-up.test.ts` from #7615, which
awaited a held import.

**Kept.** Collection-time `await Split.preload()` stays where a whole
suite renders a heavy split. That is fixture preparation through the
production API; it races no deadline. The two plugin-frontend boot tests
now load `./plugin-frontend` at collection time, because that real
import takes about 8.5 s on main too. `docs/ui-code-splitting.md` gains
a "Test lazy boundaries" section describing the contract.

No per-test timeouts, counts or other tuned numbers were added; two 5 s
overrides were removed. No production code, plugin SDK or wire changes.

## How you verified

- **Guard fails on main for the known cases.** With only the hold
applied to main's tests (no signal, no migration), the full `@bb/app`
suite failed 44 files / ~70 tests. That includes every file patched by
#6851, #7673, #7678 and #7684, failing in their current, patched form,
because each waits on a module-specific import rather than the app's own
load.
- **Signal removes the need for the patches.** I injected a 1.5 s delay
into every real lazy import, as #7678 did. Then I ran the naive,
pre-patch forms of the VoiceInputButton (#7673), SelectableMessageProse
(#7673), FilePreview (#6851) and CommandPalette thread-search (#7678)
tests. With main's behaviour: 6 failed, 187 passed. With the signal: 193
passed. The delay and naive forms were reverted afterwards.
- **Mechanism test.** `src/test/lazy-modules.test.tsx` checks four
things: hold until settle, synchronous assertions after settle, `findBy`
without a module wait, and imports started inside an awaited operation.
Re-introducing the deadlock I hit (holding imports while awaiting an
operation) fails the last case.
- `pnpm exec turbo run lint typecheck test --filter=@bb/app` after
rebasing on 77e45fa: 689 files, 7136 tests passed. One failure,
`plugin-frontend-boot-catch-up` from #7615, was migrated above; that
file and its sibling now pass.
- Shuffled (`--sequence.shuffle --sequence.seed=8821`): 685 of 686 files
passed. `SplitThreadArea.test.tsx › carries maximization…` timed out
once at its 1 s `waitFor` with no lazy imports pending. It passed 3 of 3
times alone with the same seed, so I count it as CPU contention, not
this change.

## Follow-up: imports that start just after a wait begins

`defineSplit` starts its `import()` one microtask after render. In
`fireEvent.click(...)` followed by `waitFor(...)`, the wait looked for
pending imports before that import started, found none, skipped
settling, and raced its 1 s deadline again.
`AppFileExternalNavigationHost.test.tsx`, whose 5 s timeout this PR
removed, failed 2 of 3 local runs on its own. `waitFor`/`findBy` now
always settle before and after polling. `lazy-modules.test.tsx` gains a
case for an import that starts a microtask after render and outlasts
`findBy`'s deadline. It fails without the change.

Always settling exposed `PromptBoxInternal.test.tsx › defers compact
content…`. Escape restores focus to the prompt editor through TipTap's
`focus` command, which runs one animation frame later and dismisses any
open plugin popup. The test reopened the popup inside that frame. On
main it passed only because it asserted before the frame fired; the
popup closed right after. It now lets that frame pass before reopening.

Verified with every app lazy import's result delayed 1.5 s: the 9
touched files that failed 6 tests on main pass 216/216.

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
#7714)

## Human comments

## What was wrong

Plugin settings could briefly revert a successfully saved text value
when React received mutation completion before the refreshed settings
query. The field synchronized from its still-old props after the pending
flag cleared. This also explains the intermittent autosave assertion
that expected the new text but received the previous value.

## What changed

Use the successful mutation response while the field is waiting for
refreshed props. Once the stored value changes, that external value
takes precedence. Existing guards preserve a newer unsaved draft and
failed-save state.

## How you verified

The existing autosave test now releases actual TanStack notifications
one React commit at a time. It fails against the old implementation and
passes with the fix, then checks external updates and preservation of
unsaved text. All 33 affected component/query cases pass, including the
20 settings cases, along with 7 Turbo lint/typecheck tasks.

A real browser against an isolated source app reproduced the old-value
rollback across 12 separately delivered notification callbacks. The
identical schedule keeps the saved value visible after the fix. Browser
input also verified a newer draft during a held PUT, a second blur/save,
HTTP 503 failure with the draft retained, retry, and persistence after
reload. API and matching source CLI reads agree with the visible saved
value.

The complete integration branch containing this and the related flake
repairs passed the unchanged [native CI
workflow](https://github.com/get-bb/bb/actions/runs/44130300753): 47
successful jobs and one skipped job. This uses normal Turbo cache reuse;
it is not a claim that every task reran from scratch. The earlier
standalone PR run failed in the secondary-panel readiness case repaired
by #7684. That fix is now merged into main and included in this branch;
[fresh standalone
CI](https://github.com/get-bb/bb/actions/runs/44145327987) passes.

> AGENT GENERATED
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