Skip to content
TypeScript

perf(desktop): cache compiled JavaScript between launches (#13501)

Theo Browned10bd1360ace
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 2e48f321dd4..daedb89a128 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -3,7 +3,7 @@
"version": "0.0.42",
"private": true,
"type": "module",
- "main": "dist-electron/main.cjs",
+ "main": "dist-electron/boot.cjs",
"scripts": {
"ensure:electron": "node scripts/ensure-electron-runtime.mjs",
"start": "node scripts/start-electron.mjs",
diff --git a/apps/desktop/scripts/main-process-bundle.test.mjs b/apps/desktop/scripts/main-process-bundle.test.mjs
index 28d8e37d7a9..678b62f58aa 100644
--- a/apps/desktop/scripts/main-process-bundle.test.mjs
+++ b/apps/desktop/scripts/main-process-bundle.test.mjs
@@ -1,3 +1,4 @@
+import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
@@ -108,3 +109,65 @@ void import("./linux.ts").then(({ result }) => process.emit("ready", result));`,
await NodeFSP.rm(directory, { recursive: true, force: true });
}
});
+
+it("loads the emitted packaged boot entry and backend cache preload", async () => {
+ const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-desktop-boot-"));
+ try {
+ const entries = ["src/boot.ts", "src/compileCache.ts"];
+ await NodeFSP.mkdir(NodePath.join(directory, "src"));
+ await Promise.all(
+ entries.map((entry) =>
+ NodeFSP.copyFile(new URL(`../${entry}`, import.meta.url), NodePath.join(directory, entry)),
+ ),
+ );
+ assert.ok(Array.isArray(desktopConfig.pack));
+ for (const packConfig of desktopConfig.pack) {
+ if (!Array.isArray(packConfig.entry)) continue;
+ if (!packConfig.entry.some((entry) => entries.includes(entry))) continue;
+ await build({
+ ...packConfig,
+ config: false,
+ cwd: directory,
+ tsconfig: false,
+ sourcemap: false,
+ onSuccess: undefined,
+ logLevel: "silent",
+ });
+ }
+ const outputDirectory = NodePath.join(directory, "dist-electron");
+ const fixture = `console.log(require('node:module').getCompileCacheDir() ? 'cached' : 'uncached');`;
+ await NodeFSP.writeFile(NodePath.join(outputDirectory, "main.cjs"), fixture);
+ await NodeFSP.writeFile(
+ NodePath.join(outputDirectory, "backend.mjs"),
+ `import { getCompileCacheDir } from 'node:module'; console.log(getCompileCacheDir() ? 'cached' : 'uncached');`,
+ );
+ for (const disabled of [false, true]) {
+ for (const args of [
+ [NodePath.join(outputDirectory, "boot.cjs")],
+ [
+ "--require",
+ NodePath.join(outputDirectory, "compileCache.cjs"),
+ NodePath.join(outputDirectory, "backend.mjs"),
+ ],
+ ]) {
+ const child = NodeChildProcess.spawnSync(process.execPath, args, {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ APPIMAGE: "",
+ NODE_COMPILE_CACHE: undefined,
+ NODE_DISABLE_COMPILE_CACHE: disabled ? "1" : undefined,
+ XDG_CACHE_HOME: directory,
+ TMPDIR: directory,
+ TEMP: directory,
+ TMP: directory,
+ },
+ });
+ assert.equal(child.status, 0, child.stderr);
+ assert.equal(child.stdout.trim(), disabled ? "uncached" : "cached");
+ }
+ }
+ } finally {
+ await NodeFSP.rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/scripts/smoke-test.mjs b/apps/desktop/scripts/smoke-test.mjs
index fea5f0a120e..05195bb8d8c 100644
--- a/apps/desktop/scripts/smoke-test.mjs
+++ b/apps/desktop/scripts/smoke-test.mjs
@@ -5,7 +5,7 @@ import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const desktopDir = NodePath.resolve(__dirname, "..");
-const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");
+const mainJs = NodePath.resolve(desktopDir, "dist-electron/boot.cjs");
console.log("\nLaunching Electron smoke test...");
diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts
index d6924b08ace..beb09bd50a4 100644
--- a/apps/desktop/src/app/DesktopEnvironment.ts
+++ b/apps/desktop/src/app/DesktopEnvironment.ts
@@ -66,6 +66,8 @@ export class DesktopEnvironment extends Context.Service<
readonly clientAssetsDir: string;
readonly backendCwd: string;
readonly preloadPath: string;
+ // Preload that turns on the V8 compile cache for the local backend.
+ readonly compileCachePath: string;
readonly appUpdateYmlPath: string;
readonly devServerUrl: Option.Option<URL>;
readonly devRemoteT3ServerEntryPath: Option.Option<string>;
@@ -221,6 +223,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
clientAssetsDir: path.join(serverRoot, "apps/server/dist/client"),
backendCwd: input.isPackaged ? homeDirectory : appRoot,
preloadPath: path.join(input.dirname, "preload.cjs"),
+ compileCachePath: path.join(input.dirname, "compileCache.cjs"),
appUpdateYmlPath: input.isPackaged
? path.join(resourcesPath, "app-update.yml")
: path.join(input.appPath, "dev-app-update.yml"),
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index 83189e1ee0a..8d297750f78 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -235,6 +235,11 @@ describe("DesktopBackendConfiguration", () => {
const second = yield* configuration.resolvePrimary;
assert.equal(first.executablePath, process.execPath);
+ assert.deepEqual(first.args.slice(0, 3), [
+ "--require",
+ environment.compileCachePath,
+ environment.backendEntryPath,
+ ]);
assert.equal(first.entryPath, environment.backendEntryPath);
assert.equal(first.cwd, environment.backendCwd);
assert.equal(first.captureOutput, true);
@@ -927,6 +932,8 @@ describe("DesktopBackendConfiguration", () => {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
assert.equal(config.captureOutput, true);
+ // Dev never shares the prod compile cache.
+ assert.notInclude(config.args, "--require");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
index 13b6eef442a..d400c7a3a87 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -550,7 +550,16 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
return {
executablePath: process.execPath,
- args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
+ // Packaged builds only, so a dev instance never shares the cache with the
+ // prod app it is often run from. `--require` rather than NODE_COMPILE_CACHE,
+ // so the setting does not leak into the provider and terminal processes
+ // the backend starts.
+ args: [
+ ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
+ environment.backendEntryPath,
+ "--bootstrap-fd",
+ "3",
+ ],
entryPath: environment.backendEntryPath,
cwd: environment.backendCwd,
env: {
diff --git a/apps/desktop/src/boot.ts b/apps/desktop/src/boot.ts
new file mode 100644
index 00000000000..c9eb35b24e5
--- /dev/null
+++ b/apps/desktop/src/boot.ts
@@ -0,0 +1,4 @@
+// Packaged app entry. Enables the compile cache before the main bundle loads,
+// so the cache also covers main.cjs itself.
+require("./compileCache.cjs");
+require("./main.cjs");
diff --git a/apps/desktop/src/compileCache.ts b/apps/desktop/src/compileCache.ts
new file mode 100644
index 00000000000..20f942db7db
--- /dev/null
+++ b/apps/desktop/src/compileCache.ts
@@ -0,0 +1,28 @@
+// @effect-diagnostics nodeBuiltinImport:off
+// Runs before any Effect runtime exists, so it stays on Node built-ins.
+import * as NodeModule from "node:module";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+// Turns on Node's on-disk V8 code cache for every module loaded after this one,
+// so later launches skip recompiling the large main and server bundles.
+// Packaged builds only: boot.ts loads it for the main process, and the local
+// backend gets it with `--require`. Dev launches main.cjs directly and skips it.
+// Linux uses the user's cache dir because /tmp is shared between users; the
+// macOS and Windows temp dirs are already per user.
+//
+// Skipped under AppImage: it mounts the app at a new /tmp/.mount_* path each
+// launch, and Node keys entries by path, so every launch would miss and leave
+// another copy behind. The backend inherits APPIMAGE, so this covers it too.
+try {
+ if (!process.env.APPIMAGE) {
+ const cacheRoot =
+ // oxlint-disable-next-line t3code/no-global-process-runtime -- Loads before any Effect runtime.
+ process.platform === "linux"
+ ? process.env.XDG_CACHE_HOME || NodePath.join(NodeOS.homedir(), ".cache")
+ : NodeOS.tmpdir();
+ NodeModule.enableCompileCache(NodePath.join(cacheRoot, "t3code", "compile-cache"));
+ }
+} catch {
+ // The cache is only a speedup. Never let it stop the app from starting.
+}
diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts
index c3cecf88b2e..30feb85043f 100644
--- a/apps/desktop/src/electron/ElectronProtocol.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.ts
@@ -126,6 +126,9 @@ function registerDesktopSchemePrivilegesSync(): void {
supportFetchAPI: true,
corsEnabled: true,
stream: true,
+ // Custom schemes skip Chromium's V8 code cache unless they opt in.
+ // Dev stays off: Vite serves changing code at stable URLs.
+ codeCache: true,
},
},
{
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index c451a89b576..17ce805ffe1 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -85,6 +85,19 @@ export default defineConfig({
onlyBundle: false,
},
},
+ {
+ // boot.cjs requires the other two at runtime, so all three stay separate files.
+ format: "cjs",
+ outDir: "dist-electron",
+ dts: false,
+ sourcemap: true,
+ outExtensions: () => ({ js: ".cjs" }),
+ entry: ["src/boot.ts", "src/compileCache.ts"],
+ clean: false,
+ deps: {
+ neverBundle: (id) => id === "./main.cjs" || id === "./compileCache.cjs",
+ },
+ },
{
format: "cjs",
outDir: "dist-electron",
diff --git a/apps/server/src/compileCache.test.ts b/apps/server/src/compileCache.test.ts
new file mode 100644
index 00000000000..17827bb38ba
--- /dev/null
+++ b/apps/server/src/compileCache.test.ts
@@ -0,0 +1,53 @@
+// @effect-diagnostics nodeBuiltinImport:off - the test kills a real Node process to prove the cache is on disk.
+import * as NodeChildProcess from "node:child_process";
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import { assert, it } from "@effect/vitest";
+
+it.each([false, true])(
+ "persists an enabled cache before forced exit (disabled: %s)",
+ async (disabled) => {
+ const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-compile-cache-"));
+ try {
+ const cacheDirectory = NodePath.join(directory, "cache");
+ const child = NodeChildProcess.spawnSync(
+ process.execPath,
+ [
+ "--input-type=module",
+ "--eval",
+ `import * as Effect from ${JSON.stringify(import.meta.resolve("effect/Effect"))};
+const { flushCompileCache } = await import(${JSON.stringify(new URL("./compileCache.ts", import.meta.url).href)});
+await Effect.runPromise(flushCompileCache);
+process.kill(process.pid, "SIGKILL");`,
+ ],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ NODE_COMPILE_CACHE: cacheDirectory,
+ NODE_DISABLE_COMPILE_CACHE: disabled ? "1" : undefined,
+ },
+ },
+ );
+ assert.equal(child.error, undefined);
+ assert.equal(child.stderr, "");
+ assert.notEqual(child.status, 0);
+ const entries = await NodeFSP.readdir(cacheDirectory, { recursive: true }).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return [];
+ throw error;
+ },
+ );
+ const files = await Promise.all(
+ entries.map((entry) => NodeFSP.stat(NodePath.join(cacheDirectory, entry))),
+ );
+ assert.equal(
+ files.some((entry) => entry.isFile()),
+ !disabled,
+ );
+ } finally {
+ await NodeFSP.rm(directory, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/apps/server/src/compileCache.ts b/apps/server/src/compileCache.ts
new file mode 100644
index 00000000000..d31e4305774
--- /dev/null
+++ b/apps/server/src/compileCache.ts
@@ -0,0 +1,9 @@
+import * as NodeModule from "node:module";
+import * as Effect from "effect/Effect";
+
+// Desktop enables this cache before loading the backend. Windows force-kills
+// the backend on quit, so persist it after startup instead of waiting for exit.
+// This is a no-op when caching is disabled, including normal dev launches.
+export const flushCompileCache = Effect.try(() => NodeModule.flushCompileCache()).pipe(
+ Effect.ignore,
+);
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index be0cbbc6a6b..138dbcedfa8 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -33,6 +33,7 @@ import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as ServerConfig from "./config.ts";
+import { flushCompileCache } from "./compileCache.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
@@ -1074,6 +1075,7 @@ export const make = (options?: StartupOptions) =>
}),
);
yield* Effect.logDebug("startup phase: complete");
+ yield* flushCompileCache;
}).pipe(
Effect.annotateSpans({
"server.mode": serverConfig.mode,
diff --git a/knip.jsonc b/knip.jsonc
index 5e87b4d5bc5..d2f1d7f8839 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -38,6 +38,8 @@
"src/snapShot/GlobalShiftShortcutWorker.ts!",
"src/snapShot/RegionSnapShotWorker.ts!",
"src/snapShot/SnapShotAccessibilityWorker.ts!",
+ "src/boot.ts!",
+ "src/compileCache.ts!",
"src/main.ts!",
"src/preload.ts!",
"src/preview-pick-preload.ts!",
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index c05716ced8f..d2d9df76794 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -3670,7 +3670,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
// Required by the .deb control file.
homepage: "https://t3.codes",
author: "T3 Tools",
- main: "apps/desktop/dist-electron/main.cjs",
+ main: "apps/desktop/dist-electron/boot.cjs",
build: yield* createBuildConfig(
options.platform,
options.target,