fix(desktop): harden Windows and WSL support #6068
Closedrookepoole(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/6068/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -943,4 +979,4 @@943979 Effect.provideService(HttpClient.HttpClient, httpClient),944980 Scope.provide(runScope),945981 Effect.matchEffect({946- onFailure: (error) => finalizeRun(error.message),982+ onFailure: (error) =>@@ -0,0 +38,21 @@38+39+ const auditedPty = runtimeManifest.artifacts?.find((artifact) => artifact.name === "node-pty");40+ if (!auditedPty?.sha256) throw new Error("WSL ABI manifest is missing node-pty SHA-256.");41+42+ const sourcePty = path.join(runtimeDir, "pty.node");43+ const sourceSha256 = sha256File(sourcePty);44+ if (sourceSha256 !== auditedPty.sha256) {45+ throw new Error(46+ `CI node-pty artifact hash mismatch: manifest ${auditedPty.sha256}, file ${sourceSha256}.`,47+ );48+ }49+50+ const serverRequire = createRequire(path.join(serverRoot, "package.json"));51+ const nodePtyManifestPath = serverRequire.resolve("node-pty/package.json");52+ const nodePtyDir = path.dirname(nodePtyManifestPath);53+ const nodePtyManifest = JSON.parse(readFileSync(nodePtyManifestPath, "utf8"));54+ if (typeof nodePtyManifest.version !== "string" || nodePtyManifest.version.length === 0) {55+ throw new Error(`Invalid node-pty package version in ${nodePtyManifestPath}`);56+ }57+58+ const prebuildDir = path.join(nodePtyDir, "prebuilds", `linux-${options.arch}`);@@ -0,0 +45,21 @@45+ function* (instance: DesktopBackendManager.DesktopBackendInstance) {46+ const before = yield* instance.snapshot;47+ if (!before.desiredRunning) return;48+49+ const healthy = before.ready50+ ? yield* instance.probeReady(BACKEND_PROBE_TIMEOUT)51+ : false;52+ if (healthy) {53+ yield* logRecoveryInfo("backend remained healthy after resume", { id: instance.id });54+ return;55+ }56+57+ yield* logRecoveryWarning("backend unhealthy after resume; restarting", {58+ id: instance.id,59+ readyBeforeProbe: before.ready,60+ pid: Option.getOrNull(before.activePid),61+ restartScheduled: before.restartScheduled,62+ });63+64+ yield* instance.stop({ timeout: BACKEND_STOP_TIMEOUT });65+ yield* instance.start;@@ -218,0 +287,21 @@287+function attempt(port, usedEphemeralFallback) {288+ const server = net.createServer();289+ server.once("error", (error) => {290+ if (error && error.code === "EADDRINUSE" && fallbackToEphemeral && port !== 0) {291+ attempt(0, true);292+ return;293+ }294+ const code = error && typeof error.code === "string" ? error.code : "UNKNOWN";295+ const message = error && typeof error.message === "string" ? error.message : String(error);296+ process.stderr.write(errorPrefix + code + ":" + message.replace(/[\r\n]+/g, " ") + "\n");297+ process.exitCode = 2;298+ });299+ server.listen({ host, port, exclusive: true }, () => {300+ const address = server.address();301+ if (!address || typeof address === "string") {302+ process.stderr.write(errorPrefix + "INVALID_ADDRESS:listener did not expose a TCP port\n");303+ process.exitCode = 3;304+ server.close();305+ return;306+ }307+ process.stdout.write(resultPrefix + String(address.port) + ":" + (usedEphemeralFallback ? "1" : "0") + "\n");@@ -426,3 +766,15 @@426766 } as const;427767 }428768769+ const libcCompatibilityReason = formatWslLibcCompatibilityReason(770+ distro,771+ libcFamily,772+ glibcVersion,773+ );774+ if (libcCompatibilityReason !== null) {775+ return {776+ ok: false,777+ reason: libcCompatibilityReason,778+ fatal: true,779+ } as const;780+ }@@ -503,8 +509,19 @@509+ // bind exactly that interface rather than 0.0.0.0. In mirrored mode the510+ // distro reports a Windows-owned address; bind loopback because both sides511+ // share localhost semantics. If address probing fails, fall back to loopback512+ // instead of broadening exposure to every Linux interface.513+ const distroIp =514+ preflight._tag === "Ready"515+ ? yield* wslEnvironment.getDistroIp(preflight.runningDistro)516+ : Option.none<string>();503517 const usesSharedNetworkStack = Option.match(distroIp, {504518 onNone: () => false,505519 onSome: (ip) => isLocalHostIpv4(ip),506520 });507- const rendererHost = usesSharedNetworkStack521+ const wslPrivateHost = usesSharedNetworkStack508522 ? "127.0.0.1"509523 : Option.getOrElse(distroIp, () => "127.0.0.1");510- const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);524+ const portStrategy = input.portStrategy ?? "fixed";525+ const portAllocation =526+ preflight._tag === "Ready"527+ ? yield* wslEnvironment.allocateTcpPort({@@ -0,0 +97,21 @@97+ Write-Host "Requested WSL distro: $Distro"98+99+ $startArgs = @{100+ FilePath = $executablePath101+ WorkingDirectory = $artifactRunDir102+ RedirectStandardOutput = $stdoutPath103+ RedirectStandardError = $stderrPath104+ PassThru = $true105+ }106+ $process = Start-Process @startArgs107+108+ $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)109+ $wrapperExitedAt = $null110+ while (-not (Test-Path $receiptPath)) {111+ $process.Refresh()112+ if ($process.HasExited) {113+ if ($process.ExitCode -ne 0) {114+ Write-SmokeLogs -StdoutPath $stdoutPath -StderrPath $stderrPath115+ throw "Packaged portable wrapper exited with code $($process.ExitCode) before producing a lifecycle receipt."116+ }117+ if ($null -eq $wrapperExitedAt) {@@ -173,16 +261,9 @@173261 // wslDistro when the id is the "wsl:default" sentinel).174262 // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.175263 const targetId = options?.targetEnvironmentId;176- const wslDistroFromTarget =177- targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)178- ? extractWslDistroFromEnvironmentId(targetId)179- : null;180264 const useWsl =181265 targetId !== undefined &&182266 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&183267 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);184268 const settings = yield* appSettings.get;185- // Fall back to the persisted wslDistro when the id is the186- // "wsl:default" sentinel; the orchestrator uses the same fallback187- // for the actual backend.188- const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;269+ const wslDistro = useWsl
- @@ -1127,3 +1174,19 @@11271174 Effect.map(Option.getOrElse(() => false)),11281175 );112911761177+ const probeReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>1178+ Ref.get(state).pipe(1179+ Effect.flatMap((current) => {1180+ if (!current.desiredRunning || !current.ready) return Effect.succeed(false);1181+ return Option.match(current.config, {1182+ onNone: () => Effect.succeed(false),1183+ onSome: (config) =>1184+ waitForHttpReady({1185+ executablePath: config.executablePath,1186+ entryPath: config.entryPath,1187+ cwd: config.cwd,1188+ httpBaseUrl: config.httpBaseUrl,1189+ timeout,1190+ }).pipe(1191+ Effect.as(true),1192+ Effect.catchTag("BackendReadinessTimeoutError", () => Effect.succeed(false)),@@ -0,0 +29,21 @@29+ if (TRANSIENT_WINDOWS_SYSTEM_ERROR_TAGS.has(error.reason._tag)) {30+ return true;31+ }32+ return TRANSIENT_WINDOWS_ERROR_CODES.has(readErrorCode(error.reason) ?? "");33+}34+35+/**36+ * Windows scanners, indexers, sync clients, and antivirus software can briefly37+ * hold a file between our temporary-file write and atomic rename. Effect38+ * normalizes those failures to Busy / WouldBlock / PermissionDenied (or an39+ * Unknown reason retaining the original Node errno). Retry only that bounded40+ * class; permanent filesystem failures still surface to the caller.41+ */42+export function retryWindowsFileSystemOperation<A>(43+ operation: Effect.Effect<A, PlatformError.PlatformError>,44+ options?: {45+ readonly platform?: NodeJS.Platform;46+ readonly delaysMs?: readonly number[];47+ },48+): Effect.Effect<A, PlatformError.PlatformError> {49+ const platform = options?.platform ?? process.platform;@@ -122,0 +129,21 @@129+ payload: Schema.Void,130+ result: DesktopWslStateSchema,131+ handler: Effect.fn("desktop.ipc.wsl.retry")(function* () {132+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;133+ yield* wslBackend.retry;134+ return yield* readWslState;135+ }),136+});137+138+export const getWslDiagnosticReport = makeIpcMethod({139+ channel: IpcChannels.GET_WSL_DIAGNOSTIC_REPORT_CHANNEL,140+ payload: Schema.Void,141+ result: Schema.String,142+ handler: Effect.fn("desktop.ipc.wsl.getDiagnosticReport")(function* () {143+ const state = yield* readWslState;144+ const selectedDistro =145+ state.distro ?? state.distros.find((candidate) => candidate.isDefault)?.name ?? null;146+ const report = {147+ generatedAt: new Date().toISOString(),148+ platform: process.platform,149+ arch: process.arch,@@ -0,0 +16,21 @@16+ }17+>()("@t3tools/desktop/wsl/DesktopWslDiagnostics") {}18+19+export const layer = Layer.effect(20+ DesktopWslDiagnostics,21+ Effect.gen(function* () {22+ const ref = yield* Ref.make(Option.none<DesktopWslDiagnosticRecord>());23+ return DesktopWslDiagnostics.of({24+ current: Ref.get(ref),25+ record: (diagnostic) =>26+ Ref.set(27+ ref,28+ Option.some({29+ ...diagnostic,30+ occurredAt: diagnostic.occurredAt ?? new Date().toISOString(),31+ }),32+ ),33+ clear: Ref.set(ref, Option.none()),34+ });35+ }),36+);
- @@ -408,3 +698,18 @@408698 // there rather than the monorepo root, where Bun's hoist layout omits it.409699 const linuxServerDir = `${linuxRepoRoot}/apps/server`;410700701+ let bundledNodePath: string | null = null;702+ if (options.bundledNodeWindowsPath) {703+ const bundledSource = yield* windowsToWslPath(distro, options.bundledNodeWindowsPath);704+ if (Option.isNone(bundledSource)) {705+ return {706+ ok: false,707+ reason: `wslpath conversion failed for bundled Node runtime ${options.bundledNodeWindowsPath}`,708+ fatal: false,709+ } as const;710+ }711+ const prepared = yield* runWslShell(712+ distro,713+ BUNDLED_NODE_PREP_SCRIPT(bundledSource.value),714+ PROBE_TIMEOUT,715+ { resolveUserNode: false },@@ -1129 +1176,21 @@112911761177+ const probeReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>1178+ Ref.get(state).pipe(1179+ Effect.flatMap((current) => {1180+ if (!current.desiredRunning || !current.ready) return Effect.succeed(false);1181+ return Option.match(current.config, {1182+ onNone: () => Effect.succeed(false),1183+ onSome: (config) =>1184+ waitForHttpReady({1185+ executablePath: config.executablePath,1186+ entryPath: config.entryPath,1187+ cwd: config.cwd,1188+ httpBaseUrl: config.httpBaseUrl,1189+ timeout,1190+ }).pipe(1191+ Effect.as(true),1192+ Effect.catchTag("BackendReadinessTimeoutError", () => Effect.succeed(false)),1193+ ),1194+ });1195+ }),1196+ );
rookepoole(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
e4f92de4-e55d-48ed-abde-cd0bd4da20c0You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share