Skip to content

Commit 882675d

Browse files
author
Larry
committed
Replace fixed browser-test waits with conditions, gates and the clock
Ten page.waitForTimeout calls made tests depend on runner speed. Each is replaced by the evidence the wait stood in for: - avatar-loading: an on-screen lazy sentinel image is requested only after the browser has evaluated lazy loading, so the offscreen avatar check has a completion barrier. - image-scroll: an IntersectionObserver created after the product's fires its first callback after the product's, so the "no offscreen paint" check follows the product's visibility decision. - history-loading: each wheel step waits until it scrolls or requests the older page. - layout: page.clock expires Virtua's 150ms scroll timer exactly. - navigation-groups: the frame-count barrier already samples the held decode; the extra 300ms added nothing. - sidebar-unread: wait until both revealed rows are prepared before checking for repeated reads. - thread-unread: page.clock runs the 750ms reading dwell; the own-reply check waits until the session has indexed the reply as ineligible. A Biome plugin (tests/browser/fixed-sleeps.grit) now rejects waitForTimeout anywhere in the repository. Checks: for the avatar and image barriers, making the product eager fails the test in both engines. The changed tests pass 4/4 repeats in chromium and webkit. Signed-off-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
1 parent 61da266 commit 882675d

10 files changed

Lines changed: 117 additions & 20 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ Tests must control the ordering they assert, not depend on runner speed.
135135
applied layout, or observed event. Visible initial content does not prove that
136136
background work finished. Register event observers before triggering actions.
137137
- Wait for observable conditions with retrying assertions, not fixed sleeps or
138-
immediate snapshots of asynchronous effects. Negative assertions need a
138+
immediate snapshots of asynchronous effects (lint rejects `waitForTimeout`). Negative assertions need a
139139
completion barrier proving the work that could violate them has finished.
140140
Scope selectors to the semantic content being tested, not unrelated UI.
141141
- When elapsed time is the behavior under test (expiry, debounce, retry), use a

‎biome.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@
8484
"includes": ["**", "!tests/browser/page-errors.mjs"],
8585
"plugins": ["./tests/browser/page-errors.grit"]
8686
},
87+
{
88+
"includes": ["**"],
89+
"plugins": ["./tests/browser/fixed-sleeps.grit"]
90+
},
8791
{
8892
"includes": ["src/shared/design-system/icons/**"],
8993
"linter": {

‎tests/browser/avatar-loading.spec.mjs‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,39 @@ test("shared avatars defer offscreen artwork, omit the referrer and recover from
1414
contentType: "image/png",
1515
});
1616
});
17+
let sentinelRequests = 0;
18+
await page.route("https://images.example/sentinel.png", (route) => {
19+
sentinelRequests++;
20+
return route.fulfill({ status: 204 });
21+
});
1722
await page.goto(
1823
"/tests/fixtures/agents.html?external-avatar&offscreen-avatar",
1924
);
2025
await expect(
2126
page.getByRole("region", { name: "Agents", exact: true }),
2227
).not.toBeInViewport();
23-
await page.waitForTimeout(300);
28+
const avatar = page
29+
.getByRole("region", { name: "Library identities", exact: true })
30+
.getByRole("img", { name: /^A Brain identity/ })
31+
.first();
32+
const image = avatar.locator("img");
33+
// The library cards mount after an asynchronous refresh. The offscreen
34+
// avatar must exist with its source before the barrier can say anything
35+
// about whether it was deferred.
36+
await expect(image).toHaveAttribute(
37+
"src",
38+
"https://images.example/avatar.png",
39+
);
40+
// Barrier: a lazy image added on screen now is requested only after the
41+
// browser has evaluated lazy loading for the page, including the avatar.
42+
await page.evaluate(() => {
43+
const sentinel = document.createElement("img");
44+
sentinel.loading = "lazy";
45+
sentinel.alt = "";
46+
sentinel.src = "https://images.example/sentinel.png";
47+
document.body.prepend(sentinel);
48+
});
49+
await expect.poll(() => sentinelRequests).toBe(1);
2450
expect(requests).toHaveLength(0);
2551
await page.evaluate(() =>
2652
window.scrollTo(0, document.documentElement.scrollHeight),
@@ -31,11 +57,6 @@ test("shared avatars defer offscreen artwork, omit the referrer and recover from
3157
await expect.poll(() => requests.length).toBe(1);
3258
expect(requests[0].referer).toBeUndefined();
3359

34-
const avatar = page
35-
.getByRole("region", { name: "Library identities", exact: true })
36-
.getByRole("img", { name: /^A Brain identity/ })
37-
.first();
38-
const image = avatar.locator("img");
3960
await expect
4061
.poll(() => image.evaluate((el) => el.naturalWidth))
4162
.toBeGreaterThan(0);

‎tests/browser/fixed-sleeps.grit‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
language js
2+
3+
// A fixed wait is not a synchronization primitive. Wait for an observable
4+
// condition, hold the operation with a gate, or control the clock
5+
// (page.clock). See AGENTS.md "Deterministic tests".
6+
`$page.waitForTimeout($ms)` where {
7+
register_diagnostic(span=$ms, message="Do not wait a fixed time. Wait for a condition, hold the work with a gate, or use page.clock.", severity="error")
8+
}

‎tests/browser/history-loading.spec.mjs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,17 @@ tall(
2020
).toHaveCount(0);
2121
await history(page).hover();
2222
for (let i = 0; i < 100 && !app.pending.length; i++) {
23+
const before = await history(page).evaluate((e) => e.scrollTop);
2324
await page.mouse.wheel(0, -450);
24-
await page.waitForTimeout(40);
25+
// Each wheel step must land (scroll moves or the older page is
26+
// requested) before the next one.
27+
await expect
28+
.poll(
29+
async () =>
30+
app.pending.length > 0 ||
31+
(await history(page).evaluate((e) => e.scrollTop)) < before,
32+
)
33+
.toBe(true);
2534
if (
2635
await history(page)
2736
.getByRole("button", { name: "Loading older…", exact: true })

‎tests/browser/image-scroll.spec.mjs‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,14 @@ async function holdDecodes(page, holdVisibility = false) {
263263
});
264264
};
265265
const observers = [];
266+
// Record native observe() calls on canvases so a test can wait for the
267+
// product's passive effect to register before adding its own observer.
268+
const observedCanvases = new WeakSet();
269+
const realObserve = IntersectionObserver.prototype.observe;
270+
IntersectionObserver.prototype.observe = function (target) {
271+
if (target instanceof HTMLCanvasElement) observedCanvases.add(target);
272+
return realObserve.call(this, target);
273+
};
266274
if (holdVisibility) {
267275
window.IntersectionObserver = class {
268276
constructor(callback) {
@@ -277,6 +285,7 @@ async function holdDecodes(page, holdVisibility = false) {
277285
}
278286
window.imageTest = {
279287
paints,
288+
observed: (canvas) => observedCanvases.has(canvas),
280289
waiting: (name) => pending.has(`https://image.test/${name}.svg`),
281290
release(name) {
282291
const key = `https://image.test/${name}.svg`;
@@ -339,7 +348,29 @@ test("blurhash visibility, decode swap, failure and retired source lifetimes", a
339348
`http://127.0.0.1:${server.httpServer.address().port}/tests/fixtures/attachment-image.html`,
340349
);
341350
// Mounted but offscreen (as in a long thread) must not spend pixel work.
342-
await page.waitForTimeout(150);
351+
// The product observes the canvas in a passive effect, so wait for that
352+
// registration first. Barrier: an IntersectionObserver created after the
353+
// product's delivers its first notification in the same or a later task,
354+
// so the product's initial visibility callback has already run.
355+
await expect
356+
.poll(() =>
357+
frame(page)
358+
.locator("canvas")
359+
.evaluate((canvas) => window.imageTest.observed(canvas)),
360+
)
361+
.toBe(true);
362+
await frame(page)
363+
.locator("canvas")
364+
.evaluate(
365+
(canvas) =>
366+
new Promise((resolve) => {
367+
const observer = new IntersectionObserver(() => {
368+
observer.disconnect();
369+
resolve();
370+
});
371+
observer.observe(canvas);
372+
}),
373+
);
343374
expect(await page.evaluate(() => window.imageTest.paints)).toEqual([]);
344375
await page.getByRole("button", { name: "Reveal", exact: true }).click();
345376
await expect

‎tests/browser/layout.spec.mjs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ test("narrow link panels begin after the rendered sidebar", async ({
394394
readingTest(
395395
"panel resizing preserves bottom follow and the visible reading anchor",
396396
async ({ page, app }) => {
397+
// Virtua ends an imperative scroll on a 150ms timer. The clock lets the
398+
// test expire it exactly, instead of sleeping past it on wall time.
399+
await page.clock.install();
397400
await open(page, app);
398401
await settle(page);
399402
await link(page, app, "https://github.com/block/buzz/pull/4");
@@ -418,15 +421,15 @@ readingTest(
418421
await settle(page);
419422
await expectBottom();
420423
// Late layout-only reflow must not need another message or viewport resize.
421-
// Let Virtua's 150ms imperative-scroll scheduler expire first. Change actual
424+
// Expire Virtua's 150ms imperative-scroll scheduler first. Change actual
422425
// row layout, not scroll methods/metrics or the production observer callback.
423-
await page.waitForTimeout(250);
426+
await page.clock.runFor(150);
424427
const lateLayout = await page.addStyleTag({
425428
content: `[data-message-id="${received.id}"] p { padding-bottom: 120px; }`,
426429
});
427430
await settle(page);
428431
await expectBottom();
429-
await page.waitForTimeout(250);
432+
await page.clock.runFor(150);
430433
await lateLayout.evaluate((element) => element.remove());
431434
await settle(page);
432435
await expectBottom();
@@ -470,7 +473,7 @@ readingTest(
470473
await expectAnchor(page, saved);
471474
// Reflow can arrive after Virtua's 150ms imperative-scroll scheduler ends.
472475
// Keep the selected reading anchor, not the partially clipped row above it.
473-
await page.waitForTimeout(250);
476+
await page.clock.runFor(150);
474477
const preceding = await history.evaluate((element, id) => {
475478
const rows = [...element.querySelectorAll("[data-message-id]")];
476479
const index = rows.findIndex((row) => row.dataset.messageId === id);

‎tests/browser/navigation-groups.spec.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -757,9 +757,9 @@ test("Projects → Messages keeps saved groups, selected channel, and scroll on
757757
await expect(
758758
page.getByRole("textbox", { name: "Message #Beta", exact: true }),
759759
).toBeVisible();
760-
await page.waitForTimeout(300); // Keep the decode path held for the full interval.
761760
// Wall time does not guarantee RAF callbacks on a busy runner. Wait for
762761
// samples, not correct samples: every earlier frame stays in the assertion.
762+
// The decode path stays held until finally, across all sampled frames.
763763
await page.waitForFunction(() => window.sidebarFrames.length > 3);
764764
const frames = await page.evaluate(() => {
765765
window.captureSidebar = false;

‎tests/browser/sidebar-unread.spec.mjs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -251,17 +251,26 @@ test("edge pills follow scroll and reveal the nearest unread without selection o
251251
"data-channel-id",
252252
"alpha",
253253
);
254+
// Barrier: focusing the revealed row prepares it and requests its head.
255+
// The owner allows one speculative read with no backlog, so the next reveal
256+
// may legitimately skip its own read while this one is in flight.
257+
await expect
258+
.poll(() =>
259+
heads(app)
260+
.slice(before)
261+
.map(({ filter }) => filter["#h"][0]),
262+
)
263+
.toContain("dm-030");
254264
await cue(page, "below").focus();
255265
await cue(page, "below").press("Enter");
256266
await expect.poll(() => inView(page, "dm-090")).toBe(true);
257267
await expect(cue(page, "below")).toHaveCount(0);
258268
expect(await list(page).boundingBox()).toEqual(size); // Overlay never resizes the list.
259-
await page.waitForTimeout(1000);
260269
const warmed = heads(app)
261270
.slice(before)
262271
.map(({ filter }) => filter["#h"][0]);
263-
// Background roster warmth reads each channel once, serially. Scroll and cue
264-
// interactions never add a repeated read on top of it.
272+
// A revealed channel is read at most once. Scroll and cue interactions never
273+
// add a repeated read.
265274
expect(new Set(warmed).size).toBe(warmed.length);
266275
expect(app.report.readPublications).toEqual([]);
267276
expect(

‎tests/browser/thread-unread.spec.mjs‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ test("thread buttons show observed unread independently, clear only after readin
4545
page,
4646
app,
4747
}, testInfo) => {
48+
// Reading needs a 750ms dwell (use-reading.ts). The clock runs that deadline
49+
// exactly where the test proves that something is not reading.
50+
await page.clock.install();
4851
await open(page, app);
4952
const roots = app.histories
5053
.get("primary/alpha")
@@ -209,7 +212,7 @@ test("thread buttons show observed unread independently, clear only after readin
209212
exact: true,
210213
});
211214
await replyComposer.focus();
212-
await page.waitForTimeout(1000);
215+
await page.clock.runFor(750);
213216
await expect(replyComposer).toBeFocused();
214217
await expect(first).toHaveAccessibleName(/Observed unread replies/); // Click/composer focus is not reading.
215218
await history.focus();
@@ -245,8 +248,17 @@ test("thread buttons show observed unread independently, clear only after readin
245248
await panel
246249
.getByRole("button", { name: "Close thread", exact: true })
247250
.click();
248-
app.reply(roots[0].id, true);
249-
await page.waitForTimeout(1000);
251+
const own = app.reply(roots[0].id, true);
252+
// Barrier: the session has indexed the reply, so its unread effect is final.
253+
await expect
254+
.poll(() =>
255+
page.evaluate(
256+
(id) =>
257+
window.fixtureRelay.snapshot().session.unread.attention("alpha", id),
258+
own.id,
259+
),
260+
)
261+
.toMatchObject({ status: "ineligible", unread: false });
250262
await expect(first).toHaveAccessibleName("View thread: 23 replies");
251263
app.reply(roots[0].id);
252264
await expect(first).toHaveAccessibleName(/Observed unread replies/);

0 commit comments

Comments
 (0)