From f9946a027a92da79d9321bc7ca7e4555b8ba900f Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 28 Nov 2026 11:44:36 -0800 Subject: [PATCH] Words on the glasses while recording, and "Heard:" for spoken questions (0.4.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While a recording is being made the app sends the recording so far to a new bridge route, POST /v1/transcribe, about every half second of new audio and one request at a time, and draws the words under "... is listening…", newest words kept in view. No new service: it is the Whisper already in the bridge. A preview is only ever drawn. The question is transcribed again by its own turn, so a preview can never be what the agent receives. After sending, the last preview stays under "Transcribing…", then "Heard:" shows the transcript the bridge gave the agent, now for every spoken question (it was hands free only). The reducer tracks `spoken` explicitly and treats an accepted, not yet transcribed recording as transcribing. Bridge: /v1/transcribe needs a device credential, shares the audio checks with /v1/wake, runs one at a time per device within HERMEVEN_PREVIEWS_PER_MINUTE (60), creates nothing and logs no text. An older bridge answers 404 and the client stops asking. Simulator: a scenario that launches the app as shipped (menu, hands free) as Round 18 required. A diagnostics note marks when listening for a name starts and stops. Also records the 0.3.0 deployment, upload and Dan's device report (docs/evidence/device/2026-11-28.md), and decision 0005. Not reviewed, not deployed, not uploaded, not device-tested. Co-Authored-By: Claude Fable 5.2 --- README.md | 7 +- apps/even-client/app.template.json | 2 +- apps/even-client/src/boot.ts | 3 + apps/even-client/src/core/controller.ts | 93 ++++++++++++++- apps/even-client/src/core/hud.ts | 20 ++-- apps/even-client/src/core/reducer.ts | 34 +++++- apps/even-client/src/main.ts | 1 + apps/even-client/src/net/bridgeClient.ts | 16 +++ apps/even-client/test/layout.test.ts | 4 +- docs/bridge-api.md | 1 + docs/decisions/0005-live-preview.md | 47 ++++++++ docs/device-test-plan.md | 3 + docs/evidence/device/2026-11-28.md | 39 ++++++ docs/security.md | 4 + packages/contracts/src/schemas.ts | 12 ++ services/bridge/src/config.ts | 3 + services/bridge/src/server.ts | 60 ++++++++-- tests/integration/wake.test.ts | 145 +++++++++++++++++++++++ tests/simulator/simulator.test.ts | 69 ++++++++++- 19 files changed, 531 insertions(+), 32 deletions(-) create mode 100644 docs/decisions/0005-live-preview.md create mode 100644 docs/evidence/device/2026-11-28.md diff --git a/README.md b/README.md index 0c2e8d3..4b6deec 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ the implementer read from the server's log, and what Cody reproduced independent | Path | State | |---|---| | Client, bridge and contract | Implemented. | -| Automated tests with fakes (341) | Passing. | +| Automated tests with fakes (349) | Passing. | | Client in Even's official simulator | Passing (7 scenarios). Simulator only. | | 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. | @@ -29,7 +29,8 @@ 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. Automated tests with fakes only (a tone for speech, a scripted recogniser). **Not run in the simulator, not deployed, not on the device.** The speech detector's thresholds are untested guesses. `docs/decisions/0004-always-listening.md`. | +| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | 0.3.0. Bridge deployed and build uploaded to beta on 2026-11-28 at `44ea114` (Cody: SHIP FOR TRIAL). Tried by Dan on the glasses the same day: "pretty cool"; calling a different agent by name switched to it. No item-by-item report. Not run in the simulator. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. | +| Words shown while recording; "Heard: ..." while the agent works | 0.4.0. Automated tests with fakes only. **Not deployed, not on the device.** `docs/decisions/0005-live-preview.md`. | | 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. | @@ -76,7 +77,7 @@ instructions, including building for the glasses, are in `docs/setup.md`. |---|---| | Open the app | From 0.3.0: a menu. Swipe to move, tap to open. **Hands free** is first, **Agents** (everything below, as before) second. | | In Hands free: say an agent's name, then your question | The microphone is open while the app is at rest (the status line starts with `●`). "Wendy, what's on my calendar" goes to Wendy. A name alone starts a recording that is sent when you stop speaking. Tap and swipe still work. The app stays on the glasses. | -| Tap | Start recording. The display shows `● REC` and a timer the whole time. | +| Tap | Start recording. The display shows `● REC` and a timer the whole time. From 0.4.0 the words appear as you speak, a second or two behind, and "Heard: ..." shows what was sent while the agent works. | | Tap again | Stop and send. Recording also stops by itself after 30 seconds. | | Hold, speak, release | Push-to-talk: recording starts when the glasses register the hold and is sent when you let go. A hold released in under 0.7 s behaves like a tap. | | Swipe down / up | Next / previous page of the answer. | diff --git a/apps/even-client/app.template.json b/apps/even-client/app.template.json index f329e66..0944e1b 100644 --- a/apps/even-client/app.template.json +++ b/apps/even-client/app.template.json @@ -2,7 +2,7 @@ "package_id": "xylo.hermeven", "edition": "202601", "name": "Pepper", - "version": "0.3.0", + "version": "0.4.0", "min_sdk_version": "0.0.16", "entrypoint": "index.html", "permissions": [ diff --git a/apps/even-client/src/boot.ts b/apps/even-client/src/boot.ts index fd8f9be..4736ccf 100644 --- a/apps/even-client/src/boot.ts +++ b/apps/even-client/src/boot.ts @@ -35,6 +35,8 @@ export interface BootOptions { wake?: boolean; /** `false` opens at Ready instead of on the menu. For automated simulator runs. */ menu?: boolean; + /** `false`: no words shown while recording. For automated simulator runs. */ + livePreview?: boolean; /** Reload hook, replaceable in tests. */ reload?: () => void; } @@ -99,6 +101,7 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {} // Hands free needs the glasses' microphone: never in the browser preview. wake: mode === 'even' && options.wake !== false ? {} : null, menu: options.menu !== false, + livePreview: mode === 'even' && options.livePreview !== false, ...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}), // Development builds mirror diagnostics to the console (visible in the simulator and the // Even dev console). Diagnostics never contain questions, answers or credentials. diff --git a/apps/even-client/src/core/controller.ts b/apps/even-client/src/core/controller.ts index 11c182f..51b2b51 100644 --- a/apps/even-client/src/core/controller.ts +++ b/apps/even-client/src/core/controller.ts @@ -112,6 +112,20 @@ export interface WakeTiming { pauseMs: number; } +export interface PreviewTiming { + /** Nothing is transcribed until this much has been recorded. */ + firstMs: number; + /** A new preview is asked for once this much more has been recorded (and the last one is back). */ + stepMs: number; + /** After a failure, previews are not asked for again for this long. */ + pauseMs: number; +} + +export const DEFAULT_PREVIEW_TIMING: PreviewTiming = { firstMs: 700, stepMs: 500, pauseMs: 5000 }; + +/** Lines of the body left for the words under the "… is listening…" title and a blank line. */ +const PREVIEW_LINES = HUD.bodyLines - 2; + export const DEFAULT_WAKE_TIMING: WakeTiming = { commandEndSilenceMs: 1200, armTimeoutMs: 6000, @@ -166,6 +180,11 @@ export interface ControllerOptions { * a tap. */ wake?: Partial | null; + /** + * Show the words of a recording while it is being made: every so often the recording so far + * is sent to the bridge for transcription. Off unless set. + */ + livePreview?: boolean | Partial; /** * Open on a menu (Hands free, Agents) instead of at Ready; double tap at Ready returns to it. * Without it the app opens at Ready, in hands-free mode if `wake` is given. @@ -189,6 +208,8 @@ interface Capture { startedAt: number; /** The whole question was already spoken before the recording began: send it as it is. */ complete: boolean; + /** How much of it had been recorded when the last live preview was asked for. */ + previewedBytes: number; } type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array }; @@ -253,6 +274,13 @@ export class Controller { /** Set while a long press that STARTED a recording is still held down. */ private heldPress: { generation: number; at: number } | null = null; + // ---- words shown while recording (unused when `preview` is null) + private readonly preview: PreviewTiming | null; + private previewBusy = false; + private previewPausedUntil = 0; + /** The bridge said it cannot do previews (or is too old): stop asking for this session. */ + private previewUnsupported = false; + // ---- listening for a name (all unused when `wake` is null) private readonly wake: WakeTiming | null; private readonly segmenter = new SpeechSegmenter(); @@ -287,6 +315,7 @@ export class Controller { this.exitRetryMs = options.exitRetryMs ?? 3_000; this.exitAttempts = Math.max(1, options.exitAttempts ?? 4); this.wake = options.wake ? { ...DEFAULT_WAKE_TIMING, ...options.wake } : null; + this.preview = options.livePreview ? { ...DEFAULT_PREVIEW_TIMING, ...(options.livePreview === true ? {} : options.livePreview) } : null; } // ------------------------------------------------------------------ public @@ -436,7 +465,10 @@ export class Controller { await this.device.stopMic(); } const listening = this.micOpen && this.wakeActive(); - if (listening !== this.state.wakeListening) this.dispatch({ type: 'wake_status', listening }); + if (listening !== this.state.wakeListening) { + this.note('wake', listening ? 'listening for a name' : 'stopped listening'); + this.dispatch({ type: 'wake_status', listening }); + } return this.micOpen; }); this.micChain = run.then( @@ -917,6 +949,7 @@ export class Controller { auto, startedAt: this.now(), complete: false, + previewedBytes: 0, }; if (auto) { // The name was recognised a moment after it was said, and the speaker may not have @@ -993,6 +1026,64 @@ export class Controller { this.dispatch({ type: 'capture_limit', generation: capture.generation }); } if (capture.auto && !capture.limitSent) this.followAutoCapture(capture, pcm); + if (!capture.limitSent) this.maybePreview(capture); + } + + /** + * Ask the bridge for the words so far, one request at a time. What comes back is only ever + * drawn: the recording that is finally sent is transcribed again as part of its own turn. + */ + private maybePreview(capture: Capture): void { + const timing = this.preview; + const client = this.client; + if (!timing || !client || this.previewUnsupported || this.previewBusy || this.now() < this.previewPausedUntil) return; + if (this.status?.stt_configured === false) return; + const ms = (bytes: number) => (bytes / AUDIO_FORMAT.bytesPerSecond) * 1000; + if (ms(capture.bytes) < timing.firstMs) return; + if (capture.previewedBytes > 0 && ms(capture.bytes - capture.previewedBytes) < timing.stepMs) return; + capture.previewedBytes = capture.bytes; + const usable = capture.bytes - (capture.bytes % 2); + const pcm = new Uint8Array(usable); + let offset = 0; + for (const chunk of capture.chunks) { + const take = Math.min(chunk.length, usable - offset); + pcm.set(chunk.subarray(0, take), offset); + offset += take; + } + this.previewBusy = true; + void client + .transcribe({ pcm, locale: this.options.locale }) + .then( + (result) => { + // Only for the recording it was made from, and only while that is still being made. + if (this.capture !== capture || this.stale(capture.generation) || this.state.phase !== 'listening') return; + if (result.text) this.dispatch({ type: 'capture_preview', generation: capture.generation, text: this.fitPreview(result.text) }); + }, + (err) => { + if (err instanceof BridgeApiError && err.body.code === 'not_found') { + this.previewUnsupported = true; + this.note('preview', 'this bridge cannot show words while recording'); + } else { + // Busy, over the limit or unreachable: the recording carries on without a preview. + this.previewPausedUntil = this.now() + (err instanceof BridgeApiError && err.body.code === 'rate_limited' ? 1000 : timing.pauseMs); + if (!(err instanceof BridgeApiError && err.body.code === 'rate_limited')) this.note('preview', `not available just now: ${describe(err)}`); + } + }, + ) + .finally(() => { + this.previewBusy = false; + }); + } + + /** The end of the text that fits under the title: the newest words are the ones to see. */ + private fitPreview(text: string): string { + const words = toPlainText(text).split(/\s+/).filter(Boolean); + let from = 0; + for (;;) { + const shown = (from > 0 ? '… ' : '') + words.slice(from).join(' '); + if (from >= words.length - 1 || (shown.length <= 600 && this.options.measure(shown, BODY_BOX.innerWidth) <= PREVIEW_LINES)) return shown.slice(-600); + from += Math.max(1, Math.ceil((words.length - from) / 8)); + } } /** A recording started by name: send when the speaker stops, give up if nobody speaks. */ diff --git a/apps/even-client/src/core/hud.ts b/apps/even-client/src/core/hud.ts index 0c4ac30..8910f62 100644 --- a/apps/even-client/src/core/hud.ts +++ b/apps/even-client/src/core/hud.ts @@ -106,20 +106,22 @@ function renderFrame(state: AppState, nowMs: number): HudFrame { case 'listening': { const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000; const cap = state.captureMaxSeconds; - if (state.captureAuto) { - return { - body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nAsk your question. It is sent when you stop speaking.`, - status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`, - }; - } + const title = agent ? `${agent.name} is listening…` : 'Listening…'; + const status = state.captureAuto + ? `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel` + : `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`; + // Once there are words, they replace the instructions. + if (state.preview) return { body: `${title}\n\n${state.preview}`, status }; return { - body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nRecording stops by itself after ${cap} seconds.`, - status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`, + body: state.captureAuto + ? `${title}\n\nAsk your question. It is sent when you stop speaking.` + : `${title}\n\nRecording stops by itself after ${cap} seconds.`, + status, }; } case 'transcribing': - return { body: 'Transcribing…', status: 'Double-tap: cancel' }; + return { body: state.preview ? `Transcribing…\n\n${state.preview}` : 'Transcribing…', status: 'Double-tap: cancel' }; case 'thinking': { const title = agent ? `${agent.name} is thinking…` : 'Thinking…'; diff --git a/apps/even-client/src/core/reducer.ts b/apps/even-client/src/core/reducer.ts index d1331ae..2ac96ab 100644 --- a/apps/even-client/src/core/reducer.ts +++ b/apps/even-client/src/core/reducer.ts @@ -83,8 +83,15 @@ export interface AppState { * from what the microphone actually did, so the HUD's indicator is never a guess. */ wakeListening: boolean; - /** The question as it was heard, when it was spoken after a name. Shown while the agent works. */ + /** The request in flight was spoken (recorded), not typed. */ + spoken: boolean; + /** The spoken question as the bridge transcribed it. Shown while the agent works. */ heard: string | null; + /** + * The words of the recording in progress, as far as they have been transcribed. Already cut + * by the controller to what fits the screen. A preview only: it is never what is sent. + */ + preview: string | null; pages: string[]; pageIndex: number; /** The answer is a partial one (agent stopped short). Shown on the HUD. */ @@ -119,7 +126,9 @@ export const initialState: AppState = { captureMaxSeconds: 30, captureAuto: false, wakeListening: false, + spoken: false, heard: null, + preview: null, pages: [], pageIndex: 0, partial: false, @@ -174,6 +183,8 @@ export type AppEvent = | { type: 'cancel' } | { type: 'submit_text'; freshId: string; text: string } | { type: 'capture_started'; generation: number; at: number } + /** The words so far in the recording being made (already fitted to the screen). */ + | { type: 'capture_preview'; generation: number; text: string } | { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' } | { type: 'capture_limit'; generation: number } | { type: 'conversation_created'; epoch: number; conversationId: string } @@ -224,7 +235,9 @@ function clearTurn(state: AppState): AppState { requestId: null, captureStartedAt: null, captureAuto: false, + spoken: false, heard: null, + preview: null, pages: [], pageIndex: 0, partial: false, @@ -402,7 +415,7 @@ export function reduce(state: AppState, event: AppEvent): Step { } if (state.phase === 'listening' && state.requestId) { return { - state: { ...state, phase: 'transcribing', captureStartedAt: null }, + state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true }, effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }], }; } @@ -419,7 +432,7 @@ export function reduce(state: AppState, event: AppEvent): Step { case 'capture_limit': { if (event.generation !== state.generation || state.phase !== 'listening' || !state.requestId) return same(state); return { - state: { ...state, phase: 'transcribing', captureStartedAt: null }, + state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true }, effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }], }; } @@ -502,6 +515,11 @@ export function reduce(state: AppState, event: AppEvent): Step { return same({ ...state, captureStartedAt: event.at }); } + case 'capture_preview': { + if (event.generation !== state.generation || state.phase !== 'listening') return same(state); + return same(event.text === state.preview ? state : { ...state, preview: event.text || null }); + } + case 'capture_failed': { if (event.generation !== state.generation) return same(state); if (state.phase !== 'listening' && state.phase !== 'transcribing') return same(state); @@ -522,9 +540,13 @@ export function reduce(state: AppState, event: AppEvent): Step { if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state); const result = event.result; if (!result.terminal) { - const phase: Phase = - result.state === 'transcribing' ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking'; - return same({ ...state, phase, disconnectedFrom: null, canResend: false }); + // A recording the bridge has accepted but not yet started on is still being transcribed. + const waiting = result.state === 'transcribing' || (result.state === 'accepted' && state.spoken && !result.input_text); + const phase: Phase = waiting ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking'; + // Once the bridge has the transcript of a spoken question, that is what the agent is + // being sent, and it is shown in place of the preview. + const heard = state.heard ?? (state.spoken && !waiting ? (result.input_text ?? null) : null); + return same({ ...state, phase, heard, preview: waiting ? state.preview : null, disconnectedFrom: null, canResend: false }); } const settled = { ...clearTurn(state), requestId: state.requestId }; switch (result.outcome) { diff --git a/apps/even-client/src/main.ts b/apps/even-client/src/main.ts index b449883..09d6e2a 100644 --- a/apps/even-client/src/main.ts +++ b/apps/even-client/src/main.ts @@ -25,6 +25,7 @@ const { controller } = await boot(document, window, { // `?menu=off` opens at Ready instead of on the menu. wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'), menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'), + livePreview: !(import.meta.env.DEV && new URLSearchParams(location.search).get('preview') === 'off'), }); // Development-only convenience for automated simulator runs, where nothing can type into the diff --git a/apps/even-client/src/net/bridgeClient.ts b/apps/even-client/src/net/bridgeClient.ts index 9d8a7ce..8239cfd 100644 --- a/apps/even-client/src/net/bridgeClient.ts +++ b/apps/even-client/src/net/bridgeClient.ts @@ -8,6 +8,7 @@ import { ErrorResponse, RevokeResponse, SCHEMA_VERSION, + TranscribeResponse, TurnResult, WakeResponse, type ErrorBody, @@ -191,6 +192,21 @@ export class BridgeClient { return this.call(WakeResponse, 'POST', `/v1/wake?${query}`, { binary: args.pcm }); } + /** + * The words in a recording still being made, for showing while the user speaks. Creates + * nothing on the bridge. A bridge without it answers `not_found`. + */ + transcribe(args: { locale: string; pcm: Uint8Array }): Promise { + const query = new URLSearchParams({ + schema_version: String(SCHEMA_VERSION), + locale: args.locale, + encoding: AUDIO_FORMAT.encoding, + sample_rate: String(AUDIO_FORMAT.sampleRate), + channels: String(AUDIO_FORMAT.channels), + }); + return this.call(TranscribeResponse, 'POST', `/v1/transcribe?${query}`, { binary: args.pcm }); + } + getTurn(requestId: string): Promise { return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise; } diff --git a/apps/even-client/test/layout.test.ts b/apps/even-client/test/layout.test.ts index 5bc1915..1a743a0 100644 --- a/apps/even-client/test/layout.test.ts +++ b/apps/even-client/test/layout.test.ts @@ -188,7 +188,9 @@ describe('HUD frames', () => { if (phase === 'ready') { return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }]; } - if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }]; + const words = 'what is on my calendar tomorrow and can you move the dentist to Thursday afternoon if that is free'; + if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }, { ...base, agents: few, preview: `… ${words} ${words}` }]; + if (phase === 'transcribing') return [base, { ...base, preview: `… ${words} ${words}` }]; if (phase === 'thinking') return [base, { ...base, heard: 'W'.repeat(4000) }, { ...base, agents: few, heard: 'What is on my calendar tomorrow?' }]; if (phase === 'cancelled') return [base, { ...base, ...wake }]; if (phase === 'unpaired') return [base, { ...base, storageFault: true }]; diff --git a/docs/bridge-api.md b/docs/bridge-api.md index f8f6340..d665015 100644 --- a/docs/bridge-api.md +++ b/docs/bridge-api.md @@ -22,6 +22,7 @@ Every error has the shape: | `POST /v1/conversations` | Start a new conversation. Optional `agent_id` (an id from `/v1/agents`; omitted = the default agent; anything else is 400 `invalid_request`). Closes the device's previous conversation **with that agent** only. | 201 | | `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate | | `POST /v1/wake` | One stretch of speech heard while the app was open (raw audio body, same format as an audio turn; query: `schema_version`, `locale`, `encoding`, `sample_rate`, `channels`). Transcribed in memory and dropped. Answers `{matched, agent_id, text, near_miss}`: whether it **began** with an agent's name, which agent, and what was said after the name (empty for the name alone). When not matched `text` is always empty; `near_miss` is the first word if it was close to a name. Creates no turn and sends nothing to any agent. 404 `not_found` when speech-to-text is off or no agent has a usable name (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_WAKE_CHECKS_PER_MINUTE` (default 30) or while this device's previous check is still running. A failed transcription is answered as not matched. | 200 | +| `POST /v1/transcribe` | The words in a recording that is still being made, for showing while the user speaks. Same body and query as `/v1/wake`. Answers `{text}` (empty if nothing was recognised or transcription failed). Transcribed in memory and dropped; creates no turn, sends nothing to any agent, logs no text. 404 `not_found` when speech-to-text is off (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_PREVIEWS_PER_MINUTE` (default 60) or while this device's previous preview is still running. | 200 | | `GET /v1/turns/{request_id}` | Current state and result. | 200 | | `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 | diff --git a/docs/decisions/0005-live-preview.md b/docs/decisions/0005-live-preview.md new file mode 100644 index 0000000..915e29d --- /dev/null +++ b/docs/decisions/0005-live-preview.md @@ -0,0 +1,47 @@ +# 0005: Words on the glasses while recording + +Status: implemented with fakes only; **not device-tested**. Date: 2026-11-28. + +Dan (2026-11-28): "have the live transcription going when in agent mode so that I can see what +I'm sending to the agent. I realize I'll need to subscribe to a new, paid for service to enable +this." + +## What it does (0.4.0) + +While a recording is being made (by tap, by hold, or after a name in hands free) the screen shows +the words so far under "... is listening…", newest words kept in view. After the recording is +sent, the last preview stays under "Transcribing…" and is then replaced by "Heard: ..." with the +transcript the bridge actually gave the agent. + +## How, and why no paid service yet + +No new service. About every half second of new audio, and never more than one request at a time, +the app sends **the recording so far** to `POST /v1/transcribe`, and the Whisper already in the +bridge transcribes it. On the server's own figures (1.1 to 1.7 s per clip) the words should trail +the voice by roughly one to two seconds and arrive in phrases, not word by word. + +A preview is only ever drawn. The question is transcribed again, whole, by its own turn, so a +preview can never be what the agent receives, and nothing about request ids, deduplication or +cancellation changes. + +## What a paid streaming recogniser would change + +Word-by-word text a few hundred milliseconds behind the voice, and less CPU on the server. It +would mean audio leaving the bridge host for a third party, a streaming connection through the +Even WebView (documented as allowed, untested), and a recurring cost. Not chosen or designed +here: try this first. + +## Costs of this version + +- While recording, the server transcribes continuously: one core busy for the length of the + recording. +- When the recording is sent, a preview still running is finished first, so the real + transcription can start up to one clip (about 1.5 s) later than before. +- A preview is a guess at an unfinished sentence and can differ from the final transcript. The + "Heard:" line is the one that is true. +- "Heard:" is cut at 160 characters on the glasses; the phone page has the whole text. + +## Owner decisions pending + +Whether the delay is acceptable; whether the preview should also be shown in hands free (it is); +whether the "Heard:" line during thinking is wanted in Agents (new there in 0.4.0). diff --git a/docs/device-test-plan.md b/docs/device-test-plan.md index e9ad4ff..ff82fd0 100644 --- a/docs/device-test-plan.md +++ b/docs/device-test-plan.md @@ -91,6 +91,9 @@ If A13 fails, stop and report it. It is a product-level blocker, not a bug to wo | D7 | While it is open, have a notification arrive. | Did it reach the lenses? | The cost of staying open. | | D8 | Double tap back to the menu, choose "Agents". | Does `●` go away, does tap still work, does the app leave by itself again? | Leaving hands free. | +| D9 | In Agents, tap and speak a long sentence slowly. | Do words appear while speaking? How far behind? Do they jump or flicker? | Live preview on a real G2 and the real server. | +| D10 | After sending, watch the screen. | Does "Heard: ..." show what you said? Seconds from tap to "thinking" compared with 0.3.0. | Whether a running preview delays the real transcription noticeably. | + ## Reporting Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to diff --git a/docs/evidence/device/2026-11-28.md b/docs/evidence/device/2026-11-28.md new file mode 100644 index 0000000..42c3f61 --- /dev/null +++ b/docs/evidence/device/2026-11-28.md @@ -0,0 +1,39 @@ +# 0.3.0 on the server and the glasses, 2026-11-28 + +**Whose evidence this is.** Server facts are the implementer's (Claude's) own commands and the +bridge's replies. What happened on the glasses is Dan's report, quoted. Nothing on the device was +seen by the implementer. + +## Deployment and upload + +Cody, Round 18: SHIP, trial designation SHIP FOR TRIAL, on +`44ea1148c34a271f4fdc565ef71a145adf459b42`. Asked to confirm the bridge deployment and the +upload, Dan: "go". + +| Step | Result | +|---|---| +| `git archive 44ea114` to `/root/hermeven-src`, `deploy/install.sh --bridge-url https://hermeven.xylo.gg` | All seven steps. `DEPLOYED_SHA` is `44ea1148c34a271f4fdc565ef71a145adf459b42` (was `dcb3736`). 0 files in the application tree not owned by root. | +| `systemctl restart hermeven-bridge`, 19:06 UTC | active; `stt.ready`; healthz ok locally and at `https://hermeven.xylo.gg`. Hermes was not restarted. `/etc/hermeven/bridge.env` was not changed. | +| Paired devices | Preserved (three active, as before). | +| Smoke test with a temporary device (`deploy-smoke-wake`, revoked afterwards) | `/v1/agents`: Pepper, Wendy, Cody. `POST /v1/wake` with the repository's 11 s archive speech clip (no agent name in it): 200, `matched: false`, empty text, 1.49 s. Without a credential: 401, locally and from outside. No `wake.*` log line was written for the unmatched clip. | +| Not tested on the server | A clip that begins with an agent's name (none exists). | +| Package | `hermeven.ehpk`, 104,464 bytes, SHA-256 `5c8de848431143bbf5638e3d8b192536ab4fb0f0d13b684f72450f6de77f9fcf`, built from `44ea114` with a clean tree; a second pack gave the same hash. | +| Even account | `evenhub upload` 0.3.0, then `evenhub promote 0.3.0 --to beta`. `evenhub ls`: 0.3.0 Private, beta; 0.2.0 no longer on a channel. | + +## What Dan reported + +One message, after updating: + +> "pretty cool. What's weird is that when I'm in an active wendy session, I still have to say her +> name before any time i address her. I'm undecided if this is good or not. Saying the name of a +> different agent does switch sessions... I'm tempted to leave it as is for now." + +| Establishes | | +|---|---| +| Hands free works on a real G2 through the real server | A name spoken to the glasses reached an agent, more than once, and a different name switched agent. So the microphone opened without a tap, the loudness detector found speech from the G2 microphone, and Whisper wrote at least two of the names as configured. | +| Owner decision, 0004 item 4 (the name is needed on every question) | Undecided; "leave it as is for now". No change made. | + +Not reported: which agents, how many attempts or misses, any near miss in Diagnostics, the menu +itself, the name-alone flow, the delay, false triggers, noise, battery, the locked phone, +notifications while open, or Agents mode. Section D of `docs/device-test-plan.md` has not been +run as a checklist. diff --git a/docs/security.md b/docs/security.md index 6cf5d25..b1b887b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -81,6 +81,10 @@ Stated so they are not mistaken for protections. matched exactly and only as the first word, and what was heard is shown while the agent works, but a mis-transcription, another person saying the name, or audio from a speaker can all start a turn. +3e. **From 0.4.0 a recording in progress is sent to the bridge repeatedly** (the whole recording + so far, about twice a second) so its words can be shown. This is audio the user chose to + record, going where the finished recording goes anyway; the text is returned to the app and + not logged. A cancelled recording has therefore already reached the bridge, in memory only. 4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone does the same is unknown and is on the device checklist. If it does, recordings would be visible to whoever can read that console. diff --git a/packages/contracts/src/schemas.ts b/packages/contracts/src/schemas.ts index f4d02db..7ff1bc8 100644 --- a/packages/contracts/src/schemas.ts +++ b/packages/contracts/src/schemas.ts @@ -236,6 +236,18 @@ export const WakeResponse = Type.Object( ); export type WakeResponse = Static; +/** + * Answer of POST /v1/transcribe (same query string and body as /v1/wake): the words in a + * recording that is still being made, so the app can show them while the user speaks. A + * preview only: it creates nothing, and the question that is finally sent is transcribed again + * by the turn itself. + */ +export const TranscribeResponse = Type.Object( + { schema_version: SchemaVersion, text: Type.String({ maxLength: DEFAULT_LIMITS.textMaxChars }) }, + { additionalProperties: false }, +); +export type TranscribeResponse = Static; + export const TURN_STATES = [ 'accepted', 'transcribing', diff --git a/services/bridge/src/config.ts b/services/bridge/src/config.ts index e5e6eee..824cde1 100644 --- a/services/bridge/src/config.ts +++ b/services/bridge/src/config.ts @@ -73,6 +73,8 @@ export interface BridgeConfig { turnsPerMinute: number; /** Wake checks (speech heard while the app is open, tested for a leading agent name). */ wakeChecksPerMinute: number; + /** Live previews of a recording in progress. */ + previewsPerMinute: number; pairingAttemptsPerMinute: number; }; credentials: { @@ -327,6 +329,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig { audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond, turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600), wakeChecksPerMinute: int(env, 'HERMEVEN_WAKE_CHECKS_PER_MINUTE', 30, 1, 600), + previewsPerMinute: int(env, 'HERMEVEN_PREVIEWS_PER_MINUTE', 60, 1, 600), pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60), }, credentials: { diff --git a/services/bridge/src/server.ts b/services/bridge/src/server.ts index 03fc8c9..8e1ddc7 100644 --- a/services/bridge/src/server.ts +++ b/services/bridge/src/server.ts @@ -18,6 +18,7 @@ import { type ErrorCode, type ErrorResponse, type Limits, + type TranscribeResponse, type WakeResponse, } from '@hermeven/contracts'; import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts'; @@ -148,6 +149,21 @@ export async function buildServer(deps: ServerDeps): Promise { const wakeLimiter = new RateLimiter(config.limits.wakeChecksPerMinute, 60_000); /** Devices with a wake check being transcribed: one at a time each. */ const wakeBusy = new Set(); + const previewLimiter = new RateLimiter(config.limits.previewsPerMinute, 60_000); + const previewBusy = new Set(); + + /** The checks shared by the two routes that take a clip of audio and create nothing. */ + function audioClip(req: FastifyRequest): { pcm: Buffer; locale: string } { + const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase(); + if (contentType !== 'application/octet-stream') throw new ApiError('unsupported_media', 'Unsupported content type.'); + const query = req.query as Record; + requireVersion(query.schema_version); + if (!check(WakeQuery, query)) throw new ApiError('invalid_request', 'Malformed request.'); + const pcm = req.body as Buffer; + if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.'); + if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.'); + return { pcm, locale: query.locale }; + } function authenticate(req: FastifyRequest): DeviceRow { const header = req.headers.authorization ?? ''; @@ -320,14 +336,7 @@ export async function buildServer(deps: ServerDeps): Promise { */ app.post('/v1/wake', async (req): Promise => { const device = authenticate(req); - const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase(); - if (contentType !== 'application/octet-stream') throw new ApiError('unsupported_media', 'Unsupported content type.'); - const query = req.query as Record; - requireVersion(query.schema_version); - if (!check(WakeQuery, query)) throw new ApiError('invalid_request', 'Malformed wake request.'); - const pcm = req.body as Buffer; - if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.'); - if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.'); + const { pcm, locale } = audioClip(req); // Nobody can be called by voice (no speech-to-text, or no agent with a usable name): the // app is told so once and stops sending audio. if (!deps.stt.configured || !config.agents.some((a) => a.wakeWords.length > 0)) throw new ApiError('not_found', 'Not found.'); @@ -338,7 +347,7 @@ export async function buildServer(deps: ServerDeps): Promise { const abort = new AbortController(); const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000); try { - const transcript = await deps.stt.transcribe({ pcm, locale: query.locale, signal: abort.signal }); + const transcript = await deps.stt.transcribe({ pcm, locale, signal: abort.signal }); const match = matchWake(transcript, config.agents); if (!match.matched) return { ...none, near_miss: match.nearMiss }; req.log.info({ device_id: device.id, agent_id: match.agentId, name_only: match.text === '' }, 'wake.matched'); @@ -353,6 +362,39 @@ export async function buildServer(deps: ServerDeps): Promise { } }); + // ----------------------------------------------------------------- preview + /** + * The words in a recording that is still being made, for showing on the glasses while the + * user speaks. Transcribed in memory and dropped: no turn, no row, nothing sent to any agent, + * and the text is never logged. The question that is finally sent is transcribed by its own + * turn, so a preview can never become what the agent receives. + */ + app.post('/v1/transcribe', async (req, reply): Promise => { + const device = authenticate(req); + const { pcm, locale } = audioClip(req); + if (!deps.stt.configured) throw new ApiError('not_found', 'Not found.'); + if (previewBusy.has(device.id) || !previewLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.'); + previewBusy.add(device.id); + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000); + // The app has stopped waiting (the recording was sent or cancelled): stop too, so the real + // transcription is not kept waiting behind a preview nobody will see. + reply.raw.on('close', () => { + if (!reply.raw.writableEnded) abort.abort(); + }); + try { + const text = await deps.stt.transcribe({ pcm, locale, signal: abort.signal }); + return { schema_version: SCHEMA_VERSION, text: text.trim().slice(0, config.limits.textMaxChars) }; + } catch (err) { + // No preview this time. The recording itself is unaffected. + req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'preview.transcription_failed'); + return { schema_version: SCHEMA_VERSION, text: '' }; + } finally { + clearTimeout(timer); + previewBusy.delete(device.id); + } + }); + app.get('/v1/turns/:requestId', async (req) => { const device = authenticate(req); const { requestId } = req.params as { requestId: string }; diff --git a/tests/integration/wake.test.ts b/tests/integration/wake.test.ts index 5853e3e..420e6b2 100644 --- a/tests/integration/wake.test.ts +++ b/tests/integration/wake.test.ts @@ -525,3 +525,148 @@ describe('glasses: the opening menu', () => { }); }); +describe('bridge: POST /v1/transcribe', () => { + const clip = (token: string | undefined, said: string) => { + h.stt.next({ text: said }); + return h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) }); + }; + + it('returns the words, creates nothing, and logs none of them', async () => { + await harness(); + const { token } = await h.pair(); + const res = await clip(token, ' what is on my calendar '); + expect(res.status).toBe(200); + expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, text: 'what is on my calendar' }); + expect(h.hermes.requests.filter((r) => r.method === 'POST')).toEqual([]); + expect(h.logs.join('\n')).not.toContain('calendar'); + }); + + it('needs a credential and well-formed audio; a failed transcription is an empty preview; no speech-to-text is not_found', async () => { + await harness(); + const { token } = await h.pair(); + expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { body: syntheticPcm(1) })).status).toBe(401); + expect((await h.api('POST', `/v1/transcribe?${wakeQuery({ channels: '2' })}`, { token, body: syntheticPcm(1) })).status).toBe(400); + expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: Buffer.alloc(5) })).status).toBe(400); + h.stt.next({ status: 500 }); + expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) })).body).toEqual({ schema_version: SCHEMA_VERSION, text: '' }); + await h.close(); + await harness(AGENT_ENV, { stt: false }); + expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token: (await h.pair()).token, body: syntheticPcm(1) })).status).toBe(404); + }); + + it('one at a time per device, with its own per-minute budget', async () => { + await harness({ ...AGENT_ENV, HERMEVEN_PREVIEWS_PER_MINUTE: '2' }); + const { token } = await h.pair(); + h.stt.next({ text: 'a', delayMs: 150 }); + const first = h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) }); + await new Promise((r) => setTimeout(r, 40)); + expect((await clip(token, 'b')).status).toBe(429); + expect((await first).status).toBe(200); + expect((await clip(token, 'c')).status).toBe(200); + expect((await clip(token, 'd')).status).toBe(429); + expect((await wake(token, 'Wendy, still fine')).status).toBe(200); + }); +}); + +describe('glasses: words shown while recording', () => { + beforeEach(async () => { + sent = []; + wakeRoute = 'real'; + extras = { wake: null, idleExit: null, livePreview: { firstMs: 300, stepMs: 300, pauseMs: 200 } }; + await harness(); + }); + afterEach(async () => { + await controller?.stop(); + }); + + it('the words appear as the recording grows, and what the agent is sent is the final transcript, not a preview', async () => { + await paired(); + h.stt.next({ text: 'what is' }, { text: 'what is on my calender' }, { text: 'What is on my calendar?' }); + h.hermes.next({ kind: 'complete', afterMs: 250 }); + device.tap(); + await until('recording', () => phase() === 'listening' && device.micOpen); + expect(device.frame.body).toContain('Recording stops by itself'); + device.speak(0.5); + await until('first words', () => device.frame.body === 'Pepper is listening…\n\nwhat is'); + expect(device.frame.status).toContain('● REC'); + device.speak(0.5); + await until('more words', () => device.frame.body === 'Pepper is listening…\n\nwhat is on my calender'); + device.tap(); + // The last preview stays up while the real transcription runs... + expect(device.frame.body).toBe('Transcribing…\n\nwhat is on my calender'); + // ...and is replaced by what the bridge actually sent to the agent. + await until('thinking', () => device.frame.body === 'Pepper is thinking…\n\nHeard: What is on my calendar?'); + await until('answer', () => phase() === 'answer'); + expect(snapshot.lastTurn?.input_text).toBe('What is on my calendar?'); + expect(posts('/v1/transcribe')).toBe(2); + expect(posts('/v1/turns')).toBe(1); + expect(h.hermes.executions).toBe(1); + }); + + it('a long recording shows its newest words, within the screen', async () => { + await paired(); + const long = Array.from({ length: 150 }, (_, i) => `word${i}`).join(' '); + h.stt.next({ text: long }); + device.tap(); + await until('recording', () => phase() === 'listening' && device.micOpen); + device.speak(0.5); + await until('preview', () => snapshot.state.preview !== null); + const body = device.frame.body; + expect(body.startsWith('Pepper is listening…\n\n… ')).toBe(true); + expect(body.endsWith('word149')).toBe(true); + expect(measureTextWrap(body, 568).lineCount).toBeLessThanOrEqual(9); + device.doubleTap(); + }); + + it('a preview that comes back after cancel, or for an earlier recording, is not drawn', async () => { + await paired(); + h.stt.next({ text: 'late words', delayMs: 200 }); + device.tap(); + await until('recording', () => phase() === 'listening' && device.micOpen); + device.speak(0.5); + await until('preview requested', () => posts('/v1/transcribe') === 1); + device.doubleTap(); + expect(phase()).toBe('cancelled'); + device.tap(); + await until('recording again', () => phase() === 'listening' && device.micOpen); + await pause(300); + expect(snapshot.state.preview).toBeNull(); + expect(device.frame.body).not.toContain('late words'); + device.doubleTap(); + }); + + it('a bridge without previews just records as before; typed questions never say "Heard"', async () => { + await controller?.stop(); + await h.close(); + await harness(AGENT_ENV, { stt: false }); + await paired(); + device.tap(); + await until('recording', () => phase() === 'listening' && device.micOpen); + device.speak(1); + await pause(80); + expect(posts('/v1/transcribe')).toBe(0); + device.doubleTap(); + h.hermes.next({ kind: 'complete', afterMs: 200 }); + controller.askText('typed'); + await until('thinking', () => phase() === 'thinking'); + await pause(80); + expect(device.frame.body).toBe('Pepper is thinking…'); + await until('answer', () => phase() === 'answer'); + }); + + it('works in hands free too, for the question that follows a name', async () => { + // One preview only, so the scripted recogniser's replies line up. + extras = { livePreview: { firstMs: 300, stepMs: 60_000, pauseMs: 200 } }; + await paired(); + await listening(); + h.stt.next({ text: 'Wendy' }, { text: 'are you' }, { text: 'are you there' }); + say(0.5); + await until('recording for Wendy', () => phase() === 'listening'); + device.speak(0.6); + await until('words', () => device.frame.body === 'Wendy is listening…\n\nare you'); + device.silence(1.4); + await until('answer', () => phase() === 'answer'); + expect(h.hermes.executedBy).toEqual(['wendy']); + expect(snapshot.lastTurn?.input_text).toBe('are you there'); + }); +}); diff --git a/tests/simulator/simulator.test.ts b/tests/simulator/simulator.test.ts index 0f4285b..d256625 100644 --- a/tests/simulator/simulator.test.ts +++ b/tests/simulator/simulator.test.ts @@ -149,14 +149,15 @@ function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY: let pageOriginForRelaunch = ''; /** Start a simulator on the page. `idleExit` is the development-only switch read by main.ts. */ -async function launchSimulator(idleExit: 'off' | 'fast', code: string): Promise { +async function launchSimulator(idleExit: 'off' | 'fast', code: string, legacy = true): Promise { const pageOrigin = pageOriginForRelaunch; const automationPort = await freePort(); automation = `http://127.0.0.1:${automationPort}`; const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator'); // idleExit=off: this suite drives the app for longer than the idle timeout between steps. // wake=off, menu=off: this suite covers the tap path and idle exit from Ready, as before the menu. - const url = `${pageOrigin}/?idleExit=${idleExit}&wake=off&menu=off&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`; + // `legacy = false` launches the app as it ships: opening menu, hands free and live preview on. + const url = `${pageOrigin}/?idleExit=${idleExit}${legacy ? '&wake=off&menu=off&preview=off' : ''}&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`; // alsa:null yields silence: the simulator never opens a real microphone in this test. sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], { stdio: ['ignore', 'pipe', 'pipe'], @@ -373,4 +374,68 @@ describe('Even Hub simulator 0.9.5', () => { const problems = after.filter((l) => /\[uncaught\]|\[unhandledrejection\]/.test(l)); expect(problems).toEqual([]); }, 120_000); + + it('as shipped: opens on the menu; a tap starts hands free with the microphone open; double tap returns to the menu and closes it; Agents does not listen', async () => { + // A third simulator, with nothing switched off. The microphone is alsa:null (silence), so + // this shows the menu, the gestures and the microphone opening and closing through the + // real SDK bridge. It shows nothing about hearing a name: no speech exists here. + sim.kill('SIGTERM'); + await new Promise((r) => setTimeout(r, 500)); + if (sim.exitCode === null) sim.kill('SIGKILL'); + await pumpConsole().catch(() => undefined); + const from = consoleLines.length; + lastConsoleId = 0; + const sttBefore = h.stt.calls; + const runsBefore = h.hermes.executions; + await launchSimulator('off', h.bridge.devices.createPairingCode().code, false); + await waitConsole('hud: HUD page created', 30_000, from); + await waitConsole('-> menu', 20_000, from); + await new Promise((r) => setTimeout(r, 800)); + const menu = await screenshot('10-menu'); + expect(litInBand(menu, 0, 120)).toBeGreaterThan(200); + expect(litInBand(menu, 251, 288)).toBeGreaterThan(100); + // Nothing listens on the menu. + expect(consoleLines.slice(from).some((l) => l.includes('wake: listening for a name'))).toBe(false); + + // Swiping moves the marker: the picture changes, and changes back. + await input('down'); + await new Promise((r) => setTimeout(r, 600)); + const second = await screenshot('11-menu-agents-selected'); + expect(second.png.equals(menu.png)).toBe(false); + await input('up'); + await new Promise((r) => setTimeout(r, 600)); + expect((await screenshot('12-menu-again')).png.equals(menu.png)).toBe(true); + + // First entry: hands free. + await input('click'); + await waitConsole('state: menu -> ready', 10_000, from); + await waitConsole('wake: listening for a name', 10_000, from); + await new Promise((r) => setTimeout(r, 1500)); + const handsFree = await screenshot('13-hands-free'); + expect(litInBand(handsFree, 251, 288)).toBeGreaterThan(100); + await pumpConsole(); + // Silence is never sent anywhere. + expect(h.stt.calls).toBe(sttBefore); + + // Back to the menu: the microphone closes. + let mark = consoleLines.length; + await input('double_click'); + await waitConsole('state: ready -> menu', 10_000, mark); + await waitConsole('wake: stopped listening', 10_000, mark); + + // Second entry: Agents. No listening. + mark = consoleLines.length; + await input('down'); + await input('click'); + await waitConsole('state: menu -> ready', 10_000, mark); + await new Promise((r) => setTimeout(r, 1500)); + await pumpConsole(); + expect(consoleLines.slice(mark).some((l) => l.includes('wake: listening for a name'))).toBe(false); + await screenshot('14-agents-ready'); + + expect(h.stt.calls).toBe(sttBefore); + expect(h.hermes.executions).toBe(runsBefore); + const problems = consoleLines.slice(from).filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l)); + expect(problems).toEqual([]); + }, 120_000); });