feat(desktop): run the WSL backend from the Linux CLI archive (#11511)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-09-13 21:24:22 -07:00
1 parent af6c138a0d
commit 07549200dc
8 files changed
+731 -850

No files matched your search

+223 -331
View File
@@ -17,7 +17,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
BundleNotSelfContainedError,
BuildCommandFailedError,
buildWslRuntimeArchiveArgs,
parseWslRuntimeArchiveMembers,
DesktopDmgBackgroundSourceMissingError,
createStageWorkspaceConfig,
@@ -88,32 +87,48 @@ import {
WSL_RUNTIME_ARCHIVE_HASH_NAME,
WSL_RUNTIME_ARCHIVE_NAME,
WSL_RUNTIME_EXTRA_RESOURCES,
wslRuntimeArchiveTarTarget,
WslRuntimeArchiveMissingError,
wslRuntimeArchiveStem,
} from "./build-desktop-artifact.ts";
import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
// A minimal stand-in for the staged sidecar roots packed into the WSL archive.
const stageWslRuntimeTreeFixture = Effect.fn("stageWslRuntimeTreeFixture")(function* (
root: string,
serverSource: string,
) {
// A minimal stand-in for the Linux CLI release archive: one top-level
// directory named after the archive stem holding the executable, the web
// client, and the runtime externals with node-pty built from source.
const makeLinuxCliArchiveFixture = Effect.fn("test.makeLinuxCliArchiveFixture")(function* (input: {
readonly root: string;
readonly stem: string;
readonly extraMembers?: ReadonlyArray<string>;
readonly omitMembers?: ReadonlyArray<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",
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const contentRoot = path.join(input.root, "content");
const members = [
`${input.stem}/t3`,
`${input.stem}/client/index.html`,
`${input.stem}/node_modules/node-pty/package.json`,
`${input.stem}/node_modules/node-pty/build/Release/pty.node`,
...(input.extraMembers ?? []),
].filter((member) => !(input.omitMembers ?? []).includes(member));
for (const member of members) {
const memberPath = path.join(contentRoot, member);
yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true });
yield* fs.writeFileString(memberPath, member);
}
const archivePath = path.join(input.root, `${input.stem}.tar.gz`);
const tar = yield* spawner.spawn(
ChildProcess.make("tar", ["-czf", archivePath, "-C", contentRoot, "."], {
stdin: "ignore",
stdout: "ignore",
stderr: "pipe",
}),
);
assert.equal(Number(yield* tar.exitCode), 0);
return archivePath;
});
function mockProcess(exitCode: number, stdout = "") {
@@ -154,10 +169,12 @@ function iconResizeSpawnerLayer(
);
}
const WINDOWS_PAYLOAD_FIXTURE_VERSION = "1.2.3";
const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(function* (input: {
readonly copyUnpackedNatives: boolean;
readonly serverEntrySource?: string;
readonly wslRuntime?: "valid" | "forbidden" | "bad-digest";
readonly wslRuntime?: "valid" | "loose-server-tree" | "missing-pty" | "bad-digest";
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -195,58 +212,30 @@ const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(fu
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 stem = wslRuntimeArchiveStem(WINDOWS_PAYLOAD_FIXTURE_VERSION, "x64");
const sourceArchivePath =
input.wslRuntime === "loose-server-tree"
? // The old hand-rolled runtime: apps/server/dist + node_modules at the
// archive root, no single stem directory, no `t3` executable.
yield* makeLinuxCliArchiveFixture({
root: path.join(tempDir, "wsl-runtime"),
stem: "apps",
omitMembers: ["apps/t3", "apps/client/index.html"],
extraMembers: ["apps/server/dist/bin.mjs", "node_modules/node-pty/package.json"],
})
: yield* makeLinuxCliArchiveFixture({
root: path.join(tempDir, "wsl-runtime"),
stem,
...(input.wslRuntime === "missing-pty"
? { omitMembers: [`${stem}/node_modules/node-pty/build/Release/pty.node`] }
: {}),
});
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`,
);
yield* stageWslRuntimeArchive({ sourceArchivePath, archivePath, hashPath });
if (input.wslRuntime === "bad-digest") {
yield* fs.writeFileString(hashPath, `${"0".repeat(64)}\n`);
}
}
return {
@@ -463,40 +452,20 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
libc: ["glibc"],
},
});
// The Windows app stage only serves the desktop main process; the server
// sidecar stage is the one that needs Linux natives (below).
// Windows stages only win32 natives; WSL runs the separately built Linux
// CLI archive rather than anything installed here.
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "x64" }), {
supportedArchitectures: {
os: ["win32"],
cpu: ["x64"],
},
});
// The server sidecar stage bundles the same-architecture WSL (Linux,
// glibc) backend, so its install must fetch Linux native optional deps
// (e.g. ffi-rs) too — and must be hoisted so the tree survives asar
// packing and runtime extraction without symlinks.
assert.deepStrictEqual(
createStageWorkspaceConfig({ platform: "win", arch: "x64", linuxServerBackend: true }),
{
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["x64"],
libc: ["glibc"],
},
nodeLinker: "hoisted",
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "arm64" }), {
supportedArchitectures: {
os: ["win32"],
cpu: ["arm64"],
},
);
assert.deepStrictEqual(
createStageWorkspaceConfig({ platform: "win", arch: "arm64", linuxServerBackend: true }),
{
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["arm64"],
libc: ["glibc"],
},
nodeLinker: "hoisted",
},
);
});
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
supportedArchitectures: {
os: ["darwin"],
@@ -635,7 +604,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
undefined,
true,
);
const winWithoutWslPrebuild = yield* createBuildConfig(
const winWithoutWslRuntime = yield* createBuildConfig(
"win",
"nsis",
"1.2.3",
@@ -654,8 +623,8 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.notProperty(linux, "asarUnpack");
assert.deepStrictEqual(win.asar, { smartUnpack: false });
assert.deepStrictEqual(win.asarUnpack, [WINDOWS_NATIVE_ASAR_UNPACK_GLOB]);
assert.deepStrictEqual(winWithoutWslPrebuild.asar, win.asar);
assert.deepStrictEqual(winWithoutWslPrebuild.asarUnpack, win.asarUnpack);
assert.deepStrictEqual(winWithoutWslRuntime.asar, win.asar);
assert.deepStrictEqual(winWithoutWslRuntime.asarUnpack, win.asarUnpack);
assert.deepStrictEqual(mac.extraResources, DESKTOP_EXTRA_RESOURCES);
assert.deepStrictEqual(linux.extraResources, [
...DESKTOP_EXTRA_RESOURCES,
@@ -670,9 +639,9 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
...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, [
// No Linux CLI archive means staging never writes the runtime, so
// listing it here would fail the build on a missing source file.
assert.deepStrictEqual(winWithoutWslRuntime.extraResources, [
{
from: "apps/desktop/prod-resources/resource-monitor",
to: "resource-monitor",
@@ -707,7 +676,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.deepStrictEqual(mac.files, [...DESKTOP_FILE_EXCLUSIONS, ...MAC_FILE_EXCLUSIONS]);
assert.deepStrictEqual(linux.files, [...DESKTOP_FILE_EXCLUSIONS, ...LINUX_FILE_EXCLUSIONS]);
assert.deepStrictEqual(win.files, DESKTOP_FILE_EXCLUSIONS);
assert.deepStrictEqual(winWithoutWslPrebuild.files, win.files);
assert.deepStrictEqual(winWithoutWslRuntime.files, win.files);
assert.notProperty(mac.mac as Record<string, unknown>, "sign");
for (const config of [linux, win]) {
assert.deepStrictEqual(config.electronLanguages, DESKTOP_ELECTRON_LANGUAGES);
@@ -819,60 +788,50 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
]);
});
it.effect(
"keeps target and WSL native files while excluding the other Windows architecture",
() =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({
prefix: "t3-windows-architecture-test-",
});
const sourceDir = path.join(tempDir, "server");
const nativeFiles = [
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
"node_modules/node-pty/prebuilds/win32-arm64/conpty/OpenConsole.exe",
"node_modules/node-pty/prebuilds/linux-x64/pty.node",
"node_modules/node-pty/third_party/conpty/1.0.0/win10-x64/OpenConsole.exe",
"node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64/OpenConsole.exe",
];
it.effect("keeps target native files while excluding the other Windows architecture", () =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({
prefix: "t3-windows-architecture-test-",
});
const sourceDir = path.join(tempDir, "server");
const nativeFiles = [
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
"node_modules/node-pty/prebuilds/win32-arm64/conpty/OpenConsole.exe",
"node_modules/node-pty/third_party/conpty/1.0.0/win10-x64/OpenConsole.exe",
"node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64/OpenConsole.exe",
];
for (const nativeFile of nativeFiles) {
const nativePath = path.join(sourceDir, nativeFile);
yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
yield* fs.writeFileString(nativePath, "native");
}
for (const nativeFile of nativeFiles) {
const nativePath = path.join(sourceDir, nativeFile);
yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
yield* fs.writeFileString(nativePath, "native");
}
const asarPath = path.join(tempDir, "server.asar");
yield* packWindowsServerAsar({ sourceDir, asarPath, arch: "x64" });
const unpackedRoot = `${asarPath}.unpacked`;
const asarPath = path.join(tempDir, "server.asar");
yield* packWindowsServerAsar({ sourceDir, asarPath, arch: "x64" });
const unpackedRoot = `${asarPath}.unpacked`;
assert.isTrue(
yield* fs.exists(
path.join(
unpackedRoot,
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
),
assert.isTrue(
yield* fs.exists(
path.join(
unpackedRoot,
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
),
);
assert.isTrue(
yield* fs.exists(
path.join(unpackedRoot, "node_modules/node-pty/prebuilds/linux-x64/pty.node"),
),
);
assert.isFalse(
yield* fs.exists(
path.join(unpackedRoot, "node_modules/node-pty/prebuilds/win32-arm64"),
),
);
assert.isFalse(
yield* fs.exists(
path.join(unpackedRoot, "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64"),
),
);
}),
),
),
);
assert.isFalse(
yield* fs.exists(path.join(unpackedRoot, "node_modules/node-pty/prebuilds/win32-arm64")),
);
assert.isFalse(
yield* fs.exists(
path.join(unpackedRoot, "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64"),
),
);
}),
),
);
it.effect("stages a cached resource monitor without invoking Cargo", () =>
@@ -1205,6 +1164,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
});
const secondAsarPath = path.join(path.dirname(fixture.generatedAsarPath), "second.asar");
@@ -1226,7 +1186,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
).pipe(Effect.provideService(HostProcessPlatform, "linux")),
);
it.effect("validates the emitted WSL archive and its SHA-256 sidecar", () =>
it.effect("accepts an embedded Linux CLI release archive with a matching digest", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeWindowsPayloadFixture({
@@ -1237,6 +1197,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
expectWslRuntime: true,
});
@@ -1245,6 +1206,27 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
).pipe(Effect.provideService(HostProcessPlatform, "linux")),
);
it.effect("rejects an embedded archive built for a different release version", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeWindowsPayloadFixture({
copyUnpackedNatives: true,
wslRuntime: "valid",
});
const error = yield* validateWindowsPackagedPayload({
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: "9.9.9",
expectWslRuntime: true,
}).pipe(Effect.flip);
assert.instanceOf(error, WindowsPackagedPayloadValidationError);
assert.equal(error.reason, "wsl-runtime-invalid");
}),
),
);
it.effect("rejects a Windows package missing its expected WSL runtime", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -1253,6 +1235,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
expectWslRuntime: true,
}).pipe(Effect.flip);
@@ -1262,17 +1245,18 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
),
);
it.effect("rejects forbidden native members in the emitted WSL archive", () =>
it.effect("rejects a loose server tree that is not a Linux CLI release archive", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeWindowsPayloadFixture({
copyUnpackedNatives: true,
wslRuntime: "forbidden",
wslRuntime: "loose-server-tree",
});
const error = yield* validateWindowsPackagedPayload({
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
expectWslRuntime: true,
}).pipe(Effect.flip);
@@ -1282,6 +1266,30 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
),
);
it.effect("rejects an embedded archive without the Linux node-pty binary", () =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeWindowsPayloadFixture({
copyUnpackedNatives: true,
wslRuntime: "missing-pty",
});
const error = yield* validateWindowsPackagedPayload({
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
expectWslRuntime: true,
}).pipe(Effect.flip);
assert.instanceOf(error, WindowsPackagedPayloadValidationError);
assert.equal(error.reason, "wsl-runtime-invalid");
assert.deepStrictEqual(error.missingFiles, [
`${wslRuntimeArchiveStem(WINDOWS_PAYLOAD_FIXTURE_VERSION, "x64")}/node_modules/node-pty/build/Release/pty.node`,
]);
}),
),
);
it.effect("rejects an emitted WSL archive whose sidecar digest does not match", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -1293,6 +1301,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
expectWslRuntime: true,
}).pipe(Effect.flip);
@@ -1327,6 +1336,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
});
const primaryProbe = commands.find(
@@ -1466,6 +1476,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "arm64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
});
assert.isFalse(
@@ -1502,6 +1513,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "arm64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
}).pipe(Effect.flip);
assert.instanceOf(error, WindowsPrimaryNativeProbeError);
@@ -1525,6 +1537,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
}).pipe(Effect.flip);
assert.instanceOf(error, WindowsPackagedPayloadValidationError);
@@ -1553,6 +1566,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
}).pipe(Effect.flip);
assert.instanceOf(nativeError, WindowsPackagedPayloadValidationError);
assert.equal(nativeError.reason, "unpacked-native-missing");
@@ -1573,6 +1587,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
}).pipe(Effect.flip);
assert.instanceOf(resourceMonitorError, WindowsPackagedPayloadValidationError);
assert.equal(resourceMonitorError.reason, "resource-monitor-missing");
@@ -1591,6 +1606,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
fileLimit: 2,
}).pipe(Effect.flip);
@@ -1612,6 +1628,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
stageDistDir: fixture.stageDistDir,
appExecutableName: fixture.appExecutableName,
targetArch: "x64",
appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
}).pipe(Effect.flip);
assert.instanceOf(error, BundleNotSelfContainedError);
@@ -1923,7 +1940,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.equal(resourceMonitorExecutableName("win"), "t3-resource-monitor.exe");
});
it("packages the WSL server and production dependencies as one compressed runtime", () => {
it("ships the Linux CLI release archive as the WSL 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, {
@@ -1934,190 +1951,65 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
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",
]);
// Both the staging and the packaging config hang off this one decision:
// Windows only, and only when CI handed the build a Linux CLI archive.
const runtimeArchivePath = "/tmp/t3-1.2.3-linux-x64.tar.gz";
assert.isTrue(bundlesWslRuntime({ platform: "win", runtimeArchivePath }));
assert.isFalse(bundlesWslRuntime({ platform: "win", runtimeArchivePath: undefined }));
assert.isFalse(bundlesWslRuntime({ platform: "linux", runtimeArchivePath }));
assert.isFalse(bundlesWslRuntime({ platform: "mac", runtimeArchivePath }));
assert.equal(wslRuntimeArchiveStem("1.2.3", "x64"), "t3-1.2.3-linux-x64");
});
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"],
parseWslRuntimeArchiveMembers("./t3-1.2.3-linux-x64/t3\r\nt3-1.2.3-linux-x64/client/\r\n"),
["t3-1.2.3-linux-x64/t3", "t3-1.2.3-linux-x64/client"],
);
});
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", () =>
it.effect("stages the Linux CLI archive verbatim with its SHA-256 sidecar", () =>
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 root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-wsl-runtime-stage-" });
const sourceArchivePath = yield* makeLinuxCliArchiveFixture({
root,
stem: "t3-1.2.3-linux-x64",
});
const stageAppDir = path.join(root, "app");
const archivePath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from);
const hashPath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from);
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({ sourceArchivePath, archivePath, hashPath });
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);
const [source, staged] = yield* Effect.all([
fs.readFile(sourceArchivePath),
fs.readFile(archivePath),
]);
assert.deepStrictEqual(staged, source);
// The digest both gates installation inside the distro and names the
// extracted runtime's cache directory.
const hash = yield* fs.readFileString(hashPath);
assert.equal(hash, `${NodeCrypto.createHash("sha256").update(source).digest("hex")}\n`);
}),
),
);
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.effect("fails when the Linux CLI archive handed to the build does not exist", () =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-wsl-runtime-missing-" });
const error = yield* stageWslRuntimeArchive({
sourceArchivePath: path.join(root, "t3-1.2.3-linux-x64.tar.gz"),
archivePath: path.join(root, WSL_RUNTIME_ARCHIVE_NAME),
hashPath: path.join(root, WSL_RUNTIME_ARCHIVE_HASH_NAME),
}).pipe(Effect.flip);
assert.instanceOf(error, WslRuntimeArchiveMissingError);
}),
),
);
@@ -2228,7 +2120,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
verbose: Option.none(),
mockUpdates: Option.none(),
mockUpdateServerPort: Option.none(),
wslPrebuild: Option.none(),
wslRuntime: Option.none(),
}).pipe(
Effect.provide(
Layer.mergeAll(
@@ -2268,7 +2160,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
verbose: Option.none(),
mockUpdates: Option.none(),
mockUpdateServerPort: Option.none(),
wslPrebuild: Option.none(),
wslRuntime: Option.none(),
}),
);
@@ -2292,7 +2184,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
verbose: Option.some(false),
mockUpdates: Option.some(false),
mockUpdateServerPort: Option.none(),
wslPrebuild: Option.none(),
wslRuntime: Option.none(),
}).pipe(
Effect.provide(
ConfigProvider.layer(
+116 -254
View File
@@ -89,9 +89,6 @@ const RepoRoot = Effect.service(Path.Path).pipe(
);
const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
const decodeNodePtyManifest = Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.Struct({ version: Schema.String })),
);
const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
@@ -164,7 +161,7 @@ interface BuildCliInput {
readonly verbose: Option.Option<boolean>;
readonly mockUpdates: Option.Option<boolean>;
readonly mockUpdateServerPort: Option.Option<number>;
readonly wslPrebuild: Option.Option<string>;
readonly wslRuntime: Option.Option<string>;
}
function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
@@ -399,7 +396,7 @@ const WINDOWS_DESKTOP_BUILD_PREREQUISITES = [
id: "msvc",
description: "Visual Studio Build Tools with C++, Windows SDK, and Spectre libraries",
},
{ id: "tar", description: "tar for the bundled WSL runtime" },
{ id: "tar", description: "tar to inspect the bundled WSL runtime archive" },
] as const;
export class WindowsDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<WindowsDesktopBuildPrerequisitesMissingError>()(
@@ -670,14 +667,14 @@ export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError<Des
}
}
export class WslNodePtyPrebuildMissingError extends Schema.TaggedError<WslNodePtyPrebuildMissingError>()(
"WslNodePtyPrebuildMissingError",
export class WslRuntimeArchiveMissingError extends Schema.TaggedError<WslRuntimeArchiveMissingError>()(
"WslRuntimeArchiveMissingError",
{
prebuildPath: Schema.String,
archivePath: Schema.String,
},
) {
override get message(): string {
return `WSL node-pty prebuild not found at ${this.prebuildPath}.`;
return `WSL runtime archive not found at ${this.archivePath}.`;
}
}
@@ -754,18 +751,6 @@ export class WindowsPackagedPayloadValidationError extends Schema.TaggedError<Wi
}
}
export class WslNodePtyManifestReadError extends Schema.TaggedError<WslNodePtyManifestReadError>()(
"WslNodePtyManifestReadError",
{
manifestPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not read node-pty version from ${this.manifestPath}.`;
}
}
export class LinuxIconResizeError extends Schema.TaggedError<LinuxIconResizeError>()(
"LinuxIconResizeError",
{
@@ -933,7 +918,7 @@ interface ResolvedBuildOptions {
readonly verbose: boolean;
readonly mockUpdates: boolean;
readonly mockUpdateServerPort: number | undefined;
readonly wslPrebuild: string | undefined;
readonly wslRuntime: string | undefined;
}
interface StagePackageJson {
@@ -1007,8 +992,8 @@ export function resolveMacFileExclusions(arch?: typeof BuildArch.Type) {
// 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. WSL normally uses the dedicated compressed Linux runtime below;
// DesktopWslServerTree can still materialize this sidecar as a fallback.
// runtime. WSL does not use this sidecar: it runs the Linux CLI archive
// embedded as resources/wsl-runtime.tar.gz (see WSL_RUNTIME_ARCHIVE_NAME).
export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar";
// dlopen/spawn need real files, so native modules, shared libraries, and
// helper executables live in each archive's .unpacked sibling (the standard
@@ -1064,38 +1049,16 @@ 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.
// The WSL runtime is the Linux CLI release archive (t3-<version>-linux-<arch>
// .tar.gz, built by scripts/build-cli-archive.ts) copied in verbatim, so WSL
// runs the exact bytes a Linux user downloads. This one predicate decides both
// whether the archive is staged and whether the packaging config ships it:
// listing an extraResource whose source was never written fails electron-builder.
export const bundlesWslRuntime = (input: {
readonly arch: typeof BuildArch.Type;
readonly prebuildPath: string | undefined;
}): boolean => input.prebuildPath !== undefined && resolveWslPrebuildArch(input.arch) !== undefined;
readonly platform: typeof BuildPlatform.Type;
readonly runtimeArchivePath: string | undefined;
}): boolean => input.platform === "win" && input.runtimeArchivePath !== undefined;
export const WSL_RUNTIME_EXTRA_RESOURCES = [
WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,
@@ -1515,15 +1478,8 @@ export function createStageWorkspaceConfig(input: {
readonly allowBuilds?: Record<string, boolean>;
readonly patchedDependencies?: Record<string, string>;
readonly overrides?: Record<string, string>;
// The Windows server sidecar stage runs both the Windows primary and the
// WSL Linux backend from one dependency tree, so it needs win32 + linux
// natives (e.g. @yuuang/ffi-rs-linux-x64-gnu) — and a hoisted (physical,
// symlink-free) node_modules: the tree gets packed into server.asar and
// later extracted for WSL, and neither step can rely on pnpm's
// symlink/junction layout surviving the trip.
readonly linuxServerBackend?: boolean;
}): StageWorkspaceConfig {
const { platform, arch, allowBuilds, patchedDependencies, overrides, linuxServerBackend } = input;
const { platform, arch, allowBuilds, patchedDependencies, overrides } = input;
const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
// Linux AppImages execute a Linux/glibc Node process that loads
@@ -1536,16 +1492,10 @@ export function createStageWorkspaceConfig(input: {
cpu: hostCpu,
libc: ["glibc"],
}
: linuxServerBackend
? {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
}
: {
os: [hostOs],
cpu: hostCpu,
};
: {
os: [hostOs],
cpu: hostCpu,
};
return {
supportedArchitectures,
@@ -1554,7 +1504,6 @@ export function createStageWorkspaceConfig(input: {
? { patchedDependencies }
: {}),
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
...(linuxServerBackend ? { nodeLinker: "hoisted" as const } : {}),
};
}
@@ -1600,11 +1549,10 @@ const BuildEnvConfig = Config.all({
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
mockUpdates: Config.boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)),
mockUpdateServerPort: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option),
// Path to a prebuilt Linux node-pty binary (pty.node) for the target arch,
// produced by the Linux CI job and handed to the Windows packaging job. Placed
// into the staged node-pty so the WSL backend ships a ready binary and never
// compiles on the user's machine.
wslPrebuild: Config.string("T3CODE_DESKTOP_WSL_PREBUILD").pipe(Config.option),
// Path to the Linux CLI release archive (t3-<version>-linux-x64.tar.gz) built
// by the build_linux_cli CI job. The Windows build embeds it verbatim as the
// WSL runtime.
wslRuntime: Config.string("T3CODE_DESKTOP_WSL_RUNTIME").pipe(Config.option),
});
const MockUpdateServerPortSchema = Schema.NumberFromString.check(
@@ -1696,8 +1644,8 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
),
));
const wslPrebuild =
Option.getOrUndefined(input.wslPrebuild) ?? Option.getOrUndefined(env.wslPrebuild);
const wslRuntime =
Option.getOrUndefined(input.wslRuntime) ?? Option.getOrUndefined(env.wslRuntime);
return {
platform,
@@ -1711,7 +1659,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
verbose,
mockUpdates,
mockUpdateServerPort,
wslPrebuild,
wslRuntime,
} satisfies ResolvedBuildOptions;
});
@@ -2683,9 +2631,9 @@ 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.
// Windows only, and false when no Linux CLI archive was handed to the build:
// staging skips the archive in that case, and listing a resource whose
// source file was never written fails the electron-builder step.
wslRuntimeBundled = false,
arch?: typeof BuildArch.Type,
) {
@@ -2850,114 +2798,25 @@ const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(f
}
});
// Stage the prebuilt Linux node-pty binary into the packaged app so the WSL
// backend never compiles on the user's machine. node-pty publishes no Linux
// prebuilt and the WSL Linux Node can't load the Windows/Electron binary, so the
// Linux CI job builds pty.node and hands it here. We drop it into the staged
// node-pty's prebuilds/linux-<arch>/ with a t3code marker the WSL preflight
// checks (arch + node-pty version; the binary is N-API, hence ABI-stable across
// Node versions). A missing prebuild is a warning, not an error, so local and
// non-Windows builds still succeed — they just won't ship a working WSL backend.
const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* (input: {
readonly stageAppDir: string;
readonly arch: typeof BuildArch.Type;
readonly prebuildPath: string | undefined;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (input.prebuildPath === undefined) {
yield* Effect.logWarning(
"[desktop-artifact] No WSL node-pty prebuild provided (--wsl-prebuild / T3CODE_DESKTOP_WSL_PREBUILD); the packaged WSL backend will not start until a Linux pty.node is bundled.",
);
return;
}
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.`,
);
return;
}
const prebuildExists = yield* fs
.exists(input.prebuildPath)
.pipe(Effect.orElseSucceed(() => false));
if (!prebuildExists) {
return yield* new WslNodePtyPrebuildMissingError({
prebuildPath: input.prebuildPath,
});
}
// Resolve through the (pnpm) symlink so we write into the stage's own node-pty
// copy, never a shared content-addressable store.
const nodePtyLink = path.join(input.stageAppDir, "node_modules", "node-pty");
const nodePtyDir = yield* fs.realPath(nodePtyLink).pipe(Effect.orElseSucceed(() => nodePtyLink));
const manifestPath = path.join(nodePtyDir, "package.json");
const pkgRaw = yield* fs.readFileString(manifestPath);
const manifest = yield* decodeNodePtyManifest(pkgRaw).pipe(
Effect.mapError(
(cause) =>
new WslNodePtyManifestReadError({
manifestPath,
cause,
}),
),
);
const nodePtyVersion = manifest.version;
const prebuildDir = path.join(nodePtyDir, "prebuilds", `linux-${linuxArch}`);
yield* fs.makeDirectory(prebuildDir, { recursive: true });
yield* fs.copyFile(input.prebuildPath, path.join(prebuildDir, "pty.node"));
const markerJson = yield* encodeJsonString({ arch: linuxArch, nodePtyVersion });
yield* fs.writeFileString(path.join(prebuildDir, "t3code-wsl-node-pty.json"), `${markerJson}\n`);
yield* Effect.log(
`[desktop-artifact] Staged WSL node-pty prebuild (linux-${linuxArch}, node-pty ${nodePtyVersion}).`,
);
});
// 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);
// Copy the Linux CLI release archive into the stage verbatim and record its
// SHA-256 beside it. The desktop app verifies the digest inside the distro
// before extracting, and the digest also names the extracted runtime's cache
// directory, so it must be computed from the exact bytes that ship.
export const stageWslRuntimeArchive = Effect.fn("stageWslRuntimeArchive")(function* (input: {
readonly sourceDir: string;
readonly sourceArchivePath: string;
readonly archivePath: string;
readonly hashPath: string;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sourceExists = yield* fs
.exists(input.sourceArchivePath)
.pipe(Effect.orElseSucceed(() => false));
if (!sourceExists) {
return yield* new WslRuntimeArchiveMissingError({ archivePath: input.sourceArchivePath });
}
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 },
);
yield* fs.copyFile(input.sourceArchivePath, input.archivePath);
const hash = NodeCrypto.createHash("sha256");
yield* fs
.stream(input.archivePath)
@@ -2965,16 +2824,27 @@ export const stageWslRuntimeArchive = Effect.fn("stageWslRuntimeArchive")(functi
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}).`,
`[desktop-artifact] Staged WSL runtime archive at ${input.archivePath} (${digest}).`,
);
});
// Mirrors cliArchiveStem in scripts/build-cli-archive.ts (which imports from
// this module, so it cannot be imported here). WSL runs the same CPU arch as
// the Windows host.
export const wslRuntimeArchiveStem = (version: string, arch: typeof BuildArch.Type): string =>
`t3-${version}-linux-${arch}`;
export const parseWslRuntimeArchiveMembers = (listing: string): ReadonlyArray<string> =>
listing
.split(/\r?\n/)
.map((member) => member.replace(/^\.\//, "").replace(/\/$/, ""))
.filter((member) => member.length > 0);
// 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
// ELECTRON_RUN_AS_NODE runtime; enabling WSL extracts it to a real directory.
// Shipping one packed archive instead of thousands of loose files is what
// makes the NSIS install/update fast.
// install of only its runtime-external/native dependency closure for win32.
// The Windows primary runs from the archive through the asar-aware
// ELECTRON_RUN_AS_NODE runtime. Shipping one packed archive instead of
// thousands of loose files is what makes the NSIS install/update fast.
export const packWindowsServerAsar = Effect.fn("packWindowsServerAsar")(function* (input: {
readonly sourceDir: string;
readonly asarPath: string;
@@ -3025,10 +2895,7 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(
readonly allowBuilds: Record<string, boolean>;
readonly patchedDependencies: Record<string, string>;
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;
@@ -3040,11 +2907,7 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(
const sidecarDependencies = {
...input.runtimeExternalDependencies,
// The sidecar serves two processes: the Windows primary loads win32
// natives, and the WSL backend loads the matching Linux natives (fff via
// ffi-rs) from the extracted copy of this same tree.
...resolveFffNativeDependencies("win", input.arch, input.fffNodeVersion),
...resolveFffNativeDependencies("linux", input.arch, input.fffNodeVersion),
};
const sidecarPatchedDependencies = createStagePatchedDependencies(
input.patchedDependencies,
@@ -3062,14 +2925,18 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(
path.join(serverStageDir, "package.json"),
`${sidecarPackageJsonString}\n`,
);
const sidecarWorkspaceConfig = createStageWorkspaceConfig({
platform: "win",
arch: input.arch,
allowBuilds: input.allowBuilds,
patchedDependencies: sidecarPatchedDependencies,
overrides: input.overrides,
linuxServerBackend: true,
});
const sidecarWorkspaceConfig = {
...createStageWorkspaceConfig({
platform: "win",
arch: input.arch,
allowBuilds: input.allowBuilds,
patchedDependencies: sidecarPatchedDependencies,
overrides: input.overrides,
}),
// The tree gets packed into server.asar, which cannot carry pnpm's
// symlink/junction layout, so install a physical, hoisted node_modules.
nodeLinker: "hoisted" as const,
};
const sidecarWorkspaceConfigString = yield* encodeStageWorkspaceConfig(sidecarWorkspaceConfig);
yield* fs.writeFileString(
path.join(serverStageDir, "pnpm-workspace.yaml"),
@@ -3089,22 +2956,6 @@ export const stageWindowsServerSidecar = Effect.fn("stageWindowsServerSidecar")(
{ label: "vp install --prod (server sidecar)", verbose: input.verbose },
);
yield* stageWslNodePtyPrebuild({
stageAppDir: serverStageDir,
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 });
yield* packWindowsServerAsar({
@@ -3248,6 +3099,9 @@ export const validateWindowsPackagedPayload = Effect.fn(
readonly stageDistDir: string;
readonly appExecutableName: string;
readonly targetArch: typeof BuildArch.Type;
// The version the embedded Linux CLI archive must carry; its top-level
// directory is named t3-<version>-linux-<arch>.
readonly appVersion: string;
readonly expectWslRuntime?: boolean;
readonly fileLimit?: number;
readonly verbose?: boolean;
@@ -3411,24 +3265,22 @@ export const validateWindowsPackagedPayload = Effect.fn(
);
}
const members = parseWslRuntimeArchiveMembers(listing.stdout);
const forbiddenMember = members.find((member) =>
WSL_RUNTIME_ARCHIVE_EXCLUDED_PREFIXES.some((prefix) => member.startsWith(prefix)),
);
if (forbiddenMember !== undefined) {
// A release archive unpacks to one directory named after its stem; the
// desktop app's WSL install script relies on that layout to find `t3`.
const stem = wslRuntimeArchiveStem(input.appVersion, input.targetArch);
const topLevel = new Set(members.map((member) => member.split("/")[0]));
if (topLevel.size !== 1 || !topLevel.has(stem)) {
return yield* invalidWslRuntime(
new Error(`WSL runtime archive contains forbidden member ${forbiddenMember}`),
new Error(
`WSL runtime archive must contain a single top-level directory ${stem}, found ${[...topLevel].join(", ") || "nothing"}`,
),
);
}
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`,
]),
`${stem}/t3`,
`${stem}/client`,
`${stem}/node_modules`,
`${stem}/node_modules/node-pty/build/Release/pty.node`,
];
const missingMembers = requiredMembers.filter((member) => !members.includes(member));
if (missingMembers.length > 0) {
@@ -3436,9 +3288,16 @@ export const validateWindowsPackagedPayload = Effect.fn(
reason: "wsl-runtime-invalid",
packagedAppDir,
missingFiles: missingMembers,
cause: new Error("WSL runtime archive is incomplete"),
cause: new Error("WSL runtime archive is not a Linux CLI release archive"),
});
}
// The CLI archive runs the single-executable, never a loose server bundle.
const bundleEntry = members.find((member) => member.endsWith("/bin.mjs"));
if (bundleEntry !== undefined) {
return yield* invalidWslRuntime(
new Error(`WSL runtime archive contains a server bundle entry ${bundleEntry}`),
);
}
}
const fileCount = yield* countPayloadFiles(packagedAppDir);
@@ -3487,8 +3346,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
yield* preflightWindowsDesktopBuild({
arch: options.arch,
bundlesWslRuntime: bundlesWslRuntime({
arch: options.arch,
prebuildPath: options.wslPrebuild,
platform: options.platform,
runtimeArchivePath: options.wslRuntime,
}),
});
}
@@ -3807,7 +3666,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
}
: undefined,
bundlesWslRuntime({ arch: options.arch, prebuildPath: options.wslPrebuild }),
bundlesWslRuntime({ platform: options.platform, runtimeArchivePath: options.wslRuntime }),
options.arch,
),
dependencies: stageDependencies,
@@ -3847,9 +3706,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);
yield* stageKeyringNativeBinaries(stageAppDir, options.platform, options.arch);
// WSL is Windows-only, so only the Windows artifact carries the server
// sidecar (which embeds the Linux node-pty prebuild); other platforms
// ignore the prebuild input.
// Only the Windows artifact carries the server sidecar and the WSL runtime;
// other platforms ignore the --wsl-runtime input.
if (options.platform === "win" && windowsServerAsarPath) {
yield* stageWindowsServerSidecar({
stageRoot,
@@ -3862,17 +3720,20 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
allowBuilds: workspaceAllowBuilds,
patchedDependencies: workspacePatchedDependencies,
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,
});
}
if (
options.wslRuntime !== undefined &&
bundlesWslRuntime({ platform: options.platform, runtimeArchivePath: options.wslRuntime })
) {
yield* stageWslRuntimeArchive({
sourceArchivePath: options.wslRuntime,
archivePath: path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from),
hashPath: path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from),
});
}
// electron-builder treats several set-but-empty variables (e.g. CSC_LINK="")
// as enabled, so copy the host env and scrub empty values instead of relying
@@ -3968,9 +3829,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
stageDistDir,
appExecutableName: `${resolveDesktopProductName(appVersion)}.exe`,
targetArch: options.arch,
appVersion,
expectWslRuntime: bundlesWslRuntime({
arch: options.arch,
prebuildPath: options.wslPrebuild,
platform: options.platform,
runtimeArchivePath: options.wslRuntime,
}),
verbose: options.verbose,
});
@@ -4055,9 +3917,9 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
Flag.withDescription("Mock update server port (env: T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT)."),
Flag.optional,
),
wslPrebuild: Flag.string("wsl-prebuild").pipe(
wslRuntime: Flag.string("wsl-runtime").pipe(
Flag.withDescription(
"Path to a prebuilt Linux node-pty (pty.node) for the target arch, staged for the WSL backend (env: T3CODE_DESKTOP_WSL_PREBUILD).",
"Path to the Linux CLI release archive (t3-<version>-linux-x64.tar.gz) to embed as the WSL runtime of a Windows build (env: T3CODE_DESKTOP_WSL_RUNTIME).",
),
Flag.optional,
),