Skip to content
TypeScript

feat(desktop): prepare server bytecode cache in native builds (#28572)

Yash Singh58a407c0932b
diff --git a/apps/desktop/scripts/main-process-bundle.test.mjs b/apps/desktop/scripts/main-process-bundle.test.mjs
index 678b62f58aa..6e1f767d7d3 100644
--- a/apps/desktop/scripts/main-process-bundle.test.mjs
+++ b/apps/desktop/scripts/main-process-bundle.test.mjs
@@ -3,6 +3,7 @@ import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeVM from "node:vm";
+import * as NodeURL from "node:url";
import { build } from "vite-plus/pack";
import { assert, it } from "vite-plus/test";
@@ -114,18 +115,16 @@ 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,
+ entry: packConfig.entry.map((entry) =>
+ NodeURL.fileURLToPath(new URL(`../${entry}`, import.meta.url)),
+ ),
+ outDir: NodePath.join(directory, "dist-electron"),
config: false,
cwd: directory,
tsconfig: false,
diff --git a/apps/desktop/src/compileCache.ts b/apps/desktop/src/compileCache.ts
index abf8918df2a..7bbd9adc7f4 100644
--- a/apps/desktop/src/compileCache.ts
+++ b/apps/desktop/src/compileCache.ts
@@ -2,16 +2,23 @@
import * as NodeModule from "node:module";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
+import { enablePreparedServerCache } from "../../../scripts/lib/server-compile-cache.ts";
// Linux /tmp is shared; macOS and Windows temp dirs are per user.
// AppImage mounts change paths each launch, so Node's path-keyed cache would miss and accumulate copies.
try {
- if (!process.env.APPIMAGE) {
+ if (!process.env.APPIMAGE || process.env.ELECTRON_RUN_AS_NODE === "1") {
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"));
+ const directory = NodePath.join(cacheRoot, "t3code", "compile-cache");
+ const prepared =
+ process.env.ELECTRON_RUN_AS_NODE === "1" &&
+ enablePreparedServerCache(process.argv[1] ?? "", directory);
+ if (!prepared && !process.env.APPIMAGE) {
+ NodeModule.enableCompileCache(directory);
+ }
}
} catch {}
diff --git a/apps/desktop/src/serverCompileCache.ts b/apps/desktop/src/serverCompileCache.ts
new file mode 100644
index 00000000000..01e71b1aa87
--- /dev/null
+++ b/apps/desktop/src/serverCompileCache.ts
@@ -0,0 +1 @@
+export { generatePreparedServerCache } from "../../../scripts/lib/server-compile-cache.ts";
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index 55c3aa03b64..1160d901127 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -93,7 +93,7 @@ export default defineConfig({
dts: false,
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
- entry: ["src/boot.ts", "src/compileCache.ts"],
+ entry: ["src/boot.ts", "src/compileCache.ts", "src/serverCompileCache.ts"],
clean: false,
deps: {
neverBundle: (id) => id === "./main.cjs" || id === "./compileCache.cjs",
diff --git a/apps/server/src/compileCache.ts b/apps/server/src/compileCache.ts
index 0a7345995a8..b01db74cbe3 100644
--- a/apps/server/src/compileCache.ts
+++ b/apps/server/src/compileCache.ts
@@ -2,6 +2,8 @@ import * as NodeModule from "node:module";
import * as Effect from "effect/Effect";
// Windows force-kills on quit; persist the cache after startup.
-export const flushCompileCache = Effect.try(() => NodeModule.flushCompileCache()).pipe(
- Effect.ignore,
-);
+export const flushCompileCache = Effect.try(() => {
+ if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) {
+ NodeModule.flushCompileCache();
+ }
+}).pipe(Effect.ignore);
diff --git a/docs/operations/development.md b/docs/operations/development.md
index df4affcad2a..537e574978f 100644
--- a/docs/operations/development.md
+++ b/docs/operations/development.md
@@ -261,6 +261,28 @@ DMGs default to the host architecture. Use `--arch` to choose another target and
to retain packaging files for inspection. Run `vp run dist:desktop:artifact --help` for other
options.
+### Prepared server bytecode
+
+Native desktop artifact builds generate server bytecode with the packaged Electron executable,
+after ASAR creation and before signing. Cross-platform and cross-architecture builds skip this
+step explicitly. CLI, SEA and WSL runtimes keep their existing behavior; only desktop backend
+imports covered by generation receive prepared bytecode. Worker-only modules compile normally.
+
+Electron's Node 24 cache has no read-only option and includes the producer UID in its directory
+name. The backend links individual prepared files into its writable cache with keys for the
+installed module paths. Node replaces files atomically, so regeneration cannot write through those
+links into signed resources. Windows uses hard links and falls back to normal caching when volumes
+differ or resource permissions prevent linking. Protected installations therefore may not reuse
+prepared bytecode. No cache bytes are copied during startup. AppImage backends discard their links
+on normal exit because each mount changes module paths.
+
+The key calculation follows Node's internal portable ESM format. Generation checks that the
+packaged engine produced the expected CLI entry and fails the build if that format changes.
+The manifest also checks Electron, Node, OS, architecture and V8's flags-sensitive version tag.
+Missing or rejected entries compile from the shipped JavaScript. Prepared backends skip the
+explicit startup flush; Node can persist missing entries on normal exit. The writable fallback
+keeps the explicit flush needed when Windows force-kills the backend.
+
### Linux AppImage prerequisites
Build on Linux because the browser-secret helper links against the host's libsecret. Install
diff --git a/knip.jsonc b/knip.jsonc
index c2093737fd9..615581793fb 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -32,6 +32,7 @@
"mobile-native-client.ts",
"setup-worktree.ts",
"sign-macos.ts",
+ "prepare-server-compile-cache.cjs",
"smoke-desktop-app.ts",
"verify-windows-desktop-artifact.ts",
],
@@ -73,6 +74,7 @@
"src/snapShot/SnapShotAccessibilityWorker.ts!",
"src/boot.ts!",
"src/compileCache.ts!",
+ "src/serverCompileCache.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 8ba7f1adcbb..5de3c068fc6 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -2771,6 +2771,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
arch?: typeof BuildArch.Type,
) {
const buildConfig: Record<string, unknown> = {
+ afterPack: (yield* Path.Path).join(yield* RepoRoot, "scripts/prepare-server-compile-cache.cjs"),
appId: DESKTOP_APP_ID,
productName: resolveDesktopProductName(version),
artifactName: "T3-Code-${version}-${arch}.${ext}",
diff --git a/scripts/lib/server-compile-cache.test.ts b/scripts/lib/server-compile-cache.test.ts
new file mode 100644
index 00000000000..1092de3ec51
--- /dev/null
+++ b/scripts/lib/server-compile-cache.test.ts
@@ -0,0 +1,108 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import { expect, it } from "vite-plus/test";
+import { cacheKey, seedPreparedCache } from "./server-compile-cache.ts";
+
+it("seeds relocated cache entries without allowing writes into shipped resources", () => {
+ const root = NodeFS.realpathSync(
+ NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-prepared-test-")),
+ );
+ try {
+ const prepared = NodePath.join(root, "resources", "server-compile-cache");
+ const active = NodePath.join(root, "user", "different-uid-tag");
+ NodeFS.mkdirSync(prepared, { recursive: true });
+ NodeFS.mkdirSync(active, { recursive: true });
+ NodeFS.writeFileSync(NodePath.join(prepared, "12345678"), "prepared bytes");
+ const manifest = {
+ format: 1,
+ runtime: "matching",
+ entries: [{ module: "app.asar/apps/server/dist/chunk.mjs", file: "12345678" }],
+ };
+ NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), JSON.stringify(manifest));
+ expect(seedPreparedCache(prepared, active, "wrong-engine")).toBe(false);
+ expect(seedPreparedCache(prepared, active, "matching")).toBe(true);
+ const key = cacheKey(active, NodePath.join(root, "resources", manifest.entries[0]!.module));
+ expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("prepared bytes");
+ // Node persists by replacing the directory entry, never by overwriting the linked inode.
+ NodeFS.rmSync(NodePath.join(active, key));
+ NodeFS.writeFileSync(NodePath.join(active, key), "runtime replacement");
+ expect(NodeFS.readFileSync(NodePath.join(prepared, "12345678"), "utf8")).toBe("prepared bytes");
+ expect(seedPreparedCache(prepared, active, "matching")).toBe(true);
+ expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("runtime replacement");
+ const missing = { module: "app.asar/apps/server/dist/missing.mjs", file: "87654321" };
+ for (const entries of [
+ [...manifest.entries, missing],
+ [missing, ...manifest.entries],
+ ]) {
+ NodeFS.writeFileSync(
+ NodePath.join(prepared, "manifest.json"),
+ JSON.stringify({ ...manifest, entries }),
+ );
+ expect(seedPreparedCache(prepared, active, "matching")).toBe(false);
+ }
+ NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), "corrupt");
+ expect(seedPreparedCache(prepared, active, "matching")).toBe(false);
+ expect(seedPreparedCache(NodePath.join(root, "missing"), active, "matching")).toBe(false);
+ } finally {
+ NodeFS.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+it.each(["app", "server"])(
+ "generates %s.asar cache with the consumer engine and falls back after damage",
+ async (archive) => {
+ const { spawnSync } = await import("node:child_process");
+ const helper = new URL("./server-compile-cache.ts", import.meta.url).href;
+ const root = NodeFS.realpathSync(
+ NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cache-engine-")),
+ );
+ const run = (code: string) => {
+ const env = {
+ ...process.env,
+ NODE_DEBUG_NATIVE: "COMPILE_CACHE",
+ NODE_COMPILE_CACHE: undefined,
+ NODE_DISABLE_COMPILE_CACHE: undefined,
+ };
+ const result = spawnSync(process.execPath, ["--input-type=module", "-e", code], {
+ env,
+ encoding: "utf8",
+ });
+ expect(result.status, result.stderr).toBe(0);
+ return result.stderr;
+ };
+ try {
+ const producer = NodePath.join(root, "producer", "resources");
+ const consumer = NodePath.join(root, "relocated", "resources");
+ const relative = `${archive}.asar/apps/server/dist/binCli-fixture.mjs`;
+ NodeFS.mkdirSync(NodePath.dirname(NodePath.join(producer, relative)), { recursive: true });
+ NodeFS.writeFileSync(NodePath.join(producer, relative), "export const answer = 42;");
+ run(
+ `import {generatePreparedServerCache} from ${JSON.stringify(helper)}; await generatePreparedServerCache(${JSON.stringify(producer)});`,
+ );
+ NodeFS.cpSync(producer, consumer, { recursive: true });
+ const consume = (home: string, appImage = false) =>
+ run(
+ `if (${appImage}) process.env.APPIMAGE = "fixture"; import {enablePreparedServerCache} from ${JSON.stringify(helper)}; import {pathToFileURL} from 'node:url'; if(!enablePreparedServerCache(${JSON.stringify(NodePath.join(consumer, relative))},${JSON.stringify(NodePath.join(root, home))})) throw Error('cache disabled'); const m = await import(pathToFileURL(${JSON.stringify(NodePath.join(consumer, relative))}).href); if(m.answer!==42) throw Error('source fallback failed');`,
+ );
+ const prepared = NodePath.join(consumer, "server-compile-cache");
+ NodeFS.chmodSync(prepared, 0o555);
+ expect(consume("first-user")).toContain("was accepted");
+ expect(consume("appimage-user", true)).toContain("was accepted");
+ expect(NodeFS.readdirSync(NodePath.join(root, "appimage-user", "server"))).toEqual([]);
+ NodeFS.chmodSync(prepared, 0o755);
+ for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) {
+ NodeFS.writeFileSync(NodePath.join(prepared, file), "broken");
+ }
+ expect(consume("second-user")).toContain("was not initialized");
+ for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) {
+ expect(NodeFS.readFileSync(NodePath.join(prepared, file), "utf8")).toBe("broken");
+ }
+ NodeFS.rmSync(prepared, { recursive: true });
+ expect(consume("third-user")).toContain("was not initialized");
+ } finally {
+ NodeFS.rmSync(root, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/scripts/lib/server-compile-cache.ts b/scripts/lib/server-compile-cache.ts
new file mode 100644
index 00000000000..63a21174ff6
--- /dev/null
+++ b/scripts/lib/server-compile-cache.ts
@@ -0,0 +1,136 @@
+/* oxlint-disable t3code/no-global-process-runtime -- Runs in the packaged engine before an Effect runtime exists. */
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
+import * as NodePath from "node:path";
+import * as NodeModule from "node:module";
+import * as NodeV8 from "node:v8";
+import * as NodeZlib from "node:zlib";
+import * as NodeURL from "node:url";
+
+export const runtimeIdentity = () =>
+ [
+ process.versions.electron,
+ process.version,
+ process.platform,
+ process.arch,
+ NodeV8.cachedDataVersionTag(),
+ ].join("-");
+
+// Node 24's portable key is CRC32 of the one-byte ESM type followed by the relative filename.
+// Generation verifies this against files produced by the packaged engine before shipping them.
+export const cacheKey = (active: string, filename: string) =>
+ NodeZlib.crc32(NodePath.relative(active, filename), NodeZlib.crc32(Buffer.from([1])))
+ .toString(16)
+ .padStart(8, "0");
+
+export function seedPreparedCache(prepared: string, active: string, runtime: string): boolean {
+ try {
+ const manifest: unknown = JSON.parse(
+ NodeFS.readFileSync(NodePath.join(prepared, "manifest.json"), "utf8"),
+ );
+ if (
+ typeof manifest !== "object" ||
+ manifest === null ||
+ !("format" in manifest) ||
+ manifest.format !== 1 ||
+ !("runtime" in manifest) ||
+ manifest.runtime !== runtime ||
+ !("entries" in manifest) ||
+ !Array.isArray(manifest.entries) ||
+ manifest.entries.length === 0
+ )
+ return false;
+ for (const entry of manifest.entries) {
+ if (
+ typeof entry?.module !== "string" ||
+ typeof entry?.file !== "string" ||
+ !/^[a-f0-9]{8}$/.test(entry.file) ||
+ !/^(app|server)\.asar\/apps\/server\/dist\/[^/\\]+\.mjs$/.test(entry.module)
+ )
+ return false;
+ const source = NodePath.join(prepared, entry.file);
+ const destination = NodePath.join(
+ active,
+ cacheKey(active, NodePath.join(NodePath.dirname(prepared), entry.module)),
+ );
+ try {
+ // Node replaces cache files atomically. A directory link would instead allow writes into signed resources.
+ if (process.platform === "win32") NodeFS.linkSync(source, destination);
+ else NodeFS.symlinkSync(source, destination);
+ } catch {}
+ if (!NodeFS.existsSync(destination)) return false;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function enablePreparedServerCache(entry: string, cacheRoot: string): boolean {
+ try {
+ const archive = entry.match(/^(.*[\\/](?:app|server)\.asar)[\\/]/)?.[1];
+ if (!archive) return false;
+ const resources = NodeFS.realpathSync(NodePath.dirname(archive));
+ // Keep different installations and builds separate without reading or copying their source files.
+ const prepared = NodePath.join(resources, "server-compile-cache");
+ if (process.env.APPIMAGE && !NodeFS.existsSync(NodePath.join(prepared, "manifest.json")))
+ return false;
+ const identity = NodeZlib.crc32(resources).toString(16);
+ NodeFS.mkdirSync(NodePath.join(cacheRoot, "server"), { recursive: true });
+ const directory = process.env.APPIMAGE
+ ? NodeFS.mkdtempSync(NodePath.join(cacheRoot, "server", "appimage-"))
+ : NodePath.join(cacheRoot, "server", identity);
+ if (process.env.APPIMAGE) {
+ // Each mount has different module paths; discard its links rather than accumulating caches.
+ process.once("exit", () => {
+ try {
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ } catch {}
+ });
+ }
+ const result = NodeModule.enableCompileCache({
+ directory,
+ portable: true,
+ });
+ const active = NodeModule.getCompileCacheDir();
+ if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED || !active) return false;
+ const seeded = seedPreparedCache(prepared, active, runtimeIdentity());
+ if (seeded) Reflect.set(globalThis, Symbol.for("t3code.preparedServerCache"), true);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export async function generatePreparedServerCache(resourcesInput: string): Promise<void> {
+ const resources = NodeFS.realpathSync(resourcesInput);
+ const prepared = NodePath.join(resources, "server-compile-cache");
+ const archive = NodeFS.existsSync(NodePath.join(resources, "server.asar"))
+ ? "server.asar"
+ : "app.asar";
+ const dist = NodePath.join(resources, archive, "apps/server/dist");
+ NodeFS.mkdirSync(prepared, { recursive: true });
+ const result = NodeModule.enableCompileCache({ directory: prepared, portable: true });
+ if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED)
+ throw new Error("Cannot enable release compile cache");
+ const cli = NodeFS.readdirSync(dist).find((file) => /^binCli-.*\.mjs$/.test(file));
+ if (!cli) throw new Error("Missing bundled server CLI");
+ await import(NodeURL.pathToFileURL(NodePath.join(dist, cli)).href);
+ NodeModule.flushCompileCache();
+ const active = NodeModule.getCompileCacheDir()!;
+ const entries = NodeFS.readdirSync(dist)
+ .filter((file) => file.endsWith(".mjs"))
+ .flatMap((file) => {
+ const key = cacheKey(active, NodePath.join(dist, file));
+ if (!NodeFS.existsSync(NodePath.join(active, key))) return [];
+ NodeFS.copyFileSync(NodePath.join(active, key), NodePath.join(prepared, key));
+ return [{ module: `${archive}/apps/server/dist/${file}`, file: key }];
+ });
+ if (!entries.some((entry) => entry.module.endsWith(`/${cli}`)))
+ throw new Error("Packaged engine cache key format is unsupported");
+ NodeFS.writeFileSync(
+ NodePath.join(prepared, "manifest.json"),
+ JSON.stringify({ format: 1, runtime: runtimeIdentity(), entries }),
+ );
+ NodeFS.rmSync(active, { recursive: true });
+}
diff --git a/scripts/prepare-server-compile-cache.cjs b/scripts/prepare-server-compile-cache.cjs
new file mode 100644
index 00000000000..cc3a28b4ed9
--- /dev/null
+++ b/scripts/prepare-server-compile-cache.cjs
@@ -0,0 +1,55 @@
+/* oxlint-disable t3code/no-global-process-runtime -- Packaging must compare the build host with the executable target. */
+const { spawnSync } = require("node:child_process");
+const path = require("node:path");
+const fs = require("node:fs");
+const os = require("node:os");
+
+// afterPack runs before signing and installer creation, against the final ASAR layout.
+module.exports = async ({ appOutDir, electronPlatformName, arch, packager }) => {
+ const targetArch = ["ia32", "x64", "armv7l", "arm64", "universal"][arch];
+ if (electronPlatformName !== process.platform || targetArch !== process.arch) {
+ console.log(
+ `[server-compile-cache] Skipping unexecutable target ${electronPlatformName}/${targetArch}`,
+ );
+ return;
+ }
+ const product = packager.appInfo.productFilename;
+ const resources =
+ electronPlatformName === "darwin"
+ ? path.join(appOutDir, `${product}.app`, "Contents", "Resources")
+ : path.join(appOutDir, "resources");
+ const executable =
+ electronPlatformName === "darwin"
+ ? path.join(appOutDir, `${product}.app`, "Contents", "MacOS", product)
+ : path.join(
+ appOutDir,
+ electronPlatformName === "win32" ? `${product}.exe` : packager.executableName,
+ );
+ const helper = path.join(
+ resources,
+ "app.asar",
+ "apps/desktop/dist-electron/serverCompileCache.cjs",
+ );
+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
+ for (const name of Object.keys(env)) {
+ if (name.startsWith("NODE_") || name.startsWith("T3CODE_")) delete env[name];
+ }
+ const state = fs.mkdtempSync(path.join(os.tmpdir(), "t3-release-cache-"));
+ env.T3CODE_HOME = state;
+ let result;
+ try {
+ result = spawnSync(
+ executable,
+ [
+ "-e",
+ `require(${JSON.stringify(helper)}).generatePreparedServerCache(${JSON.stringify(resources)}).then(()=>process.exit(0),e=>{console.error(e);process.exit(1)})`,
+ ],
+ { env, encoding: "utf8", timeout: 120000 },
+ );
+ } finally {
+ fs.rmSync(state, { recursive: true, force: true });
+ }
+ if (result.status !== 0)
+ throw new Error(`Server compile cache generation failed: ${result.error || result.stderr}`);
+ console.log("[server-compile-cache] Prepared server bytecode with packaged Electron");
+};