From aea8ed80a947d225582d097ca040f173eedea456 Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 29 Nov 2026 11:42:05 -0800 Subject: [PATCH] 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 names e4c102a / 0.4.0; 44ea114 is historical. Co-Authored-By: Claude Fable 5.2 --- README.md | 8 +- apps/even-client/src/ui/soundCheck.ts | 81 ++++++--- apps/even-client/test/soundCheck.test.ts | 206 +++++++++++++++++++++++ 3 files changed, 266 insertions(+), 29 deletions(-) create mode 100644 apps/even-client/test/soundCheck.test.ts diff --git a/README.md b/README.md index 6fcf594..cb77c11 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,11 @@ the implementer read from the server's log, and what Cody reproduced independent |---|---| | **What is where today** | Server (bridge and static page): `e4c102a5391464cec6f540f5a41f5557a3f61e0b`, since 2026-11-28 21:44 UTC. Even account, beta channel: client 0.4.0, built from that commit. This repository's client is **0.4.1, a candidate: not deployed, not uploaded, not on the device.** | | Client, bridge and contract | Implemented. | -| Automated tests with fakes (351) | Passing. | +| Automated tests with fakes (357) | Passing. | | Client in Even's official simulator | 9 scenarios, run by the implementer, simulator only. Eight run with the menu, hands free and live preview switched off (the tap path and idle exit); the ninth launches the app as shipped and covers the menu and the microphone opening and closing for hands free, with a silent microphone, so no name is ever heard. Live preview is not exercised in the simulator. One unexplained failure of the idle-exit scenario in the Round 19 runs; see `docs/test-evidence.md`. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | | Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. | -| Running on a droplet | Since 2026-11-28 19:06 UTC the server runs commit `44ea1148c34a271f4fdc565ef71a145adf459b42` (bridge and static page), which holds Cody's SHIP FOR TRIAL (Round 18). Checks performed: `docs/evidence/device/2026-11-28.md`; earlier deployments: `docs/evidence/droplet/2026-11-21.md`. | +| Running on a droplet | Since 2026-11-28 21:44 UTC the server runs commit `e4c102a5391464cec6f540f5a41f5557a3f61e0b` (bridge and static page), which holds Cody's SHIP FOR TRIAL (Round 20). Deployed and checked by the implementer; not reproduced by Cody. Checks performed: `docs/evidence/device/2026-11-28.md`, second half. Earlier: `44ea1148c34a271f4fdc565ef71a145adf459b42` (0.3.0, same file, first half) and `docs/evidence/droplet/2026-11-21.md`. | | Phone page in an ordinary phone browser | Paired and answered one typed question (Chrome on Android, reported by Dan). This is **not** the Even app: a browser cannot reach the glasses. | | Phone page inside the Even app, physical G2 | First runs on 2026-11-21, QR-sideloaded, phone unlocked: paired, four spoken questions answered on the glasses. See `docs/evidence/device/2026-11-21.md` for exactly which builds and what was and was not observed. | | Installed as an Even Hub private build ("Pepper", `xylo.hermeven` 0.1.0) | Runs from the Even app with no QR code: paired, and four spoken questions answered on the glasses, including hold-to-talk and one that had the agent send a Telegram message (Dan's report plus the bridge log, 2026-11-21). Needs `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*` on the bridge. | @@ -31,9 +31,9 @@ the implementer read from the server's log, and what Cody reproduced independent | Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. | | Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** | | More than one agent (swipe at Ready to choose) | 0.2.0. Deployed on 2026-11-22 with three agents; a question sent through the bridge was answered by a second Hermes profile (`docs/evidence/droplet/2026-11-21.md`). Installed on the device and tried by Dan, who reported "All tests check out" without detail (`docs/evidence/device/2026-11-21.md`, sixth session). The agent screens have not been run in the simulator. | -| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | 0.3.0, which is what is deployed and on beta (`44ea114`). Fakes: passing. Simulator: menu and microphone open/close only (scenario 9). Device: tried by Dan on 2026-11-28, "pretty cool"; a name reached an agent and a different name switched agent. No item-by-item report; section D of the device plan has not been run. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. | +| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | Introduced in 0.3.0 (`44ea114`, no longer deployed); part of what is deployed and on beta now (0.4.0, `e4c102a`). Fakes: passing. Simulator: menu and microphone open/close only (scenario 9). Device: tried by Dan on 2026-11-28, "pretty cool"; a name reached an agent and a different name switched agent. No item-by-item report; section D of the device plan has not been run. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. | | Words shown while recording (Agents only); "Heard: ..." while the agent works | 0.4.0, deployed and on beta (`e4c102a`). Fakes: passing. Not in the simulator. Device, Dan, 2026-11-28: "Heard" appears; **live words did not appear**, cause unknown; and Dan wants them in hands free, not Agents (open, not built). `docs/decisions/0005-live-preview.md`, `docs/evidence/device/2026-11-28.md`. | -| Sound check on the phone page (can the page play sound, untouched, in the background; which outputs it sees) | 0.4.1 candidate. A probe for issue #1 (spoken answers), not a feature. Typechecked and built only: **no automated test, not in the simulator, not on the device.** | +| Sound check on the phone page (can the page play sound, untouched, in the background; which outputs it sees) | 0.4.1 candidate. A probe for issue #1 (spoken answers), not a feature. Tested with a fake sound engine in a fake browser (`apps/even-client/test/soundCheck.test.ts`). **Never run in a real browser, the simulator, the Even app or on the device; not deployed, not uploaded.** | | Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. | | Sustained load, backups, monitoring, upgrades on the server | **Not verified.** | | Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. | diff --git a/apps/even-client/src/ui/soundCheck.ts b/apps/even-client/src/ui/soundCheck.ts index b122231..f623443 100644 --- a/apps/even-client/src/ui/soundCheck.ts +++ b/apps/even-client/src/ui/soundCheck.ts @@ -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 { + /** + * 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 { 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; 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 { + 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. diff --git a/apps/even-client/test/soundCheck.test.ts b/apps/even-client/test/soundCheck.test.ts new file mode 100644 index 0000000..d4e2ca3 --- /dev/null +++ b/apps/even-client/test/soundCheck.test.ts @@ -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 { + 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; +let enumerate: ReturnType; +let fetchSpy: ReturnType; +let storageSpy: ReturnType; +let getUserMedia: ReturnType; +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(); + }); +});