Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(voice): add fake-clock coverage for the idle model unload

liuzixiang42ae1d3f69d7
diff --git a/apps/desktop/test/helpers/electron-voice-stub.mjs b/apps/desktop/test/helpers/electron-voice-stub.mjs
new file mode 100644
index 000000000..491a6ba6a
--- /dev/null
+++ b/apps/desktop/test/helpers/electron-voice-stub.mjs
@@ -0,0 +1,17 @@
+/**
+ * Minimal `electron` module stub for importing voice-service.ts under
+ * `node --test`: the service itself only touches `app` (in the
+ * createVoiceService wrapper) and `BrowserWindow` as a type, while
+ * audio-backend.ts reads `systemPreferences` for the macOS microphone
+ * permission path.
+ */
+export const app = {
+ once: () => undefined,
+};
+
+export const BrowserWindow = class BrowserWindow {};
+
+export const systemPreferences = {
+ getMediaAccessStatus: () => "granted",
+ askForMediaAccess: async () => true,
+};
diff --git a/apps/desktop/test/helpers/voice-runtime-stub.mjs b/apps/desktop/test/helpers/voice-runtime-stub.mjs
new file mode 100644
index 000000000..bae84b013
--- /dev/null
+++ b/apps/desktop/test/helpers/voice-runtime-stub.mjs
@@ -0,0 +1,93 @@
+/**
+ * Controllable stand-in for `@pi-desktop/voice-runtime`, loaded in place of
+ * the real package by helpers/voice-service-stubs-hook.mjs. Exposes the
+ * value exports audio-backend.ts imports plus the three classes
+ * VoiceService lazily instantiates, with observability for the idle-unload
+ * tests: `StubVoiceController.last` keeps the most recent instance so a test
+ * can drive `stateChange` events, and `StubModelManager.unloadCalls` counts
+ * unload invocations.
+ */
+import { EventEmitter } from "node:events";
+
+export const CAPTURE_SAMPLE_RATE = 16000;
+export const FRAME_LENGTH = 512;
+export function convertFrames() {
+ return new Float32Array(0);
+}
+
+export class StubModelManager {
+ constructor(cacheDir) {
+ this.cacheDir = cacheDir;
+ this.unloadCalls = 0;
+ }
+ unload() {
+ this.unloadCalls += 1;
+ }
+ getAllStates() {
+ return [];
+ }
+ getState() {
+ return undefined;
+ }
+ getLoadedModelId() {
+ return null;
+ }
+ async *download() {
+ yield 1;
+ }
+ async deleteModel() {}
+}
+
+export class StubTranscriptionEngine {
+ constructor(modelManager) {
+ this.modelManager = modelManager;
+ }
+ async transcribe() {
+ return "";
+ }
+ createStream() {
+ return null;
+ }
+ async shutdown() {}
+}
+
+export class StubVoiceController extends EventEmitter {
+ static last = null;
+
+ constructor(engine, captureFactory, getSettings) {
+ super();
+ this.engine = engine;
+ this.modelManager = engine.modelManager;
+ this.state = { phase: "idle", durationSeconds: 0, volumeLevel: 0 };
+ StubVoiceController.last = this;
+ }
+
+ async start() {
+ this.setPhase("listening");
+ }
+
+ async stop() {
+ this.setPhase("done");
+ return { text: "", speechSeconds: 0, transcribeSeconds: 0, language: "en" };
+ }
+
+ cancel() {
+ this.setPhase("idle");
+ }
+
+ dispose() {
+ this.setPhase("idle");
+ }
+
+ setPhase(phase) {
+ this.state = { ...this.state, phase };
+ this.emit("stateChange", this.state);
+ }
+}
+
+// VoiceService destructures the canonical names out of its dynamic import.
+export {
+ StubModelManager as ModelManager,
+ StubTranscriptionEngine as TranscriptionEngine,
+ StubVoiceController as VoiceController,
+};
diff --git a/apps/desktop/test/helpers/voice-service-stubs-hook.mjs b/apps/desktop/test/helpers/voice-service-stubs-hook.mjs
new file mode 100644
index 000000000..fe7bda7c6
--- /dev/null
+++ b/apps/desktop/test/helpers/voice-service-stubs-hook.mjs
@@ -0,0 +1,47 @@
+/**
+ * Module hooks for importing the real voice-service.ts under `node --test`.
+ *
+ * The service uses constructor parameter properties, which node's strip-only
+ * TypeScript mode rejects, and vite's ssrLoadModule runs modules in an
+ * isolated realm whose global timers a test cannot mock — both dead ends for
+ * fake-clock coverage. So instead: resolve redirects `electron` and
+ * `@pi-desktop/voice-runtime` to test stubs and maps bundler-style `.js`
+ * specifiers to their `.ts` siblings, and load transforms `.ts` with
+ * esbuild (via vite's exported transformWithEsbuild) so the module executes
+ * on the test's own ESM pipeline and realm.
+ *
+ * Register with:
+ * register(new URL("./helpers/voice-service-stubs-hook.mjs", import.meta.url).href);
+ */
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { transformWithEsbuild } from "vite";
+import { resolve as resolveTypeScriptSibling } from "./ts-import-hooks.mjs";
+
+const stubs = new Map([
+ ["electron", new URL("./electron-voice-stub.mjs", import.meta.url).href],
+ [
+ "@pi-desktop/voice-runtime",
+ new URL("./voice-runtime-stub.mjs", import.meta.url).href,
+ ],
+]);
+
+export async function resolve(specifier, context, next) {
+ const stub = stubs.get(specifier);
+ if (stub) {
+ return next(stub, { ...context, parentURL: undefined });
+ }
+ return resolveTypeScriptSibling(specifier, context, next);
+}
+
+export async function load(url, context, nextLoad) {
+ if (!url.endsWith(".ts")) {
+ return nextLoad(url, context);
+ }
+ const source = await readFile(fileURLToPath(url), "utf8");
+ const { code } = await transformWithEsbuild(source, url, {
+ loader: "ts",
+ format: "esm",
+ });
+ return { format: "module", shortCircuit: true, source: code };
+}
diff --git a/apps/desktop/test/voice-service-idle-unload.test.mjs b/apps/desktop/test/voice-service-idle-unload.test.mjs
new file mode 100644
index 000000000..fab14bee5
--- /dev/null
+++ b/apps/desktop/test/voice-service-idle-unload.test.mjs
@@ -0,0 +1,122 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { StubVoiceController } from "./helpers/voice-runtime-stub.mjs";
+
+// Redirect `electron` / `@pi-desktop/voice-runtime` to stubs and esbuild-
+// transform the service's TypeScript so it runs on this realm's ESM pipeline,
+// where the fake clock below can intercept its timers.
+register(
+ new URL("./helpers/voice-service-stubs-hook.mjs", import.meta.url).href,
+);
+
+const { VoiceService } = await import("../electron/main/voice-service.ts");
+
+const MODEL_IDLE_UNLOAD_MS = 10 * 60 * 1000;
+
+// Manual fake clock for the idle-unload timer.
+function fakeClock(t) {
+ const pending = new Map();
+ let now = 0;
+ let seq = 0;
+ t.mock.method(globalThis, "setTimeout", (callback, delay) => {
+ seq += 1;
+ pending.set(seq, { callback, at: now + (delay ?? 0) });
+ return { id: seq, ref() {}, unref() {}, hasRef: () => true };
+ });
+ t.mock.method(globalThis, "clearTimeout", (handle) => {
+ pending.delete(handle?.id);
+ });
+ return {
+ advance(ms) {
+ now += ms;
+ for (const [id, job] of [...pending.entries()]) {
+ if (job.at <= now) {
+ pending.delete(id);
+ job.callback();
+ }
+ }
+ },
+ };
+}
+
+async function startedService(t) {
+ const clock = fakeClock(t);
+ const service = new VoiceService("unused-model-cache-dir", () => null);
+ await service.start();
+ const controller = StubVoiceController.last;
+ assert.ok(controller, "stub controller was constructed");
+ return { service, controller, modelManager: controller.modelManager, clock };
+}
+
+test("unloads the model one idle window after a recording settles in a terminal phase", async (t) => {
+ const { service, modelManager, clock } = await startedService(t);
+
+ await service.stop(); // → phase "done", schedules the idle unload
+ assert.equal(modelManager.unloadCalls, 0);
+
+ clock.advance(MODEL_IDLE_UNLOAD_MS - 1);
+ assert.equal(modelManager.unloadCalls, 0, "must not unload early");
+
+ clock.advance(1);
+ assert.equal(modelManager.unloadCalls, 1);
+});
+
+test("an error phase schedules the idle unload as well", async (t) => {
+ const { controller, modelManager, clock } = await startedService(t);
+
+ controller.setPhase("error");
+ clock.advance(MODEL_IDLE_UNLOAD_MS);
+ assert.equal(modelManager.unloadCalls, 1);
+});
+
+test("starting the next recording cancels the pending idle unload", async (t) => {
+ const { service, controller, modelManager, clock } = await startedService(t);
+
+ await service.stop(); // schedules the unload
+ clock.advance(MODEL_IDLE_UNLOAD_MS - 60 * 1000);
+ controller.setPhase("idle"); // renderer acknowledged the result
+ await service.start(); // new recording cancels the pending timer
+
+ clock.advance(MODEL_IDLE_UNLOAD_MS * 2);
+ assert.equal(
+ modelManager.unloadCalls,
+ 0,
+ "unload must stay cancelled while recording",
+ );
+
+ // Once that recording settles, the timer arms again.
+ await service.stop();
+ clock.advance(MODEL_IDLE_UNLOAD_MS);
+ assert.equal(modelManager.unloadCalls, 1);
+});
+
+test("a recording that began after scheduling is never interrupted by the unload", async (t) => {
+ const { service, controller, modelManager, clock } = await startedService(t);
+
+ await service.stop(); // schedules the unload
+ // A new recording reaches "listening" without passing through
+ // service.start() (a race with the renderer); the callback must re-check
+ // the live phase and skip the unload.
+ controller.setPhase("listening");
+ clock.advance(MODEL_IDLE_UNLOAD_MS * 2);
+ assert.equal(modelManager.unloadCalls, 0);
+});
+
+test("dispose cancels the pending idle unload and cannot re-arm it", async (t) => {
+ const { service, modelManager, clock } = await startedService(t);
+
+ await service.stop(); // schedules the unload
+ service.dispose(); // also drives the controller's idle stateChange
+ clock.advance(MODEL_IDLE_UNLOAD_MS * 2);
+ assert.equal(modelManager.unloadCalls, 0);
+});
+
+test("cancel() from an idle phase still schedules exactly one idle unload", async (t) => {
+ const { service, controller, modelManager, clock } = await startedService(t);
+
+ controller.setPhase("idle"); // schedules once
+ service.cancel(); // idle cancel emits no fresh terminal stateChange in real code; re-scheduling is idempotent
+ clock.advance(MODEL_IDLE_UNLOAD_MS);
+ assert.equal(modelManager.unloadCalls, 1);
+});