Skip to content
Merged
7 changes: 7 additions & 0 deletions docs/process/test-waits.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// <reference types="@vitest/browser-playwright" />
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";
Expand Down Expand Up @@ -227,14 +227,17 @@ 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");
targets[0].focus();
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);
Expand All @@ -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" }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -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" }] }] });
Expand Down
3 changes: 2 additions & 1 deletion packages/ui-react/tests/browser/conversation.offline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-react/tests/browser/recording-limits.offline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions packages/ui-react/tests/browser/share-review/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>` 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<LockManager["request"]>) {
const pending = (lockRequest as (...args: Parameters<LockManager["request"]>) => Promise<unknown>).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;
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading