diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md
index 833d618324..7986c6f8c8 100644
--- a/docs/process/test-waits.md
+++ b/docs/process/test-waits.md
@@ -128,6 +128,13 @@ any reclassification and its mutation receipts.
| Failure maxima, reason in source | `app-http-drain`, `app-metadata-cancellation`, `close-cancels-shared-runs`, `dialogue-storage`, `reference-source`, `reference-tools` and `write-worker` races whose expected outcome settles first | The deadline branch is never awaited on success. |
| Negative windows kept, reason in source | Writer-gate waiters in `host-fallback-gates` and `schedule-ignore-admission`; the `reference-writes-offloop` `pending` helper; app shutdown in `app-writer-cleanup`; the replayed tombstone in `contextual-refusals`; the `relayed-runtime-traffic-probe` exit window | A gate waiter polls every 5 ms and reports no refused attempt. The `pending` helper's callers read database rows that must be read inside the hold. A marker request for the replayed tombstone would start its own turn and change the counts. The shutdown windows cover real-IO round trips that correct code never completes, so no event marks them. |
| Kept real time, reason in source | `native-identity-inspector` abort during a blocking FIFO open; geo `routing` admission-write latency while the transport deadline is armed; the delayed-fsync spies in `native-observation-storage`, `transcript-archive` and `native-observation-settlement` (event-loop liveness under slow IO) | The inspector's blocked state has no portable signal. The geo latency and fsync delays are the stimulus itself. |
+| ui-react `share-review/commands.ts`, review admission refused or retired | A failed copy, another account, a live owner in another tab, a racing tab or an expired record never admits review | The fixture counts its share-review lock requests and their settlements; a request that admits stays open. The command waits until a request made after a mark has settled, or a review is admitted, instead of 1.2–1.5 s. The racing loser waits for an attempt made after the winner admitted. Where the account's review rows and stashed originals are empty or sealed, nothing can be admitted, so no window is needed. Dismiss waits for the queue to empty, which follows the durable delete. |
+| Same file, a lost response | The upload's response opens, then loses its body, so Chromium cannot retry it transparently | The socket closes from the write callback of the partial body, instead of 50 ms later. Closing before the flush lets Chromium retry, and the case fails. |
+| ui-react `storage-guidance.layout.tsx`, late and refused responses | A response for the prior account or a replaced root never replaces current evidence; a refused route never opens Settings | The fixture counts the responses it answers and the bodies the consumer reads. The tests wait for the held response to be read, or for the route's refused read to be answered, instead of 50 ms. The route change is committed with `flushSync`, so its open decision has run. |
+| ui-react `transcript-qualifiers.offline.tsx` and `conversation-controls.offline.tsx`, tooltip and reply holds | Escape keeps a qualifier hint hidden; the pointer can rest on a hint; short playback gaps keep Speaking | The qualifier's 300 ms show and 150 ms hide timers, and the strip's 300 ms reply hold, run on vitest's fake `setTimeout`. The tests advance them or run every pending timer, instead of 350 ms windows and real gaps. |
+| ui-react `conversation-endpoint`, `conversation-consent` and `conversation.offline.tsx` | No speech block arrives after the drain; consent alone, or a pending opening after Mute, never reopens capture | The first audio frame below the speaking threshold follows every queued speaking block, instead of a 200 ms drain. Frames are handled on delivery and a capture calls `getUserMedia` synchronously, so the consent cases read the open count once epoch 2 is applied, or at once, instead of after 100 ms or 30 ms. |
+| Kept, reason in source | ui-react `recording-limits` source starvation; the drains in `dialogue-browser-server` and `contextual-conversation-browser-server` | The starvation is the real-time stimulus. The fixture drains only pace or batch frames: tests poll step replies for every outcome. |
+| Reclassified, no change | `hygiene-lifecycle-command` 234 (cancellation-safety release cap); `storage-server-command` 39 (startup failure maximum); `liveness-clock` 53 (the page timer under the controlled clock) | Each is a maximum or the timer under test, and its reason is in source. |
## Continuity settling boundaries
diff --git a/packages/ui-react/tests/browser/conversation-consent.offline.tsx b/packages/ui-react/tests/browser/conversation-consent.offline.tsx
index 2f194aa0eb..c4e69df828 100644
--- a/packages/ui-react/tests/browser/conversation-consent.offline.tsx
+++ b/packages/ui-react/tests/browser/conversation-consent.offline.tsx
@@ -104,9 +104,13 @@ test("review: provider closure during pending opening settles without late captu
s.deliver({ type: "conversation_closed", conversationId: PROFILE.conversationId, epoch: 1, reason: "provider_closed" });
s.client.mute();
s.opened(2);
- await new Promise(resolve => setTimeout(resolve, 100));
- expect(s.client.state.getState().micOn).toBe(false);
+ // Frames are handled as they are delivered, and a capture opens the
+ // microphone synchronously, so once epoch 2 is applied any capture its
+ // opening or readiness allowed has already called getUserMedia. Without a
+ // new capture session the microphone cannot turn on later.
+ await expect.poll(() => s.client.state.getState().profile?.epoch).toBe(2);
expect(mic.opens()).toBe(1);
+ expect(s.client.state.getState().micOn).toBe(false);
});
test("review: hiding during replacement opening cannot delete the retained conversation", async ctx => {
diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx
index f4ad7eb276..1c83c74775 100644
--- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx
+++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx
@@ -1,5 +1,5 @@
///
-import { afterAll, beforeAll, expect, test, type TestContext } from "vitest";
+import { afterAll, beforeAll, expect, test, vi, type TestContext } from "vitest";
import { commands, page, userEvent } from "vitest/browser";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
@@ -227,6 +227,9 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale
const bounds = targets.map(node => node.getBoundingClientRect());
expect(targets[1].getAttribute("aria-disabled")).toBe("true");
for (const box of bounds) { expect(box.height).toBeGreaterThanOrEqual(44); expect(box.width).toBeGreaterThanOrEqual(44); }
+ // The strip holds Speaking for 300 ms after playback stops. That timer runs
+ // on a fake clock, so each gap is exact rather than a real wait.
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); });
for (const gap of [10, 40, 100, 20]) {
flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" }));
await expect.element(page.getByRole("button", { name: "Stop reply", exact: true })).not.toHaveAttribute("aria-disabled", "true");
@@ -234,7 +237,7 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale
await userEvent.keyboard("{Tab}");
expect(document.activeElement, "Tab reaches Stop reply in its stable slot").toBe(targets[1]);
flushSync(() => s.client.state.setState({ playing: false, interaction: gap === 40 ? "Listening" : "Review before sending" }));
- await new Promise(resolve => setTimeout(resolve, gap));
+ flushSync(() => vi.advanceTimersByTime(gap));
expect(s.strip().children[1].textContent, "short PCM gaps retain Speaking feedback").toContain("Speaking");
expect(s.client.state.getState().micOn, "display smoothing must not mute or resume capture").toBe(true);
expect(s.client.state.getState().playing, "presentation must not alter sample-level state").toBe(false);
@@ -248,6 +251,8 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale
expect(document.activeElement).toBe(targets[1]);
}
await s.capture("reply-gap");
+ flushSync(() => vi.runOnlyPendingTimers());
+ vi.useRealTimers();
await expect.poll(() => targets[1].getAttribute("aria-disabled")).toBe("true");
expect(s.strip().children[1].textContent).toContain("Review before sending");
flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" }));
diff --git a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx
index 195f16905b..2dbb7df257 100644
--- a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx
+++ b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx
@@ -84,6 +84,14 @@ function controlledMicrophone(ctx: TestContext, freshStreams = false) {
+/** A PCM16 frame below the client's speaking threshold (RMS 0.015). */
+function silent(pcm: string) {
+ const bytes = Uint8Array.from(atob(pcm), char => char.charCodeAt(0)), view = new DataView(bytes.buffer);
+ let energy = 0;
+ for (let i = 0; i < bytes.length; i += 2) energy += (view.getInt16(i, true) / 32768) ** 2;
+ return Math.sqrt(energy / (bytes.length / 2)) <= 0.015;
+}
+
// Real AudioWorklet capture and playback exercise the interval before the
// natural 700 ms endpoint. Provider frames remain entirely offline.
for (const action of ["send", "discard", "answer", "mute"] as const) for (const noisy of [false, true]) test(`manual ${action}: ${noisy ? "bounded noisy deadline" : "quiet recovery"} after interrupted speech`, async ctx => {
@@ -99,9 +107,12 @@ for (const action of ["send", "discard", "answer", "mute"] as const) for (const
await expect.poll(() => s.client.state.getState().playing).toBe(true);
mic.speak();
await expect.poll(() => s.client.state.getState().outputRecovery).toBe("speaking");
+ const quietFrom = s.socket.frames("conversation_audio").length;
mic.quiet();
// Drain queued real microphone blocks, still before the 700 ms endpoint.
- await new Promise(resolve => setTimeout(resolve, 200));
+ // Blocks arrive in order, so the first frame below the client's speaking
+ // threshold follows every speaking block queued before quiet().
+ await expect.poll(() => s.socket.frames("conversation_audio").slice(quietFrom).some(frame => silent(String(frame.pcm)))).toBe(true);
if (action === "answer") {
s.deliver({ type: "text_delta", sessionId: SESSION, turnId: "ithaca-turn", text: "Which departure works?" });
s.deliver({ type: "ask_user_request", sessionId: SESSION, turnId: "ithaca-turn", requestId: "ithaca-question", questions: [{ question: "Which day?", header: "Day", multiSelect: false, options: [{ label: "Tomorrow", description: "Before departure" }] }] });
diff --git a/packages/ui-react/tests/browser/conversation.offline.tsx b/packages/ui-react/tests/browser/conversation.offline.tsx
index 34ca2dd83d..bc4619a7eb 100644
--- a/packages/ui-react/tests/browser/conversation.offline.tsx
+++ b/packages/ui-react/tests/browser/conversation.offline.tsx
@@ -1246,7 +1246,8 @@ for (const reason of ["disconnected", "provider_closed"] as const) test(`recover
expect(mic.streams[0]!.getTracks().every(track => track.readyState === "ended")).toBe(true);
expect(s.client.state.getState().text).toBe("Ask Nestor about the ships");
// Withhold the replacement receipt: consent alone cannot reopen capture.
- await new Promise(resolve => setTimeout(resolve, 30));
+ // The closure was handled as it was delivered, and a capture opens the
+ // microphone synchronously, so no window is needed to see that none started.
assertPrivate();
expect(mic.opens()).toBe(1);
s.opened(2);
diff --git a/packages/ui-react/tests/browser/recording-limits.offline.tsx b/packages/ui-react/tests/browser/recording-limits.offline.tsx
index 66dadbdf7c..2b87283fd6 100644
--- a/packages/ui-react/tests/browser/recording-limits.offline.tsx
+++ b/packages/ui-react/tests/browser/recording-limits.offline.tsx
@@ -183,6 +183,9 @@ test("source starvation reports only encoded audio", async (ctx) => {
const capture = await c.store.start({ timesliceMs: 250 });
await expect.poll(() => c.events.filter(e => e.kind === "committed").length).toBeGreaterThanOrEqual(2);
await mic.contexts[0]!.suspend();
+ // Kept: the starvation is real time under test. The suspended source must
+ // stay silent for longer than the 800 ms margin asserted below, while the
+ // wall clock runs, so no condition or fake clock can stand in for it.
await new Promise(resolve => setTimeout(resolve, 1200));
await mic.contexts[0]!.resume();
const before = c.events.filter(e => e.kind === "committed").length;
diff --git a/packages/ui-react/tests/browser/share-review/app.tsx b/packages/ui-react/tests/browser/share-review/app.tsx
index 667da493f8..11f1a28a42 100644
--- a/packages/ui-react/tests/browser/share-review/app.tsx
+++ b/packages/ui-react/tests/browser/share-review/app.tsx
@@ -31,6 +31,26 @@ window.addEventListener("pagehide", () => {
if (onlineDescriptor) Object.defineProperty(navigator, "onLine", onlineDescriptor);
else delete (navigator as { onLine?: boolean }).onLine;
});
+// Review admission takes the native lock `brain-ui:share-review:` with
+// `ifAvailable` (`holdShareReview`, src/lib/share-review.ts). A request that
+// admits the review stays open while this tab owns it; every other request
+// settles once its attempt ends: the lock was taken elsewhere, the original
+// could not be recovered for this account, or recovery failed. Counting
+// requests and settlements lets a test wait for this tab's admission decision
+// instead of a fixed window. The native lock itself is untouched.
+const locks = navigator.locks;
+const lockRequest = locks.request;
+const admission = { requested: 0, settled: 0 };
+Object.defineProperty(locks, "request", { configurable: true, value(this: LockManager, ...args: Parameters) {
+ const pending = (lockRequest as (...args: Parameters) => Promise).apply(this, args);
+ if (String(args[0]).startsWith("brain-ui:share-review:")) {
+ admission.requested++;
+ const settle = () => { admission.settled++; };
+ pending.then(settle, settle);
+ }
+ return pending;
+} });
+window.addEventListener("pagehide", () => Reflect.deleteProperty(locks, "request"));
let holdAdmission = false;
let refuseSend = false;
let pendingAdmission: { requestId: string } | undefined;
@@ -81,6 +101,7 @@ const fixture = {
refuseSend: () => { refuseSend = true; },
startConfirm: () => { void intake!.confirm(ui.stores.share.getState().queue[0]!); },
pending: () => pendingAdmission !== undefined,
+ admission: () => ({ ...admission }),
accept: () => {
if (!pendingAdmission) return;
const { requestId } = pendingAdmission;
diff --git a/packages/ui-react/tests/browser/share-review/commands.ts b/packages/ui-react/tests/browser/share-review/commands.ts
index ecd6ace89e..bbd610a204 100644
--- a/packages/ui-react/tests/browser/share-review/commands.ts
+++ b/packages/ui-react/tests/browser/share-review/commands.ts
@@ -14,7 +14,23 @@ async function action(page: Page, method: string): Promise {
return page.evaluate(method => (window as unknown as { shareProof: Record unknown> }).shareProof[method]!(), method) as Promise;
}
async function ready(page: Page) { await page.waitForFunction(() => "shareProof" in window); }
+type Admission = { requested: number; settled: number };
+const admission = (page: Page) => action(page, "admission");
+/**
+ * Wait for this page's review admission to decide, instead of a fixed window.
+ * Decided means a review was admitted, or at least one share-review lock
+ * request was made after `since` and every request has settled: each attempt
+ * ended without holding review (see `admission` in app.tsx).
+ */
+async function decided(page: Page, since = 0) {
+ await page.waitForFunction(since => {
+ const proof = (window as unknown as { shareProof: { queue(): string[]; admission(): Admission } }).shareProof;
+ const { requested, settled } = proof.admission();
+ return proof.queue().length > 0 || (requested > since && settled === requested);
+ }, since);
+}
async function queue(page: Page) { await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 1); }
+async function empty(page: Page) { await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 0); }
async function original(page: Page) {
const originals = await action(page, "inventory");
assert.equal(originals.length, 1, "one durable original remains before authoritative handoff");
@@ -39,8 +55,8 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
if (scenario === "lost-response" && uploads === 1) {
// Start the response before losing its body. An unopened response on
// a reused connection can be transparently retried by Chromium.
- res.writeHead(201, { "content-type": "application/json" }); res.write("{");
- setTimeout(() => res.destroy(), 50); return;
+ // Close only after the opened response is flushed to the socket.
+ res.writeHead(201, { "content-type": "application/json" }); res.write("{", () => res.destroy()); return;
}
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ ...(scenario === "lost-admission" && uploads > 1 ? { filingSessionId: "odysseus-filing" } : {}), id: "odysseus-intake", receivedAt: Date.now(), dir: ".brain/inbox/odysseus-intake", text: "Penelope keeps the original loom plan.", files: scenario === "partial" ? [] : [{ name: "loom.pdf", path: ".brain/inbox/odysseus-intake/loom.pdf", mediaType: "application/pdf", bytes: 5 }] }));
@@ -64,7 +80,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
const landing = await action(page, "stash");
if (scenario === "transfer" || scenario === "transfer-signout") {
const faulty = new URL(landing); faulty.searchParams.set("copyFailure", "yes");
- await page.goto(faulty.href); await ready(page); await page.waitForTimeout(1200);
+ await page.goto(faulty.href); await ready(page); await decided(page);
assert.deepEqual(await action(page, "queue"), [], "failed durable copy never admits memory-only review");
await original(page);
assert.equal((await action<{ shares: number }>(page, "loss")).shares, 1, "sign-out inventory includes the interrupted transfer");
@@ -73,7 +89,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
assert.deepEqual(await action(page, "cleared"), { originals: 0, account: true }, "intentional sign-out removes the transfer remnant as well as account work");
assert.equal(uploads, 0); assert.deepEqual(egress, []); return "passed";
}
- const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other); await other.waitForTimeout(1200);
+ const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other); await decided(other);
assert.deepEqual(await action(other, "queue"), [], "transfer journal prevents cross-account adoption after a failed copy");
await other.close(); await page.goto(landing); await ready(page); await queue(page); await original(page);
assert.equal(uploads, 0); assert.deepEqual(egress, [], "fixture has no external egress"); return "passed";
@@ -116,9 +132,11 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
await action(page, "expire");
assert.deepEqual(await action(page, "queue"), [], "auth lock drops the memory payload");
const other = await context.newPage(); await other.goto(`${origin}/?account=odysseus-sparta`); await ready(other);
- await other.waitForTimeout(1500);
- assert.deepEqual(await action(other, "queue"), [], "another account cannot recover this original");
+ // Admission reads only this account's review rows and the stashed
+ // originals, which `inventory` reads too. Both are empty, so this page
+ // has nothing it could admit and the queue check needs no window.
assert.deepEqual(await action(other, "inventory"), [], "another account cannot read this original");
+ assert.deepEqual(await action(other, "queue"), [], "another account cannot recover this original");
await other.close();
assert.equal(await action(page, "restore"), true, "real auth lock restores the same account");
await queue(page); await original(page); assert.equal(uploads, 0);
@@ -127,7 +145,8 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
assert.deepEqual(await action(page, "queue"), [], "unmount drops review memory when releasing ownership");
await original(page);
const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await queue(peer);
- await action(page, "remount"); await page.waitForTimeout(1200);
+ const since = (await admission(page)).requested;
+ await action(page, "remount"); await decided(page, since);
assert.deepEqual(await action(page, "queue"), [], "a remounted root cannot show another tab's review");
await peer.close(); await queue(page); await original(page);
assert.equal(uploads, 0);
@@ -135,7 +154,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
await action(page, "mountSecond"); await action(page, "unmount");
assert.equal((await action(page, "queue")).length, 1, "a remaining consumer keeps the root's ownership");
await action(page, "confirm"); await original(page);
- const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await peer.waitForTimeout(1200);
+ const peer = await context.newPage(); await peer.goto(origin); await ready(peer); await decided(peer);
assert.deepEqual(await action(peer, "queue"), [], "another tab cannot claim a root with a live consumer");
await action(page, "resume");
await page.waitForFunction(() => (window as unknown as { shareProof: { queue(): string[] } }).shareProof.queue().length === 0);
@@ -159,16 +178,25 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
await page.close();
const [first, second] = await Promise.all([context.newPage(), context.newPage()]);
await Promise.all([first.goto(landing), second.goto(landing)]); await Promise.all([ready(first), ready(second)]);
- await first.waitForTimeout(1500);
+ // Wait for one tab to admit. The other's first attempt may have run while
+ // the closed owner still held the lock, so wait for one of its attempts
+ // that starts after the admission: that one meets the winner's lock.
+ const admitted = [first, second].map(tab => queue(tab).then(() => tab));
+ admitted.forEach(wait => wait.catch(() => {}));
+ const loser = await Promise.race(admitted) === first ? second : first;
+ await decided(loser, (await admission(loser)).requested);
const counts = [(await action(first, "queue")).length, (await action(second, "queue")).length];
assert.equal(counts[0]! + counts[1]!, 1, "native lock admits exactly one racing tab");
const owner = counts[0] ? first : second; const survivor = counts[0] ? second : first;
await owner.close(); await queue(survivor); await original(survivor);
assert.equal(uploads, 0, "abandonment does not grant consent");
} else if (scenario === "dismiss") {
- await action(page, "dismiss"); await page.waitForTimeout(100);
+ // Dismiss removes the review from the queue only after its durable delete.
+ await action(page, "dismiss"); await empty(page);
assert.deepEqual(await action(page, "inventory"), [], "dismiss commits durable cleanup");
- await page.reload(); await ready(page); await page.waitForTimeout(1200);
+ await page.reload(); await ready(page);
+ // Nothing is left to admit (see "auth"), so the queue check needs no window.
+ assert.deepEqual(await action(page, "inventory"), []);
assert.deepEqual(await action(page, "queue"), []); assert.equal(uploads, 0);
} else if (scenario === "signout") {
assert.equal((await action<{ shares: number }>(page, "loss")).shares, 1, "sign-out warns about the retained original");
@@ -186,11 +214,14 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
await page.getByRole("button", { name: "Keep working", exact: true }).click();
await original(page);
await action(page, "clear"); await page.close();
- const fresh = await context.newPage(); await fresh.goto(origin); await ready(fresh); await fresh.waitForTimeout(1200);
+ const fresh = await context.newPage(); await fresh.goto(origin); await ready(fresh);
+ // Sign-out removed the originals and sealed the account partition, so
+ // this page has nothing it could admit and the queue check needs no window.
+ assert.deepEqual(await action(fresh, "cleared"), { originals: 0, account: true }, "account sign-out clear removes retained originals");
assert.deepEqual(await action(fresh, "queue"), [], "account sign-out clear removes retained shares");
assert.equal(uploads, 0);
} else if (scenario === "ttl") {
- await action(page, "expireRecord"); await page.reload(); await ready(page); await page.waitForTimeout(1200);
+ await action(page, "expireRecord"); await page.reload(); await ready(page); await decided(page);
assert.deepEqual(await action(page, "queue"), [], "expired account reviews are not admitted");
assert.deepEqual(await action(page, "inventory"), [], "existing TTL bounds retained originals");
assert.equal(uploads, 0);
@@ -198,7 +229,7 @@ export const shareReview: BrowserCommand<[Scenario], string> = async (ctx, scena
await action(page, "resume"); await action(page, "confirm");
assert.equal(uploads, 1); await original(page);
assert.equal(await action(page, "chats"), 0, "incomplete receipt never hands off or starts chat");
- await action(page, "dismiss"); await page.waitForTimeout(100);
+ await action(page, "dismiss"); await empty(page);
assert.deepEqual(await action(page, "inventory"), []);
} else {
if (scenario === "lost-response") await action(page, "resume");
diff --git a/packages/ui-react/tests/browser/storage-guidance.layout.tsx b/packages/ui-react/tests/browser/storage-guidance.layout.tsx
index a6382cb0aa..712ecf5452 100644
--- a/packages/ui-react/tests/browser/storage-guidance.layout.tsx
+++ b/packages/ui-react/tests/browser/storage-guidance.layout.tsx
@@ -293,8 +293,10 @@ test("A late response from the prior account cannot replace current evidence", a
f.guidance.capacities[0]!.severity = "low";
ui.stores.connection.getState().setVpnStatus("connected", "athena");
await expect.poll(() => warning()?.textContent).toContain("Low space");
+ const delivered = f.delivered();
release();
- await new Promise((resolve) => setTimeout(resolve, 50));
+ // The late response has been read; its ownership check has run.
+ await expect.poll(f.delivered).toBeGreaterThan(delivered);
expect(
warning()?.textContent,
"STORAGE_ACCOUNT_RESPONSE_OWNERSHIP"
@@ -325,8 +327,12 @@ test("Indicator and authenticated tap-through honor Settings leave guards and cl
refresh();
await expect.poll(warning).toBeNull();
history.replaceState(null, "", "#/settings/storage");
- window.dispatchEvent(new HashChangeEvent("hashchange"));
- await new Promise((resolve) => setTimeout(resolve, 50));
+ const answered = f.answered();
+ // Commit the route change and its effects synchronously: the open decision
+ // has run when flushSync returns. Then wait for the read the route starts
+ // to be answered (refused) and handled, so the next refresh is a new read.
+ flushSync(() => window.dispatchEvent(new HashChangeEvent("hashchange")));
+ await expect.poll(f.answered).toBeGreaterThan(answered);
expect(
ui.stores.ui.getState().settingsPanelOpen,
"STORAGE_TAP_REQUIRES_AUTHORITY"
@@ -449,8 +455,10 @@ test("A replaced root cannot publish its late operational response", async () =>
)
);
await expect.poll(() => next.reads.length).toBeGreaterThan(0);
+ const delivered = oldFixture.delivered();
release();
- await new Promise((resolve) => setTimeout(resolve, 50));
+ // The old root's late response has been read; its ownership check has run.
+ await expect.poll(oldFixture.delivered).toBeGreaterThan(delivered);
expect(warning(), "STORAGE_REPLACED_ROOT_HIDES_OLD_GUIDANCE").toBeNull();
old.dispose();
});
diff --git a/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx b/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx
index 0086dd19ff..82cee5dc5a 100644
--- a/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx
+++ b/packages/ui-react/tests/browser/transcript-qualifiers.offline.tsx
@@ -1,5 +1,5 @@
///
-import { afterAll, beforeAll, expect, test, type TestContext } from "vitest";
+import { afterAll, beforeAll, expect, test, vi, type TestContext } from "vitest";
import { commands, page, userEvent } from "vitest/browser";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
@@ -61,7 +61,11 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280])
const box = trigger.getBoundingClientRect();
expect(box.width).toBeGreaterThanOrEqual(44); expect(box.height).toBeGreaterThanOrEqual(44);
for (const [x,y] of [[box.left + 2,box.top + box.height/2],[box.right-2,box.top+box.height/2],[box.left+box.width/2,box.top+2],[box.left+box.width/2,box.bottom-2]]) expect(document.elementFromPoint(x,y)?.closest("button")).toBe(trigger);
+ // The qualifier's 300 ms show delay and 150 ms hide grace run on a fake
+ // clock, so "every pending timer has run" is a step, not a window.
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); });
trigger.focus();
+ flushSync(() => vi.advanceTimersByTime(300));
await expect.poll(() => document.querySelector('[role="tooltip"]')?.textContent).toContain("Words may be uncertain; speaker unverified.");
const hint = document.querySelector('[role="tooltip"]')!;
expect(hint.getBoundingClientRect().left).toBeGreaterThanOrEqual(0);
@@ -70,8 +74,9 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280])
expect(getComputedStyle(trigger).outlineWidth).toBe("2px");
await userEvent.keyboard("{Escape}");
await expect.poll(() => document.querySelector('[role="tooltip"]')).toBeNull();
- await new Promise(r => setTimeout(r, 350));
+ flushSync(() => vi.runOnlyPendingTimers());
expect(document.querySelector('[role="tooltip"]'), "Escape suppresses while still focused").toBeNull();
+ vi.useRealTimers();
await userEvent.keyboard("{Enter}");
const dialog = document.querySelector('dialog[open]')!;
expect(dialog, "native Enter opens evidence").not.toBeNull();
@@ -104,12 +109,16 @@ test("pointer can read tooltip then tap details; playback and restoration are in
const s = await scene(ctx, 320, "light", 1, false);
s.render(<>>);
const trigger = qualifier(s.host, "generated");
+ // As above: the show delay and hide grace run on a fake clock.
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); });
await userEvent.hover(trigger);
+ flushSync(() => vi.advanceTimersByTime(300));
await expect.poll(() => document.querySelector('[role="tooltip"]')?.textContent).toContain("Remaining reply not spoken locally. Earlier spoken portion unknown.");
const hint = document.querySelector('[role="tooltip"]')!;
await userEvent.hover(hint);
- await new Promise(r => setTimeout(r, 350));
+ flushSync(() => vi.runOnlyPendingTimers());
expect(hint.isConnected, "hoverable explanation persists").toBe(true);
+ vi.useRealTimers();
await userEvent.keyboard("{Escape}");
expect(document.querySelector('[role="tooltip"]')).toBeNull();
const box = trigger.getBoundingClientRect();
diff --git a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts
index 26ccf2c068..112a1f03e0 100644
--- a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts
+++ b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts
@@ -157,6 +157,8 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
if (body.releaseValidation) releaseValidation();
if (body.identify) identify();
if (body.release) release();
+ // Kept, pacing only: the reply is a snapshot, and tests poll "step" until
+ // their condition holds, so this drain only batches more frames into it.
await Bun.sleep(10);
return Response.json({ frames: frames.splice(0), sent: sent.splice(0), tasks, released, opening, validationHeld, validationCalls, historyPending: pendingHistory.length > 0, providerOpens, providerCloses, missingChatExists: catalog.hasSession!("odysseus-ithaca"), effect: existsSync(join(root, "notes/contextual-raft.md")) });
} });
diff --git a/packages/ui-react/tests/fixtures/dialogue-browser-server.ts b/packages/ui-react/tests/fixtures/dialogue-browser-server.ts
index a99c7c805a..2bbed7843d 100644
--- a/packages/ui-react/tests/fixtures/dialogue-browser-server.ts
+++ b/packages/ui-react/tests/fixtures/dialogue-browser-server.ts
@@ -237,6 +237,10 @@ const server = Bun.serve({
if(body.parallelStarts && (frame as {type?:string}).type==="conversation_start") parallel!.handlers.onMessage({data:JSON.stringify({...frame as object,requestId:"pylos-parallel",disclosed:host.conversations!.profile(true)})} as MessageEvent,parallel!.ws);
}
if(body.parallelLeave && parallel){const opened=parallel.frames.find(f=>f.type==="conversation_opened");if(opened?.type!=="conversation_opened")throw Error("Parallel conversation did not open");parallel.handlers.onMessage({data:JSON.stringify({type:"conversation_stop",conversationId:opened.conversationId})} as MessageEvent,parallel.ws);}
+ // Kept, pacing only: each client frame's dispatch starts on a microtask
+ // and has no completion handle (createWsHandlers onMessage). The browser
+ // tests poll "step" replies until their condition holds, so this drain
+ // only lets one reply carry the frames' effects; it decides no outcome.
await Bun.sleep(10);
if(body.backendPrefix) emitPrefix?.(body.backendPrefix);
if (body.seedTypedHistory) {
@@ -275,6 +279,8 @@ const server = Bun.serve({
}
let delivered=0;
for (const frame of body.provider ?? []) {
+ // Kept, pacing for the interleaving under test: the task completes during
+ // delivery, between two provider frames. Tests poll for the outcome.
if(body.finishDuring===delivered){if(body.resultText)FACT=body.resultText;complete?.();await Bun.sleep(5);}
ingress.push(frame);delivered++;
if (remote?.readyState === WebSocket.OPEN) remote.send(JSON.stringify(frame));
@@ -286,6 +292,9 @@ const server = Bun.serve({
backendTailQuota=body.backendTailQuota===true; multipart=body.multipart===true;
failResult=body.failResult===true;
if (body.release) complete?.();
+ // Kept, pacing under the held writer, as above: the adapter consumes these
+ // frames while the quota or pressure hold is still in place. Tests poll
+ // for the outcome; historySettled below is the barrier when no writes are held.
await Bun.sleep(20);
await releaseQuota?.();
if(body.expireWrites){deadlineClock?.expire();await new Promise(resolve=>setImmediate(resolve));}
diff --git a/packages/ui-react/tests/fixtures/storage-guidance.ts b/packages/ui-react/tests/fixtures/storage-guidance.ts
index af50686f2f..cc64f8a464 100644
--- a/packages/ui-react/tests/fixtures/storage-guidance.ts
+++ b/packages/ui-react/tests/fixtures/storage-guidance.ts
@@ -167,6 +167,12 @@ export function storageGuidanceFixture() {
let status = 200,
hold: Promise | null = null;
const reads: string[] = [];
+ // Guidance and history responses handed to the consumer, and those whose
+ // body it has read. The consumer's handling runs in the microtasks that
+ // follow, so a test can wait for a response to have been handled instead of
+ // a fixed window. A refused response is answered but never read.
+ let answered = 0,
+ delivered = 0;
const request = async (url: string, init?: RequestInit) => {
const path = new URL(url, "http://fixture.invalid").pathname;
if (!path.endsWith("/guidance") && !path.endsWith("/history"))
@@ -178,10 +184,14 @@ export function storageGuidanceFixture() {
responseStatus = status,
wait = hold;
if (wait) await wait; // Intentionally ignores abort: exercise the consumer's response ownership guard.
- return Response.json(
+ const response = Response.json(
responseStatus === 200 ? body : { error: "Synthetic authority response" },
{ status: responseStatus }
);
+ const json = response.json.bind(response);
+ response.json = () => json().finally(() => { delivered++; });
+ answered++;
+ return response;
};
return {
inventory,
@@ -189,6 +199,8 @@ export function storageGuidanceFixture() {
history,
request,
reads,
+ answered: () => answered,
+ delivered: () => delivered,
setStatus(value: number) {
status = value;
},