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

+103 -40
View File
@@ -354,21 +354,28 @@ jobs:
# job — the Windows artifact then ships a ready WSL backend binary with no
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
build_wsl_node_pty:
name: Build WSL node-pty (linux-x64)
# The Linux CLI archive is built ahead of the desktop matrix because two
# consumers need it: the Linux desktop entry attaches it to the release, and
# the Windows desktop entry embeds it as the WSL runtime. Building it once
# here means the WSL backend runs the exact bytes a Linux user downloads.
build_linux_cli:
name: Build CLI archive (linux-x64)
# Same gating as relay_public_config: only the release commit is needed, so
# this runs alongside preflight. See the condition comment there.
needs: [resolve_commit]
if: |
needs.resolve_commit.result == 'success' &&
(github.event_name != 'schedule' || needs.resolve_commit.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 15
needs: [resolve_commit, preflight, relay_public_config]
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: blacksmith-32vcpu-ubuntu-2404
timeout-minutes: 20
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.resolve_commit.outputs.ref }}
ref: ${{ needs.preflight.outputs.ref }}
sparse-checkout: |
/*
!/.repos/
@@ -382,38 +389,92 @@ jobs:
run-install: |
args:
- --filter=t3...
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
- name: Build node-pty linux-x64 prebuild
- name: Cache resource monitor
id: resource_monitor_cache
uses: actions/cache@v6
with:
path: native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor
key: resource-monitor-x86_64-unknown-linux-gnu-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }}
- name: Setup Rust
if: steps.resource_monitor_cache.outputs.cache-hit != 'true'
uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-unknown-linux-gnu
- name: Build resource monitor
if: steps.resource_monitor_cache.outputs.cache-hit != 'true'
run: cargo build --locked --release --manifest-path native/resource-monitor/Cargo.toml --target x86_64-unknown-linux-gnu
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
name: relay-client-tracing-config
path: ${{ runner.temp }}/relay-client-tracing
- name: Load relay client tracing config
shell: bash
run: |
set -euo pipefail
# Resolve node-pty from apps/server (where it's a dependency) and build
# its native binary from source for Linux. node-addon-api resolves from
# node-pty's own dependency tree, so node-gyp has everything it needs.
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
pty_dir="$(dirname "$pty_pkg")"
( cd "$pty_dir" && npx --yes node-gyp rebuild )
mkdir -p wsl-prebuild
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
file wsl-prebuild/pty.node
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
echo "::add-mask::$tracing_token"
cat "$config_path" >> "$GITHUB_ENV"
- name: Upload node-pty linux-x64 prebuild
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
# The t3 build task depends on @t3tools/web#build, so the web client is
# built as part of this step.
- name: Build CLI package
run: vp run --filter t3 build
- name: Build CLI single-executable
env:
# The exact version, not a major: vp downloads it from nodejs.org/dist on
# the runner, and only exact versions have a dist directory. Keep in
# step with SEA_NODE_VERSION in apps/server/vite.config.ts.
VP_NODE_VERSION: "26.8.2"
run: node apps/server/scripts/cli.ts build-exe --verbose
- name: Stage resource monitor for the CLI archive
run: |
set -euo pipefail
target_dir="$RUNNER_TEMP/cli-resource-monitor/linux-x64"
mkdir -p "$target_dir"
cp native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor "$target_dir/"
- name: Build CLI archive
run: |
node scripts/build-cli-archive.ts \
--platform linux \
--arch x64 \
--version "${{ needs.preflight.outputs.version }}" \
--resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \
--output-dir release-cli
- name: Smoke-test CLI archive
run: node scripts/smoke-cli-archive.ts --archive release-cli/* --expect-version "${{ needs.preflight.outputs.version }}"
- name: Upload CLI archive
uses: actions/upload-artifact@v7
with:
name: wsl-node-pty-x64
path: wsl-prebuild/pty.node
name: cli-linux-x64
path: release-cli/*
if-no-files-found: error
build:
name: Build ${{ matrix.label }}
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
# available to download, but only the Windows matrix entry consumes it. We
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
# build_wsl_node_pty failed; the Windows-only download step below then fails
# that single platform if the prebuild is missing.
needs: [preflight, relay_public_config, build_wsl_node_pty]
# build_linux_cli stays in `needs` so it runs first and its artifact is
# available to download, but only the Windows matrix entry consumes it (as
# the WSL runtime). The job is gated on preflight + relay WITHOUT requiring
# build_linux_cli, so a failed Linux archive doesn't skip the macOS builds.
# `!cancelled()` (not `!failure()`) lets the job run even when
# build_linux_cli failed; the Windows-only download step below then fails
# that single platform if the archive is missing.
needs: [preflight, relay_public_config, build_linux_cli]
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
@@ -448,6 +509,7 @@ jobs:
rust_target: x86_64-apple-darwin
resource_key: darwin-x64
cli_archive: false
# The Linux CLI archive is produced by build_linux_cli, not here.
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
@@ -455,7 +517,7 @@ jobs:
arch: x64
rust_target: x86_64-unknown-linux-gnu
resource_key: linux-x64
cli_archive: true
cli_archive: false
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
platform: win
@@ -553,12 +615,14 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Download WSL node-pty prebuild
# The WSL backend runs the Linux CLI archive inside the distro, so the
# Windows desktop embeds the same archive the release attaches.
- name: Download Linux CLI archive for WSL
if: matrix.platform == 'win'
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
name: wsl-node-pty-x64
path: wsl-prebuild
name: cli-linux-x64
path: wsl-runtime
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
@@ -720,10 +784,9 @@ jobs:
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
# so the packaged WSL backend ships a ready binary (no first-launch
# compile). Required for a working WSL backend on Windows.
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
# Embed the Linux CLI archive built by build_linux_cli as the WSL
# runtime. Required for a working WSL backend on Windows.
args+=(--wsl-runtime "$GITHUB_WORKSPACE"/wsl-runtime/t3-*-linux-x64.tar.gz)
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
@@ -374,9 +374,10 @@ describe("DesktopBackendConfiguration", () => {
runtimeId: string;
sha256: string;
}> = [];
const observedNodePtyRoots: string[] = [];
const observedProbeRoots: string[] = [];
let legacyCleanupCount = 0;
const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64";
const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin";
return withPackagedWslHarness(
{
@@ -394,9 +395,14 @@ describe("DesktopBackendConfiguration", () => {
});
return { ok: true, linuxAppRoot };
},
ensureNodePty: (_distro, root) => {
observedNodePtyRoots.push(root);
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
probeRuntime: (_distro, root) => {
observedProbeRoots.push(root);
return { ok: true, resolvedPath };
},
// The staged runtime carries its own Node, so the preflight must not
// go looking for one in the distro.
ensureNodePty: () => {
throw new Error("the staged runtime must not probe for Node");
},
}),
},
@@ -413,12 +419,22 @@ describe("DesktopBackendConfiguration", () => {
sha256: archiveHash,
},
]);
assert.deepEqual(observedNodePtyRoots, [linuxAppRoot]);
assert.deepEqual(observedProbeRoots, [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.deepEqual(config.args, [
"-d",
"Ubuntu",
"--exec",
"env",
`PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`,
`${linuxAppRoot}/t3`,
"--bootstrap-fd",
"0",
]);
assert.notInclude(config.args, "/usr/bin/node");
assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`);
assert.equal(legacyCleanupCount, 1);
assert.isTrue(Option.isNone(config.preflightFailure));
@@ -457,8 +473,11 @@ describe("DesktopBackendConfiguration", () => {
assert.deepEqual(observedRuntimeIds, [`sha256-${firstHash}`, `sha256-${secondHash}`]);
assert.equal(first.wslRuntimeId, observedRuntimeIds[0]);
assert.include(first.args, `/runtime/sha256-${firstHash}/t3`);
assert.equal(second.wslRuntimeId, observedRuntimeIds[1]);
assert.include(second.args, `/runtime/sha256-${secondHash}/t3`);
assert.isUndefined(invalidIdentity.wslRuntimeId);
assert.include(invalidIdentity.args, "/usr/bin/node");
assert.include(invalidIdentity.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
}),
);
@@ -484,6 +503,7 @@ describe("DesktopBackendConfiguration", () => {
assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
assert.equal(config.entryPath, mountedEntryPath);
assert.include(config.args, "/usr/bin/node");
assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
assert.isUndefined(config.wslRuntimeId);
assert.isTrue(Option.isNone(config.preflightFailure));
@@ -491,9 +511,10 @@ describe("DesktopBackendConfiguration", () => {
);
});
it.effect("resolveWsl retires a staged runtime that cannot load node-pty", () => {
it.effect("resolveWsl retires a staged runtime whose executable does not start", () => {
const archiveHash = "c".repeat(64);
const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
const observedProbeRoots: string[] = [];
const observedNodePtyRoots: string[] = [];
const invalidatedRuntimeIds: string[] = [];
return withPackagedWslHarness(
@@ -505,11 +526,13 @@ describe("DesktopBackendConfiguration", () => {
Effect.sync(() => {
invalidatedRuntimeIds.push(runtimeId);
}),
probeRuntime: (_distro, root) => {
observedProbeRoots.push(root);
return { ok: false, reason: `${root}/t3 --version failed (exit 127)` };
},
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" };
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
},
}),
},
@@ -518,8 +541,11 @@ describe("DesktopBackendConfiguration", () => {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
assert.deepEqual(observedNodePtyRoots, [stagedAppRoot, mountedAppRoot]);
assert.deepEqual(observedProbeRoots, [stagedAppRoot]);
assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
assert.include(config.args, "/usr/bin/node");
assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
assert.notInclude(config.args, `${stagedAppRoot}/t3`);
assert.equal(config.entryPath, mountedEntryPath);
assert.isUndefined(config.wslRuntimeId);
assert.isTrue(Option.isNone(config.preflightFailure));
@@ -540,12 +566,13 @@ describe("DesktopBackendConfiguration", () => {
Effect.sync(() => {
invalidatedRuntimeIds.push(runtimeId);
}),
ensureNodePty: (_distro, root) => ({
probeRuntime: () => ({
ok: false,
reason:
root === stagedAppRoot
? "unsupported CPU architecture or incompatible system libraries"
: "mounted tree is broken in some other way",
reason: "unsupported CPU architecture or incompatible system libraries",
}),
ensureNodePty: () => ({
ok: false,
reason: "mounted tree is broken in some other way",
fatal: true,
}),
}),
@@ -575,51 +602,11 @@ describe("DesktopBackendConfiguration", () => {
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);
}),
probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }),
ensureNodePty: () => ({
ok: false,
reason: "WSL backend preflight timed out while probing for Node.js.",
fatal: false,
retryLimit: 12,
}),
}),
},
@@ -95,6 +95,11 @@ const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const nodeBinDirOf = (nodePath: string): string => {
const lastSlash = nodePath.lastIndexOf("/");
return lastSlash > 0 ? nodePath.slice(0, lastSlash) : "/usr/bin";
};
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
@@ -210,18 +215,31 @@ interface SharedBootstrapInput {
readonly observabilitySettings: BackendObservabilitySettings;
}
// What the launch runs inside the distro. The staged runtime is the release's
// self-contained `t3` executable (Node inside); the mounted server tree is a
// script that needs the distro's own Node.
type WslPreflightRuntime =
| {
readonly kind: "executable";
readonly entryPath: string;
}
| {
readonly kind: "node-script";
// 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 doesn't fall through to a different/old node than the one
// node-pty was probed with.
readonly nodePath: string;
readonly linuxEntryPath: string;
};
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
// doesn't fall through to a different/old node than the one node-pty was
// built against.
readonly nodePath: string;
// PATH captured from the same login shell after the shared resolver loaded
// version managers. The launch forwards this value directly without a shell.
readonly runtime: WslPreflightRuntime;
// PATH captured from the user's login shell. The launch forwards this value
// directly without a shell so the server can spawn provider CLIs by name.
readonly resolvedPath: string;
// Identifies the distro-local runtime cache selected from the packaged archive.
readonly runtimeId?: string;
@@ -355,39 +373,36 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
// 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;
let stagedFailure: { readonly runtimeId: string; readonly reason: string } | undefined;
const failedStaged = (failure: { readonly reason: string }) =>
({
_tag: "Failed",
reason: `WSL runtime unavailable: ${failure.reason}`,
fatal: true,
}) as const;
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) {
// The staged runtime is self-contained, so the only question is whether
// it runs here; there is no Node to find or node-pty to load.
const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
if (stagedProbe.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,
runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
resolvedPath: stagedProbe.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 },
"The staged WSL runtime did not start; retrying from the mounted server tree.",
{ reason: stagedProbe.reason },
);
stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, nodePty: stagedNodePty };
stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
} else {
yield* Effect.logWarning(
"Could not stage the WSL runtime; launching from the mounted server tree instead.",
@@ -399,7 +414,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
const mounted = yield* resolveMountedAppRoot;
if (!mounted.ok) {
return stagedFailure && mounted.fatal
? failedNodePty(stagedFailure.nodePty)
? failedStaged(stagedFailure)
: ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
}
@@ -413,9 +428,9 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
// 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,
);
return stagedFailure && nodePtyResult.fatal
? failedStaged(stagedFailure)
: failedNodePty(nodePtyResult);
}
// The mounted tree runs what the cache could not, so the cache is the broken
@@ -429,8 +444,11 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f
_tag: "Ready",
runningDistro,
windowsEntryPath: mounted.windowsEntryPath,
linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
nodePath: nodePtyResult.nodePath,
runtime: {
kind: "node-script",
nodePath: nodePtyResult.nodePath,
linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
},
resolvedPath: nodePtyResult.resolvedPath,
} as const;
});
@@ -610,13 +628,13 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
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.
// Packaged builds run the self-contained Linux runtime and, on fallback,
// whatever Linux node-pty the mounted tree carries, 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 Linux binary, and
// developers have the toolchain. In packaged builds we instead surface a
// clear diagnostic if the binary can't load (unsupported arch/distro),
// rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
});
@@ -709,15 +727,23 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
// live on the user's login-shell PATH, which `wsl.exe --exec` does NOT put on
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
// user PATH entries captured by the login-shell preflight. Every dynamic
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
// for the bootstrap envelope.
const lastSlash = preflight.nodePath.lastIndexOf("/");
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
// user PATH entries captured by the preflight. Every dynamic value is a
// separate argv entry under `wsl.exe --exec`; no shell command is involved,
// so Windows cannot mangle nested quotes and stdin remains reserved for the
// bootstrap envelope. A node-script runtime additionally leads with the
// probed Node's bin dir so the server cannot pick up a different node than
// the one node-pty was probed with.
const runtime = preflight.runtime;
const launchPath =
runtime.kind === "executable"
? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
: `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
const command =
runtime.kind === "executable"
? [runtime.entryPath]
: [runtime.nodePath, runtime.linuxEntryPath];
return {
...baseConfig,
@@ -726,8 +752,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
"--exec",
"env",
`PATH=${launchPath}`,
preflight.nodePath,
preflight.linuxEntryPath,
...command,
"--bootstrap-fd",
"0",
...devUrlArgs,
@@ -74,7 +74,9 @@ const readField = (stdout: string, field: string) => {
return line.slice(field.length + 1).trim();
};
const SERVER_ENTRY_SOURCE = 'console.log("t3code wsl runtime test server");';
// Stands in for the release's self-contained `t3` executable: the install
// script only asks it for `--version`.
const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n';
const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
ChildProcessSpawner.make(() =>
@@ -164,21 +166,22 @@ describe("WSL runtime cache", () => {
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).toContain(' runtime_entry_runs "$runtime_root" &&');
expect(script).toContain("if runtime_is_ready; then");
expect(script).not.toContain("bin.mjs");
expect(script).not.toContain("node-pty");
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('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"');
// The release archive wraps everything in one `t3-<version>-linux-x64/`
// directory; stripping it puts the executable at `$runtime_root/t3`.
expect(script).toContain(
"tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\"",
"tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\" --strip-components=1",
);
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('if ! runtime_entry_runs "$runtime_tmp"; then');
expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"');
expect(script).not.toContain('rm -rf "$runtime_root"');
@@ -248,46 +251,39 @@ describe("WSL runtime cache", () => {
expect(deleted).toBeGreaterThan(kept);
});
it("treats a runtime whose native payload went missing as a cache miss", () => {
it("treats a runtime whose executable no longer runs 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');
// The same proof the SSH runner and CLI installers use: executable, and
// `--version` exits 0. That is what decides arch and loadability, so no
// separate native probe is needed.
expect(script).toContain(' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null 2>&1');
// Readiness gates the short-circuit, so a cache missing the payload
// Readiness gates the short-circuit, so a cache whose executable broke
// reinstalls from the archive instead of being reused forever.
const payloadCheckDefined = script.indexOf("node_pty_payload_present() {");
const entryCheckDefined = script.indexOf("runtime_entry_runs() {");
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(entryCheckDefined).toBeGreaterThan(-1);
expect(entryCheckDefined).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", () => {
// A swapped or half-written `t3` can still exist and even still answer
// `--version`, and launch then runs something this install never verified.
// The digest the install records is what turns that into a miss.
it("re-hashes the executable 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(` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`);
expect(script).toContain(
' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]',
);
@@ -310,18 +306,18 @@ describe("WSL runtime cache", () => {
expect(promoted).toBeGreaterThan(markerWritten);
});
it("refuses to mark an archive without a native payload as ready", () => {
it("refuses to mark an archive whose executable does not run 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');
expect(script).toContain('if ! runtime_entry_runs "$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 payloadValidated = script.indexOf('runtime_entry_runs "$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);
@@ -351,7 +347,7 @@ describe("WSL runtime cache", () => {
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 running backend's argv holds `<runtime>/t3`, 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.
@@ -394,7 +390,7 @@ describe("WSL runtime cache", () => {
});
// 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
// whose entry 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)", () => {
@@ -410,13 +406,14 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
[
"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`,
// Mirrors the release archive: one top-level versioned directory that
// holds the executable and its native addons.
'stage="$work/stage/t3-0.0.0-linux-x64"',
'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"',
`printf '%s' ${sh(SERVER_ENTRY_SOURCE)} > "$stage/t3"`,
'chmod +x "$stage/t3"',
`printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`,
`tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`,
`printf 'work:%s\\n' "$work"`,
`printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`,
].join("\n"),
@@ -443,7 +440,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
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`,
serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`,
installScript,
install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)),
};
@@ -462,7 +459,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot);
});
it("reinstalls a cache whose server entry was truncated", () => {
it("reinstalls a cache whose executable was truncated", () => {
const fixture = createFixture();
expect(fixture.install().status).toBe(0);
expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0);
@@ -645,7 +642,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
`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 &',
'sh -c "sleep 30" "$runtime_root/t3" >/dev/null 2>&1 &',
"active_pid=$!",
"sleep 0.1",
fixture.installScript(),
@@ -672,7 +669,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
'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() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }',
"make_ready sha256-current",
"make_ready sha256-previous",
"make_ready sha256-active",
@@ -683,7 +680,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed
'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 &',
'sh -c "sleep 30" "$runtime_parent/sha256-active/t3" >/dev/null 2>&1 &',
"active_pid=$!",
"(",
' exec 9> "$runtime_parent/.sha256-locked.install.lock"',
+125 -71
View File
@@ -66,6 +66,19 @@ export type EnsureWslNodePtyResult =
readonly retryLimit?: number;
};
// Outcome of asking the staged self-contained runtime to prove itself. Any
// failure sends the launch to the mounted server tree; the caller decides what
// to do with the cache.
export type ProbeWslRuntimeResult =
| {
readonly ok: true;
readonly resolvedPath: string;
}
| {
readonly ok: false;
readonly reason: string;
};
export class DesktopWslDistroListError extends Schema.TaggedError<DesktopWslDistroListError>()(
"DesktopWslDistroListError",
{ reason: Schema.String },
@@ -108,6 +121,13 @@ export class DesktopWslEnvironment extends Context.Service<
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>;
// Proves a staged self-contained runtime can run (`<root>/t3 --version`)
// and captures the user's login-shell PATH for the launch. Needs no Node
// in the distro; the mounted server tree still goes through ensureNodePty.
readonly probeRuntime: (
distro: string | null,
linuxAppRoot: string,
) => Effect.Effect<ProbeWslRuntimeResult>;
readonly ensureNodePty: (
distro: string | null,
linuxAppRoot: string,
@@ -149,14 +169,15 @@ const TIMEOUT_RESULT: ShellResult = {
const formatWslShellTransportFailureReason = (
failure: ShellResult["transportFailure"],
subject = "Node.js",
): string | null => {
switch (failure) {
case "timeout":
return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
return `WSL backend preflight timed out while probing for ${subject}. WSL may be slow to start; retry, or check that the distro is healthy.`;
case "spawn":
return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
return `WSL backend preflight could not start wsl.exe to probe for ${subject}. Check that WSL is installed and the distro is accessible.`;
case "process":
return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
return `WSL backend preflight lost communication with wsl.exe while probing for ${subject}. Retry, or check that the distro is healthy.`;
case null:
return null;
}
@@ -255,7 +276,7 @@ const runWslShell = (
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
// Holds the sha256 of the runtime's server entry, written when the install
// Holds the sha256 of the runtime's `t3` executable, 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.
@@ -279,35 +300,25 @@ export const buildWslRuntimeInstallScript = (
'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",
// The runtime is a self-contained `t3` executable with Node inside, so the
// readiness proof is the same one the SSH runner and the CLI installers
// use: the file is executable and `t3 --version` exits 0. That covers the
// truncated-binary and wrong-arch cases without a separate native probe.
"runtime_entry_runs() {",
' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null 2>&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.
// Hashing the entry is what tells a working cache from one whose `t3` was
// swapped or half-written after install: the file is still there and may
// even still run, and launch then picks an executable that is not what
// this install verified. Hashing the executable measures in tens of
// 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`,
` sha256sum "$1/t3" 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" &&',
' runtime_entry_runs "$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.
@@ -370,15 +381,14 @@ export const buildWslRuntimeInstallScript = (
`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
// The release archive has one top-level `t3-<version>-linux-<arch>/`
// directory; strip it so the executable lands at `$runtime_root/t3`.
`tar -xzf ${shellQuote(linuxArchivePath)} -C "$runtime_tmp" --strip-components=1`,
// Never write the ready marker over a tree whose executable does not run.
// 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",
'if ! runtime_entry_runs "$runtime_tmp"; then',
" printf 'WSL runtime archive does not contain a working t3 executable\\n' >&2",
" exit 1",
"fi",
// The archive's bytes were verified against archiveSha256 above, so the
@@ -466,12 +476,12 @@ export const buildWslRuntimePruneScript = (runtimeId: string): string => {
};
// 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.
// archive. Readiness is decided inside the install script, so a cached tree
// that passes there but fails the launch-time probe (a distro whose glibc the
// executable needs, a tree copied from another machine) would stay ready
// forever and fail 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 [
@@ -488,22 +498,29 @@ export const parseWslRuntimeRoot = (stdout: string): string | null => {
return runtimeRoot.startsWith("/") ? runtimeRoot : null;
};
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
// The mounted server tree carries no Linux pty.node unless the build put one
// there. Distinct from a binary that is present but will not load, which is a
// distro problem rather than a build problem.
const NODE_PTY_BINARY_MISSING_EXIT_CODE = 4;
const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
exitCode === NODE_PTY_BINARY_MISSING_EXIT_CODE
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Install a build that includes WSL support."
: null;
// Captures the login-shell PATH as `resolvedPath:` so the launch can forward the
// user's PATH; the server spawns provider CLIs (`codex`, `claude`) by name.
const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`;
const NODE_PTY_PROBE_SCRIPT = (
linuxServerDir: string,
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
${RESOLVED_PATH_LINE}
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The WSL Node can't read inside app.asar, so confirm what the server needs is
// unpacked on the real filesystem before reporting the backend healthy. Exit 3
// marks this distinct from a node-pty prebuild problem so the caller can report
// marks this distinct from a node-pty binary problem so the caller can report
// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
// launch (which, in wsl-only mode, would just fail to launch with no fallback).
//
@@ -517,26 +534,27 @@ const fs = require("node:fs");
const path = require("node:path");
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
// Node versions — require() succeeding IS the real compatibility test. Compare
// only arch and node-pty version (a stale binary from a different node-pty),
// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
// whenever the user's WSL Node ABI differs from the build's, defeating the
// whole point of shipping one prebuilt for all Node versions.
const expected = {
arch: process.arch,
nodePtyVersion: require("node-pty/package.json").version,
};
const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
const binary = path.join(prebuildDir, "pty.node");
if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
// Node versions — require() succeeding IS the real compatibility test. Look in
// the same places node-pty's own loader does.
const candidates = [
path.join(pkgDir, "build", "Release", "pty.node"),
path.join(pkgDir, "prebuilds", "linux-" + process.arch, "pty.node"),
];
if (!candidates.some((candidate) => fs.existsSync(candidate))) process.exit(${NODE_PTY_BINARY_MISSING_EXIT_CODE});
require("node-pty");
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
for (const key of Object.keys(expected)) {
if (actual[key] !== expected[key]) process.exit(2);
}
NODE`;
// Readiness proof for a staged self-contained runtime: the executable runs and
// reports its version, and the login shell's PATH is captured for the launch.
// This runs under plain `sh` (no Node resolver preamble, since the runtime
// needs no Node), so the login shell is entered explicitly for the PATH
// capture; a distro without bash falls back to the PATH sh was started with.
const RUNTIME_PROBE_SCRIPT = (linuxAppRoot: string) =>
[
`bash -lc ${shellQuote(RESOLVED_PATH_LINE)} 2>/dev/null || ${RESOLVED_PATH_LINE}`,
`${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`,
].join("\n");
const TOOLCHAIN_CHECK_SCRIPT = [
"for tool in node make g++ python3; do",
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
@@ -552,15 +570,8 @@ const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
"set -e",
`cd ${shellQuote(linuxServerDir)}`,
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
`arch=$(node -p "process.arch")`,
`modules=$(node -p "process.versions.modules")`,
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
`cd "$pkg_dir"`,
"npx --yes node-gyp rebuild",
`prebuild_dir="prebuilds/linux-$arch"`,
`mkdir -p "$prebuild_dir"`,
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
`node -e 'require("node-pty")'`,
].join("\n");
@@ -660,6 +671,38 @@ export const formatMissingToolsReason = (
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
};
const probeWslRuntimeImpl = (
distro: string | null,
linuxAppRoot: string,
): Effect.Effect<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const probe = yield* runWslShell(distro, RUNTIME_PROBE_SCRIPT(linuxAppRoot), PROBE_TIMEOUT, {
resolveNode: false,
});
const transportFailureReason = formatWslShellTransportFailureReason(
probe.transportFailure,
"the staged runtime",
);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason } as const;
}
if (probe.exitCode !== 0) {
const trimmedTail = probe.stderr.trim().slice(-500);
return {
ok: false,
reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
} as const;
}
const resolvedPath = parseResolvedPath(probe.stdout);
if (resolvedPath === null) {
return {
ok: false,
reason: "WSL login-shell PATH could not be resolved during backend preflight.",
} as const;
}
return { ok: true, resolvedPath } as const;
});
const ensureNodePtyImpl = (
distro: string | null,
linuxRepoRoot: string,
@@ -1133,6 +1176,9 @@ export interface DesktopWslEnvironmentTestStub {
) => PrepareWslRuntimeResult;
readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect<void>;
// Defaults to success with a plain PATH: a staged runtime that was prepared
// is assumed to run unless the test says otherwise.
readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult;
readonly ensureNodePty?: (
distro: string | null,
linuxAppRoot: string,
@@ -1165,6 +1211,10 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,
invalidateRuntime: (distro, runtimeId) =>
stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,
probeRuntime: (distro, linuxAppRoot) =>
Effect.succeed(
stub.probeRuntime?.(distro, linuxAppRoot) ?? { ok: true, resolvedPath: "/usr/bin:/bin" },
),
ensureNodePty: (distro, linuxAppRoot, options) =>
Effect.succeed(
stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
@@ -1259,6 +1309,10 @@ export const layer = Layer.effect(
provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(
Effect.withSpan("desktop.wsl.invalidateRuntime"),
),
probeRuntime: (distro, linuxAppRoot) =>
provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)).pipe(
Effect.withSpan("desktop.wsl.probeRuntime"),
),
ensureNodePty: (distro, linuxAppRoot, options) =>
provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(
Effect.withSpan("desktop.wsl.ensureNodePty"),
+3 -2
View File
@@ -191,8 +191,9 @@ rustup target add x86_64-pc-windows-msvc
rustup target add aarch64-pc-windows-msvc
```
NSIS is downloaded by electron-builder. WSL support additionally needs a Linux node-pty prebuild;
see the [release runbook](./release.md#windows-payload-topology-and-update-validation).
NSIS is downloaded by electron-builder. WSL support additionally needs the Linux CLI archive
passed as `--wsl-runtime`; see the
[release runbook](./release.md#windows-payload-topology-and-update-validation).
### Signing and passkeys
+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,
),