Skip to content

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

perf(desktop): shrink packaged app and load transcription natively

vastsa1def4c58dcb5
diff --git a/Cargo.toml b/Cargo.toml
index c22c8820e..69c6dd8b6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,3 +6,13 @@ resolver = "2"
edition = "2021"
license = "LGPL-3.0-or-later"
version = "0.21.0"
+
+# Release builds ship inside the installer; nothing reads host-core's symbol
+# table at runtime (panic messages keep their file:line locations), so strip it.
+# Whole-program LTO with one codegen unit cuts the binary by about a third
+# (19.5 MB -> 12.8 MB on macOS arm64) at the cost of a slower release build;
+# dev and test profiles are unaffected.
+[profile.release]
+strip = true
+lto = true
+codegen-units = 1
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index a50651a87..3ea0a835a 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -42,8 +42,44 @@ function dropLegacyFontFallbacks(): Plugin {
};
}
+// Main bundles both its own imports and the workspace agent packages. pnpm
+// gives `@earendil-works/pi-ai` a separate peer variant per importer (its
+// `openai` peer resolves a different optional `undici`), and the workspace
+// packages pin different `typebox` patches, so Rollup otherwise ships two
+// copies of pi-ai, openai and typebox (~2 MB of duplicate code). Resolve these
+// bare imports from the agent runtime package, the owner of the Pi kernel pin,
+// so every importer in Main shares one copy.
+const MAIN_SHARED_PACKAGES = ["@earendil-works/pi-ai", "typebox"];
+const AGENT_RUNTIME_ANCHOR = resolve(
+ __dirname,
+ "../../packages/agent-runtime/package.json",
+);
+
+function dedupeMainPackages(): Plugin {
+ const pattern = new RegExp(
+ `^(?:${MAIN_SHARED_PACKAGES.map((name) => name.replace(/[/.]/g, "\\$&")).join("|")})(?:/|$)`,
+ );
+ return {
+ name: "pi-dedupe-main-packages",
+ apply: "build",
+ enforce: "pre",
+ async resolveId(source, importer, options) {
+ if (!pattern.test(source) || importer === AGENT_RUNTIME_ANCHOR) return null;
+ const resolved = await this.resolve(source, AGENT_RUNTIME_ANCHOR, {
+ ...options,
+ skipSelf: true,
+ });
+ if (!resolved) {
+ this.error(`pi-dedupe-main-packages: cannot resolve ${source} from the agent runtime`);
+ }
+ return resolved;
+ },
+ };
+}
+
export default defineConfig({
main: {
+ plugins: [dedupeMainPackages()],
// `ws` loads its optional native accelerators (bufferutil, utf-8-validate)
// inside `require` + try/catch and falls back to its own JavaScript
// implementation when they are absent. A bundle cannot fail a require, and
@@ -57,7 +93,15 @@ export default defineConfig({
// the CommonJS `__dirname` global used by Electron's relative asset paths.
"__dirname": "import.meta.dirname",
},
+ // Packaged builds ship no source maps, so keep identifiers intact for
+ // readable stack traces in logs and only strip whitespace and syntax.
+ esbuild: {
+ minifyIdentifiers: false,
+ },
build: {
+ // electron-vite leaves Main unminified; whitespace/syntax minification
+ // shrinks the packaged Main bundle without renaming anything.
+ minify: "esbuild",
rollupOptions: {
// Bundle JS workspace packages into Main. Native voice modules must
// resolve from packaged node_modules because their loaders locate
diff --git a/apps/desktop/electron/main/transcribe-native-library.ts b/apps/desktop/electron/main/transcribe-native-library.ts
new file mode 100644
index 000000000..3960842c1
--- /dev/null
+++ b/apps/desktop/electron/main/transcribe-native-library.ts
@@ -0,0 +1,93 @@
+/**
+ * Points transcribe-cpp at the unpacked copy of its native library in
+ * packaged builds.
+ *
+ * transcribe-cpp resolves its `@transcribe-cpp/<platform>` provider with
+ * `require.resolve`, which in a packaged app yields a path inside
+ * `app.asar`. Electron's fs shims make that path readable, but koffi hands
+ * it to the OS loader (dlopen / LoadLibrary), which cannot see into an asar
+ * archive, so local transcription fails to load. The provider is listed in
+ * `asarUnpack`; this module redirects the loader to that real file through
+ * transcribe-cpp's documented `TRANSCRIBE_LIBRARY` override. Development
+ * trees contain no `app.asar` segment and are left untouched.
+ */
+
+import { existsSync } from "node:fs";
+import path from "node:path";
+
+const ASAR_SEGMENT = "app.asar";
+const UNPACKED_SEGMENT = "app.asar.unpacked";
+
+/** Library file name transcribe-cpp loads from its provider directory. */
+export function transcribeLibraryFileName(platform: NodeJS.Platform): string {
+ if (platform === "darwin") return "libtranscribe.dylib";
+ if (platform === "win32") return "transcribe.dll";
+ return "libtranscribe.so";
+}
+
+/**
+ * Map a path inside `app.asar` to its `app.asar.unpacked` sibling, or return
+ * null when the path is not inside an asar archive.
+ */
+export function toUnpackedAsarPath(filePath: string, sep: string = path.sep): string | null {
+ const segments = filePath.split(sep);
+ const index = segments.indexOf(ASAR_SEGMENT);
+ if (index < 0) return null;
+ segments[index] = UNPACKED_SEGMENT;
+ return segments.join(sep);
+}
+
+export interface TranscribeLibraryOverrideInput {
+ /** Current `TRANSCRIBE_LIBRARY` value; an explicit override always wins. */
+ readonly currentOverride: string | undefined;
+ /** transcribe-cpp's resolved provider directory. */
+ readonly artifactDir: string;
+ readonly platform: NodeJS.Platform;
+ readonly sep?: string;
+ readonly exists: (filePath: string) => boolean;
+}
+
+/**
+ * Return the unpacked library path to export as `TRANSCRIBE_LIBRARY`, or null
+ * when no redirect is needed or possible.
+ */
+export function resolveTranscribeLibraryOverride(
+ input: TranscribeLibraryOverrideInput,
+): string | null {
+ if (input.currentOverride) return null;
+ const sep = input.sep ?? path.sep;
+ const unpackedDir = toUnpackedAsarPath(input.artifactDir, sep);
+ if (!unpackedDir) return null;
+ const libraryPath = [unpackedDir, transcribeLibraryFileName(input.platform)].join(sep);
+ return input.exists(libraryPath) ? libraryPath : null;
+}
+
+type TranscribeCppModule = { artifactDir(): string };
+
+/**
+ * Export `TRANSCRIBE_LIBRARY` for the unpacked provider before transcribe-cpp
+ * loads its native library. Resolution failures are left for transcribe-cpp to
+ * report with its own diagnostics when the model actually loads.
+ */
+export async function pinUnpackedTranscribeLibrary(
+ env: NodeJS.ProcessEnv = process.env,
+ loadModule: () => Promise<TranscribeCppModule> = () =>
+ import("transcribe-cpp") as Promise<TranscribeCppModule>,
+): Promise<void> {
+ if (env.TRANSCRIBE_LIBRARY) return;
+ let artifactDir: string;
+ try {
+ artifactDir = (await loadModule()).artifactDir();
+ } catch {
+ // Missing or partial provider installs surface through ModelManager's
+ // load error, which carries transcribe-cpp's install diagnosis.
+ return;
+ }
+ const override = resolveTranscribeLibraryOverride({
+ currentOverride: env.TRANSCRIBE_LIBRARY,
+ artifactDir,
+ platform: process.platform,
+ exists: existsSync,
+ });
+ if (override) env.TRANSCRIBE_LIBRARY = override;
+}
diff --git a/apps/desktop/electron/main/voice-service.ts b/apps/desktop/electron/main/voice-service.ts
index fd91f43bb..99bed581a 100644
--- a/apps/desktop/electron/main/voice-service.ts
+++ b/apps/desktop/electron/main/voice-service.ts
@@ -9,6 +9,7 @@ import { BrowserWindow } from "electron";
import { randomUUID } from "node:crypto";
import { onConfirmedQuit } from "./bootstrap/confirmed-quit";
import { PvRecorderBackend, checkMicrophonePermission, requestMicrophonePermission } from "./audio-backend";
+import { pinUnpackedTranscribeLibrary } from "./transcribe-native-library";
import type {
AudioCaptureFactory,
AudioInputDevice,
@@ -75,6 +76,9 @@ export class VoiceService {
private async ensureRuntime(): Promise<void> {
if (this.controller) return;
+ // Must run before ModelManager first imports transcribe-cpp's loader.
+ await pinUnpackedTranscribeLibrary();
+
const {
VoiceController,
TranscriptionEngine,
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 7aa732226..49d735575 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -104,7 +104,11 @@
"!**/node_modules/**/*.{test,spec}.{js,cjs,mjs}",
"!**/node_modules/node-addon-api/tools/**",
"!**/node_modules/node-addon-api/*.{c,gyp,gypi,h,js,json}",
- "!**/node_modules/node-addon-api/README.md"
+ "!**/node_modules/node-addon-api/README.md",
+ "!**/node_modules/koffi/{doc,vendor}/**",
+ "!**/node_modules/@picovoice/pvrecorder-node/{src/**,copy.js,jest.config.js,tsconfig.json}",
+ "!**/node_modules/@picovoice/pvrecorder-node/lib/!(${os}*|raspberry-pi)/**",
+ "!**/node_modules/@picovoice/pvrecorder-node/[!${os}]ib/raspberry-pi/**"
],
"electronLanguages": [
"en-US",
@@ -291,6 +295,8 @@
"asarUnpack": [
"node_modules/transcribe-cpp/**/*.node",
"node_modules/transcribe-cpp/**/bin/**",
+ "node_modules/@transcribe-cpp/**",
+ "node_modules/@koromix/**/*.node",
"node_modules/@picovoice/pvrecorder-node/**/*.node",
"node_modules/@picovoice/pvrecorder-node/**/lib/**"
],
diff --git a/apps/desktop/test/packaging-footprint.test.mjs b/apps/desktop/test/packaging-footprint.test.mjs
index 831d796be..f581fe1be 100644
--- a/apps/desktop/test/packaging-footprint.test.mjs
+++ b/apps/desktop/test/packaging-footprint.test.mjs
@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
import test from "node:test";
+const require = createRequire(import.meta.url);
+
const packageJson = JSON.parse(
await readFile(new URL("../package.json", import.meta.url), "utf8"),
);
@@ -274,9 +277,73 @@ test("packaging keeps voice native payloads unpacked and excludes removed PTY pa
assert.deepEqual(packageJson.build.asarUnpack, [
"node_modules/transcribe-cpp/**/*.node",
"node_modules/transcribe-cpp/**/bin/**",
+ // koffi hands the provider's library path straight to dlopen/LoadLibrary,
+ // which cannot read inside app.asar (see transcribe-native-library.ts).
+ "node_modules/@transcribe-cpp/**",
+ "node_modules/@koromix/**/*.node",
"node_modules/@picovoice/pvrecorder-node/**/*.node",
"node_modules/@picovoice/pvrecorder-node/**/lib/**",
]);
assert.doesNotMatch(JSON.stringify(packageJson.build.files), /node-pty/);
assert.doesNotMatch(JSON.stringify(packageJson.build.extraResources), /node-pty/);
});
+
+test("packaging ships only the target platform's voice native payloads", () => {
+ // electron-builder merges platform-level `files` into a matcher that holds
+ // only exclusions and then includes the whole app directory, so per-target
+ // filtering lives in the root list through the `${os}` macro (mac | win |
+ // linux). Patterns are evaluated in order, like electron-builder's filter.
+ const builderRequire = createRequire(require.resolve("electron-builder"));
+ const { Minimatch } = createRequire(builderRequire.resolve("app-builder-lib"))("minimatch");
+ const recorderPatterns = packageJson.build.files.filter((pattern) =>
+ pattern.startsWith("!**/node_modules/@picovoice/pvrecorder-node/") && pattern.includes("${os}"),
+ );
+ assert.equal(recorderPatterns.length, 2);
+ const libDirs = ["mac/arm64", "mac/x86_64", "windows/amd64", "windows/arm64", "linux/x86_64",
+ "raspberry-pi/cortex-a72-aarch64"];
+ const shipped = (os) => {
+ const matchers = ["**/*", ...recorderPatterns].map(
+ (pattern) => new Minimatch(pattern.replaceAll("${os}", os), { dot: true }),
+ );
+ return libDirs.filter((dir) => {
+ const file = `node_modules/@picovoice/pvrecorder-node/lib/${dir}/pv_recorder.node`;
+ let match = false;
+ for (const matcher of matchers) {
+ if (match !== matcher.negate) continue;
+ match = matcher.match(file);
+ }
+ return match;
+ });
+ };
+ assert.deepEqual(shipped("mac"), ["mac/arm64", "mac/x86_64"]);
+ assert.deepEqual(shipped("win"), ["windows/amd64", "windows/arm64"]);
+ // Linux arm64 loads the Raspberry Pi builds (pvrecorder's own platform map).
+ assert.deepEqual(shipped("linux"), ["linux/x86_64", "raspberry-pi/cortex-a72-aarch64"]);
+
+ for (const platform of ["mac", "win", "linux"]) {
+ assert.equal(packageJson.build[platform].files, undefined, `${platform}.files would ship src/`);
+ }
+ for (const pattern of [
+ "!**/node_modules/koffi/{doc,vendor}/**",
+ "!**/node_modules/@picovoice/pvrecorder-node/{src/**,copy.js,jest.config.js,tsconfig.json}",
+ ]) {
+ assert.ok(packageJson.build.files.includes(pattern), `${pattern} must stay excluded`);
+ }
+ // koffi's JS entry imports src/koffi/src/static.js at runtime.
+ assert.ok(packageJson.build.files.every((pattern) => !pattern.includes("koffi/src")));
+});
+
+test("main output is minified without renaming and shares one Pi SDK copy", () => {
+ const mainConfig = viteConfigSource.slice(
+ viteConfigSource.indexOf(" main: {"),
+ viteConfigSource.indexOf(" preload: {"),
+ );
+ assert.match(mainConfig, /minify:\s*"esbuild"/);
+ // Packaged builds ship no source maps; identifiers keep stack traces readable.
+ assert.match(mainConfig, /minifyIdentifiers:\s*false/);
+ assert.match(mainConfig, /plugins:\s*\[dedupeMainPackages\(\)\]/);
+ assert.match(
+ viteConfigSource,
+ /MAIN_SHARED_PACKAGES = \["@earendil-works\/pi-ai", "typebox"\]/,
+ );
+});
diff --git a/apps/desktop/test/transcribe-native-library.test.mjs b/apps/desktop/test/transcribe-native-library.test.mjs
new file mode 100644
index 000000000..ed17cfec5
--- /dev/null
+++ b/apps/desktop/test/transcribe-native-library.test.mjs
@@ -0,0 +1,96 @@
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url).href);
+
+const {
+ pinUnpackedTranscribeLibrary,
+ resolveTranscribeLibraryOverride,
+ toUnpackedAsarPath,
+ transcribeLibraryFileName,
+} = await import("../electron/main/transcribe-native-library.ts");
+
+test("maps only the app.asar path segment to its unpacked sibling", () => {
+ assert.equal(
+ toUnpackedAsarPath("/A.app/Contents/Resources/app.asar/node_modules/@transcribe-cpp/x", "/"),
+ "/A.app/Contents/Resources/app.asar.unpacked/node_modules/@transcribe-cpp/x",
+ );
+ assert.equal(
+ toUnpackedAsarPath("C:\\PI\\resources\\app.asar\\node_modules\\@transcribe-cpp\\x", "\\"),
+ "C:\\PI\\resources\\app.asar.unpacked\\node_modules\\@transcribe-cpp\\x",
+ );
+ // Development trees and look-alike names are not asar archives.
+ assert.equal(toUnpackedAsarPath("/repo/node_modules/@transcribe-cpp/x", "/"), null);
+ assert.equal(toUnpackedAsarPath("/repo/my-app.asar.d/x", "/"), null);
+ assert.equal(toUnpackedAsarPath("/A/app.asar.unpacked/x", "/"), null);
+});
+
+test("library file names follow transcribe-cpp's per-platform loader", () => {
+ assert.equal(transcribeLibraryFileName("darwin"), "libtranscribe.dylib");
+ assert.equal(transcribeLibraryFileName("win32"), "transcribe.dll");
+ assert.equal(transcribeLibraryFileName("linux"), "libtranscribe.so");
+});
+
+test("override targets the unpacked library only when it exists and none is set", () => {
+ const artifactDir = "/R/app.asar/node_modules/@transcribe-cpp/darwin-arm64-metal";
+ const expected = "/R/app.asar.unpacked/node_modules/@transcribe-cpp/darwin-arm64-metal/libtranscribe.dylib";
+ const base = { artifactDir, platform: "darwin", sep: "/" };
+
+ assert.equal(
+ resolveTranscribeLibraryOverride({ ...base, currentOverride: undefined, exists: (p) => p === expected }),
+ expected,
+ );
+ assert.equal(
+ resolveTranscribeLibraryOverride({ ...base, currentOverride: undefined, exists: () => false }),
+ null,
+ "a missing unpacked copy must leave transcribe-cpp's own resolution in place",
+ );
+ assert.equal(
+ resolveTranscribeLibraryOverride({ ...base, currentOverride: "/custom/lib.dylib", exists: () => true }),
+ null,
+ "an explicit TRANSCRIBE_LIBRARY always wins",
+ );
+ assert.equal(
+ resolveTranscribeLibraryOverride({
+ ...base,
+ artifactDir: "/repo/node_modules/@transcribe-cpp/darwin-arm64-metal",
+ currentOverride: undefined,
+ exists: () => true,
+ }),
+ null,
+ );
+});
+
+test("pins TRANSCRIBE_LIBRARY to a real unpacked provider before loading", async () => {
+ const root = await mkdtemp(join(tmpdir(), "pi-transcribe-unpacked-"));
+ try {
+ const provider = join("node_modules", "@transcribe-cpp", "tuple");
+ const unpackedDir = join(root, "app.asar.unpacked", provider);
+ await mkdir(unpackedDir, { recursive: true });
+ const library = join(unpackedDir, transcribeLibraryFileName(process.platform));
+ await writeFile(library, "");
+ const loadModule = async () => ({ artifactDir: () => join(root, "app.asar", provider) });
+
+ const env = {};
+ await pinUnpackedTranscribeLibrary(env, loadModule);
+ assert.equal(env.TRANSCRIBE_LIBRARY, library);
+
+ const userEnv = { TRANSCRIBE_LIBRARY: "/custom/lib" };
+ await pinUnpackedTranscribeLibrary(userEnv, loadModule);
+ assert.equal(userEnv.TRANSCRIBE_LIBRARY, "/custom/lib");
+
+ const missingEnv = {};
+ await pinUnpackedTranscribeLibrary(missingEnv, async () => ({
+ artifactDir: () => {
+ throw new Error("provider not installed");
+ },
+ }));
+ assert.equal(missingEnv.TRANSCRIBE_LIBRARY, undefined);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});