From da782dadd8e7bd5db5aba1c71d7d82bef423bfb8 Mon Sep 17 00:00:00 2001 From: Josh Gratton Date: Wed, 10 Jun 2026 20:44:48 -0400 Subject: [PATCH] fix(desktop): ship a prebuilt Linux node-pty for the packaged WSL backend In packaged builds the server bundle and node-pty were sealed inside app.asar, which the WSL backend's Linux Node cannot read, so the WSL backend never started in release builds. It dead-ended on a misleading "node-pty not prepared / run prepare:wsl" error. node-pty also publishes no Linux prebuilt, and the Windows artifact is built on a Windows CI runner that cannot compile one. - asarUnpack the server bundle and node-pty, and point the WSL backend at the app.asar.unpacked sibling. The Windows primary still reads app.asar via ELECTRON_RUN_AS_NODE, so it is unaffected and there is no payload duplication. - Build the Linux pty.node in a dedicated Linux CI job and hand it to the Windows packaging job as an artifact. build-desktop-artifact stages it into node-pty/prebuilds/linux-/ with a marker, so the packaged app ships a ready binary and needs no compiler, node-gyp, or network on first launch. - node-pty is N-API, so one Linux binary works across all WSL Node versions; drop the modules ABI comparison from the preflight probe accordingly. - Runtime compile is now dev-only (allowBuild: !isPackaged). In packaged builds a prebuilt that cannot load surfaces a clear arch/distro diagnostic instead of nagging for build tools or silently compiling. --- .github/workflows/release.yml | 62 +++++++++- .../backend/DesktopBackendConfiguration.ts | 25 +++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 39 +++++-- scripts/build-desktop-artifact.test.ts | 1 + scripts/build-desktop-artifact.ts | 107 ++++++++++++++++++ 5 files changed, 218 insertions(+), 16 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 67e6aeb51a..59f5ba2ae6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -218,10 +218,57 @@ jobs: echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT" echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT" + # node-pty publishes no Linux prebuilt and the WSL backend runs under the + # distro's own (Linux) Node, which can't load the Windows/Electron binary. We + # build the Linux pty.node here, on Linux, and hand it to the Windows packaging + # 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) + needs: [preflight] + if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }} + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ needs.preflight.outputs.ref }} + fetch-depth: 0 + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: true + + - name: Build node-pty linux-x64 prebuild + 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 + + - name: Upload node-pty linux-x64 prebuild + uses: actions/upload-artifact@v7 + with: + name: wsl-node-pty-x64 + path: wsl-prebuild/pty.node + if-no-files-found: error + build: name: Build ${{ matrix.label }} - needs: [preflight, relay_public_config] - if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }} + needs: [preflight, relay_public_config, build_wsl_node_pty] + if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.build_wsl_node_pty.result == 'success' }} runs-on: ${{ matrix.runner }} timeout-minutes: 30 env: @@ -275,6 +322,13 @@ 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 + if: matrix.platform == 'win' + uses: actions/download-artifact@v7 + with: + name: wsl-node-pty-x64 + path: wsl-prebuild + - name: Install Spectre-mitigated MSVC libs if: matrix.platform == 'win' shell: pwsh @@ -413,6 +467,10 @@ 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") if has_all \ "$AZURE_TENANT_ID" \ "$AZURE_CLIENT_ID" \ diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index a99420e407..44f36ca9c9 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -376,10 +376,29 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...buildObservabilityFragment(input.observabilitySettings), }; + // In packaged builds environment.appRoot is .../resources/app.asar — an + // archive FILE. The Windows primary reads its entry through + // ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain + // `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks + // the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts) + // to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is + // already a real directory, so this is a no-op. + const wslAppRoot = environment.isPackaged + ? environment.path.join(environment.resourcesPath, "app.asar.unpacked") + : environment.appRoot; + const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs"); + const preflight = yield* runWslPreflight({ distro: input.distro, - windowsEntryPath: environment.backendEntryPath, - windowsRepoRoot: environment.appRoot, + windowsEntryPath: wslEntryPath, + windowsRepoRoot: wslAppRoot, + // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and + // attached to the Windows artifact — see build-desktop-artifact.ts), so the + // WSL backend never needs a compiler, node-gyp, or network on first launch. + // Compiling from source is a dev-only convenience: a checkout has no shipped + // prebuilt, and developers have the toolchain. In packaged builds we instead + // surface a clear diagnostic if the prebuilt can't load (unsupported + // arch/distro), rather than silently dropping into a fragile runtime build. allowBuild: !environment.isPackaged, }); @@ -408,7 +427,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const baseConfig = { executablePath: "wsl.exe", - entryPath: environment.backendEntryPath, + entryPath: wslEntryPath, cwd: environment.backendCwd, env: { ...parentEnvWithoutT3Home, diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 516c152617..51cb891e0b 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -161,9 +161,14 @@ cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1 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, - modules: process.versions.modules, nodePtyVersion: require("node-pty/package.json").version, }; const marker = path.join(pkgDir, "prebuilds", "linux-" + process.arch, "t3code-wsl-node-pty.json"); @@ -325,11 +330,7 @@ const ensureNodePtyImpl = ( if (probe.exitCode === 0) return { ok: true, nodePath } as const; - // node exists but node-pty isn't ready. Run the toolchain check before the - // allowBuild branch so an out-of-range version or missing build tools - // surfaces as a specific, actionable message in both dev and packaged - // builds — otherwise users saw a generic "node-pty is not prepared" error - // pointing at a script that itself would have failed for the same reason. + // node is present but node-pty's native module didn't load. const toolchainCheck = yield* runWslShell( distro, TOOLCHAIN_CHECK_SCRIPT, @@ -337,19 +338,35 @@ const ensureNodePtyImpl = ( options, ); const report = parseToolchainReport(toolchainCheck.stdout); - const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null); - if (missingReason !== null) { - return { ok: false, reason: missingReason } as const; - } if (options.allowBuild !== true) { + // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp, + // or network is needed — and we must not nag the user to install build + // tools they don't need. Still surface a missing/too-old Node (both the + // prebuilt and the server require a compatible Node); otherwise reaching + // here means the bundled binary itself couldn't load, which is almost + // always an unsupported CPU architecture or incompatible system libraries. + const nodeOnlyReason = formatMissingToolsReason( + { missingTools: report.missingTools.filter((tool) => tool === "node"), nodeVersion: report.nodeVersion }, + options.nodeEngineRange?.trim() || null, + ); return { ok: false, reason: - "node-pty is not prepared for this WSL Node runtime. Run `bun run prepare:wsl` from this checkout, then restart the desktop app.", + nodeOnlyReason ?? + "The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.", } as const; } + // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from + // source. Run the toolchain check first so a missing compiler or out-of-range + // Node surfaces a specific, actionable message instead of an opaque node-gyp + // failure. Developers have the toolchain; end users never reach this path. + const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null); + if (missingReason !== null) { + return { ok: false, reason: missingReason } as const; + } + const build = yield* runWslShell( distro, NODE_PTY_BUILD_SCRIPT(linuxServerDir), diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 8dc23484ab..7350412a4c 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -136,6 +136,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { verbose: Option.some(false), mockUpdates: Option.some(false), mockUpdateServerPort: Option.none(), + wslPrebuild: Option.none(), }).pipe( Effect.provide( ConfigProvider.layer( diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 4d63a11dbb..a3c383ed43 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -41,6 +41,9 @@ const RepoRoot = Effect.service(Path.Path).pipe( ); const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString); const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig)); +const decodeNodePtyManifest = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ version: Schema.String })), +); const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () { const fs = yield* FileSystem.FileSystem; @@ -92,6 +95,7 @@ interface BuildCliInput { readonly verbose: Option.Option; readonly mockUpdates: Option.Option; readonly mockUpdateServerPort: Option.Option; + readonly wslPrebuild: Option.Option; } function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined { @@ -249,6 +253,7 @@ interface ResolvedBuildOptions { readonly verbose: boolean; readonly mockUpdates: boolean; readonly mockUpdateServerPort: number | undefined; + readonly wslPrebuild: string | undefined; } interface StagePackageJson { @@ -318,6 +323,11 @@ 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), }); const MockUpdateServerPortSchema = Schema.NumberFromString.check( @@ -390,6 +400,9 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* ( ), )); + const wslPrebuild = + Option.getOrUndefined(input.wslPrebuild) ?? Option.getOrUndefined(env.wslPrebuild); + return { platform, target, @@ -402,6 +415,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* ( verbose, mockUpdates, mockUpdateServerPort, + wslPrebuild, } satisfies ResolvedBuildOptions; }); @@ -694,6 +708,14 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( directories: { buildResources: "apps/desktop/resources", }, + // The Windows primary backend runs the server bundle through + // ELECTRON_RUN_AS_NODE (asar-aware), so it reads bin.mjs straight out of + // app.asar. The WSL backend instead launches plain `wsl.exe -- node`, which + // cannot read inside an asar archive — it needs the server bundle and + // node-pty on the real filesystem. Unpack both to app.asar.unpacked (the + // Windows primary's asar reads are transparently redirected to the same + // unpacked copy, so there's no duplication). + asarUnpack: ["apps/server/dist/**", "**/node_modules/node-pty/**/*"], }; const updateChannel = resolveDesktopUpdateChannel(version); const publishConfig = resolveGitHubPublishConfig(updateChannel); @@ -774,6 +796,75 @@ 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-/ 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; + } + + // WSL runs the same CPU arch as the Windows host; universal is mac-only. + const linuxArch = input.arch === "x64" ? "x64" : input.arch === "arm64" ? "arm64" : undefined; + 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 BuildScriptError({ + message: `WSL node-pty prebuild not found at ${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 pkgRaw = yield* fs.readFileString(path.join(nodePtyDir, "package.json")); + const manifest = yield* decodeNodePtyManifest(pkgRaw).pipe( + Effect.mapError( + (cause) => + new BuildScriptError({ + message: `Could not read node-pty version from ${nodePtyDir}.`, + 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}).`, + ); +}); + const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ( options: ResolvedBuildOptions, ) { @@ -942,6 +1033,16 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ( { label: "vp install --prod --no-optional", verbose: options.verbose }, ); + // WSL is Windows-only, so only the Windows artifact carries the Linux backend + // binary; other platforms ignore the prebuild input. + if (options.platform === "win") { + yield* stageWslNodePtyPrebuild({ + stageAppDir, + arch: options.arch, + prebuildPath: options.wslPrebuild, + }); + } + const buildEnv: NodeJS.ProcessEnv = { ...process.env, }; @@ -1075,6 +1176,12 @@ 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( + 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).", + ), + Flag.optional, + ), }).pipe( Command.withDescription("Build a desktop artifact for T3 Code."), Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),