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

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-09-24 23:43:48 -07:00
1 parent c13f7d93ff
commit d10bd1360a
15 files changed
+200 -4

No files matched your search

+1 -1
View File
@@ -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",
@@ -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 });
}
});
+1 -1
View File
@@ -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...");
@@ -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"),
@@ -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(
@@ -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: {
+4
View File
@@ -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");
+28
View File
@@ -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.
}
@@ -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,
},
},
{
+13
View File
@@ -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",
+53
View File
@@ -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 });
}
},
);
+9
View File
@@ -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,
);
+2
View File
@@ -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,
+2
View File
@@ -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!",
+1 -1
View File
@@ -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,