hex/perf/dictation.bench.ts
Luke Parker 3b66d3bdc0
Windows listener: stop polling every 5 ms while it records (#1232)
* Windows listener: stop polling every 5 ms while it records

With the microphone streaming, its chunks (about every 10 ms) wake the loop while it records too, as they already did while idle: shortcut events and commands are taken at the next chunk, and a release's tail ends on one. A shortcut's audio boundaries come from its event's own time, so nothing about the clip changes. Only an opening or recovering microphone is still polled. Adds perf/dictation.bench.ts (recording) on HEX_AUDIO_FIXTURE.

* bench: name the fixture PR
2026-11-03 23:42:35 -06:00

100 lines
4.5 KiB
TypeScript

// Dictation end to end (docs/perf.md). The copy hears `speech.wav`, one
// spoken sentence and then silence, instead of a microphone
// (HEX_AUDIO_FIXTURE, seeds/dictation.ts), so nobody is recorded. The bench
// drives it through its local API as `hex dictation` does: `start` as the
// sentence begins, then `stop --print` in the silence after it, which
// returns the processed text instead of pasting it. Nothing reaches another
// app. Only bench builds that have HEX_AUDIO_FIXTURE (#1230): an
// older one opens the real microphone, which setup notices too late.
// - `warm`: the microphone open while idle, the default (`hex-dictation`).
// - `released`: Release microphone while idle (`hex-dictation-released`).
import { bench, native } from "@hona/strobe"
import { readFileSync } from "node:fs"
import { join } from "node:path"
import { dictationSeed, SILENCE_MS, speechMs } from "./seeds/dictation"
const home = dictationSeed()
if (!home) throw new Error("dictation.bench.ts needs Hex's English model installed and a text-to-speech voice")
const SPEECH_MS = speechMs(home)
/** The fixture's length: it loops. */
const PERIOD_MS = SPEECH_MS + SILENCE_MS
/** Each dictation stops this long into the silence after the sentence. */
const STOP_AFTER_MS = SPEECH_MS + 500
type Ctx = { home: string; target: string; page: { wait(ms: number): Promise<unknown> } }
type Reply = { status: string; text?: string; code?: string; message?: string }
/** One `POST /control` to the copy, as the `hex` CLI sends it (docs/cli.md). */
async function control(ctx: Ctx, command: Record<string, unknown>): Promise<Reply> {
const api = JSON.parse(readFileSync(join(ctx.home, "hex-data", "local-api.json"), "utf8"))
const response = await fetch(`http://127.0.0.1:${api.port}/control`, {
method: "POST",
headers: { authorization: `Bearer ${api.token}`, "content-type": "application/json" },
body: JSON.stringify({ version: 4, ...command }),
})
return (await response.json()) as Reply
}
const stop = (ctx: Ctx) => control(ctx, { command: "dictation", action: "stop", print: true })
/** When the fixture last opened (epoch ms), from the copy's log: it plays from its start at each open. */
function fixtureOpened(ctx: Ctx): number {
const log = readFileSync(join(ctx.home, "hex-data", "logs", "process.log"), "utf8")
const opened = [...log.matchAll(/^\S*?(\d{4}-\d\d-\d\dT[\d:.]+Z).*HEX_AUDIO_FIXTURE replaces the microphone/gm)]
if (!opened.length) throw new Error("the copy never opened its audio fixture")
return Date.parse(opened[opened.length - 1][1])
}
/** Starts a dictation as the sentence begins. A released microphone opens
* the fixture at its start; an open one waits for the loop to come round. */
async function start(ctx: Ctx): Promise<Reply> {
if (ctx.target === "warm") {
const into = (Date.now() - fixtureOpened(ctx)) % PERIOD_MS
await ctx.page.wait(PERIOD_MS - into)
}
return control(ctx, { command: "dictation", action: "start" })
}
async function printed(reply: Reply): Promise<string> {
if (reply.status !== "transcript" || !reply.text) throw new Error(`stop --print answered ${JSON.stringify(reply)}`)
return reply.text
}
export default bench({
targets: {
warm: native("hex-dictation", { args: ["--hidden"], home, window: false }),
released: native("hex-dictation-released", { args: ["--hidden"], home, window: false }),
},
// The model loads and the listener starts; one dictation then warms the
// whole path (stream, model, output).
async setup(ctx) {
const deadline = Date.now() + 60_000
for (;;) {
const reply = await control(ctx, { command: "dictation", action: "start" }).catch((error) => ({ status: "error", message: String(error) }) as Reply)
if (reply.status === "done") break
if (Date.now() > deadline) throw new Error(`dictation start answered ${JSON.stringify(reply)}`)
await ctx.page.wait(500)
}
await ctx.page.wait(STOP_AFTER_MS)
await printed(await stop(ctx))
fixtureOpened(ctx)
if (ctx.case === "recording") await start(ctx)
},
cases: {
// While a dictation records: the audio path, the live stream's
// inference, and the HUD meter's plumbing. Each run is 6 s of one
// recording; reset finishes it and starts the next.
recording: {
primary: "cpu.wakes",
metrics: ["cpu.work", "memory.app.host"],
async run({ page }) {
await page.wait(6_000)
},
async reset(ctx) {
await printed(await stop(ctx))
await start(ctx)
},
},
},
})