TypeScript
fix(desktop): Cache Runtime locally on WSL Filesystem, dramatically improving launch times (#5769)
Matheson Steplockf94a0d646ed7
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.tsindex 2bbde73abaa..accfdf70b3a 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts@@ -58,14 +58,16 @@ function makeEnvironmentLayer(readonly devServerUrl?: string;readonly platform?: NodeJS.Platform;readonly resourcesPath?: string;+ readonly appVersion?: string;+ readonly processArch?: NodeJS.Architecture;},) {return DesktopEnvironment.layer({dirname: options?.dirname ?? "/repo/apps/desktop/src",homeDirectory: baseDir,platform: options?.platform ?? "darwin",- processArch: "x64",- appVersion: "1.2.3",+ processArch: options?.processArch ?? "x64",+ appVersion: options?.appVersion ?? "1.2.3",appPath: options?.appPath ?? "/repo",isPackaged: options?.isPackaged ?? true,resourcesPath: options?.resourcesPath ?? "/missing/resources",@@ -123,7 +125,107 @@ const withHarness = <A, E, R>();}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));+interface PackagedWslHarnessContext {+ readonly baseDir: string;+ readonly archivePath: string;+ readonly hashPath: string;+ readonly archiveHash: string;+ readonly mountedAppRoot: string;+ readonly mountedEntryPath: string;+}++const withPackagedWslHarness = <A, E, R>(+ input: {+ readonly archiveHash: string;+ readonly wsl: (+ context: PackagedWslHarnessContext,+ ) => DesktopWslEnvironment.DesktopWslEnvironmentTestStub;+ readonly forbidFallback?: string;+ readonly cleanupLegacy?: Effect.Effect<void>;+ readonly forbidCleanup?: string;+ },+ effect: (+ context: PackagedWslHarnessContext,+ ) => Effect.Effect<+ A,+ E,+ R | FileSystem.FileSystem | Path.Path | DesktopBackendConfiguration.DesktopBackendConfiguration+ >,+) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-desktop-backend-config-test-",+ });+ const archivePath = path.join(baseDir, "wsl-runtime.tar.gz");+ const hashPath = `${archivePath}.sha256`;+ const mountedAppRoot = "/mnt/c/app.asar.unpacked";+ const mountedEntryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");+ yield* fileSystem.makeDirectory(path.dirname(mountedEntryPath), { recursive: true });+ yield* fileSystem.writeFileString(mountedEntryPath, "");+ yield* fileSystem.writeFileString(archivePath, "archive");+ yield* fileSystem.writeFileString(hashPath, `${input.archiveHash}\n`);++ const context = {+ baseDir,+ archivePath,+ hashPath,+ archiveHash: input.archiveHash,+ mountedAppRoot,+ mountedEntryPath,+ } satisfies PackagedWslHarnessContext;+ const serverTreeLayer = input.forbidFallback+ ? Layer.succeed(+ DesktopWslServerTree.DesktopWslServerTree,+ DesktopWslServerTree.DesktopWslServerTree.of({+ ensure: Effect.die(input.forbidFallback),+ cleanupLegacy: input.forbidCleanup+ ? Effect.die(input.forbidCleanup)+ : (input.cleanupLegacy ?? Effect.void),+ }),+ )+ : DesktopWslServerTree.layerTest({+ result: { ok: true, root: path.join(baseDir, "app.asar.unpacked") },+ cleanupLegacy: input.cleanupLegacy ?? Effect.void,+ });++ return yield* effect(context).pipe(+ Effect.provide(+ DesktopBackendConfiguration.layer.pipe(+ Layer.provideMerge(serverExposureLayer),+ Layer.provideMerge(DesktopAppSettings.layerTest()),+ Layer.provideMerge(serverTreeLayer),+ Layer.provideMerge(+ DesktopWslEnvironment.layerTest({+ isAvailable: true,+ distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],+ windowsToWslPath: () => Option.some(mountedAppRoot),+ getDistroIp: () => Option.some("172.27.0.99"),+ ...input.wsl(context),+ }),+ ),+ Layer.provideMerge(+ makeEnvironmentLayer(baseDir, {+ appPath: baseDir,+ platform: "win32",+ resourcesPath: baseDir,+ }),+ ),+ ),+ ),+ );+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));+describe("DesktopBackendConfiguration", () => {+ it("accepts only normalized SHA-256 archive identities", () => {+ assert.equal(+ DesktopBackendConfiguration.parseWslRuntimeArchiveHash(` ${"A".repeat(64)}\n`),+ "a".repeat(64),+ );+ assert.isNull(DesktopBackendConfiguration.parseWslRuntimeArchiveHash("abc123"));+ });+it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>withHarness(Effect.gen(function* () {@@ -158,10 +260,11 @@ describe("DesktopBackendConfiguration", () => {it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const baseDir = yield* fileSystem.makeTempDirectoryScoped({prefix: "t3-desktop-backend-config-test-",});- const resourcesPath = `${baseDir}/resources`;+ const resourcesPath = path.join(baseDir, "resources");const config = yield* Effect.gen(function* () {const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;@@ -177,6 +280,7 @@ describe("DesktopBackendConfiguration", () => {DesktopWslServerTree.DesktopWslServerTree,DesktopWslServerTree.DesktopWslServerTree.of({ensure: Effect.die("Windows primary must not extract the WSL server tree"),+ cleanupLegacy: Effect.die("Windows primary must not clean the WSL server tree"),}),),),@@ -191,7 +295,10 @@ describe("DesktopBackendConfiguration", () => {),);- assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);+ assert.equal(+ config.entryPath,+ path.join(resourcesPath, "server.asar/apps/server/dist/bin.mjs"),+ );assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);@@ -239,7 +346,7 @@ describe("DesktopBackendConfiguration", () => {],windowsToWslPath: (distro) => {observedDistros.push(distro);- return Option.some("/repo/apps/server/dist/bin.mjs");+ return Option.some("/repo");},ensureNodePty: (distro) => {observedDistros.push(distro);@@ -269,6 +376,275 @@ describe("DesktopBackendConfiguration", () => {}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);+ it.effect("resolveWsl launches a packaged backend from the WSL-local runtime cache", () => {+ const observedArchives: Array<{+ windowsArchivePath: string;+ runtimeId: string;+ sha256: string;+ }> = [];+ const observedNodePtyRoots: string[] = [];+ let legacyCleanupCount = 0;+ const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64";++ return withPackagedWslHarness(+ {+ archiveHash: "a".repeat(64),+ forbidFallback: "A valid WSL archive must not extract the Windows fallback",+ cleanupLegacy: Effect.sync(() => {+ legacyCleanupCount += 1;+ }),+ wsl: () => ({+ prepareRuntime: (_distro, archive) => {+ observedArchives.push({+ windowsArchivePath: archive.windowsPath,+ runtimeId: archive.runtimeId,+ sha256: archive.sha256,+ });+ return { ok: true, linuxAppRoot };+ },+ ensureNodePty: (_distro, root) => {+ observedNodePtyRoots.push(root);+ return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };+ },+ }),+ },+ ({ archiveHash, archivePath, baseDir }) =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });++ assert.deepEqual(observedArchives, [+ {+ windowsArchivePath: archivePath,+ runtimeId: `sha256-${archiveHash}`,+ sha256: archiveHash,+ },+ ]);+ assert.deepEqual(observedNodePtyRoots, [linuxAppRoot]);+ assert.equal(+ config.entryPath,+ path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"),+ );+ assert.include(config.args, `${linuxAppRoot}/apps/server/dist/bin.mjs`);+ assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`);+ assert.equal(legacyCleanupCount, 1);+ assert.isTrue(Option.isNone(config.preflightFailure));+ }),+ );+ });++ it.effect("resolveWsl changes the cache id when the packaged archive changes", () => {+ const firstHash = "a".repeat(64);+ const secondHash = "b".repeat(64);+ const observedRuntimeIds: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash: firstHash,+ wsl: () => ({+ prepareRuntime: (_distro, archive) => {+ observedRuntimeIds.push(archive.runtimeId);+ return { ok: true, linuxAppRoot: `/runtime/${archive.runtimeId}` };+ },+ ensureNodePty: () => ({+ ok: true,+ nodePath: "/usr/bin/node",+ resolvedPath: "/usr/bin:/bin",+ }),+ }),+ },+ ({ hashPath, mountedAppRoot }) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const first = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });+ yield* fileSystem.writeFileString(hashPath, secondHash);+ const second = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });+ yield* fileSystem.writeFileString(hashPath, "not-a-sha256");+ const invalidIdentity = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });++ assert.deepEqual(observedRuntimeIds, [`sha256-${firstHash}`, `sha256-${secondHash}`]);+ assert.equal(first.wslRuntimeId, observedRuntimeIds[0]);+ assert.equal(second.wslRuntimeId, observedRuntimeIds[1]);+ assert.isUndefined(invalidIdentity.wslRuntimeId);+ assert.include(invalidIdentity.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);+ }),+ );+ });++ it.effect("resolveWsl falls back to the mounted runtime when archive staging fails", () => {+ const observedNodePtyRoots: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash: "b".repeat(64),+ wsl: () => ({+ prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }),+ ensureNodePty: (_distro, root) => {+ observedNodePtyRoots.push(root);+ return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };+ },+ }),+ },+ ({ mountedAppRoot, mountedEntryPath }) =>+ Effect.gen(function* () {+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });++ assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);+ assert.equal(config.entryPath, mountedEntryPath);+ assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);+ assert.isUndefined(config.wslRuntimeId);+ assert.isTrue(Option.isNone(config.preflightFailure));+ }),+ );+ });++ it.effect("resolveWsl retires a staged runtime that cannot load node-pty", () => {+ const archiveHash = "c".repeat(64);+ const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;+ const observedNodePtyRoots: string[] = [];+ const invalidatedRuntimeIds: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash,+ wsl: () => ({+ prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),+ invalidateRuntime: (_distro, runtimeId) =>+ Effect.sync(() => {+ invalidatedRuntimeIds.push(runtimeId);+ }),+ ensureNodePty: (_distro, root) => {+ observedNodePtyRoots.push(root);+ return root === stagedAppRoot+ ? { ok: false, reason: "pty.node could not be loaded", fatal: true }+ : { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };+ },+ }),+ },+ ({ mountedAppRoot, mountedEntryPath }) =>+ Effect.gen(function* () {+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });++ assert.deepEqual(observedNodePtyRoots, [stagedAppRoot, mountedAppRoot]);+ assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);+ assert.equal(config.entryPath, mountedEntryPath);+ assert.isUndefined(config.wslRuntimeId);+ assert.isTrue(Option.isNone(config.preflightFailure));+ assert.deepEqual(invalidatedRuntimeIds, [`sha256-${archiveHash}`]);+ }),+ );+ });++ it.effect("resolveWsl keeps the staged runtime when the mounted tree fails too", () => {+ const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";+ const invalidatedRuntimeIds: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash: "d".repeat(64),+ wsl: () => ({+ prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),+ invalidateRuntime: (_distro, runtimeId) =>+ Effect.sync(() => {+ invalidatedRuntimeIds.push(runtimeId);+ }),+ ensureNodePty: (_distro, root) => ({+ ok: false,+ reason:+ root === stagedAppRoot+ ? "unsupported CPU architecture or incompatible system libraries"+ : "mounted tree is broken in some other way",+ fatal: true,+ }),+ }),+ },+ () =>+ Effect.gen(function* () {+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });+ const failure = Option.getOrThrow(config.preflightFailure);++ assert.isTrue(failure.fatal);+ assert.include(failure.reason, "unsupported CPU architecture");+ assert.deepEqual(invalidatedRuntimeIds, []);+ }),+ );+ });++ it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => {+ const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";+ const invalidatedRuntimeIds: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash: "f".repeat(64),+ wsl: () => ({+ prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),+ invalidateRuntime: (_distro, runtimeId) =>+ Effect.sync(() => {+ invalidatedRuntimeIds.push(runtimeId);+ }),+ ensureNodePty: (_distro, root) =>+ root === stagedAppRoot+ ? { ok: false, reason: "pty.node could not be loaded", fatal: true }+ : {+ ok: false,+ reason: "WSL backend preflight timed out while probing for Node.js.",+ fatal: false,+ },+ }),+ },+ () =>+ Effect.gen(function* () {+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });+ const failure = Option.getOrThrow(config.preflightFailure);++ assert.isFalse(failure.fatal);+ assert.equal(failure.retryLimit, 12);+ assert.include(failure.reason, "timed out");+ assert.deepEqual(invalidatedRuntimeIds, []);+ }),+ );+ });++ it.effect("resolveWsl retries the staged runtime after a transient probe failure", () => {+ const invalidatedRuntimeIds: string[] = [];+ return withPackagedWslHarness(+ {+ archiveHash: "e".repeat(64),+ forbidFallback: "A transient probe failure must not extract the fallback",+ forbidCleanup: "A transient probe failure must not clean the fallback tree",+ wsl: () => ({+ prepareRuntime: () => ({+ ok: true,+ linuxAppRoot: "/home/test/.t3/wsl-runtime/cache",+ }),+ invalidateRuntime: (_distro, runtimeId) =>+ Effect.sync(() => {+ invalidatedRuntimeIds.push(runtimeId);+ }),+ ensureNodePty: () => ({+ ok: false,+ reason: "WSL backend preflight timed out while probing for Node.js.",+ fatal: false,+ retryLimit: 12,+ }),+ }),+ },+ () =>+ Effect.gen(function* () {+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;+ const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });+ const failure = Option.getOrThrow(config.preflightFailure);++ assert.isFalse(failure.fatal);+ assert.equal(failure.retryLimit, 12);+ assert.include(failure.reason, "timed out");+ assert.deepEqual(invalidatedRuntimeIds, []);+ }),+ );+ });+it.effect("resolveWsl preserves inherited PATH with quote-sensitive values as separate args",() =>@@ -283,7 +659,8 @@ describe("DesktopBackendConfiguration", () => {yield* fileSystem.writeFileString(entryPath, "");const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";- const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";+ const linuxAppRoot = "/tmp/t3 code's launch";+ const linuxEntryPath = `${linuxAppRoot}/apps/server/dist/bin.mjs`;const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";const config = yield* Effect.gen(function* () {@@ -299,7 +676,7 @@ describe("DesktopBackendConfiguration", () => {DesktopWslEnvironment.layerTest({isAvailable: true,distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],- windowsToWslPath: () => Option.some(linuxEntryPath),+ windowsToWslPath: () => Option.some(linuxAppRoot),ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),getDistroIp: () => Option.some("172.27.0.99"),}),@@ -815,13 +1192,14 @@ describe("DesktopBackendConfiguration", () => {it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const baseDir = yield* fileSystem.makeTempDirectoryScoped({prefix: "t3-desktop-backend-config-test-",});- const resourcesPath = `${baseDir}/resources`;+ const resourcesPath = path.join(baseDir, "resources");const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;- const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;+ const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");yield* fileSystem.makeDirectory(`${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,{ recursive: true },diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.tsindex bcce731a595..4c43070b5f9 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts@@ -213,6 +213,7 @@ interface SharedBootstrapInput {interface WslPreflightSuccess {readonly _tag: "Ready";readonly runningDistro: string;+ readonly windowsEntryPath: string;readonly linuxEntryPath: string;// Absolute path to the node binary the preflight validated after the shared// remote resolver repaired PATH. The launch must use this exact path so it@@ -222,6 +223,8 @@ interface WslPreflightSuccess {// PATH captured from the same login shell after the shared resolver loaded// version managers. The launch forwards this value directly without a shell.readonly resolvedPath: string;+ // Identifies the distro-local runtime cache selected from the packaged archive.+ readonly runtimeId?: string;}interface WslPreflightFailure {@@ -236,18 +239,35 @@ interface WslPreflightFailure {}const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;+const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";+const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;+const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;++export const parseWslRuntimeArchiveHash = (value: string): string | null => {+ const trimmed = value.trim();+ return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;+};++type FailedNodePtyResult = Extract<+ DesktopWslEnvironment.EnsureWslNodePtyResult,+ { readonly ok: false }+>;const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {readonly distro: string | null;- readonly windowsEntryPath: string;- readonly windowsRepoRoot: string;+ readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;readonly allowBuild: boolean;}): Effect.fn.Return<WslPreflightSuccess | WslPreflightFailure,never,- DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem+ | DesktopEnvironment.DesktopEnvironment+ | DesktopWslEnvironment.DesktopWslEnvironment+ | DesktopWslServerTree.DesktopWslServerTree+ | FileSystem.FileSystem> {+ const environment = yield* DesktopEnvironment.DesktopEnvironment;const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;+ const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;const fileSystem = yield* FileSystem.FileSystem;const wslAvailable = yield* wslEnv.isAvailable;@@ -289,43 +309,127 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f} as const;}- const entryExists = yield* fileSystem- .exists(input.windowsEntryPath)- .pipe(Effect.orElseSucceed(() => false));- if (!entryExists) {- return {+ const nodePtyOptions = {+ allowBuild: input.allowBuild,+ nodeEngineRange: serverPackageJson.engines.node,+ };+ const failedNodePty = (result: FailedNodePtyResult) =>+ ({_tag: "Failed",- reason: `missing server entry at ${input.windowsEntryPath}`,- fatal: true,- } as const;+ reason: `WSL node-pty unavailable: ${result.reason}`,+ fatal: result.fatal,+ ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),+ }) as const;++ // The mounted server tree is the fallback runtime: the Windows-side copy the+ // distro reads over /mnt. Slower to launch from, but always installed.+ const resolveMountedAppRoot = Effect.gen(function* () {+ const serverTree = yield* wslServerTree.ensure;+ if (!serverTree.ok) {+ return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;+ }+ const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");+ const entryExists = yield* fileSystem+ .exists(windowsEntryPath)+ .pipe(Effect.orElseSucceed(() => false));+ if (!entryExists) {+ return {+ ok: false,+ reason: `missing server entry at ${windowsEntryPath}`,+ fatal: true,+ } as const;+ }+ const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);+ return Option.isNone(mountedAppRoot)+ ? ({+ ok: false,+ reason: `wslpath conversion failed for ${serverTree.root}`,+ fatal: false,+ } as const)+ : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);+ });++ // Set once a staged runtime has been ruled out by the probe, and carried+ // through the mounted attempt: if the mounted tree works the cache is the+ // broken part and gets invalidated, and if the mounted tree returns its own+ // fatal verdict the cached reason is the more actionable one to report.+ // A transient mounted failure is neither — it rules nothing out, so it stays+ // retryable and the staged verdict waits for an attempt that can answer.+ let stagedFailure:+ | { readonly runtimeId: string; readonly nodePty: FailedNodePtyResult }+ | undefined;++ if (input.runtimeArchive !== null) {+ const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);+ if (runtime.ok) {+ const stagedNodePty = yield* wslEnv.ensureNodePty(+ runningDistro,+ runtime.linuxAppRoot,+ nodePtyOptions,+ );+ if (stagedNodePty.ok) {+ yield* wslServerTree.cleanupLegacy;+ return {+ _tag: "Ready",+ runningDistro,+ windowsEntryPath: environment.backendEntryPath,+ linuxEntryPath: `${runtime.linuxAppRoot}/apps/server/dist/bin.mjs`,+ nodePath: stagedNodePty.nodePath,+ resolvedPath: stagedNodePty.resolvedPath,+ runtimeId: input.runtimeArchive.runtimeId,+ } as const;+ }+ // A transport failure says nothing about the staged tree, so it is+ // retried against the same cache rather than spending a second probe on+ // the mounted tree and risking a needless reinstall.+ if (!stagedNodePty.fatal) return failedNodePty(stagedNodePty);+ yield* Effect.logWarning(+ "The staged WSL runtime could not load node-pty; retrying from the mounted server tree.",+ { reason: stagedNodePty.reason },+ );+ stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, nodePty: stagedNodePty };+ } else {+ yield* Effect.logWarning(+ "Could not stage the WSL runtime; launching from the mounted server tree instead.",+ { reason: runtime.reason },+ );+ }}- const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);- if (Option.isNone(linuxEntry)) {- return {- _tag: "Failed",- reason: `wslpath conversion failed for ${input.windowsEntryPath}`,- fatal: false,- } as const;+ const mounted = yield* resolveMountedAppRoot;+ if (!mounted.ok) {+ return stagedFailure && mounted.fatal+ ? failedNodePty(stagedFailure.nodePty)+ : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);}- const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {- allowBuild: input.allowBuild,- nodeEngineRange: serverPackageJson.engines.node,- });+ const nodePtyResult = yield* wslEnv.ensureNodePty(+ runningDistro,+ mounted.linuxAppRoot,+ nodePtyOptions,+ );if (!nodePtyResult.ok) {- return {- _tag: "Failed",- reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,- fatal: nodePtyResult.fatal,- ...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),- } as const;+ // Substituting the staged verdict for a transient mounted failure would+ // turn a retryable failure into a fatal one, ending the WSL attempt (and,+ // in wsl-only mode, persisting Windows) before the slow /mnt path had a+ // chance to answer and clear the bad cache.+ return failedNodePty(+ stagedFailure && nodePtyResult.fatal ? stagedFailure.nodePty : nodePtyResult,+ );+ }++ // The mounted tree runs what the cache could not, so the cache is the broken+ // copy: revoke its ready marker so the next launch reinstalls it instead of+ // reusing a tree that has already been proven unloadable.+ if (stagedFailure) {+ yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);}return {_tag: "Ready",runningDistro,- linuxEntryPath: linuxEntry.value,+ windowsEntryPath: mounted.windowsEntryPath,+ linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,nodePath: nodePtyResult.nodePath,resolvedPath: nodePtyResult.resolvedPath,} as const;@@ -430,7 +534,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl> {const environment = yield* DesktopEnvironment.DesktopEnvironment;const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;- const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;+ const fileSystem = yield* FileSystem.FileSystem;// Bind to 0.0.0.0 inside WSL so the backend is reachable both via// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1@@ -467,31 +571,54 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl...buildObservabilityFragment(input.observabilitySettings),};- // In packaged builds the server tree ships inside resources/server.asar —- // an archive FILE the Windows primary reads through ELECTRON_RUN_AS_NODE- // (asar-aware). The WSL backend launches plain `wsl.exe -- node`, which- // can't read an asar, so materialize (or reuse) the extracted copy of the- // sidecar before preflighting. In dev the server tree is the real checkout- // directory and ensure returns it unchanged.- const serverTree = yield* wslServerTree.ensure;- const wslAppRoot = serverTree.ok ? serverTree.root : environment.serverRoot;- const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");-- const preflight = serverTree.ok- ? yield* runWslPreflight({- distro: input.distro,- windowsEntryPath: wslEntryPath,- windowsRepoRoot: wslAppRoot,- // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and- // attached to the Windows artifact — see build-desktop-artifact.ts), so the- // WSL backend never needs a compiler, node-gyp, or network on first launch.- // Compiling from source is a dev-only convenience: a checkout has no shipped- // prebuilt, and developers have the toolchain. In packaged builds we instead- // surface a clear diagnostic if the prebuilt can't load (unsupported- // arch/distro), rather than silently dropping into a fragile runtime build.- allowBuild: !environment.isPackaged,- })- : ({ _tag: "Failed", reason: serverTree.reason, fatal: serverTree.fatal } as const);+ // The archive is the primary packaged WSL path: it installs directly into+ // the distro's ext4 filesystem. The server.asar extraction service is only+ // consulted lazily if the archive is unavailable or cannot be staged.+ const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);+ const archiveHashPath = environment.path.join(+ environment.resourcesPath,+ WSL_RUNTIME_ARCHIVE_HASH_NAME,+ );++ const hasArchive = environment.isPackaged+ ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))+ : false;+ const archiveHash = hasArchive+ ? yield* fileSystem.readFileString(archiveHashPath).pipe(+ Effect.map(parseWslRuntimeArchiveHash),+ Effect.orElseSucceed(() => null),+ )+ : null;+ if (hasArchive && archiveHash === null) {+ yield* Effect.logWarning(+ "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",+ { hashPath: archiveHashPath },+ );+ }++ const preflight = yield* runWslPreflight({+ distro: input.distro,+ runtimeArchive:+ archiveHash === null+ ? null+ : {+ windowsPath: archivePath,+ // The verified archive bytes are the cache identity. Release builds+ // embed the release version and pnpm install metadata, so the+ // archive changes on every update even when application logic does+ // not. Later launches of that update still reuse this directory.+ runtimeId: `sha256-${archiveHash}`,+ sha256: archiveHash,+ },+ // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and+ // attached to the Windows artifact — see build-desktop-artifact.ts), so the+ // WSL backend never needs a compiler, node-gyp, or network on first launch.+ // Compiling from source is a dev-only convenience: a checkout has no shipped+ // prebuilt, and developers have the toolchain. In packaged builds we instead+ // surface a clear diagnostic if the prebuilt can't load (unsupported+ // arch/distro), rather than silently dropping into a fragile runtime build.+ allowBuild: !environment.isPackaged,+ });// Every operation after preflight uses the same concrete distro. In// default-tracking mode this closes the race where the system default@@ -537,7 +664,8 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWslconst baseConfig = {executablePath: "wsl.exe",- entryPath: wslEntryPath,+ entryPath:+ preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,cwd: environment.backendCwd,env: {...parentEnvWithoutT3Home,@@ -605,6 +733,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl...devUrlArgs,],preflightFailure: Option.none(),+ ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),} satisfies DesktopBackendManager.DesktopBackendStartConfig;});diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.tsindex 3efc81ed5b6..e6c9a2c17c1 100644--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts@@ -25,6 +25,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";import * as DesktopBackendManager from "./DesktopBackendManager.ts";import * as DesktopObservability from "../app/DesktopObservability.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";+import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";const decodeDesktopBackendBootstrap = Schema.decodeEffect(Schema.fromJsonString(DesktopBackendBootstrap),@@ -132,6 +133,7 @@ interface MakeInstanceInput {readonly desktopTelemetryPublisher?: Partial<DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]>;+ readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;}// Helper that constructs a primary backend instance using the factory@@ -167,6 +169,9 @@ function makeTestInstance(input: MakeInstanceInput) {removeControlSource: () => Effect.void,...input.desktopTelemetryPublisher,}),+ DesktopWslEnvironment.layerTest(+ input.pruneRuntimes === undefined ? {} : { pruneRuntimes: input.pruneRuntimes },+ ),);const instance = DesktopBackendManager.makeBackendInstance({@@ -647,10 +652,13 @@ describe("DesktopBackendManager", () => {Effect.scoped(Effect.gen(function* () {const requestUrls: Array<string> = [];+ const prunedRuntimes: Array<[string | null, string]> = [];const statuses = [503, 200];let readyCount = 0;const firstRequest = yield* Deferred.make<void>();- const ready = yield* Deferred.make<void>();+ const backendReady = yield* Deferred.make<void>();+ const processExit = yield* Deferred.make<void>();+ const pruneComplete = yield* Deferred.make<void>();const exited = yield* Queue.unbounded<void>();const spawnerLayer = Layer.succeed(@@ -658,7 +666,9 @@ describe("DesktopBackendManager", () => {ChildProcessSpawner.make(() =>Effect.succeed(makeProcess({- exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),+ exitCode: Deferred.await(processExit).pipe(+ Effect.as(ChildProcessSpawner.ExitCode(0)),+ ),}),),),@@ -666,6 +676,15 @@ describe("DesktopBackendManager", () => {const instance = yield* makeTestInstance({spawnerLayer,+ config: {+ ...baseConfig,+ runningDistro: "Ubuntu",+ wslRuntimeId: "1.2.3-x64",+ },+ pruneRuntimes: (distro, runtimeId) =>+ Effect.sync(() => {+ prunedRuntimes.push([distro, runtimeId]);+ }).pipe(Effect.andThen(Deferred.succeed(pruneComplete, void 0)), Effect.asVoid),httpClientLayer: httpClientLayer((request) =>Effect.gen(function* () {const status = statuses.shift();@@ -677,7 +696,7 @@ describe("DesktopBackendManager", () => {),onReady: Effect.sync(() => {readyCount += 1;- }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),+ }).pipe(Effect.andThen(Deferred.succeed(backendReady, void 0)), Effect.asVoid),backendOutputLog: {persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),},@@ -687,12 +706,17 @@ describe("DesktopBackendManager", () => {yield* Deferred.await(firstRequest);assert.equal(readyCount, 0);+ assert.deepEqual(prunedRuntimes, []);assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]);yield* TestClock.adjust(Duration.millis(100));+ yield* Deferred.await(backendReady);+ yield* Deferred.await(pruneComplete);+ yield* Deferred.succeed(processExit, void 0);yield* Queue.take(exited);assert.equal(readyCount, 1);+ assert.deepEqual(prunedRuntimes, [["Ubuntu", "1.2.3-x64"]]);assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment","http://127.0.0.1:3773/.well-known/t3/environment",diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.tsindex fc196818090..60bfe780ad6 100644--- a/apps/desktop/src/backend/DesktopBackendManager.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.ts@@ -52,6 +52,7 @@ import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpimport * as DesktopObservability from "../app/DesktopObservability.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";+import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";const INITIAL_RESTART_DELAY = Duration.millis(500);const MAX_RESTART_DELAY = Duration.seconds(10);@@ -99,6 +100,10 @@ export interface DesktopBackendStartConfig extends BackendProcessContext {// Present for a WSL run after the configured/default distro has been// resolved to the concrete distro passed to wsl.exe.readonly runningDistro?: string;+ // Present only when this run launched from a staged WSL-local runtime.+ // Once HTTP readiness succeeds, the manager uses it to retain this cache+ // plus the newest previous cache and prune older versions.+ readonly wslRuntimeId?: string;}// A preflight failure records whether it is fatal. Transient failures (WSL@@ -637,6 +642,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (| HttpClient.HttpClient| DesktopObservability.DesktopBackendOutputLogFactory| DesktopTelemetryPublisher.DesktopTelemetryPublisher+ | DesktopWslEnvironment.DesktopWslEnvironment| Scope.Scope> {const parentScope = yield* Scope.Scope;@@ -644,6 +650,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;const httpClient = yield* HttpClient.HttpClient;const state = yield* Ref.make(initialState);@@ -939,6 +946,15 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (}yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;+ if (+ config.value.runningDistro !== undefined &&+ config.value.wslRuntimeId !== undefined+ ) {+ yield* wslEnvironment.pruneRuntimes(+ config.value.runningDistro,+ config.value.wslRuntimeId,+ );+ }}),onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(function* (error) {diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.tsindex 98bd4065fbe..97d4359e166 100644--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts@@ -14,6 +14,7 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";import * as ElectronDialog from "../electron/ElectronDialog.ts";import * as DesktopWindow from "../window/DesktopWindow.ts";+import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";import * as DesktopBackendPool from "./DesktopBackendPool.ts";import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";@@ -79,6 +80,7 @@ function makePoolLayer(resolveWsl: () => Effect.die("unexpected WSL config resolve"),} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),DesktopAppSettings.layerTest(),+ DesktopWslEnvironment.layerTest(),ElectronDialog.layer,Layer.succeed(DesktopWindow.DesktopWindow, {createMain: Effect.die("unexpected window create"),diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.tsindex 9b85d1bb243..27e24d55c6b 100644--- a/apps/desktop/src/backend/DesktopBackendPool.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.ts@@ -99,6 +99,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";import * as DesktopWindow from "../window/DesktopWindow.ts";+import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";import * as ElectronDialog from "../electron/ElectronDialog.ts";const { logWarning: logBackendPoolWarning } =@@ -178,7 +179,8 @@ export type BackendInstanceFactoryRequirements =| ChildProcessSpawner.ChildProcessSpawner| HttpClient.HttpClient| DesktopObservability.DesktopBackendOutputLogFactory- | DesktopTelemetryPublisher.DesktopTelemetryPublisher;+ | DesktopTelemetryPublisher.DesktopTelemetryPublisher+ | DesktopWslEnvironment.DesktopWslEnvironment;interface ActiveRegisteredInstance {readonly _tag: "Active";diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.tsindex 895d246e368..1c6b64464d1 100644--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts@@ -1,5 +1,7 @@+// @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell.import { describe, it } from "@effect/vitest";-import { expect } from "vite-plus/test";+import { afterAll, expect } from "vite-plus/test";+import * as NodeChildProcess from "node:child_process";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";@@ -11,6 +13,9 @@ import { ChildProcessSpawner } from "effect/unstable/process";import {buildWslNodeEnvPreamble,+ buildWslRuntimeInstallScript,+ buildWslRuntimeInvalidateScript,+ buildWslRuntimePruneScript,DesktopWslDistroListError,formatMissingToolsReason,formatNodePtyProbeFailureReason,@@ -19,11 +24,62 @@ import {parseNodeVersion,parseResolvedPath,parseToolchainReport,+ parseWslRuntimeRoot,probeWslDistros,+ sanitizeWslRuntimeId,} from "./DesktopWslEnvironment.ts";const encoder = new TextEncoder();+// The install script only fails the way this file cares about when a real shell+// runs it, so find one that has the tools it needs: bash directly on Linux, and+// the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere+// else the executed suite skips and the generated-text assertions stand alone.+const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const;++const posixShellRunner = (() => {+ // Candidates rather than a platform switch: wsl.exe simply fails to spawn+ // where it does not exist, which is the same answer as a shell missing flock.+ const candidates = [+ { file: "bash", args: [] as ReadonlyArray<string> },+ { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> },+ ];+ const probe = [+ "[ -d /proc/1 ] || exit 1",+ ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`),+ ].join("\n");+ return (+ candidates.find((candidate) => {+ const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], {+ encoding: "utf8",+ });+ return result.status === 0;+ }) ?? null+ );+})();++const runShell = (script: string) => {+ if (posixShellRunner === null) throw new Error("no POSIX shell runner available");+ // The install script arrives on stdin in production too, which is what lets+ // its own /proc scan not match itself.+ const result = NodeChildProcess.spawnSync(+ posixShellRunner.file,+ [...posixShellRunner.args, "-s"],+ { input: script, encoding: "utf8" },+ );+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };+};++const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;++const readField = (stdout: string, field: string) => {+ const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`));+ if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`);+ return line.slice(field.length + 1).trim();+};++const SERVER_ENTRY_SOURCE = 'console.log("t3code wsl runtime test server");';+const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>ChildProcessSpawner.make(() =>Effect.succeed(@@ -125,6 +181,572 @@ describe("buildWslNodeEnvPreamble", () => {});});+describe("WSL runtime cache", () => {+ it("sanitizes cache ids before interpolating them into Linux paths", () => {+ expect(sanitizeWslRuntimeId("1.2.3/x64; touch /tmp/nope")).toBe("1.2.3_x64__touch__tmp_nope");+ });++ it("installs through a temporary directory and only reuses valid completed caches", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "1.2.3-x64",+ "b".repeat(64),+ );++ expect(script).toContain('runtime_parent="$HOME/.t3/wsl-runtime"');+ expect(script).toContain(' [ -f "$ready_marker" ] &&');+ expect(script).toContain(' [ -f "$runtime_root/apps/server/dist/bin.mjs" ] &&');+ expect(script).toContain(' [ -f "$runtime_root/node_modules/node-pty/package.json" ] &&');+ expect(script).toContain(' node_pty_payload_present "$runtime_root"');+ expect(script).not.toContain("node_modules/effect/package.json");+ expect(script).toContain("if runtime_is_ready; then");+ expect(script).toContain("trap 'exit 1' HUP INT TERM");+ expect(script).toContain('exec 9> "$runtime_lock"');+ expect(script).toContain("flock -x 9");+ expect(script).not.toContain("runtime_lock_pid");+ expect(script).not.toContain("sleep 0.1");+ expect(script).not.toContain('rm -rf "$runtime_lock"');+ expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"');+ expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"');+ expect(script).toContain(+ "tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\"",+ );+ expect(script).toContain('test -f "$runtime_tmp/apps/server/dist/bin.mjs"');+ expect(script).toContain('test -f "$runtime_tmp/node_modules/node-pty/package.json"');+ expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"');+ expect(script).not.toContain('rm -rf "$runtime_root"');++ const lockAcquired = script.indexOf("flock -x 9");+ const readinessAfterLock = script.indexOf("if runtime_is_ready; then", lockAcquired + 1);+ const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');+ expect(lockAcquired).toBeGreaterThan(-1);+ expect(readinessAfterLock).toBeGreaterThan(lockAcquired);+ expect(existingRuntimeMoved).toBeGreaterThan(readinessAfterLock);+ });++ it("verifies the archive digest before extracting, and only on a cache miss", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "1.2.3-x64",+ "b".repeat(64),+ );++ const expected = "b".repeat(64);+ expect(script).toContain(+ "archive_sha=$(sha256sum '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' | cut -d ' ' -f 1)",+ );+ expect(script).toContain(`if [ "$archive_sha" != '${expected}' ]; then`);++ // A warm cache exits before the hash, so reuse never pays for it, and the+ // mismatch check runs before anything mutates the cache.+ const readyShortCircuit = script.indexOf("if runtime_is_ready; then");+ const digestChecked = script.indexOf("archive_sha=$(sha256sum");+ const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');+ const extracted = script.indexOf("tar -xzf");+ expect(digestChecked).toBeGreaterThan(readyShortCircuit);+ expect(existingRuntimeMoved).toBeGreaterThan(digestChecked);+ expect(extracted).toBeGreaterThan(digestChecked);+ });++ // Invalidation revokes the ready marker without stopping the backend that+ // failed the probe, so the next install can find an unready tree that a live+ // process is still running out of. Deleting it there unlinks node_modules+ // under that process; the pruner already refuses to touch in-use caches, and+ // the install path has to refuse too.+ it("moves an in-use runtime aside instead of deleting it under a live backend", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "sha256-" + "c".repeat(64),+ "b".repeat(64),+ );++ expect(script).toContain('grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');+ // No /proc means no way to tell, and guessing wrong costs a backend its+ // runtime, so an unknowable answer has to count as in use.+ expect(script).toContain(" [ -d /proc/1 ] || return 0");+ expect(script).toContain(' if runtime_in_use "$runtime_root"; then');++ // A process's cmdline keeps the pre-rename path, so the question is only+ // answerable before the move.+ const inUseChecked = script.indexOf('if runtime_in_use "$runtime_root"; then');+ const moved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"');+ expect(inUseChecked).toBeGreaterThan(-1);+ expect(inUseChecked).toBeLessThan(moved);++ // In use: keep the tree and restart the sweep's clock, because renaming+ // preserves the directory's mtime and a long-installed tree would otherwise+ // already be past the age gate. Idle: delete it now, as before.+ const kept = script.indexOf('touch "$runtime_stale"');+ const deleted = script.indexOf('rm -rf "$runtime_stale"');+ expect(kept).toBeGreaterThan(moved);+ expect(deleted).toBeGreaterThan(kept);+ });++ it("treats a runtime whose native payload went missing as a cache miss", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "1.2.3-x64",+ "b".repeat(64),+ );++ // A glob, not a mapped `uname -m`: this is a presence check, and the later+ // native probe is what judges arch and loadability.+ expect(script).toContain(+ ' for candidate in "$1"/node_modules/node-pty/prebuilds/linux-*/pty.node; do',+ );+ // The marker the probe reads must sit beside the binary, or the runtime is+ // just as unusable as one missing pty.node outright.+ expect(script).toContain(' [ -f "${candidate%/*}/t3code-wsl-node-pty.json" ] || continue');++ // Readiness gates the short-circuit, so a cache missing the payload+ // reinstalls from the archive instead of being reused forever.+ const payloadCheckDefined = script.indexOf("node_pty_payload_present() {");+ const readinessDefined = script.indexOf("runtime_is_ready() {");+ const readyShortCircuit = script.indexOf("if runtime_is_ready; then");+ expect(payloadCheckDefined).toBeGreaterThan(-1);+ expect(payloadCheckDefined).toBeLessThan(readinessDefined);+ expect(readinessDefined).toBeLessThan(readyShortCircuit);+ });++ // A truncated or half-written bin.mjs passes every presence check the cache+ // had: the file exists, node-pty still loads, and launch then picks a server+ // that exits before it becomes ready — forever, because nothing ever+ // reinstalls. The digest the install records is what turns that into a miss.+ it("re-hashes the server entry against the digest the install recorded", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "1.2.3-x64",+ "b".repeat(64),+ );++ expect(script).toContain(+ ` sha256sum "$1/apps/server/dist/bin.mjs" 2>/dev/null | cut -d ' ' -f 1`,+ );+ expect(script).toContain(+ ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',+ );+ // A runtime installed before the marker carried a digest reads as empty,+ // which has to be a miss rather than a pass.+ expect(script).toContain(' [ -n "$recorded_entry_digest" ] &&');+ expect(script).toContain(+ `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/.t3code-wsl-runtime-ready"`,+ );++ // The digest is recorded after extraction and before promotion.+ const extracted = script.indexOf("tar -xzf");+ const digestRecorded = script.indexOf(+ 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',+ );+ const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');+ const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');+ expect(digestRecorded).toBeGreaterThan(extracted);+ expect(markerWritten).toBeGreaterThan(digestRecorded);+ expect(promoted).toBeGreaterThan(markerWritten);+ });++ it("refuses to mark an archive without a native payload as ready", () => {+ const script = buildWslRuntimeInstallScript(+ "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz",+ "1.2.3-x64",+ "b".repeat(64),+ );++ expect(script).toContain('if ! node_pty_payload_present "$runtime_tmp"; then');++ // The extracted tree is rejected before the ready marker is written, so a+ // defective archive falls back to the mounted tree instead of caching.+ const payloadValidated = script.indexOf('node_pty_payload_present "$runtime_tmp"');+ const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"');+ const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"');+ expect(payloadValidated).toBeGreaterThan(-1);+ expect(markerWritten).toBeGreaterThan(payloadValidated);+ expect(promoted).toBeGreaterThan(payloadValidated);+ });++ it("parses only absolute Linux runtime paths", () => {+ expect(parseWslRuntimeRoot("runtimeRoot:/home/josh/.t3/wsl-runtime/1.2.3-x64\n")).toBe(+ "/home/josh/.t3/wsl-runtime/1.2.3-x64",+ );+ expect(parseWslRuntimeRoot("runtimeRoot:relative/path\n")).toBeNull();+ expect(parseWslRuntimeRoot("noise\n")).toBeNull();+ });++ it("prunes completed runtimes except the current and newest previous cache", () => {+ const script = buildWslRuntimePruneScript("1.2.3/x64");++ expect(script).toContain('current_runtime="$runtime_parent/1.2.3_x64"');+ expect(script).toContain('[ "$candidate" -nt "$previous_runtime" ]');+ expect(script).toContain('[ "$candidate" != "$current_runtime" ] || continue');+ expect(script).toContain('[ "$candidate" != "$previous_runtime" ] || continue');+ expect(script).toContain('[ -f "$candidate/.t3code-wsl-runtime-ready" ] || continue');+ expect(script).toContain('rm -rf -- "$candidate"');+ });++ it("never deletes a runtime another backend is running from", () => {+ const script = buildWslRuntimePruneScript("1.2.3/x64");++ // The running backend's argv holds `<runtime>/apps/server/dist/bin.mjs`, so+ // the process itself is the lease and exiting releases it. Nothing has to be+ // registered up front, which is what makes this cover backends already+ // running from an older version that knows nothing about pruning.+ expect(script).toContain(' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null');+ expect(script).toContain(' ! runtime_in_use "$candidate" || continue');++ // Without visible processes the retention rules cannot tell a live cache+ // from an abandoned one, so the sweep is skipped rather than guessed at.+ expect(script).toContain("[ -d /proc/1 ] || exit 0");++ // The guard has to gate the delete, not just exist.+ const inUseChecked = script.indexOf('! runtime_in_use "$candidate"');+ const removed = script.indexOf('rm -rf -- "$candidate"');+ expect(inUseChecked).toBeGreaterThan(-1);+ expect(removed).toBeGreaterThan(inUseChecked);+ });++ it("sweeps orphaned install scratch directories the ready-marker loops cannot see", () => {+ const script = buildWslRuntimePruneScript("1.2.3/x64");++ // Dot-prefixed, so `"$runtime_parent"/*` never matches them, and they carry+ // no ready marker either; without this pass a killed install leaks forever.+ expect(script).toContain(+ 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',+ );+ // Age guard: a scratch directory younger than this belongs to a live install.+ expect(script).toContain('find "$scratch" -maxdepth 0 -mmin +120');+ });++ it("invalidates a cache by dropping its ready marker, not the tree", () => {+ const script = buildWslRuntimeInvalidateScript("1.2.3/x64");++ // Readiness is a presence check, so a tree whose pty.node is present but+ // unloadable stays ready forever unless the probe can revoke the marker.+ expect(script).toContain('rm -f "$HOME/.t3/wsl-runtime/1.2.3_x64/.t3code-wsl-runtime-ready"');+ // Deleting the tree here would pull it out from under any backend still+ // running from it; the next install moves an unready root aside instead.+ expect(script).not.toContain("rm -rf");+ });+});++// Reading the generated script proves what it says, not what it does. A cache+// whose bin.mjs was truncated satisfied every assertion above and still got+// reused, so these run the real script against a real archive in a throwaway+// HOME and check the outcome.+describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => {+ const fixtures: Array<string> = [];++ afterAll(() => {+ for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`);+ fixtures.length = 0;+ });++ const createFixture = () => {+ const result = runShell(+ [+ "set -eu",+ "work=$(mktemp -d)",+ 'stage="$work/stage"',+ 'mkdir -p "$stage/apps/server/dist" "$stage/node_modules/node-pty/prebuilds/linux-x64" "$work/home"',+ `printf '%s' ${sh(SERVER_ENTRY_SOURCE)} > "$stage/apps/server/dist/bin.mjs"`,+ `printf '%s' '{"name":"node-pty","version":"0.0.0-test"}' > "$stage/node_modules/node-pty/package.json"`,+ `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/prebuilds/linux-x64/pty.node"`,+ `printf '%s' '{"arch":"x64"}' > "$stage/node_modules/node-pty/prebuilds/linux-x64/t3code-wsl-node-pty.json"`,+ `tar -czf "$work/wsl-runtime.tar.gz" -C "$stage" apps/server/dist node_modules`,+ `printf 'work:%s\\n' "$work"`,+ `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,+ ].join("\n"),+ );+ expect(result.status, result.stderr).toBe(0);++ const work = readField(result.stdout, "work");+ fixtures.push(work);+ const archivePath = `${work}/wsl-runtime.tar.gz`;+ const archiveSha = readField(result.stdout, "archiveSha");+ const runtimeId = `sha256-${archiveSha}`;+ // The script reads $HOME, and WSL does not inherit the parent process's+ // environment, so the home override rides in the script itself.+ const installScript = (archive = archivePath, sha = archiveSha) =>+ [+ `HOME=${sh(`${work}/home`)}`,+ "export HOME",+ buildWslRuntimeInstallScript(archive, runtimeId, sha),+ ].join("\n");+ return {+ work,+ archivePath,+ archiveSha,+ runtimeId,+ runtimeParent: `${work}/home/.t3/wsl-runtime`,+ runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`,+ serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/apps/server/dist/bin.mjs`,+ installScript,+ install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),+ };+ };++ it("reuses a warm cache without touching the archive", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ // Deleting the archive is how the test tells reuse apart from a silent+ // reinstall: only the warm path can succeed without it.+ expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);++ const warm = fixture.install();++ expect(warm.status, warm.stderr).toBe(0);+ expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);+ });++ it("reinstalls a cache whose server entry was truncated", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);++ const repaired = fixture.install();++ expect(repaired.status, repaired.stderr).toBe(0);+ expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot);+ const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`);+ expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE);+ });++ it("falls back instead of launching a corrupted cache it cannot reinstall", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);+ expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0);++ const broken = fixture.install();++ // Non-zero with no runtimeRoot is what sends the backend to the mounted+ // server tree. Exiting 0 here is the bug: launch would pick the zero-byte+ // server, fail to become ready, and do it again on every restart.+ expect(broken.status).not.toBe(0);+ expect(parseWslRuntimeRoot(broken.stdout)).toBeNull();+ });++ it("extracts once when two installs race for the same cache", () => {+ const fixture = createFixture();+ // A tar shim counts extractions and holds the critical section open long+ // enough that the second install is certain to arrive while the first is+ // still inside it. One extraction is the answer either way the runs+ // interleave: whoever waits for the lock re-checks readiness before+ // spending an extract, so a broken lock shows up as two.+ const raced = runShell(+ [+ "set -eu",+ `work=${sh(fixture.work)}`,+ 'mkdir -p "$work/bin"',+ "real_tar=$(command -v tar)",+ `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`,+ 'chmod +x "$work/bin/tar"',+ ': > "$work/tar-calls"',+ 'PATH="$work/bin:$PATH"',+ "export PATH",+ `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`,+ fixture.installScript(),+ "T3CODE_INSTALL_SCRIPT",+ // Both racers run the same file, and neither file path contains the+ // runtime root, so the script's own /proc scan cannot see them.+ 'sh "$work/install.sh" > "$work/first.out" 2>&1 &',+ "first=$!",+ 'sh "$work/install.sh" > "$work/second.out" 2>&1 &',+ "second=$!",+ "if wait $first; then first_status=0; else first_status=$?; fi",+ "if wait $second; then second_status=0; else second_status=$?; fi",+ `printf 'firstStatus:%s\\n' "$first_status"`,+ `printf 'secondStatus:%s\\n' "$second_status"`,+ `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`,+ `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`,+ `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`,+ ].join("\n"),+ );++ expect(raced.status, raced.stderr).toBe(0);+ expect(readField(raced.stdout, "firstStatus")).toBe("0");+ expect(readField(raced.stdout, "secondStatus")).toBe("0");+ expect(readField(raced.stdout, "extractions")).toBe("1");+ expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot);+ expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot);+ });++ it("leaves no half-built cache when extraction fails", () => {+ const fixture = createFixture();+ // Truncating the archive and re-recording its digest gets the install past+ // the digest gate and into a tar that dies mid-stream, which is what a full+ // disk or an interrupted write looks like from inside the distro.+ const truncated = runShell(+ [+ "set -eu",+ `work=${sh(fixture.work)}`,+ 'size=$(wc -c < "$work/wsl-runtime.tar.gz")',+ 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"',+ `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`,+ ].join("\n"),+ );+ expect(truncated.status, truncated.stderr).toBe(0);++ const failed = fixture.install(+ `${fixture.work}/truncated.tar.gz`,+ readField(truncated.stdout, "sha"),+ );++ expect(failed.status).not.toBe(0);+ expect(parseWslRuntimeRoot(failed.stdout)).toBeNull();+ // A partial extract that survived under the cache name would be promoted by+ // the next launch's readiness check; scratch that survived would sit there+ // until the pruner's age sweep. Neither is left behind. Only directories+ // are counted: the empty flock file stays on purpose, which is what keeps+ // the lock from carrying stale state across a killed install.+ const leftovers = runShell(+ `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,+ );+ expect(leftovers.stdout.trim()).toBe("");+ });++ // The archive and the identity recorded beside it can diverge — a partial+ // download, or a rebuilt archive dropped next to an older sidecar. Either+ // gate firing means the bytes never reach the cache under a name that claims+ // to describe something else.+ it("refuses an archive whose bytes do not match the digest recorded for it", () => {+ const fixture = createFixture();++ const refused = fixture.install(fixture.archivePath, "e".repeat(64));++ expect(refused.status).not.toBe(0);+ expect(refused.stderr).toContain("does not match its recorded SHA-256");+ expect(parseWslRuntimeRoot(refused.stdout)).toBeNull();+ const leftovers = runShell(+ `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`,+ );+ expect(leftovers.stdout.trim()).toBe("");+ });++ it("leases a warm cache across the prepare-to-spawn handoff", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ const selected = runShell(+ [+ "set -eu",+ `runtime_parent=${sh(fixture.runtimeParent)}`,+ 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',+ 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',+ 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',+ `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,+ 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',+ `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`,+ fixture.installScript(),+ "T3CODE_SELECT_SCRIPT",+ `sh ${sh(`${fixture.work}/select.sh`)}`,+ `HOME=${sh(`${fixture.work}/home`)}`,+ "export HOME",+ buildWslRuntimePruneScript("sha256-current"),+ `test -d ${sh(fixture.runtimeRoot)}`,+ ].join("\n"),+ );++ expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0);+ });++ it("prunes a selected cache after its prepare-to-spawn grace period expires", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ const result = runShell(+ [+ "set -eu",+ `runtime_parent=${sh(fixture.runtimeParent)}`,+ 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"',+ 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"',+ 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"',+ `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`,+ `touch -d "10 minutes ago" ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-selected`)}`,+ 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',+ `HOME=${sh(`${fixture.work}/home`)}`,+ "export HOME",+ buildWslRuntimePruneScript("sha256-current"),+ `test ! -e ${sh(fixture.runtimeRoot)}`,+ ].join("\n"),+ );++ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);+ });++ it("removes an aged stale tree after replacing an active unready cache", () => {+ const fixture = createFixture();+ expect(fixture.install().status).toBe(0);+ const result = runShell(+ [+ "set -eu",+ `runtime_root=${sh(fixture.runtimeRoot)}`,+ `runtime_parent=${sh(fixture.runtimeParent)}`,+ 'rm "$runtime_root/.t3code-wsl-runtime-ready"',+ 'sh -c "sleep 30" "$runtime_root/apps/server/dist/bin.mjs" >/dev/null 2>&1 &',+ "active_pid=$!",+ "sleep 0.1",+ fixture.installScript(),+ 'stale=$(find "$runtime_parent" -maxdepth 1 -type d -name ".sha256-*.stale.*" -print -quit)',+ 'test -n "$stale"',+ 'touch -d "180 minutes ago" "$stale"',+ `HOME=${sh(`${fixture.work}/home`)}`,+ "export HOME",+ buildWslRuntimePruneScript(fixture.runtimeId),+ 'test ! -e "$stale"',+ "kill $active_pid",+ "wait $active_pid 2>/dev/null || true",+ ].join("\n"),+ );++ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);+ });++ it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => {+ const result = runShell(+ [+ "set -eu",+ "work=$(mktemp -d)",+ 'home="$work/home"',+ 'runtime_parent="$home/.t3/wsl-runtime"',+ 'mkdir -p "$runtime_parent"',+ 'make_ready() { mkdir -p "$runtime_parent/$1/apps/server/dist"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',+ "make_ready sha256-current",+ "make_ready sha256-previous",+ "make_ready sha256-active",+ "make_ready sha256-old",+ "make_ready sha256-locked",+ 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"',+ 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"',+ 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"',+ 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"',+ 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"',+ 'sh -c "sleep 30" "$runtime_parent/sha256-active/apps/server/dist/bin.mjs" >/dev/null 2>&1 &',+ "active_pid=$!",+ "(",+ ' exec 9> "$runtime_parent/.sha256-locked.install.lock"',+ " flock -x 9",+ " sleep 30",+ ") >/dev/null 2>&1 &",+ "lock_pid=$!",+ "sleep 0.1",+ `HOME="$home"`,+ "export HOME",+ buildWslRuntimePruneScript("sha256-current"),+ 'test -d "$runtime_parent/sha256-current"',+ 'test -d "$runtime_parent/sha256-previous"',+ 'test -d "$runtime_parent/sha256-active"',+ 'test -d "$runtime_parent/sha256-locked"',+ 'test -d "$runtime_parent/versions"',+ 'test ! -e "$runtime_parent/sha256-old"',+ 'test ! -e "$runtime_parent/sha256-markerless"',+ "kill $active_pid $lock_pid",+ "wait $active_pid 2>/dev/null || true",+ "wait $lock_pid 2>/dev/null || true",+ 'rm -rf "$work"',+ ].join("\n"),+ );++ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);+ });+});+describe("parseToolchainReport", () => {it("returns no missing tools and no node version on empty output", () => {expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.tsindex 164117727ea..b0c9f5ffe44 100644--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts@@ -22,6 +22,9 @@ const WSLPATH_TIMEOUT = Duration.seconds(10);const PROBE_TIMEOUT = Duration.seconds(10);const TOOLCHAIN_TIMEOUT = Duration.seconds(10);const BUILD_TIMEOUT = Duration.minutes(5);+const RUNTIME_INSTALL_TIMEOUT = Duration.minutes(2);+const RUNTIME_PRUNE_TIMEOUT = Duration.seconds(30);+const RUNTIME_INVALIDATE_TIMEOUT = Duration.seconds(15);const USER_HOME_TIMEOUT = Duration.seconds(5);const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;const BUILD_TRANSPORT_RETRY_LIMIT = 2;@@ -31,6 +34,25 @@ export interface EnsureWslNodePtyOptions {readonly nodeEngineRange?: string | null;}+// The packaged WSL runtime archive plus the SHA-256 identity the build recorded+// for it. The cache key derives from the same digest, and installation verifies+// the bytes before promoting the extracted tree.+export interface WslRuntimeArchive {+ readonly windowsPath: string;+ readonly runtimeId: string;+ readonly sha256: string;+}++export type PrepareWslRuntimeResult =+ | {+ readonly ok: true;+ readonly linuxAppRoot: string;+ }+ | {+ readonly ok: false;+ readonly reason: string;+ };+export type EnsureWslNodePtyResult =| {readonly ok: true;@@ -79,9 +101,16 @@ export class DesktopWslEnvironment extends Context.Service<// (the backend can be listening for 30+ seconds before wslhost starts// forwarding 127.0.0.1:port to WSL-side localhost).readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;+ readonly prepareRuntime: (+ distro: string | null,+ archive: WslRuntimeArchive,+ ) => Effect.Effect<PrepareWslRuntimeResult>;+ readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect<void>;+ // Marks a staged runtime as unusable so the next launch reinstalls it.+ readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect<void>;readonly ensureNodePty: (distro: string | null,- windowsRepoRoot: string,+ linuxAppRoot: string,options?: EnsureWslNodePtyOptions,) => Effect.Effect<EnsureWslNodePtyResult>;}@@ -149,18 +178,28 @@ const runWslShell = (distro: string | null,bashScript: string,timeout: Duration.Duration,- options: EnsureWslNodePtyOptions = {},+ options: {+ readonly nodeEngineRange?: string | null;+ readonly resolveNode?: boolean;+ } = {},): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {const spawner = ChildProcessSpawner.ChildProcessSpawner;- // -l picks up profile-managed PATH; the shared resolver covers supported- // version managers that non-interactive login shells can miss. -s so bash- // reads the script from stdin.+ // Node probes use a login bash so profile-managed PATH entries and supported+ // version managers are available. Runtime installation needs only POSIX tools,+ // so it skips profile loading and runs sh directly.+ const resolveNode = options.resolveNode !== false;const command = ChildProcess.make("wsl.exe",- [...buildDistroArgs(distro), "--", "bash", "-l", "-s"],+ resolveNode+ ? [...buildDistroArgs(distro), "--", "bash", "-l", "-s"]+ : [...buildDistroArgs(distro), "--exec", "sh", "-s"],{stdin: Stream.encodeText(- Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),+ Stream.make(+ resolveNode+ ? `${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`+ : bashScript,+ ),),stdout: "pipe",stderr: "pipe",@@ -216,6 +255,240 @@ const runWslShell = (const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;+// Holds the sha256 of the runtime's server entry, written when the install+// promotes a verified tree. Presence alone only says an install once finished+// here; the digest is what lets a later launch prove the entry still is what+// that install wrote.+const WSL_RUNTIME_READY_MARKER = ".t3code-wsl-runtime-ready";+const WSL_RUNTIME_SELECTED_MARKER = ".t3code-wsl-runtime-selected";+const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5;++export const sanitizeWslRuntimeId = (value: string): string =>+ value.replace(/[^A-Za-z0-9._-]/g, "_");++// `archiveSha256` is the digest the build recorded alongside the archive. The+// install verifies the bytes before extracting, so an archive can never be+// promoted under an identity that does not describe it.+export const buildWslRuntimeInstallScript = (+ linuxArchivePath: string,+ runtimeId: string,+ archiveSha256: string,+): string => {+ const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);+ return [+ "set -eu",+ 'runtime_parent="$HOME/.t3/wsl-runtime"',+ `runtime_root="$runtime_parent/${safeRuntimeId}"`,+ `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`,+ // The native payload is the part of the tree the WSL backend actually+ // dlopens, and the only part a user can plausibly break by hand. Checking+ // node-pty's package.json alone let a runtime whose pty.node had gone+ // missing stay cache-ready forever: every launch reused it and then failed+ // the native probe, with no reinstall and no fallback. Match on the glob+ // rather than a mapped `uname -m` so this stays a presence check; the probe+ // is what decides whether the binary is the right arch and loadable.+ "node_pty_payload_present() {",+ ' for candidate in "$1"/node_modules/node-pty/prebuilds/linux-*/pty.node; do',+ ' [ -f "$candidate" ] || continue',+ ' [ -f "${candidate%/*}/t3code-wsl-node-pty.json" ] || continue',+ " return 0",+ " done",+ " return 1",+ "}",+ // Hashing the server entry is the only check that can tell a working cache+ // from one whose bin.mjs was truncated or half-written: the file is still+ // there, the native probe still passes, and launch then picks a server that+ // exits before it can become ready, on every restart. Hashing the ~7MB+ // entry measures in single-digit milliseconds inside the distro, once per+ // launch, against a cold reinstall of a few hundred megabytes.+ "runtime_server_entry_digest() {",+ ` sha256sum "$1/apps/server/dist/bin.mjs" 2>/dev/null | cut -d ' ' -f 1`,+ "}",+ "runtime_is_ready() {",+ ' [ -f "$ready_marker" ] &&',+ ' [ -f "$runtime_root/apps/server/dist/bin.mjs" ] &&',+ ' [ -f "$runtime_root/node_modules/node-pty/package.json" ] &&',+ ' node_pty_payload_present "$runtime_root" &&',+ // An empty or unreadable marker is a miss, not a pass: that is what a+ // runtime installed before the marker carried a digest looks like, and one+ // reinstall is the cheapest way to make it verifiable from then on.+ ` recorded_entry_digest=$(tr -d '[:space:]' < "$ready_marker" 2>/dev/null) &&`,+ ' [ -n "$recorded_entry_digest" ] &&',+ ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',+ "}",+ 'mkdir -p "$runtime_parent"',+ `runtime_lock="$runtime_parent/.${safeRuntimeId}.install.lock"`,+ "trap 'exit 1' HUP INT TERM",+ 'exec 9> "$runtime_lock"',+ "flock -x 9",+ "if runtime_is_ready; then",+ ` touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,+ ` printf 'runtimeRoot:%s\\n' "$runtime_root"`,+ " exit 0",+ "fi",+ // Hash only on a cache miss: a warm launch already exited above, and a cold+ // install is about to read the whole archive through tar anyway. `set -eu`+ // turns a distro without sha256sum into an install failure, which falls back+ // to the mounted server tree rather than trusting unverified bytes.+ `archive_sha=$(sha256sum ${shellQuote(linuxArchivePath)} | cut -d ' ' -f 1)`,+ `if [ "$archive_sha" != ${shellQuote(archiveSha256)} ]; then`,+ ` printf 'WSL runtime archive does not match its recorded SHA-256 (expected %s, got %s)\\n' ${shellQuote(archiveSha256)} "$archive_sha" >&2`,+ " exit 1",+ "fi",+ // A backend can still be running out of an unready tree: the probe revokes+ // the ready marker without stopping the process it just failed for, and+ // invalidation deliberately leaves the tree in place for exactly that+ // reason. Deleting it here unlinks node_modules from under a live backend,+ // which then breaks the moment it lazily loads anything it had not already+ // read. Move it aside either way, but only delete it now when nothing is+ // running from it; otherwise hand it to the pruner's scratch sweep, which+ // is what that delay is for. A process's cmdline keeps the pre-rename path,+ // so this has to be asked before the move, not after. This script arrives+ // on stdin, so it cannot match itself.+ "runtime_in_use() {",+ // No /proc means no way to tell, and guessing wrong costs a live backend+ // its runtime. Keeping the tree only costs disk until the sweep runs.+ " [ -d /proc/1 ] || return 0",+ ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',+ "}",+ 'if [ -e "$runtime_root" ]; then',+ ' if runtime_in_use "$runtime_root"; then',+ " runtime_root_in_use=1",+ " else",+ " runtime_root_in_use=0",+ " fi",+ ` runtime_stale=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.stale.XXXXXX")`,+ ' rmdir "$runtime_stale"',+ ' if mv -T "$runtime_root" "$runtime_stale" 2>/dev/null; then',+ ' if [ "$runtime_root_in_use" = 1 ]; then',+ // Renaming keeps the directory's old mtime, so restart the cleanup clock.+ ' touch "$runtime_stale"',+ " else",+ ' rm -rf "$runtime_stale"',+ " fi",+ " fi",+ "fi",+ `runtime_tmp=$(mktemp -d "$runtime_parent/.${safeRuntimeId}.tmp.XXXXXX")`,+ 'cleanup_runtime_install() { rm -rf "$runtime_tmp"; }',+ "trap cleanup_runtime_install EXIT",+ `tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp"`,+ 'test -f "$runtime_tmp/apps/server/dist/bin.mjs"',+ 'test -f "$runtime_tmp/node_modules/node-pty/package.json"',++ // Never write the ready marker over a tree that is missing the native+ // payload. Failing here drops out to the mounted-tree fallback, which is+ // recoverable; promoting it would mark the defect ready and cache it.+ 'if ! node_pty_payload_present "$runtime_tmp"; then',+ " printf 'WSL runtime archive is missing its Linux node-pty binary\\n' >&2",+ " exit 1",+ "fi",+ // The archive's bytes were verified against archiveSha256 above, so the+ // digest recorded here describes content this install proved. Every later+ // warm reuse checks the entry against it.+ 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")',+ 'if [ -z "$installed_entry_digest" ]; then',+ " printf 'Could not hash the WSL runtime server entry\\n' >&2",+ " exit 1",+ "fi",+ `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/${WSL_RUNTIME_READY_MARKER}"`,+ 'if mv -T "$runtime_tmp" "$runtime_root" 2>/dev/null; then',+ " :",+ "elif runtime_is_ready; then",+ ' rm -rf "$runtime_tmp"',+ "else",+ ` printf 'Could not promote WSL runtime cache at %s\\n' "$runtime_root" >&2`,+ " exit 1",+ "fi",+ `touch "$runtime_root/${WSL_RUNTIME_SELECTED_MARKER}"`,+ `printf 'runtimeRoot:%s\\n' "$runtime_root"`,+ ].join("\n");+};++// An interrupted install leaves a dot-prefixed scratch directory behind. A cold+// install extracts a few hundred MB inside the distro, so two hours is far past+// any live install while still bounding how long an orphan survives.+const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120;++export const buildWslRuntimePruneScript = (runtimeId: string): string => {+ const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);+ return [+ "set -eu",+ 'runtime_parent="$HOME/.t3/wsl-runtime"',+ `current_runtime="$runtime_parent/${safeRuntimeId}"`,+ '[ -d "$runtime_parent" ] || exit 0',+ // Serialize the whole retention decision so two backends cannot select+ // different "previous" caches and delete around one another.+ 'prune_lock="$runtime_parent/.prune.lock"',+ 'exec 8> "$prune_lock"',+ "flock -x 8",+ // Without a way to see the distro's processes we cannot tell which caches+ // are load-bearing, and the retention rules below are not safe on their own.+ "[ -d /proc/1 ] || exit 0",+ "runtime_in_use() {",+ ' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null',+ "}",+ 'previous_runtime=""',+ 'for candidate in "$runtime_parent"/sha256-*; do',+ ' [ -d "$candidate" ] || continue',+ ' [ "$candidate" != "$current_runtime" ] || continue',+ ` [ -f "$candidate/${WSL_RUNTIME_READY_MARKER}" ] || continue`,+ ' if [ -z "$previous_runtime" ] || [ "$candidate" -nt "$previous_runtime" ]; then',+ ' previous_runtime="$candidate"',+ " fi",+ "done",+ // Only this desktop-owned prefix is eligible. Markerless roots are broken+ // caches left by invalidation and must not become permanent disk leaks.+ 'for candidate in "$runtime_parent"/sha256-*; do',+ ' [ -d "$candidate" ] || continue',+ ' [ "$candidate" != "$current_runtime" ] || continue',+ ' [ "$candidate" != "$previous_runtime" ] || continue',+ ' ! runtime_in_use "$candidate" || continue',+ " candidate_name=${candidate##*/}",+ ' candidate_lock="$runtime_parent/.${candidate_name}.install.lock"',+ ' exec 9> "$candidate_lock"',+ // A held lock means another launch is installing or repairing this cache.+ // Skip instead of waiting or deleting underneath it.+ " flock -n 9 || continue",+ ` selected_marker="$candidate/${WSL_RUNTIME_SELECTED_MARKER}"`,+ ` if [ -f "$selected_marker" ] && find "$selected_marker" -maxdepth 0 -mmin -${String(WSL_RUNTIME_SELECTION_GRACE_MINUTES)} -print -quit | grep -q .; then`,+ " flock -u 9",+ " continue",+ " fi",+ ' rm -rf -- "$candidate"',+ " flock -u 9",+ "done",+ // Interrupted installs use dot-prefixed names under this dedicated parent.+ 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do',+ ' [ -d "$scratch" ] || continue',+ ` find "$scratch" -maxdepth 0 -mmin +${String(ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES)} -print -quit | grep -q . || continue`,+ ' rm -rf -- "$scratch"',+ "done",+ ].join("\n");+};++// Drops the ready marker so the next launch reinstalls the runtime from the+// archive. Readiness is a presence check by design, so a cached tree whose+// native payload is present but unloadable (truncated pty.node, a distro whose+// glibc the binary needs and the tree was copied from another machine) stays+// ready forever and fails the probe on every launch. Only the probe can see+// that, so the probe is what revokes the marker. The tree itself is left in+// place: the install script moves an unready root aside before extracting.+export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => {+ const safeRuntimeId = sanitizeWslRuntimeId(runtimeId);+ return [+ "set -eu",+ `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`,+ ].join("\n");+};++export const parseWslRuntimeRoot = (stdout: string): string | null => {+ const prefix = "runtimeRoot:";+ const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));+ if (line === undefined) return null;+ const runtimeRoot = line.slice(prefix.length).replace(/\r$/, "");+ return runtimeRoot.startsWith("/") ? runtimeRoot : null;+};+const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>@@ -390,23 +663,10 @@ export const formatMissingToolsReason = (const ensureNodePtyImpl = (distro: string | null,- windowsRepoRoot: string,- windowsToWslPath: (- distro: string | null,- windowsPath: string,- ) => Effect.Effect<Option.Option<string>>,+ linuxRepoRoot: string,options: EnsureWslNodePtyOptions = {},): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>Effect.gen(function* () {- const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);- if (Option.isNone(linuxRepoRootOption)) {- return {- ok: false,- reason: `wslpath conversion failed for ${windowsRepoRoot}`,- fatal: false,- } as const;- }- const linuxRepoRoot = linuxRepoRootOption.value;// node-pty lives in the apps/server workspace's node_modules; resolve from// there rather than the monorepo root, where Bun's hoist layout omits it.const linuxServerDir = `${linuxRepoRoot}/apps/server`;@@ -584,6 +844,96 @@ const ensureNodePtyImpl = (} as const;});+const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (+ distro: string | null,+ archive: WslRuntimeArchive,+ windowsToWslPath: (+ distro: string | null,+ windowsPath: string,+ ) => Effect.Effect<Option.Option<string>>,+): Effect.fn.Return<PrepareWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {+ const linuxArchivePath = yield* windowsToWslPath(distro, archive.windowsPath);+ if (Option.isNone(linuxArchivePath)) {+ return {+ ok: false,+ reason: `wslpath conversion failed for ${archive.windowsPath}`,+ } as const;+ }++ const install = yield* runWslShell(+ distro,+ buildWslRuntimeInstallScript(linuxArchivePath.value, archive.runtimeId, archive.sha256),+ RUNTIME_INSTALL_TIMEOUT,+ { resolveNode: false },+ );+ if (install.transportFailure !== null) {+ return {+ ok: false,+ reason:+ install.transportFailure === "timeout"+ ? "WSL runtime installation timed out. Check that the distro has free disk space, then retry."+ : "WSL runtime installation lost communication with wsl.exe. Retry, or check that the distro is healthy.",+ } as const;+ }+ if (install.exitCode !== 0) {+ const trimmedTail = `${install.stdout}${install.stderr}`.trim().slice(-500);+ return {+ ok: false,+ reason: `WSL runtime installation failed (exit ${install.exitCode}): ${trimmedTail || "no stderr captured"}`,+ } as const;+ }++ const linuxAppRoot = parseWslRuntimeRoot(install.stdout);+ return linuxAppRoot === null+ ? {+ ok: false,+ reason: "WSL runtime installation completed without reporting its cache path.",+ }+ : { ok: true, linuxAppRoot };+});++const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* (+ distro: string | null,+ runtimeId: string,+): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {+ const result = yield* runWslShell(+ distro,+ buildWslRuntimePruneScript(runtimeId),+ RUNTIME_PRUNE_TIMEOUT,+ { resolveNode: false },+ );+ if (result.transportFailure === null && result.exitCode === 0) return;++ const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);+ yield* Effect.logWarning("Could not prune old WSL runtime caches.", {+ distro,+ runtimeId,+ detail: detail || `exit ${result.exitCode}`,+ });+});++const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* (+ distro: string | null,+ runtimeId: string,+): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {+ const result = yield* runWslShell(+ distro,+ buildWslRuntimeInvalidateScript(runtimeId),+ RUNTIME_INVALIDATE_TIMEOUT,+ { resolveNode: false },+ );+ if (result.transportFailure === null && result.exitCode === 0) return;++ const detail = `${result.stdout}${result.stderr}`.trim().slice(-500);+ // Best effort: the caller has already fallen back to the mounted tree, so a+ // failure here only costs the reinstall that would have repaired the cache.+ yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", {+ distro,+ runtimeId,+ detail: detail || `exit ${result.exitCode}`,+ });+});+export const probeWslDistros: Effect.Effect<readonly WslDistro[],DesktopWslDistroListError,@@ -778,9 +1128,15 @@ export interface DesktopWslEnvironmentTestStub {readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;readonly getUserHome?: (distro: string | null) => Option.Option<string>;readonly getDistroIp?: (distro: string | null) => Option.Option<string>;+ readonly prepareRuntime?: (+ distro: string | null,+ archive: WslRuntimeArchive,+ ) => PrepareWslRuntimeResult;+ readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;+ readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;readonly ensureNodePty?: (distro: string | null,- windowsRepoRoot: string,+ linuxAppRoot: string,options?: EnsureWslNodePtyOptions,) => EnsureWslNodePtyResult;}@@ -800,9 +1156,19 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),- ensureNodePty: (distro, windowsRepoRoot, options) =>+ prepareRuntime: (distro, archive) =>+ Effect.succeed(+ stub.prepareRuntime?.(distro, archive) ?? {+ ok: false,+ reason: "prepareRuntime stub not configured",+ },+ ),+ pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,+ invalidateRuntime: (distro, runtimeId) =>+ stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,+ ensureNodePty: (distro, linuxAppRoot, options) =>Effect.succeed(- stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {+ stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {ok: false,reason: "ensureNodePty stub not configured",fatal: true,@@ -882,8 +1248,20 @@ export const layer = Layer.effect(windowsToWslPath,getUserHome,getDistroIp,- ensureNodePty: (distro, windowsRepoRoot, options) =>- provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(+ prepareRuntime: (distro, archive) =>+ provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)).pipe(+ Effect.withSpan("desktop.wsl.prepareRuntime"),+ ),+ pruneRuntimes: (distro, runtimeId) =>+ provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)).pipe(+ Effect.withSpan("desktop.wsl.pruneRuntimes"),+ ),+ invalidateRuntime: (distro, runtimeId) =>+ provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(+ Effect.withSpan("desktop.wsl.invalidateRuntime"),+ ),+ ensureNodePty: (distro, linuxAppRoot, options) =>+ provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(Effect.withSpan("desktop.wsl.ensureNodePty"),),});diff --git a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts b/apps/desktop/src/wsl/DesktopWslServerTree.test.tsindex 8c1a5b020b1..0c020806166 100644--- a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts+++ b/apps/desktop/src/wsl/DesktopWslServerTree.test.ts@@ -297,6 +297,93 @@ describe("DesktopWslServerTree", () => {).pipe(Effect.provide(NodeServices.layer)),);+ it.effect("removes the legacy Windows extraction tree without preparing a fallback", () =>+ withTempDir((tempDir) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const resourcesPath = path.join(tempDir, "resources");+ const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");+ yield* fileSystem.makeDirectory(path.join(treeRoot, "1.2.3"), { recursive: true });+ yield* fileSystem.writeFileString(path.join(treeRoot, "1.2.3", "legacy"), "old");++ yield* Effect.gen(function* () {+ const tree = yield* DesktopWslServerTree.DesktopWslServerTree;+ yield* tree.cleanupLegacy;+ }).pipe(+ Effect.provide(+ DesktopWslServerTree.layer.pipe(+ Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),+ ),+ ),+ );++ assert.isFalse(yield* fileSystem.exists(treeRoot));+ }),+ ).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("re-extracts after legacy cleanup partially deletes the completed tree", () =>+ withTempDir((tempDir) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const resourcesPath = path.join(tempDir, "resources");+ const serverRoot = path.join(resourcesPath, "server.asar");+ const sourceEntryPath = path.join(serverRoot, "apps/server/dist/bin.mjs");+ yield* fileSystem.makeDirectory(path.dirname(sourceEntryPath), { recursive: true });+ yield* fileSystem.writeFileString(sourceEntryPath, "fresh-server-entry");++ const initial = yield* ensureWith({ baseDir: tempDir, resourcesPath });+ assert.isTrue(initial.ok);+ const versionDir = initial.ok ? initial.root : "";+ const treeRoot = path.dirname(versionDir);+ const extractedEntryPath = path.join(versionDir, "apps/server/dist/bin.mjs");+ let cleanupFailed = false;+ const partialCleanupFileSystem = Layer.effect(+ FileSystem.FileSystem,+ Effect.gen(function* () {+ const realFileSystem = yield* FileSystem.FileSystem;+ return {+ ...realFileSystem,+ remove: (target, options) =>+ String(target) === treeRoot && options?.recursive === true && !cleanupFailed+ ? Effect.gen(function* () {+ cleanupFailed = true;+ yield* realFileSystem.remove(extractedEntryPath);+ return yield* PlatformError.systemError({+ _tag: "PermissionDenied",+ module: "FileSystem",+ method: "remove",+ pathOrDescriptor: treeRoot,+ description: "simulated partial legacy cleanup",+ });+ })+ : realFileSystem.remove(target, options),+ } satisfies FileSystem.FileSystem;+ }),+ ).pipe(Layer.provide(NodeServices.layer));++ const result = yield* Effect.gen(function* () {+ const tree = yield* DesktopWslServerTree.DesktopWslServerTree;+ yield* tree.cleanupLegacy;+ return yield* tree.ensure;+ }).pipe(+ Effect.provide(+ DesktopWslServerTree.layer.pipe(+ Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),+ Layer.provideMerge(partialCleanupFileSystem),+ ),+ ),+ );++ assert.isTrue(cleanupFailed);+ assert.isTrue(result.ok);+ assert.equal(yield* fileSystem.readFileString(extractedEntryPath), "fresh-server-entry");+ }),+ ).pipe(Effect.provide(NodeServices.layer)),+ );+it.effect("reports a retryable failure when the archive cannot be read", () =>withTempDir((tempDir) =>Effect.gen(function* () {diff --git a/apps/desktop/src/wsl/DesktopWslServerTree.ts b/apps/desktop/src/wsl/DesktopWslServerTree.tsindex 0b87f7bf1fe..c6094e780ca 100644--- a/apps/desktop/src/wsl/DesktopWslServerTree.ts+++ b/apps/desktop/src/wsl/DesktopWslServerTree.ts@@ -11,10 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";// Packaged Windows builds ship the server tree inside resources/server.asar// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL-// backend launches plain `wsl.exe -- node`, which cannot read an asar-// archive. This service materializes the archive into a real, version-keyed-// directory the first time the WSL backend starts, and reuses it afterwards —-// so only users who enable WSL ever pay for a loose copy of the server tree.+// backend launches plain `wsl.exe -- node`, which cannot read an asar archive.+// This fallback service materializes the archive into a real, version-keyed+// directory only when the distro-local runtime cannot be prepared.//// Reading through Electron's patched fs also transparently returns the// contents of files that electron-builder/asar left in the server.asar.unpacked@@ -52,6 +51,10 @@ export class DesktopWslServerTree extends Context.Service<// the checkout already is that directory; packaged Windows builds extract// server.asar on first use.readonly ensure: Effect.Effect<WslServerTreeResult>;+ // Removes the Windows-side extraction cache after a distro-local runtime+ // has proven healthy. Serialized with ensure so cleanup cannot race an+ // extraction that the mounted fallback is preparing.+ readonly cleanupLegacy: Effect.Effect<void>;}>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}@@ -173,6 +176,28 @@ export const make = Effect.gen(function* () {// first caller extracts, later callers see the marker and reuse the tree.const gate = yield* Semaphore.make(1);+ const cleanupLegacy = gate+ .withPermits(1)(+ needsExtraction+ ? Effect.gen(function* () {+ // Invalidate completeness before recursive deletion. Windows can+ // remove part of a tree and then fail on a locked file; without+ // this ordering, a surviving marker makes ensure reuse that+ // half-deleted fallback instead of extracting it again.+ yield* fs.remove(join(versionDir, MARKER_FILE_NAME), { force: true });+ yield* fs.remove(treeRoot, { recursive: true, force: true });+ }).pipe(+ Effect.catch((cause) =>+ Effect.logWarning("[wsl-server-tree] Could not remove the legacy extraction cache.", {+ treeRoot,+ cause,+ }),+ ),+ )+ : Effect.void,+ )+ .pipe(Effect.withSpan("desktop.wslServerTree.cleanupLegacy"));+const ensure: Effect.Effect<WslServerTreeResult> = gate.withPermits(1)(Effect.gen(function* () {@@ -205,13 +230,14 @@ export const make = Effect.gen(function* () {).pipe(Effect.withSpan("desktop.wslServerTree.ensure"));- return DesktopWslServerTree.of({ ensure });+ return DesktopWslServerTree.of({ ensure, cleanupLegacy });});export const layer = Layer.effect(DesktopWslServerTree, make);export interface DesktopWslServerTreeTestStub {readonly result?: WslServerTreeResult;+ readonly cleanupLegacy?: Effect.Effect<void>;}export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>@@ -221,6 +247,7 @@ export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>const environment = yield* DesktopEnvironment.DesktopEnvironment;return DesktopWslServerTree.of({ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),+ cleanupLegacy: stub.cleanupLegacy ?? Effect.void,});}),);diff --git a/docs/operations/release.md b/docs/operations/release.mdindex 68f2e8da578..e5a4d3544c3 100644--- a/docs/operations/release.md+++ b/docs/operations/release.md@@ -222,10 +222,12 @@ Windows packages the bundled server and only its runtime-external/nativedependency closure in `resources/server.asar`. Native modules and helperexecutables declared as unpacked by that archive must be present at the matchingpaths below `resources/server.asar.unpacked`. The Windows-native backend reads-the archive in place through Electron. WSL cannot read ASAR files, so enabling-the WSL backend extracts the server tree once into the desktop state directory-under `wsl-server-tree/<version>` and reuses the completed version until the app-is updated.+the archive in place through Electron. Packaged Windows builds also ship a+Linux-only `resources/wsl-runtime.tar.gz` plus its SHA-256 sidecar. WSL verifies+and extracts that archive into `~/.t3/wsl-runtime/sha256-<archive-digest>` inside+the selected distro, then reuses it for later launches of the same update. The+Windows-side `wsl-server-tree/<version>` extraction remains a fallback and is+removed after the distro-local runtime passes preflight.The artifact builder rejects a Windows package when any of these invariantsbreak:@@ -236,6 +238,11 @@ break:- On same-architecture Windows builds, the packaged primary cannot load the fffnative library from inside `server.asar` through its `.unpacked` sibling.- The isolated, extracted sidecar cannot load the server entry with plain Node.+- A Windows build with a WSL node-pty prebuild omits the WSL archive or SHA-256+ sidecar, the sidecar digest does not match the emitted archive, or required+ Linux runtime members are absent.+- The emitted WSL archive contains Windows/Darwin node-pty payloads, ConPTY,+ pnpm install metadata, or Windows-only FFF, ffi-rs, or msgpackr bindings.- The external Windows resource monitor is absent.- The unpacked Windows application contains more than 80 files.diff --git a/docs/user/install.md b/docs/user/install.mdindex 7ef7b97f937..d6d194ee310 100644--- a/docs/user/install.md+++ b/docs/user/install.md@@ -49,6 +49,16 @@ Nightly:yay -S t3code-nightly-bin```+### Windows Subsystem for Linux++When the desktop app runs a WSL backend, it installs the matching server runtime into+`~/.t3/wsl-runtime` inside the selected distro. The first launch after installing or updating T3+Code may take a little longer while that release's runtime is extracted. Later launches reuse the+Linux-local copy so startup does not depend on reading application files through `/mnt/c`. After a+successful launch, T3 Code keeps the current runtime and one previous runtime for rollback and+removes older caches automatically. If a cached runtime stops working, T3 Code launches from the+application files under `/mnt/c` instead and reinstalls the runtime on the next launch.+## ProvidersT3 Code drives provider CLIs; it does not ship them. Install the CLI for each provider you wantdiff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.tsindex a7bb1b9b7c4..c12c73bfc1a 100644--- a/scripts/build-desktop-artifact.test.ts+++ b/scripts/build-desktop-artifact.test.ts@@ -1,3 +1,6 @@+// @effect-diagnostics nodeBuiltinImport:off - packaged-archive fixtures compute the sidecar digest with the same Node primitive as the builder.+import * as NodeCrypto from "node:crypto";+import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import * as ConfigProvider from "effect/ConfigProvider";@@ -8,11 +11,13 @@ import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";-import { ChildProcessSpawner } from "effect/unstable/process";+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";import {BundleNotSelfContainedError,BuildCommandFailedError,+ buildWslRuntimeArchiveArgs,+ parseWslRuntimeArchiveMembers,DesktopDmgBackgroundSourceMissingError,createStageWorkspaceConfig,createStagePatchedDependencies,@@ -51,6 +56,8 @@ import {stageLinuxIconSize,stageDesktopDmgBackground,stageResourceMonitor,+ stageWslRuntimeArchive,+ bundlesWslRuntime,STAGE_INSTALL_ARGS,ancestorNodeModulesPaths,copyDirectoryPreservingSymlinks,@@ -63,10 +70,38 @@ import {WINDOWS_SERVER_ASAR_RESOURCE,WINDOWS_SERVER_ASAR_UNPACK_GLOB,WINDOWS_SERVER_RESOURCE_SOURCE_DIR,+ WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,+ WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE,+ WSL_RUNTIME_ARCHIVE_HASH_NAME,+ WSL_RUNTIME_ARCHIVE_NAME,+ WSL_RUNTIME_EXTRA_RESOURCES,+ wslRuntimeArchiveTarTarget,} from "./build-desktop-artifact.ts";import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";+// A minimal stand-in for the staged sidecar roots packed into the WSL archive.+const stageWslRuntimeTreeFixture = Effect.fn("stageWslRuntimeTreeFixture")(function* (+ root: string,+ serverSource: string,+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.makeDirectory(path.join(root, "apps/server/dist"), { recursive: true });+ yield* fs.writeFileString(path.join(root, "apps/server/dist/bin.mjs"), serverSource);+ yield* fs.makeDirectory(path.join(root, "node_modules/node-pty/prebuilds/linux-x64"), {+ recursive: true,+ });+ yield* fs.writeFileString(+ path.join(root, "node_modules/node-pty/package.json"),+ '{"name":"node-pty"}\n',+ );+ yield* fs.writeFileString(+ path.join(root, "node_modules/node-pty/prebuilds/linux-x64/pty.node"),+ "pty",+ );+});+function mockProcess(exitCode: number) {return ChildProcessSpawner.makeHandle({pid: ChildProcessSpawner.ProcessId(1),@@ -107,6 +142,7 @@ function iconResizeSpawnerLayer(const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(function* (input: {readonly copyUnpackedNatives: boolean;readonly serverEntrySource?: string;+ readonly wslRuntime?: "valid" | "forbidden" | "bad-digest";}) {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;@@ -143,6 +179,61 @@ const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(fuyield* fs.writeFileString(path.join(packagedAppDir, appExecutableName), "electron");yield* fs.writeFileString(path.join(packagedAppDir, "chrome_crashpad_handler.exe"), "crashpad");+ if (input.wslRuntime !== undefined) {+ const wslSourceDir = path.join(tempDir, "wsl-source");+ const linuxPrebuildDir = path.join(wslSourceDir, "node_modules/node-pty/prebuilds/linux-x64");+ yield* fs.makeDirectory(path.join(wslSourceDir, "apps/server/dist"), { recursive: true });+ yield* fs.makeDirectory(linuxPrebuildDir, { recursive: true });+ yield* fs.writeFileString(+ path.join(wslSourceDir, "apps/server/dist/bin.mjs"),+ "console.log('wsl server');\n",+ );+ yield* fs.writeFileString(+ path.join(wslSourceDir, "node_modules/node-pty/package.json"),+ '{"name":"node-pty"}',+ );+ yield* fs.writeFileString(path.join(linuxPrebuildDir, "pty.node"), "linux-pty");+ yield* fs.writeFileString(+ path.join(linuxPrebuildDir, "t3code-wsl-node-pty.json"),+ '{"arch":"x64"}',+ );+ if (input.wslRuntime === "forbidden") {+ const windowsPrebuildDir = path.join(+ wslSourceDir,+ "node_modules/node-pty/prebuilds/win32-x64",+ );+ yield* fs.makeDirectory(windowsPrebuildDir, { recursive: true });+ yield* fs.writeFileString(path.join(windowsPrebuildDir, "pty.node"), "windows-pty");+ }++ const archivePath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_NAME);+ const hashPath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_HASH_NAME);+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const tar = yield* spawner.spawn(+ ChildProcess.make(+ "tar",+ [+ "-czf",+ wslRuntimeArchiveTarTarget(path.relative(wslSourceDir, archivePath)),+ "apps/server/dist",+ "node_modules",+ ],+ { cwd: wslSourceDir, stdin: "ignore", stdout: "ignore", stderr: "pipe" },+ ),+ );+ assert.equal(Number(yield* tar.exitCode), 0);+ const archiveDigest = NodeCrypto.createHash("sha256");+ yield* fs+ .stream(archivePath)+ .pipe(Stream.runForEach((chunk) => Effect.sync(() => archiveDigest.update(chunk))));+ yield* fs.writeFileString(+ hashPath,+ input.wslRuntime === "bad-digest"+ ? `${"0".repeat(64)}\n`+ : `${archiveDigest.digest("hex")}\n`,+ );+ }+return {stageDistDir,packagedAppDir,@@ -434,12 +525,27 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {);});- it("limits Electron locales and excludes the unused Claude SDK executable", () => {+ it("limits Electron locales and excludes separately packaged resources", () => {assert.deepStrictEqual(DESKTOP_ELECTRON_LANGUAGES, ["en-US"]);+ // Every WSL staging input is emitted once at resources/, so adding one+ // without its exclusion silently packs a second copy into app.asar. The+ // snapshot below cannot catch that on its own: adding a resource and+ // forgetting the exclusion leaves the exclusion list untouched, so it still+ // matches. Assert the invariant first, where the failure names the culprit.+ for (const resource of WSL_RUNTIME_EXTRA_RESOURCES) {+ assert.include(+ DESKTOP_FILE_EXCLUSIONS,+ `!${resource.from}`,+ `${resource.from} ships via extraResources and must be excluded from app.asar`,+ );+ }+assert.deepStrictEqual(DESKTOP_FILE_EXCLUSIONS, ["!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*","!apps/desktop/prod-resources/windows-server","!apps/desktop/prod-resources/windows-server/**/*",+ "!apps/desktop/prod-resources/wsl-runtime.tar.gz",+ "!apps/desktop/prod-resources/wsl-runtime.tar.gz.sha256",]);assert.equal(WINDOWS_SERVER_RESOURCE_SOURCE_DIR, "apps/desktop/prod-resources/windows-server");assert.deepStrictEqual(WINDOWS_SERVER_EXTRA_RESOURCES, [@@ -479,6 +585,17 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {false,undefined,undefined,+ true,+ );+ const winWithoutWslPrebuild = yield* createBuildConfig(+ "win",+ "nsis",+ "1.2.3",+ false,+ false,+ undefined,+ undefined,+ false,);// All platforms keep app.asar fully packed; Windows ships the server@@ -493,6 +610,16 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {to: "resource-monitor",},...WINDOWS_SERVER_EXTRA_RESOURCES,+ ...WSL_RUNTIME_EXTRA_RESOURCES,+ ]);+ // No Linux prebuild means the sidecar staging never writes the archive,+ // so listing it here would fail the build on a missing source file.+ assert.deepStrictEqual(winWithoutWslPrebuild.extraResources, [+ {+ from: "apps/desktop/prod-resources/resource-monitor",+ to: "resource-monitor",+ },+ ...WINDOWS_SERVER_EXTRA_RESOURCES,]);assert.deepStrictEqual(win.nsis, { differentialPackage: true });// Native binaries and helper executables cannot load from inside an@@ -716,6 +843,82 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {),);+ it.effect("validates the emitted WSL archive and its SHA-256 sidecar", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeWindowsPayloadFixture({+ copyUnpackedNatives: true,+ wslRuntime: "valid",+ });+ const result = yield* validateWindowsPackagedPayload({+ stageDistDir: fixture.stageDistDir,+ appExecutableName: fixture.appExecutableName,+ targetArch: "x64",+ expectWslRuntime: true,+ });++ assert.equal(result.packagedAppDir, fixture.packagedAppDir);+ }),+ ),+ );++ it.effect("rejects a Windows package missing its expected WSL runtime", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });+ const error = yield* validateWindowsPackagedPayload({+ stageDistDir: fixture.stageDistDir,+ appExecutableName: fixture.appExecutableName,+ targetArch: "x64",+ expectWslRuntime: true,+ }).pipe(Effect.flip);++ assert.instanceOf(error, WindowsPackagedPayloadValidationError);+ assert.equal(error.reason, "wsl-runtime-missing");+ }),+ ),+ );++ it.effect("rejects forbidden native members in the emitted WSL archive", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeWindowsPayloadFixture({+ copyUnpackedNatives: true,+ wslRuntime: "forbidden",+ });+ const error = yield* validateWindowsPackagedPayload({+ stageDistDir: fixture.stageDistDir,+ appExecutableName: fixture.appExecutableName,+ targetArch: "x64",+ expectWslRuntime: true,+ }).pipe(Effect.flip);++ assert.instanceOf(error, WindowsPackagedPayloadValidationError);+ assert.equal(error.reason, "wsl-runtime-invalid");+ }),+ ),+ );++ it.effect("rejects an emitted WSL archive whose sidecar digest does not match", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeWindowsPayloadFixture({+ copyUnpackedNatives: true,+ wslRuntime: "bad-digest",+ });+ const error = yield* validateWindowsPackagedPayload({+ stageDistDir: fixture.stageDistDir,+ appExecutableName: fixture.appExecutableName,+ targetArch: "x64",+ expectWslRuntime: true,+ }).pipe(Effect.flip);++ assert.instanceOf(error, WindowsPackagedPayloadValidationError);+ assert.equal(error.reason, "wsl-runtime-invalid");+ }),+ ),+ );+it.effect("probes fff through the packaged Windows primary instead of helper executables", () => {const commands: Array<{readonly command: string;@@ -1257,6 +1460,206 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {assert.equal(resourceMonitorExecutableName("mac"), "t3-resource-monitor");assert.equal(resourceMonitorExecutableName("win"), "t3-resource-monitor.exe");});++ it("packages the WSL server and production dependencies as one compressed runtime", () => {+ assert.equal(WSL_RUNTIME_ARCHIVE_NAME, "wsl-runtime.tar.gz");+ assert.equal(WSL_RUNTIME_ARCHIVE_HASH_NAME, "wsl-runtime.tar.gz.sha256");+ assert.deepStrictEqual(WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE, {+ from: "apps/desktop/prod-resources/wsl-runtime.tar.gz",+ to: "wsl-runtime.tar.gz",+ });+ assert.deepStrictEqual(WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE, {+ from: "apps/desktop/prod-resources/wsl-runtime.tar.gz.sha256",+ to: "wsl-runtime.tar.gz.sha256",+ });+ // The archive is only usable alongside a Linux pty.node, so both the+ // staging and the packaging config hang off this one decision.+ assert.isTrue(bundlesWslRuntime({ arch: "x64", prebuildPath: "/tmp/pty.node" }));+ assert.isTrue(bundlesWslRuntime({ arch: "arm64", prebuildPath: "/tmp/pty.node" }));+ assert.isFalse(bundlesWslRuntime({ arch: "x64", prebuildPath: undefined }));+ assert.isFalse(bundlesWslRuntime({ arch: "universal", prebuildPath: "/tmp/pty.node" }));++ assert.deepStrictEqual(buildWslRuntimeArchiveArgs(), [+ "-czf",+ "apps/desktop/prod-resources/wsl-runtime.tar.gz",+ "--exclude=node_modules/@anthropic-ai/claude-agent-sdk-*",+ "--exclude=node_modules/.bin*",+ "--exclude=node_modules/.pnpm*",+ "--exclude=node_modules/.modules.yaml*",+ "--exclude=node_modules/.pnpm-workspace-state-v1.json*",+ "--exclude=node_modules/node-pty/prebuilds/darwin-*",+ "--exclude=node_modules/node-pty/prebuilds/win32-*",+ "--exclude=node_modules/node-pty/build*",+ "--exclude=node_modules/node-pty/third_party/conpty*",+ "--exclude=node_modules/@ff-labs/fff-bin-win32-*",+ "--exclude=node_modules/@yuuang/ffi-rs-win32-*",+ "--exclude=node_modules/@msgpackr-extract/msgpackr-extract-win32-*",+ "apps/server/dist",+ "node_modules",+ ]);+ });++ it("parses Windows bsdtar member listings with CRLF line endings", () => {+ assert.deepStrictEqual(+ parseWslRuntimeArchiveMembers(+ "./apps/server/dist/bin.mjs\r\nnode_modules/node-pty/package.json\r\n",+ ),+ ["apps/server/dist/bin.mjs", "node_modules/node-pty/package.json"],+ );+ });++ it("keeps Windows tar targets colon-free so GNU tar does not read them as remote hosts", () => {+ assert.equal(+ wslRuntimeArchiveTarTarget("..\\app\\apps\\desktop\\prod-resources\\wsl-runtime.tar.gz"),+ "../app/apps/desktop/prod-resources/wsl-runtime.tar.gz",+ );+ assert.equal(+ wslRuntimeArchiveTarTarget("../app/apps/desktop/prod-resources/wsl-runtime.tar.gz"),+ "../app/apps/desktop/prod-resources/wsl-runtime.tar.gz",+ );+ });++ // The staged source tree and the archive live in sibling stage directories,+ // so this covers the real call: on Windows the archive path is an absolute+ // C:\... path, and handing that to tar is what made Git's GNU tar try to+ // reach a host named "C".+ it.effect("spawns tar with an archive target relative to the staged source tree", () => {+ const commands: Array<{+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ readonly options: { readonly cwd?: string };+ }> = [];++ return Effect.scoped(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const stageRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-wsl-runtime-archive-" });+ const sourceDir = path.join(stageRoot, "server");+ const stageAppDir = path.join(stageRoot, "app");+ const archivePath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from);+ const hashPath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from);+ yield* stageWslRuntimeTreeFixture(sourceDir, "export const serve = 1;\n");++ const spawnerLayer = Layer.succeed(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make((command) => {+ const childProcess = command as unknown as (typeof commands)[number];+ commands.push(childProcess);+ // Stand in for tar: write the archive by resolving the -f target+ // against the cwd tar was spawned in, exactly as tar would.+ const target = path.resolve(childProcess.options.cwd ?? "", childProcess.args[1] ?? "");+ return Effect.as(fs.writeFileString(target, "wsl-runtime-archive"), mockProcess(0));+ }),+ );++ yield* stageWslRuntimeArchive({ sourceDir, archivePath, hashPath }).pipe(+ Effect.provide(spawnerLayer),+ );++ const tarCommand = commands.find((command) => command.command === "tar");+ if (tarCommand === undefined) return assert.fail("tar was not spawned");++ const target = tarCommand.args[1] ?? "";+ assert.equal(tarCommand.options.cwd, sourceDir);+ assert.notInclude(target, ":");+ assert.isFalse(path.isAbsolute(target));+ // Relative or not, tar has to land the archive where the build expects it.+ assert.equal(path.resolve(sourceDir, target), archivePath);+ assert.isTrue(yield* fs.exists(archivePath));++ // The archive digest both gates installation and names the cache.+ const hash = yield* fs.readFileString(hashPath);+ assert.match(hash.trim(), /^[0-9a-f]{64}$/);+ }),+ );+ });++ it.effect("ships only Linux runtime members in the WSL archive", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-wsl-runtime-members-" });+ const sourceDir = path.join(root, "server");+ const archivePath = path.join(root, "wsl-runtime.tar.gz");+ const hashPath = `${archivePath}.sha256`;+ yield* stageWslRuntimeTreeFixture(sourceDir, "export const serve = 1;\n");++ const members = [+ "node_modules/node-pty/prebuilds/darwin-x64/pty.node",+ "node_modules/node-pty/prebuilds/win32-x64/pty.node",+ "node_modules/node-pty/build/Release/pty.node",+ "node_modules/node-pty/third_party/conpty/win10-x64/conpty.dll",+ "node_modules/@ff-labs/fff-bin-win32-x64/fff.dll",+ "node_modules/@ff-labs/fff-bin-linux-x64-gnu/libfff.so",+ "node_modules/@yuuang/ffi-rs-win32-x64-msvc/ffi.dll",+ "node_modules/@yuuang/ffi-rs-linux-x64-gnu/libffi.so",+ "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64/addon.node",+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/addon.node",+ "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64/index.js",+ "node_modules/.bin/tool",+ "node_modules/.pnpm/lock.yaml",+ "node_modules/.modules.yaml",+ "node_modules/.pnpm-workspace-state-v1.json",+ ] as const;+ yield* Effect.forEach(+ members,+ (member) =>+ Effect.gen(function* () {+ const memberPath = path.join(sourceDir, member);+ yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true });+ yield* fs.writeFileString(memberPath, member);+ }),+ { discard: true },+ );++ yield* stageWslRuntimeArchive({ sourceDir, archivePath, hashPath });+ const process = yield* spawner.spawn(+ ChildProcess.make("tar", ["-tzf", archivePath], {+ stdin: "ignore",+ stdout: "pipe",+ stderr: "pipe",+ }),+ );+ const listing = yield* process.stdout.pipe(+ Stream.decodeText(),+ Stream.runFold(+ () => "",+ (output, chunk) => output + chunk,+ ),+ );+ assert.equal(Number(yield* process.exitCode), 0);++ assert.include(listing, "apps/server/dist/bin.mjs");+ assert.include(listing, "node_modules/node-pty/prebuilds/linux-x64/pty.node");+ assert.include(listing, "node_modules/@ff-labs/fff-bin-linux-x64-gnu/libfff.so");+ assert.include(listing, "node_modules/@yuuang/ffi-rs-linux-x64-gnu/libffi.so");+ assert.include(+ listing,+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64/addon.node",+ );+ for (const excluded of [+ "prebuilds/darwin-",+ "prebuilds/win32-",+ "node-pty/build",+ "third_party/conpty",+ "fff-bin-win32-",+ "ffi-rs-win32-",+ "msgpackr-extract-win32-",+ "claude-agent-sdk-",+ "node_modules/.bin",+ "node_modules/.pnpm",+ "node_modules/.modules.yaml",+ "node_modules/.pnpm-workspace-state-v1.json",+ ]) {+ assert.notInclude(listing, excluded);+ }+ }),+ ),+ );+it("promotes target fff binaries to direct staged dependencies", () => {assert.deepStrictEqual(resolveFffNativeDependencies("mac", "arm64", "0.9.4"), {"@ff-labs/fff-bin-darwin-arm64": "0.9.4",diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex dd8355e4c76..8709be2a259 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -2,6 +2,7 @@// @effect-diagnostics nodeBuiltinImport:off - Node's typed junction API avoids Windows symlink privileges while keeping the probe isolated.import * as NodeFSP from "node:fs/promises";+import * as NodeCrypto from "node:crypto";import * as NodeModule from "node:module";import {@@ -560,6 +561,8 @@ const WindowsPackagedPayloadValidationReason = Schema.Literals(["sidecar-invalid","unpacked-native-missing","resource-monitor-missing",+ "wsl-runtime-missing",+ "wsl-runtime-invalid","file-limit-exceeded",]);@@ -584,6 +587,12 @@ export class WindowsPackagedPayloadValidationError extends Schema.TaggedErrorClaif (this.reason === "resource-monitor-missing") {return "Windows packaged payload is missing the resource monitor executable.";}+ if (this.reason === "wsl-runtime-missing") {+ return "Windows packaged payload is missing the WSL runtime archive or SHA-256 sidecar.";+ }+ if (this.reason === "wsl-runtime-invalid") {+ return "Windows packaged payload contains an invalid WSL runtime archive.";+ }if (this.reason === "sidecar-invalid") {return "Windows packaged payload contains an invalid server.asar sidecar.";}@@ -795,6 +804,8 @@ export const DESKTOP_FILE_EXCLUSIONS = [// staging inputs out of app.asar; they are emitted once at resources/."!apps/desktop/prod-resources/windows-server","!apps/desktop/prod-resources/windows-server/**/*",+ "!apps/desktop/prod-resources/wsl-runtime.tar.gz",+ "!apps/desktop/prod-resources/wsl-runtime.tar.gz.sha256",] as const;// Windows terminal helpers cannot run on macOS and slow signing and notarization.export const MAC_FILE_EXCLUSIONS = [@@ -806,8 +817,8 @@ export const MAC_FILE_EXCLUSIONS = [// then extracts a handful of large archives instead of thousands of small// files, which dominates install (and update) time. The Windows primary runs// the server from inside server.asar via the asar-aware ELECTRON_RUN_AS_NODE-// runtime; the WSL backend cannot read asar archives, so enabling WSL lazily-// extracts the sidecar to a version-keyed directory (see DesktopWslServerTree).+// runtime. WSL normally uses the dedicated compressed Linux runtime below;+// DesktopWslServerTree can still materialize this sidecar as a fallback.export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar";// dlopen/spawn need real files, so native modules, shared libraries, and// helper executables live in the server.asar.unpacked sibling (the standard@@ -852,6 +863,53 @@ export const WINDOWS_SERVER_EXTRA_RESOURCES = [filter: [WINDOWS_SERVER_ASAR_RESOURCE, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked/**/*`],},] as const;+export const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";+export const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;+export const WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE = {+ from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_NAME}`,+ to: WSL_RUNTIME_ARCHIVE_NAME,+} as const;+export const WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE = {+ from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_HASH_NAME}`,+ to: WSL_RUNTIME_ARCHIVE_HASH_NAME,+} as const;+export const WSL_RUNTIME_ARCHIVE_CONTENT_ROOTS = ["apps/server/dist", "node_modules"] as const;++// The WSL runtime uses only the Linux half of the shared Windows/WSL sidecar.+// Keep build/install metadata and target-native packages that cannot run in+// WSL out of the compressed archive.+export const WSL_RUNTIME_ARCHIVE_EXCLUDED_PREFIXES = [+ "node_modules/@anthropic-ai/claude-agent-sdk-",+ "node_modules/.bin",+ "node_modules/.pnpm",+ "node_modules/.modules.yaml",+ "node_modules/.pnpm-workspace-state-v1.json",+ "node_modules/node-pty/prebuilds/darwin-",+ "node_modules/node-pty/prebuilds/win32-",+ "node_modules/node-pty/build",+ "node_modules/node-pty/third_party/conpty",+ "node_modules/@ff-labs/fff-bin-win32-",+ "node_modules/@yuuang/ffi-rs-win32-",+ "node_modules/@msgpackr-extract/msgpackr-extract-win32-",+] as const;+// WSL runs the same CPU arch as the Windows host; universal is mac-only.+export const resolveWslPrebuildArch = (arch: typeof BuildArch.Type): "x64" | "arm64" | undefined =>+ arch === "x64" ? "x64" : arch === "arm64" ? "arm64" : undefined;++// A packaged WSL runtime is only usable when a Linux pty.node is bundled with+// it, so this one predicate decides both whether the archive is built and+// whether the packaging config ships it. Without it the build would produce an+// archive that can never pass the install script's payload check, and every+// launch would extract a few hundred MB from /mnt/c only to throw it away.+export const bundlesWslRuntime = (input: {+ readonly arch: typeof BuildArch.Type;+ readonly prebuildPath: string | undefined;+}): boolean => input.prebuildPath !== undefined && resolveWslPrebuildArch(input.arch) !== undefined;++export const WSL_RUNTIME_EXTRA_RESOURCES = [+ WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,+ WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE,+] as const;export const DESKTOP_EXTRA_RESOURCES = [{from: "apps/desktop/prod-resources/resource-monitor",@@ -2077,6 +2135,10 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (readonly provisioningProfilePath: string;}| undefined,+ // Windows only, and false when no Linux node-pty prebuild was bundled: the+ // sidecar staging skips the archive in that case, and listing a resource+ // whose source file was never written fails the electron-builder step.+ wslRuntimeBundled = false,) {const buildConfig: Record<string, unknown> = {appId: DESKTOP_APP_ID,@@ -2094,6 +2156,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (extraResources: [...DESKTOP_EXTRA_RESOURCES,...(platform === "win" ? WINDOWS_SERVER_EXTRA_RESOURCES : []),+ ...(platform === "win" && wslRuntimeBundled ? WSL_RUNTIME_EXTRA_RESOURCES : []),],};const updateChannel = resolveDesktopUpdateChannel(version);@@ -2247,8 +2310,7 @@ const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* (return;}- // WSL runs the same CPU arch as the Windows host; universal is mac-only.- const linuxArch = input.arch === "x64" ? "x64" : input.arch === "arm64" ? "arm64" : undefined;+ const linuxArch = resolveWslPrebuildArch(input.arch);if (linuxArch === undefined) {yield* Effect.logWarning(`[desktop-artifact] No WSL node-pty prebuild mapping for arch "${input.arch}"; skipping WSL backend bundling.`,@@ -2294,6 +2356,56 @@ const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* ();});+// tar reads an `-f` target containing a colon as `host:path` and tries to reach+// it over rsh, so handing it a Windows drive path (C:\...\wsl-runtime.tar.gz)+// makes Git for Windows' GNU tar fail with "Cannot connect to C: resolve+// failed". The staged source tree and the archive both live under the build's+// stage root, so the target is always expressible relative to tar's cwd.+export const wslRuntimeArchiveTarTarget = (relativeArchivePath: string): string =>+ relativeArchivePath.replaceAll("\\", "/");++// `archivePath` is relative to the cwd tar runs in; see wslRuntimeArchiveTarTarget.+export const buildWslRuntimeArchiveArgs = (+ archivePath: string = WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from,+): ReadonlyArray<string> => [+ "-czf",+ archivePath,+ ...WSL_RUNTIME_ARCHIVE_EXCLUDED_PREFIXES.map((prefix) => `--exclude=${prefix}*`),+ ...WSL_RUNTIME_ARCHIVE_CONTENT_ROOTS,+];++export const parseWslRuntimeArchiveMembers = (listing: string): ReadonlyArray<string> =>+ listing+ .split(/\r?\n/)+ .map((member) => member.replace(/^\.\//, "").replace(/\/$/, ""))+ .filter((member) => member.length > 0);++export const stageWslRuntimeArchive = Effect.fn("stageWslRuntimeArchive")(function* (input: {+ readonly sourceDir: string;+ readonly archivePath: string;+ readonly hashPath: string;+}) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.makeDirectory(path.dirname(input.archivePath), { recursive: true });+ const tarTarget = wslRuntimeArchiveTarTarget(path.relative(input.sourceDir, input.archivePath));+ yield* runCommand(+ ChildProcess.make("tar", buildWslRuntimeArchiveArgs(tarTarget), {+ cwd: input.sourceDir,+ }),+ { label: "tar WSL runtime", verbose: false },+ );+ const hash = NodeCrypto.createHash("sha256");+ yield* fs+ .stream(input.archivePath)+ .pipe(Stream.runForEach((chunk) => Effect.sync(() => hash.update(chunk))));+ const digest = hash.digest("hex");+ yield* fs.writeFileString(input.hashPath, `${digest}\n`);+ yield* Effect.log(+ `[desktop-artifact] Staged compressed WSL runtime at ${input.archivePath} (${digest}).`,+ );+});+// Stage and pack the Windows server sidecar: the bundled server plus a hoisted// install of only its runtime-external/native dependency closure for win32 and// WSL Linux. The Windows primary runs from the archive through the asar-aware@@ -2337,6 +2449,8 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(readonly overrides: Record<string, string>;readonly wslPrebuildPath: string | undefined;readonly asarPath: string;+ readonly wslRuntimeArchivePath: string;+ readonly wslRuntimeArchiveHashPath: string;readonly verbose: boolean;}) {const fs = yield* FileSystem.FileSystem;@@ -2402,6 +2516,16 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(arch: input.arch,prebuildPath: input.wslPrebuildPath,});+ // Skip the archive entirely rather than shipping one the install script must+ // extract and reject on every launch. The desktop app treats a missing+ // archive as "no WSL-local runtime" and goes straight to the mounted tree.+ if (bundlesWslRuntime({ arch: input.arch, prebuildPath: input.wslPrebuildPath })) {+ yield* stageWslRuntimeArchive({+ sourceDir: serverStageDir,+ archivePath: input.wslRuntimeArchivePath,+ hashPath: input.wslRuntimeArchiveHashPath,+ });+ }yield* Effect.log("[desktop-artifact] Packing server.asar...");yield* fs.makeDirectory(path.dirname(input.asarPath), { recursive: true });@@ -2546,6 +2670,7 @@ export const validateWindowsPackagedPayload = Effect.fn(readonly stageDistDir: string;readonly appExecutableName: string;readonly targetArch: typeof BuildArch.Type;+ readonly expectWslRuntime?: boolean;readonly fileLimit?: number;readonly verbose?: boolean;}) {@@ -2645,6 +2770,99 @@ export const validateWindowsPackagedPayload = Effect.fn(});}+ const wslArchivePath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_NAME);+ const wslArchiveHashPath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_HASH_NAME);+ const [hasWslArchive, hasWslArchiveHash] = yield* Effect.all([+ isFile(wslArchivePath),+ isFile(wslArchiveHashPath),+ ]);+ if (input.expectWslRuntime === true && (!hasWslArchive || !hasWslArchiveHash)) {+ return yield* new WindowsPackagedPayloadValidationError({+ reason: "wsl-runtime-missing",+ packagedAppDir,+ missingFiles: [+ ...(hasWslArchive ? [] : [WSL_RUNTIME_ARCHIVE_NAME]),+ ...(hasWslArchiveHash ? [] : [WSL_RUNTIME_ARCHIVE_HASH_NAME]),+ ],+ });+ }+ if (hasWslArchive !== hasWslArchiveHash) {+ return yield* new WindowsPackagedPayloadValidationError({+ reason: "wsl-runtime-missing",+ packagedAppDir,+ missingFiles: [hasWslArchive ? WSL_RUNTIME_ARCHIVE_HASH_NAME : WSL_RUNTIME_ARCHIVE_NAME],+ });+ }+ if (hasWslArchive && hasWslArchiveHash) {+ const invalidWslRuntime = (cause: unknown) =>+ new WindowsPackagedPayloadValidationError({+ reason: "wsl-runtime-invalid",+ packagedAppDir,+ cause,+ });+ const recordedHash = yield* fs+ .readFileString(wslArchiveHashPath)+ .pipe(Effect.mapError(invalidWslRuntime));+ const expectedHash = recordedHash.trim().toLowerCase();+ if (!/^[0-9a-f]{64}$/.test(expectedHash)) {+ return yield* invalidWslRuntime(new Error("invalid WSL runtime SHA-256 sidecar"));+ }+ const archiveHash = NodeCrypto.createHash("sha256");+ yield* fs.stream(wslArchivePath).pipe(+ Stream.runForEach((chunk) => Effect.sync(() => archiveHash.update(chunk))),+ Effect.mapError(invalidWslRuntime),+ );+ const actualHash = archiveHash.digest("hex");+ if (actualHash !== expectedHash) {+ return yield* invalidWslRuntime(+ new Error(`WSL runtime SHA-256 mismatch: expected ${expectedHash}, got ${actualHash}`),+ );+ }++ const listing = yield* spawnAndCollectOutput(+ ChildProcess.make("tar", ["-tzf", WSL_RUNTIME_ARCHIVE_NAME], {+ cwd: resourcesDir,+ stdin: "ignore",+ stdout: "pipe",+ stderr: "pipe",+ }),+ ).pipe(Effect.mapError(invalidWslRuntime));+ if (listing.exitCode !== 0) {+ return yield* invalidWslRuntime(+ new Error(`tar could not list WSL runtime archive: ${listing.stderr.trim()}`),+ );+ }+ const members = parseWslRuntimeArchiveMembers(listing.stdout);+ const forbiddenMember = members.find((member) =>+ WSL_RUNTIME_ARCHIVE_EXCLUDED_PREFIXES.some((prefix) => member.startsWith(prefix)),+ );+ if (forbiddenMember !== undefined) {+ return yield* invalidWslRuntime(+ new Error(`WSL runtime archive contains forbidden member ${forbiddenMember}`),+ );+ }+ const wslArch = resolveWslPrebuildArch(input.targetArch);+ const requiredMembers = [+ "apps/server/dist/bin.mjs",+ "node_modules/node-pty/package.json",+ ...(wslArch === undefined+ ? []+ : [+ `node_modules/node-pty/prebuilds/linux-${wslArch}/pty.node`,+ `node_modules/node-pty/prebuilds/linux-${wslArch}/t3code-wsl-node-pty.json`,+ ]),+ ];+ const missingMembers = requiredMembers.filter((member) => !members.includes(member));+ if (missingMembers.length > 0) {+ return yield* new WindowsPackagedPayloadValidationError({+ reason: "wsl-runtime-invalid",+ packagedAppDir,+ missingFiles: missingMembers,+ cause: new Error("WSL runtime archive is incomplete"),+ });+ }+ }+const fileCount = yield* countPayloadFiles(packagedAppDir);if (fileCount > fileLimit) {return yield* new WindowsPackagedPayloadValidationError({@@ -2979,6 +3197,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (provisioningProfilePath: macPasskeySigning.provisioningProfilePath,}: undefined,+ bundlesWslRuntime({ arch: options.arch, prebuildPath: options.wslPrebuild }),),dependencies: stageDependencies,devDependencies: {@@ -3033,6 +3252,12 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (overrides: resolvedOverrides,wslPrebuildPath: options.wslPrebuild,asarPath: windowsServerAsarPath,+ wslRuntimeArchivePath: path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from),+ wslRuntimeArchiveHashPath: path.join(+ stageAppDir,+ WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from,+ ),+verbose: options.verbose,});}@@ -3131,6 +3356,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (stageDistDir,appExecutableName: `${resolveDesktopProductName(appVersion)}.exe`,targetArch: options.arch,+ expectWslRuntime: bundlesWslRuntime({+ arch: options.arch,+ prebuildPath: options.wslPrebuild,+ }),verbose: options.verbose,});}