CODY-024: the delayed sound is primed during its own press; CODY-023: README current-state rows
- soundCheck: prime() calls AudioContext.resume() synchronously in the click handler of both sound buttons; the delayed sound is scheduled only once the engine is running, and a refusal is shown and re-enables the button. - apps/even-client/test/soundCheck.test.ts: six tests with a fake, activation-gated sound engine. - README: every current-state row namese4c102a/ 0.4.0;44ea114is historical. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -50,26 +50,47 @@ export function mountSoundCheck(doc: Document, win: Window): HTMLElement {
|
||||
return context;
|
||||
};
|
||||
|
||||
/** Two short notes. Resolves with whether the sound engine was actually running. */
|
||||
async function tone(): Promise<string> {
|
||||
/**
|
||||
* Start the sound engine. MUST be called synchronously from a button's click handler: a
|
||||
* browser that blocks sound only lets `resume()` through while the press is still "active",
|
||||
* and that expires before any timer fires. Resolves with null when the engine is running, or
|
||||
* with the reason it is not. Never rejects.
|
||||
*/
|
||||
function prime(): Promise<string | null> {
|
||||
const ctx = getContext();
|
||||
if (!ctx) return 'no sound engine in this page';
|
||||
if (!ctx) return Promise.resolve('no sound engine in this page');
|
||||
let resumed: Promise<unknown>;
|
||||
try {
|
||||
await Promise.race([ctx.resume(), new Promise((r) => win.setTimeout(r, 800))]);
|
||||
resumed = ctx.resume();
|
||||
} catch (err) {
|
||||
return `blocked (${reason(err)})`;
|
||||
return Promise.resolve(`blocked (${reason(err)})`);
|
||||
}
|
||||
// A blocked resume() may never settle at all, so do not wait for it for ever.
|
||||
return Promise.race([resumed, new Promise((r) => win.setTimeout(r, 800))]).then(
|
||||
() => (ctx.state === 'running' ? null : `blocked (sound engine is ${ctx.state})`),
|
||||
(err) => `blocked (${reason(err)})`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Two short notes, if the engine can be started. Resolves with what happened. */
|
||||
async function tone(): Promise<string> {
|
||||
const blocked = await prime();
|
||||
const ctx = context;
|
||||
if (blocked || !ctx) return blocked ?? 'no sound engine in this page';
|
||||
try {
|
||||
const gain = ctx.createGain();
|
||||
gain.gain.value = 0.2;
|
||||
gain.connect(ctx.destination);
|
||||
[660, 880].forEach((frequency, i) => {
|
||||
const osc = ctx.createOscillator();
|
||||
osc.frequency.value = frequency;
|
||||
osc.connect(gain);
|
||||
osc.start(ctx.currentTime + i * 0.45);
|
||||
osc.stop(ctx.currentTime + i * 0.45 + 0.35);
|
||||
});
|
||||
} catch (err) {
|
||||
return `failed (${reason(err)})`;
|
||||
}
|
||||
if (ctx.state !== 'running') return `blocked (sound engine is ${ctx.state})`;
|
||||
const gain = ctx.createGain();
|
||||
gain.gain.value = 0.2;
|
||||
gain.connect(ctx.destination);
|
||||
[660, 880].forEach((frequency, i) => {
|
||||
const osc = ctx.createOscillator();
|
||||
osc.frequency.value = frequency;
|
||||
osc.connect(gain);
|
||||
osc.start(ctx.currentTime + i * 0.45);
|
||||
osc.stop(ctx.currentTime + i * 0.45 + 0.35);
|
||||
});
|
||||
return 'played';
|
||||
}
|
||||
const stamp = () => new Date().toLocaleTimeString();
|
||||
@@ -96,20 +117,30 @@ export function mountSoundCheck(doc: Document, win: Window): HTMLElement {
|
||||
void tone().then((outcome) => show('Test sound', `${outcome} at ${stamp()}`));
|
||||
});
|
||||
|
||||
// 3. A sound later, with nobody touching anything at that moment.
|
||||
// 3. A sound later, with nobody touching anything at that moment. The engine is started by
|
||||
// THIS press (see prime), so what is measured 20 s later is whether sound that was allowed
|
||||
// keeps working in the background, not whether the press has worn off.
|
||||
const laterButton = node(doc, 'button', `Play again in ${DELAY_SECONDS} s`, 'secondary');
|
||||
laterButton.type = 'button';
|
||||
laterButton.addEventListener('click', () => {
|
||||
laterButton.disabled = true;
|
||||
show('Delayed sound', `waiting since ${stamp()}; lock the phone or leave the app now`);
|
||||
const due = Date.now() + DELAY_SECONDS * 1000;
|
||||
win.setTimeout(() => {
|
||||
const lateMs = Date.now() - due;
|
||||
void tone().then((outcome) => {
|
||||
show('Delayed sound', `${outcome} at ${stamp()}${lateMs > 1500 ? `, ${Math.round(lateMs / 1000)} s late` : ''}`);
|
||||
show('Delayed sound', 'starting…');
|
||||
void prime().then((blocked) => {
|
||||
if (blocked) {
|
||||
show('Delayed sound', `not started: ${blocked} at ${stamp()}`);
|
||||
laterButton.disabled = false;
|
||||
});
|
||||
}, DELAY_SECONDS * 1000);
|
||||
return;
|
||||
}
|
||||
show('Delayed sound', `waiting since ${stamp()}; lock the phone or leave the app now`);
|
||||
const due = Date.now() + DELAY_SECONDS * 1000;
|
||||
win.setTimeout(() => {
|
||||
const lateMs = Date.now() - due;
|
||||
void tone().then((outcome) => {
|
||||
show('Delayed sound', `${outcome} at ${stamp()}${lateMs > 1500 ? `, ${Math.round(lateMs / 1000)} s late` : ''}`);
|
||||
laterButton.disabled = false;
|
||||
});
|
||||
}, DELAY_SECONDS * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
// The phone's own voice, as a free fallback to a paid one.
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// @vitest-environment happy-dom
|
||||
/**
|
||||
* The sound check against a FAKE sound engine in a FAKE browser (happy-dom). This shows what the
|
||||
* page asks for and when; it says nothing about what a real phone, WebView or earbud does.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mountSoundCheck } from '../src/ui/soundCheck.ts';
|
||||
|
||||
/** True only while a click is being dispatched, like a browser's transient user activation. */
|
||||
let pressing = false;
|
||||
type ResumeMode = 'gated' | 'rejects';
|
||||
|
||||
class FakeAudioContext {
|
||||
static instances: FakeAudioContext[] = [];
|
||||
static mode: ResumeMode = 'gated';
|
||||
state: 'suspended' | 'running' = 'suspended';
|
||||
currentTime = 0;
|
||||
destination = {};
|
||||
/** Whether each resume() call was made during a press. */
|
||||
resumeCalls: boolean[] = [];
|
||||
oscillators = 0;
|
||||
constructor() {
|
||||
FakeAudioContext.instances.push(this);
|
||||
}
|
||||
resume(): Promise<void> {
|
||||
this.resumeCalls.push(pressing);
|
||||
if (FakeAudioContext.mode === 'rejects') return Promise.reject(new DOMException('not allowed here', 'NotAllowedError'));
|
||||
if (this.state === 'running') return Promise.resolve();
|
||||
if (pressing) {
|
||||
this.state = 'running';
|
||||
return Promise.resolve();
|
||||
}
|
||||
// Blocked: like Chrome, the promise simply does not settle.
|
||||
return new Promise(() => {});
|
||||
}
|
||||
createGain() {
|
||||
return { gain: { value: 1 }, connect: () => {} };
|
||||
}
|
||||
createOscillator() {
|
||||
this.oscillators += 1;
|
||||
return { frequency: { value: 0 }, connect: () => {}, start: () => {}, stop: () => {} };
|
||||
}
|
||||
}
|
||||
|
||||
let speak: ReturnType<typeof vi.fn>;
|
||||
let enumerate: ReturnType<typeof vi.fn>;
|
||||
let fetchSpy: ReturnType<typeof vi.spyOn>;
|
||||
let storageSpy: ReturnType<typeof vi.spyOn>;
|
||||
let getUserMedia: ReturnType<typeof vi.fn>;
|
||||
let root: HTMLElement;
|
||||
|
||||
function mount(): void {
|
||||
const win = {
|
||||
AudioContext: FakeAudioContext,
|
||||
setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),
|
||||
speechSynthesis: { speak, getVoices: () => [] },
|
||||
SpeechSynthesisUtterance: class {
|
||||
onend: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
constructor(public text: string) {}
|
||||
},
|
||||
navigator: { mediaDevices: { enumerateDevices: enumerate, addEventListener: () => {}, getUserMedia } },
|
||||
};
|
||||
root = mountSoundCheck(document, win as unknown as Window);
|
||||
document.body.replaceChildren(root);
|
||||
}
|
||||
const button = (label: string) => [...root.querySelectorAll('button')].find((b) => b.textContent!.startsWith(label))!;
|
||||
const press = (b: HTMLButtonElement) => {
|
||||
pressing = true;
|
||||
try {
|
||||
b.click();
|
||||
} finally {
|
||||
pressing = false;
|
||||
}
|
||||
};
|
||||
const result = (key: string): string | undefined => {
|
||||
const dt = [...root.querySelectorAll('dt')].find((d) => d.textContent === key);
|
||||
return dt?.nextElementSibling?.textContent ?? undefined;
|
||||
};
|
||||
const ctx = () => FakeAudioContext.instances[0]!;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
FakeAudioContext.instances = [];
|
||||
FakeAudioContext.mode = 'gated';
|
||||
pressing = false;
|
||||
speak = vi.fn();
|
||||
getUserMedia = vi.fn();
|
||||
enumerate = vi.fn(async () => [
|
||||
{ kind: 'audiooutput', label: 'Buds' },
|
||||
{ kind: 'audioinput', label: '' },
|
||||
]);
|
||||
fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(''));
|
||||
storageSpy = vi.spyOn(Storage.prototype, 'setItem');
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('sound check (fake sound engine)', () => {
|
||||
it('on opening: no tone, no speech, no request, no storage, no microphone; reports that sound is blocked until a press', async () => {
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(FakeAudioContext.instances).toHaveLength(1);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
expect(speak).not.toHaveBeenCalled();
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(storageSpy).not.toHaveBeenCalled();
|
||||
expect(getUserMedia).not.toHaveBeenCalled();
|
||||
expect(result('Without touching the phone')).toBe('not allowed until a button here is pressed (suspended)');
|
||||
expect(result('Outputs this page can see')).toBe('1: Buds');
|
||||
expect(result('Test sound')).toBeUndefined();
|
||||
expect(result('Delayed sound')).toBeUndefined();
|
||||
// Still nothing a long time later.
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
expect(speak).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('the delayed button, used first and alone, starts the engine during its own press and plays 20 s later', async () => {
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const later = button('Play again in');
|
||||
const before = ctx().resumeCalls.length;
|
||||
press(later);
|
||||
// resume() was called synchronously, inside the press.
|
||||
expect(ctx().resumeCalls.slice(before)).toEqual([true]);
|
||||
expect(later.disabled).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx().state).toBe('running');
|
||||
expect(result('Delayed sound')).toMatch(/^waiting since .*lock the phone/);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(19_000);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
expect(later.disabled).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(1_100);
|
||||
expect(ctx().oscillators).toBe(2);
|
||||
expect(result('Delayed sound')).toMatch(/^played at /);
|
||||
expect(later.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('a delayed sound whose engine has stopped by the time it is due says so, and the button comes back', async () => {
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const later = button('Play again in');
|
||||
press(later);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
ctx().state = 'suspended'; // e.g. the page was put to sleep in the background
|
||||
await vi.advanceTimersByTimeAsync(21_000);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
expect(result('Delayed sound')).toMatch(/^blocked \(sound engine is suspended\) at /);
|
||||
expect(later.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('an engine that refuses to start is reported, nothing is scheduled, nothing is left unhandled', async () => {
|
||||
const unhandled = vi.fn();
|
||||
// The client's tests are typed for a browser; the test runner itself is Node.
|
||||
const proc = (globalThis as unknown as { process: { on(e: string, f: () => void): void; off(e: string, f: () => void): void } }).process;
|
||||
proc.on('unhandledRejection', unhandled);
|
||||
try {
|
||||
FakeAudioContext.mode = 'rejects';
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const later = button('Play again in');
|
||||
press(later);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(result('Delayed sound')).toMatch(/^not started: blocked \(NotAllowedError: not allowed here\) at /);
|
||||
expect(later.disabled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(ctx().oscillators).toBe(0);
|
||||
expect(result('Delayed sound')).toMatch(/^not started: /);
|
||||
press(button('Play test sound'));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(result('Test sound')).toMatch(/^blocked \(NotAllowedError: not allowed here\) at /);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(unhandled).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
proc.off('unhandledRejection', unhandled);
|
||||
}
|
||||
});
|
||||
|
||||
it('the immediate test sound also starts the engine during its press', async () => {
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const before = ctx().resumeCalls.length;
|
||||
press(button('Play test sound'));
|
||||
expect(ctx().resumeCalls.slice(before)).toEqual([true]);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx().oscillators).toBe(2);
|
||||
expect(result('Test sound')).toMatch(/^played at /);
|
||||
});
|
||||
|
||||
it('speech only on its button; output names stay on the page', async () => {
|
||||
mount();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
press(button('Speak with'));
|
||||
expect(speak).toHaveBeenCalledTimes(1);
|
||||
press(button('List outputs'));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(enumerate).toHaveBeenCalledTimes(2);
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(storageSpy).not.toHaveBeenCalled();
|
||||
expect(getUserMedia).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user