Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(voice): make model downloads atomic and route stream write errors
liuzixiang9552100761c4
diff --git a/apps/desktop/test/helpers/hub-stub-hook.mjs b/apps/desktop/test/helpers/hub-stub-hook.mjsnew file mode 100644index 000000000..fdb90b5cb--- /dev/null+++ b/apps/desktop/test/helpers/hub-stub-hook.mjs@@ -0,0 +1,35 @@+/**+ * Module hooks for importing packages/voice-runtime sources under+ * `node --test`: `@huggingface/hub` is redirected to the controllable stub,+ * and `.ts` sources are esbuild-transformed (via vite's exported+ * transformWithEsbuild) onto the test's own ESM pipeline, so plain node+ * builds without native type-stripping can run them.+ *+ * Register with:+ * register(new URL("./helpers/hub-stub-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 hubStub = new URL("./hub-stub.mjs", import.meta.url).href;++export async function resolve(specifier, context, next) {+ if (specifier === "@huggingface/hub") {+ return next(hubStub, { ...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/helpers/hub-stub.mjs b/apps/desktop/test/helpers/hub-stub.mjsnew file mode 100644index 000000000..dcb8370cf--- /dev/null+++ b/apps/desktop/test/helpers/hub-stub.mjs@@ -0,0 +1,18 @@+/**+ * Controllable stand-in loaded in place of `@huggingface/hub` by+ * helpers/hub-stub-hook.mjs. A test installs a behavior function via+ * `setBehavior` and `downloadFile` forwards to it, so tests can stream+ * success bytes, fail mid-stream, or simulate any Response-like shape+ * without network access.+ */+let behavior = () => {+ throw new Error("hub-stub: no behavior installed");+};++export function setBehavior(next) {+ behavior = next;+}++export async function downloadFile(args) {+ return behavior(args);+}diff --git a/apps/desktop/test/voice-model-download.test.mjs b/apps/desktop/test/voice-model-download.test.mjsnew file mode 100644index 000000000..8217616af--- /dev/null+++ b/apps/desktop/test/voice-model-download.test.mjs@@ -0,0 +1,93 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+import { mkdtemp, mkdir, readFile, readdir, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++// Redirect `@huggingface/hub` to the stub and esbuild-transform the+// voice-runtime sources so the real downloader runs without network access.+register(new URL("./helpers/hub-stub-hook.mjs", import.meta.url).href);++const { downloadModel } = await import(+ "../../../packages/voice-runtime/src/model-downloader.ts"+);+const { setBehavior } = await import("./helpers/hub-stub.mjs");++const MODEL = {+ id: "whisper-small",+ hfRepo: "fixture/whisper-small-GGUF",+ hfFilename: "ggml-small-q8_0.bin",+ sizeBytes: 9,+};++function responseFrom(chunks, { failAfter } = {}) {+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);+ let sent = 0;+ const body = new ReadableStream({+ start(controller) {+ for (const chunk of chunks) {+ sent += 1;+ controller.enqueue(new Uint8Array(chunk));+ if (failAfter !== undefined && sent >= failAfter) {+ controller.error(new Error("hub connection reset mid-stream"));+ return;+ }+ }+ if (failAfter === undefined) controller.close();+ },+ });+ return {+ headers: { get: () => String(total) },+ body,+ };+}++async function tmpDir(t) {+ const dir = await mkdtemp(join(tmpdir(), "voice-download-"));+ t.after(() => rm(dir, { recursive: true, force: true }));+ return dir;+}++async function consume(generator) {+ let last = 0;+ for await (const progress of generator) last = progress;+ return last;+}++test("a completed download lands at the final path with the .part file gone", async (t) => {+ const dir = await tmpDir(t);+ setBehavior(() => responseFrom([[1, 2, 3], [4, 5], [6, 7, 8, 9]]));++ const last = await consume(downloadModel(MODEL, dir));+ assert.equal(last, 1);+ const bytes = await readFile(join(dir, "ggml-small-q8_0.bin"));+ assert.deepEqual([...bytes], [1, 2, 3, 4, 5, 6, 7, 8, 9]);+ const entries = await readdir(dir);+ assert.deepEqual(entries, ["ggml-small-q8_0.bin"], "no .part residue");+});++test("a mid-stream source failure rejects and leaves neither the final file nor the .part", async (t) => {+ const dir = await tmpDir(t);+ setBehavior(() => responseFrom([[1, 2, 3], [4, 5, 6]], { failAfter: 2 }));++ await assert.rejects(+ consume(downloadModel(MODEL, dir)),+ /hub connection reset mid-stream/,+ );+ const entries = await readdir(dir);+ assert.deepEqual(entries, [], "no truncated model, no .part residue");+});++test("an unwritable .part path surfaces a download failure instead of crashing the process", async (t) => {+ const dir = await tmpDir(t);+ setBehavior(() => responseFrom([[1, 2, 3]]));+ // A directory sitting at the .part path makes the WriteStream's open fail+ // asynchronously — the exact "unhandled stream error" shape that used to+ // take down the Electron main process.+ await mkdir(join(dir, "ggml-small-q8_0.bin.part"));++ await assert.rejects(consume(downloadModel(MODEL, dir)));+ const entries = await readdir(dir);+ assert.deepEqual(entries, ["ggml-small-q8_0.bin.part"], "final path never created");+});diff --git a/packages/voice-runtime/src/model-downloader.ts b/packages/voice-runtime/src/model-downloader.tsindex 592a0e4f2..0df1a0461 100644--- a/packages/voice-runtime/src/model-downloader.ts+++ b/packages/voice-runtime/src/model-downloader.ts@@ -1,10 +1,14 @@-import { mkdir } from "node:fs/promises";+import { mkdir, rename, unlink } from "node:fs/promises";import path from "node:path";import type { ModelInfo } from "./types.js";/*** Download a model from HuggingFace Hub to targetDir.* Yields progress 0–1. Supports abort via signal.+ *+ * Bytes land at `<target>.part` and are renamed into place only after the+ * stream completed, so an interrupted download never leaves a truncated+ * file behind for `ModelManager` to mistake for a finished one.*/export async function* downloadModel(info: ModelInfo,@@ -14,6 +18,7 @@ export async function* downloadModel(await mkdir(targetDir, { recursive: true });const targetPath = path.join(targetDir, info.hfFilename);+ const partPath = `${targetPath}.part`;// Dynamic import of @huggingface/hubconst { downloadFile } = await import("@huggingface/hub");@@ -34,18 +39,40 @@ export async function* downloadModel(let received = 0;const { createWriteStream } = await import("node:fs");- const writer = createWriteStream(targetPath);+ const writer = createWriteStream(partPath);+ // A write error (ENOSPC, EIO) must surface as a failed download, not as+ // an unhandled 'error' event — downloads run in the Electron main+ // process, where that is an app crash. The rejection races the source+ // reads below; the pre-attached catch keeps a rejection nobody is+ // awaiting from turning into an unhandledRejection.+ let streamError: unknown = null;+ let rejectStreamFailure: ((error: unknown) => void) | null = null;+ const streamFailure = new Promise<never>((_, reject) => {+ rejectStreamFailure = reject;+ });+ streamFailure.catch(() => {});+ writer.on("error", (error: unknown) => {+ streamError = error;+ rejectStreamFailure?.(error);+ });+ // 'close' fires on every terminal path (end, destroy, autoClose on+ // error) and means the file handle is released — awaited before the+ // rename and before unlinking a failed download, both of which fail+ // with EBUSY/EPERM on Windows while the handle is still open.+ const writerClosed = new Promise<void>((resolve) => {+ writer.once("close", () => resolve());+ });- try {- const reader = response.body.getReader();+ const reader = response.body.getReader();+ try {while (true) {if (signal?.aborted) {reader.cancel();throw new DOMException("Download aborted", "AbortError");}- const { done, value } = await reader.read();+ const { done, value } = await Promise.race([reader.read(), streamFailure]);if (done) break;writer.write(Buffer.from(value));@@ -57,13 +84,16 @@ export async function* downloadModel(writer.end(() => resolve());writer.on("error", reject);});+ if (streamError) throw streamError;+ await writerClosed;+ await rename(partPath, targetPath);yield 1;} catch (error) {writer.destroy();- // Clean up partial file- const { unlink } = await import("node:fs/promises");- await unlink(targetPath).catch(() => {});+ await writerClosed;+ // Clean up the partial download; the final path is never touched.+ await unlink(partPath).catch(() => {});throw error;}}