Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendConfiguration.ts

796 lines32.0 KB

1import * as NodeOS from "node:os";
2​
3import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as Encoding from "effect/Encoding";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as SynchronizedRef from "effect/SynchronizedRef";
14​
15import serverPackageJson from "../../../server/package.json" with { type: "json" };
16​
17import * as DesktopBackendManager from "./DesktopBackendManager.ts";
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as DesktopServerExposure from "./DesktopServerExposure.ts";
20import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
21import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
22import {
23 parseWslRuntimeArchiveHash,
24 WSL_RUNTIME_ARCHIVE_FILENAME,
25 WSL_RUNTIME_ARCHIVE_HASH_FILENAME,
26} from "@t3tools/shared/wslRuntimeArchive";
27​
28export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
29 "DesktopBackendObservabilitySettingsReadError",
30 {
31 settingsPath: Schema.String,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
37 }
39​
40export class DesktopBackendConfiguration extends Context.Service<
41 DesktopBackendConfiguration,
42 {
43 // Build the Windows-native primary backend's start config. Reads the
44 // primary's port/host/exposure from DesktopServerExposure. Can fail
45 // with PlatformError because bootstrap token generation now uses
46 // crypto.randomBytes under the hood (post Effect 4 migration).
47 readonly resolvePrimary: Effect.Effect<
48 DesktopBackendManager.DesktopBackendStartConfig,
49 PlatformError.PlatformError
50 >;
51 // Build a WSL backend start config for the given distro on the given
52 // port. The WSL backend is always loopback-only (the primary owns LAN
53 // exposure when the user opts in), so this takes the port directly and
54 // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
55 // forwarded to wsl.exe with no -d flag.
56 readonly resolveWsl: (input: {
57 readonly port: number;
58 readonly distro: string | null;
59 }) => Effect.Effect<
60 DesktopBackendManager.DesktopBackendStartConfig,
61 PlatformError.PlatformError
62 >;
63 // The renderer-facing label for the primary instance, derived from the
64 // same decision resolvePrimary makes (including the WSL-availability
65 // fall-back to Windows), so the env switcher can't show "WSL" for a
66 // backend that actually resolved to Windows.
67 readonly resolvePrimaryLabel: Effect.Effect<string>;
68 }
69>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
70​
71interface BackendObservabilitySettings {
72 readonly otlpTracesUrl: Option.Option<string>;
73 readonly otlpMetricsUrl: Option.Option<string>;
75​
76const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
77 otlpTracesUrl: Option.none(),
78 otlpMetricsUrl: Option.none(),
79};
80​
81const DESKTOP_BACKEND_ENV_NAMES = [
82 "T3CODE_PORT",
83 "T3CODE_MODE",
84 "T3CODE_NO_BROWSER",
85 "T3CODE_HOST",
86 "T3CODE_DESKTOP_WS_URL",
87 "T3CODE_DESKTOP_LAN_ACCESS",
88 "T3CODE_DESKTOP_LAN_HOST",
89 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
90 "T3CODE_TAILSCALE_SERVE",
91 "T3CODE_TAILSCALE_SERVE_PORT",
92] as const;
93​
94// Sensitive env vars that the WSL backend needs but Windows process.env won't
95// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
96// handled separately via a `--dev-url` CLI flag because WSLENV translation of
97// URL-shaped values (colons / slashes) is unreliable.
98const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
99​
100const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
101​
102const backendChildEnvPatch = (): Record<string, string | undefined> =>
103 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
104​
105const getWslEnvEntryName = (entry: string): string => {
106 const slashIndex = entry.indexOf("/");
107 return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
108};
109​
110const mergeWslEnv = (
111 existingWslEnv: string | undefined,
112 forwardedEnvNames: ReadonlyArray<string>,
113): string | undefined => {
114 const existing = existingWslEnv?.trim() ?? "";
115​
116 // Names already declared, so we don't forward a duplicate. We parse the
117 // existing value only for this membership test — the string itself is
118 // preserved verbatim below rather than re-serialized.
119 const seenNames = new Set(
120 existing
121 .split(":")
122 .map((entry) => getWslEnvEntryName(entry.trim()))
123 .filter((name) => name.length > 0),
124 );
125​
126 const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
127​
128 // Preserve the user's WSLENV exactly as Windows handed it to us — empty
129 // "::" segments and duplicate entries are harmless no-ops to WSL and not
130 // ours to normalize — and only append the secrets we need to forward
131 // across the wsl.exe boundary.
132 const parts = [existing, ...additions].filter((part) => part.length > 0);
133 return parts.length > 0 ? parts.join(":") : undefined;
134};
135​
136const logBackendObservabilitySettingsReadFailure = (
137 settingsPath: string,
138 cause: PlatformError.PlatformError,
139) => {
140 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
141 return Effect.logWarning(error).pipe(
142 Effect.annotateLogs({
143 component: "desktop-backend-configuration",
144 error,
145 }),
146 );
147};
148​
149function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
150 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
152​
153const resolveResourceMonitorPath = Effect.fn(
154 "desktop.backendConfiguration.resolveResourceMonitorPath",
155)(function* () {
156 const environment = yield* DesktopEnvironment.DesktopEnvironment;
157 const fileSystem = yield* FileSystem.FileSystem;
158 const binaryName = resourceMonitorBinaryName(environment.platform);
159 const candidates = environment.isDevelopment
160 ? [
161 environment.path.join(
162 environment.rootDir,
163 "native/resource-monitor/target/release",
164 binaryName,
165 ),
166 environment.path.join(
167 environment.rootDir,
168 "native/resource-monitor/target/debug",
169 binaryName,
170 ),
171 ]
172 : environment.isPackaged
173 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
174 : environment.resolveResourcePathCandidates(
175 environment.path.join("resource-monitor", binaryName),
176 );
177​
178 for (const candidate of candidates) {
179 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
180 return Option.some(candidate);
181 }
182 }
183​
184 return Option.none<string>();
185});
186​
187const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
188 const fileSystem = yield* FileSystem.FileSystem;
189 const environment = yield* DesktopEnvironment.DesktopEnvironment;
190 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
191 Effect.map(Option.some),
192 Effect.catchTags({
193 PlatformError: (cause) =>
194 cause.reason._tag === "NotFound"
195 ? Effect.succeed(Option.none())
196 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
197 Effect.as(Option.none()),
198 ),
199 }),
200 );
201 if (Option.isNone(raw)) {
202 return emptyBackendObservabilitySettings;
203 }
204​
205 const parsed = parsePersistedServerObservabilitySettings(raw.value);
206 return {
207 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
208 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
209 };
210});
211​
212interface SharedBootstrapInput {
213 readonly bootstrapToken: string;
214 readonly observabilitySettings: BackendObservabilitySettings;
216​
217interface WslPreflightSuccess {
218 readonly _tag: "Ready";
219 readonly runningDistro: string;
220 readonly linuxEntryPath: string;
221 // Absolute path to the node binary the preflight validated after the shared
222 // remote resolver repaired PATH. The launch must use this exact path so it
223 // doesn't fall through to a different/old node than the one node-pty was
224 // built against.
225 readonly nodePath: string;
226 // PATH captured from the same login shell after the shared resolver loaded
227 // version managers. The launch forwards this value directly without a shell.
228 readonly resolvedPath: string;
230​
231interface WslPreflightFailure {
232 readonly _tag: "Failed";
233 readonly reason: string;
234 // Fatal: the WSL distro is misconfigured (no node, wrong version, missing
235 // build tools) and retrying won't help — surface it and (wsl-only) fall back
236 // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
237 // boots), with a bounded window for self-healing before fallback.
238 readonly fatal: boolean;
239 readonly retryLimit?: number;
241​
242const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
243​
244const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
245 readonly distro: string | null;
246 readonly isPackaged: boolean;
247 readonly packagedRuntime: {
248 readonly windowsArchivePath: string;
249 readonly archiveHash: string;
250 } | null;
251 readonly windowsEntryPath: string;
252 readonly windowsRepoRoot: string;
253 readonly allowBuild: boolean;
254}): Effect.fn.Return<
255 WslPreflightSuccess | WslPreflightFailure,
256 never,
257 DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
258> {
259 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
260 const fileSystem = yield* FileSystem.FileSystem;
261​
262 const wslAvailable = yield* wslEnv.isAvailable;
263 if (!wslAvailable) {
264 return {
265 _tag: "Failed",
266 reason: "WSL is not available on this system",
267 fatal: false,
268 } as const;
269 }
270​
271 const distroProbe = yield* wslEnv.probeDistros.pipe(
272 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
273 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
274 );
275 if (distroProbe._tag === "Failure") {
276 return {
277 _tag: "Failed",
278 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
279 fatal: false,
280 } as const;
281 }
282​
283 const installedDistros = distroProbe.distros;
284 const runningDistro = input.distro
285 ? (installedDistros.find(
286 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
287 )?.name ?? null)
288 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
289 if (runningDistro === null) {
290 return {
291 _tag: "Failed",
292 reason: input.distro
293 ? `WSL distro is not installed: ${input.distro}`
294 : installedDistros.length === 0
295 ? "WSL has no installed distributions"
296 : "WSL has no default distribution",
297 fatal: true,
298 } as const;
299 }
300​
301 const entryExists = yield* fileSystem
302 .exists(input.windowsEntryPath)
303 .pipe(Effect.orElseSucceed(() => false));
304 if (!entryExists) {
305 return {
306 _tag: "Failed",
307 reason: `missing server entry at ${input.windowsEntryPath}`,
308 fatal: true,
309 } as const;
310 }
311​
312 let linuxRepoRoot: string | null = null;
313 if (input.isPackaged && input.packagedRuntime !== null) {
314 const prepared = yield* wslEnv.preparePackagedRuntime(
315 runningDistro,
316 input.packagedRuntime.windowsArchivePath,
317 input.packagedRuntime.archiveHash,
318 );
319 if (!prepared.ok) {
320 yield* Effect.logWarning(
321 `Could not prepare the Linux-native WSL runtime; using the packaged runtime from its Windows mount instead. ${prepared.reason}`,
322 );
323 } else {
324 linuxRepoRoot = prepared.linuxRepoRoot;
325 }
326 }
327​
328 if (linuxRepoRoot === null) {
329 const convertedRepoRoot = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsRepoRoot);
330 if (Option.isNone(convertedRepoRoot)) {
331 return {
332 _tag: "Failed",
333 reason: `wslpath conversion failed for ${input.windowsRepoRoot}`,
334 fatal: false,
335 } as const;
336 }
337 linuxRepoRoot = convertedRepoRoot.value;
338 }
339​
340 const linuxEntryPath = `${linuxRepoRoot.replace(/\/+$/, "")}/apps/server/dist/bin.mjs`;
341 const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, linuxRepoRoot, {
342 allowBuild: input.allowBuild,
343 nodeEngineRange: serverPackageJson.engines.node,
344 });
345 if (!nodePtyResult.ok) {
346 return {
347 _tag: "Failed",
348 reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
349 fatal: nodePtyResult.fatal,
350 ...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
351 } as const;
352 }
353​
354 return {
355 _tag: "Ready",
356 runningDistro,
357 linuxEntryPath,
358 nodePath: nodePtyResult.nodePath,
359 resolvedPath: nodePtyResult.resolvedPath,
360 } as const;
361});
362​
363// True when the given IPv4 belongs to a Windows-side network
364// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
365// host's, which is the signature we use to detect that mode and
366// switch the renderer URL to loopback.
367const isLocalHostIpv4 = (ip: string): boolean => {
368 const interfaces = NodeOS.networkInterfaces();
369 for (const list of Object.values(interfaces)) {
370 if (!list) continue;
371 for (const entry of list) {
372 // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
373 // the Node build Electron ships (41 / Node 22, verified), but some Node
374 // builds report the numeric 4. Normalize to a string so a future runtime
375 // bump can't silently break mirrored-mode detection and leave the
376 // renderer pointed at the distro IP instead of loopback.
377 const family = String(entry.family);
378 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
379 }
380 }
381 return false;
382};
383​
384const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
385 ...Option.match(observabilitySettings.otlpTracesUrl, {
386 onNone: () => ({}),
387 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
388 }),
389 ...Option.match(observabilitySettings.otlpMetricsUrl, {
390 onNone: () => ({}),
391 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
392 }),
393});
394​
395const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
396 function* (
397 input: SharedBootstrapInput & {
398 readonly resourceMonitorPath: Option.Option<string>;
399 },
400 ): Effect.fn.Return<
401 DesktopBackendManager.DesktopBackendStartConfig,
402 never,
403 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
404 > {
405 const environment = yield* DesktopEnvironment.DesktopEnvironment;
406 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
407 const backendExposure = yield* serverExposure.backendConfig;
408​
409 const bootstrap = {
410 mode: "desktop" as const,
411 noBrowser: true,
412 port: backendExposure.port,
413 t3Home: environment.baseDir,
414 host: backendExposure.bindHost,
415 desktopBootstrapToken: input.bootstrapToken,
416 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
417 tailscaleServePort: backendExposure.tailscaleServePort,
418 desktopTelemetryFd: 4,
419 desktopTelemetryControlFd: 5,
420 ...Option.match(input.resourceMonitorPath, {
421 onNone: () => ({}),
422 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
423 }),
424 ...buildObservabilityFragment(input.observabilitySettings),
425 };
426​
427 return {
428 executablePath: process.execPath,
429 args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
430 entryPath: environment.backendEntryPath,
431 cwd: environment.backendCwd,
432 env: {
433 ...backendChildEnvPatch(),
434 ELECTRON_RUN_AS_NODE: "1",
435 },
436 // Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
437 extendEnv: true,
438 bootstrap,
439 bootstrapDelivery: "fd3",
440 httpBaseUrl: backendExposure.httpBaseUrl,
441 captureOutput: true,
442 preflightFailure: Option.none(),
443 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
444 },
445);
446​
447const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
448 input: SharedBootstrapInput & {
449 readonly port: number;
450 readonly distro: string | null;
451 },
452): Effect.fn.Return<
453 DesktopBackendManager.DesktopBackendStartConfig,
454 never,
455 | DesktopEnvironment.DesktopEnvironment
456 | DesktopWslEnvironment.DesktopWslEnvironment
457 | FileSystem.FileSystem
458> {
459 const environment = yield* DesktopEnvironment.DesktopEnvironment;
460 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
461 const fileSystem = yield* FileSystem.FileSystem;
462​
463 // Bind to 0.0.0.0 inside WSL so the backend is reachable both via
464 // WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
465 // -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
466 // Windows. wslhost forwarding is unreliable on some Windows hosts:
467 // the desktop's readiness probe and the renderer's saved-env-style
468 // fetch both saw "Failed to fetch" when the backend only bound to
469 // 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
470 // WSL IP as the renderer-visible URL avoids that dependency.
471 // Security-wise this is acceptable for the local-only WSL backend:
472 // the network it exposes on is the WSL-vEthernet network, not the
473 // LAN; the primary owns LAN exposure when the user opts in.
474 const wslBindHost = "0.0.0.0";
475​
476 const bootstrap = {
477 mode: "desktop" as const,
478 noBrowser: true,
479 port: input.port,
480 // Omit t3Home so the Linux backend uses its own home dir instead of
481 // the Windows-side baseDir (which would be a /mnt/c path and share
482 // the SQLite file with the primary).
483 host: wslBindHost,
484 desktopBootstrapToken: input.bootstrapToken,
485 // PortSchema rejects 0, so when tailscale serve is disabled we still
486 // need a valid number in this slot. The backend reads tailscaleServePort
487 // only when tailscaleServeEnabled is true, so the actual value here is
488 // inert.
489 tailscaleServeEnabled: false,
490 tailscaleServePort: 443,
491 // The packaged sidecar is a Windows executable and cannot run inside the
492 // Linux WSL backend. Keep the field absent instead of passing an unusable
493 // `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
494 // See docs/architecture/resource-telemetry.md.
495 ...buildObservabilityFragment(input.observabilitySettings),
496 };
497​
498 // In packaged builds environment.appRoot is .../resources/app.asar — an
499 // archive FILE. The Windows primary reads its entry through
500 // ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
501 // `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
502 // the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
503 // to the app.asar.unpacked sibling. That directory is the packaged staging
504 // source; preflight copies it to WSL's native filesystem and launches there.
505 // In dev appRoot is already a real checkout, so preflight uses it in place.
506 const wslAppRoot = environment.isPackaged
507 ? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
508 : environment.appRoot;
509 const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
510 const runtimeArchivePath = environment.path.join(
511 environment.resourcesPath,
512 WSL_RUNTIME_ARCHIVE_FILENAME,
513 );
514 const runtimeArchiveHashPath = environment.path.join(
515 environment.resourcesPath,
516 WSL_RUNTIME_ARCHIVE_HASH_FILENAME,
517 );
518 const runtimeArchiveHash = environment.isPackaged
519 ? yield* fileSystem.readFileString(runtimeArchiveHashPath).pipe(
520 Effect.map(parseWslRuntimeArchiveHash),
521 Effect.orElseSucceed(() => null),
522 )
523 : null;
524 if (environment.isPackaged && runtimeArchiveHash === null) {
525 yield* Effect.logWarning(
526 "The packaged WSL runtime archive identity is missing or invalid; using the existing Windows-mounted runtime.",
527 );
528 }
529​
530 const preflight = yield* runWslPreflight({
531 distro: input.distro,
532 isPackaged: environment.isPackaged,
533 packagedRuntime:
534 environment.isPackaged && runtimeArchiveHash !== null
535 ? { windowsArchivePath: runtimeArchivePath, archiveHash: runtimeArchiveHash }
536 : null,
537 windowsEntryPath: wslEntryPath,
538 windowsRepoRoot: wslAppRoot,
539 // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
540 // attached to the Windows artifact — see build-desktop-artifact.ts), so the
541 // WSL backend never needs a compiler, node-gyp, or network on first launch.
542 // Compiling from source is a dev-only convenience: a checkout has no shipped
543 // prebuilt, and developers have the toolchain. In packaged builds we instead
544 // surface a clear diagnostic if the prebuilt can't load (unsupported
545 // arch/distro), rather than silently dropping into a fragile runtime build.
546 allowBuild: !environment.isPackaged,
547 });
548​
549 // Every operation after preflight uses the same concrete distro. In
550 // default-tracking mode this closes the race where the system default
551 // changes between probing and spawning the backend.
552 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
553 const distroForConfig = runningDistro ?? input.distro;
554​
555 // Resolve the selected distro's IPv4 address. In mirrored mode the distro
556 // reports a host interface, so use loopback instead; a failed probe also
557 // falls back to loopback and preserves the previous behavior.
558 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
559 const usesSharedNetworkStack = Option.match(distroIp, {
560 onNone: () => false,
561 onSome: (ip) => isLocalHostIpv4(ip),
562 });
563 const rendererHost = usesSharedNetworkStack
564 ? "127.0.0.1"
565 : Option.getOrElse(distroIp, () => "127.0.0.1");
566 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
567​
568 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
569 const forwardedEnv: Record<string, string> = {};
570 const forwardedEnvNames: string[] = [];
571 for (const name of WSL_FORWARDED_ENV_NAMES) {
572 const value = process.env[name];
573 if (value !== undefined && value.length > 0) {
574 forwardedEnv[name] = value;
575 forwardedEnvNames.push(name);
576 }
577 }
578​
579 // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
580 // exports the Windows-side base dir for the primary; if it leaks into
581 // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
582 // /mnt/c, which means both backends read/write the same database and
583 // their env-ids collide).
584 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
585 for (const [key, value] of Object.entries(process.env)) {
586 if (key === "T3CODE_HOME") continue;
587 parentEnvWithoutT3Home[key] = value;
588 }
589 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
590​
591 const baseConfig = {
592 executablePath: "wsl.exe",
593 entryPath: wslEntryPath,
594 cwd: environment.backendCwd,
595 env: {
596 ...parentEnvWithoutT3Home,
597 ...backendChildEnvPatch(),
598 ...forwardedEnv,
599 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
600 },
601 // env is already a complete process.env minus T3CODE_HOME; pass it
602 // verbatim instead of letting the spawner re-merge process.env on top.
603 extendEnv: false,
604 bootstrap,
605 bootstrapDelivery: "stdin" as const,
606 httpBaseUrl,
607 captureOutput: true,
608 ...(runningDistro !== null ? { runningDistro } : {}),
609 };
610​
611 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
612 // config resolution lands in dev/ instead of userdata/. Inheriting through
613 // WSLENV is unreliable in practice (URL-shaped values with colons /
614 // slashes get translated unpredictably depending on flags), and the
615 // packaged build leaves devServerUrl as None anyway.
616 const devUrlArgs = Option.match(environment.devServerUrl, {
617 onNone: () => [] as ReadonlyArray<string>,
618 onSome: (url) => ["--dev-url", url.href],
619 });
620​
621 if (preflight._tag === "Failed") {
622 const retryLimit =
623 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
624 return {
625 ...baseConfig,
626 args: [...distroArgs, "--", "node", "--version"],
627 preflightFailure: Option.some({
628 reason: preflight.reason,
629 fatal: preflight.fatal,
630 ...(retryLimit === undefined ? {} : { retryLimit }),
631 }),
632 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
633 }
634​
635 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
636 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
637 // live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
638 // the process PATH, so `npm install -g ...` fails with NotFound. Pass the
639 // user PATH entries captured by the login-shell preflight. Every dynamic
640 // value is a separate argv entry under `wsl.exe --exec`; no shell command is
641 // involved, so Windows cannot mangle nested quotes and stdin remains reserved
642 // for the bootstrap envelope.
643 const lastSlash = preflight.nodePath.lastIndexOf("/");
644 const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
645 const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
646​
647 return {
648 ...baseConfig,
649 args: [
650 ...distroArgs,
651 "--exec",
652 "env",
653 `PATH=${launchPath}`,
654 preflight.nodePath,
655 preflight.linuxEntryPath,
656 "--bootstrap-fd",
657 "0",
658 ...devUrlArgs,
659 ],
660 preflightFailure: Option.none(),
661 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
662});
663​
664export const make = Effect.gen(function* () {
665 const environment = yield* DesktopEnvironment.DesktopEnvironment;
666 const fileSystem = yield* FileSystem.FileSystem;
667 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
668 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
669 const settings = yield* DesktopAppSettings.DesktopAppSettings;
670 const crypto = yield* Crypto.Crypto;
671 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
672 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
673 // resolve concurrently; with a plain Ref both could observe None, generate
674 // distinct tokens, and one would overwrite the other — leaving the two
675 // backends holding mismatched tokens and breaking the shared-token
676 // invariant the renderer relies on. modifyEffect serializes the whole
677 // get-or-create so the first caller wins and the rest reuse its token.
678 const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
679 const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
680 Option.match(current, {
681 onSome: (token) => Effect.succeed([token, current] as const),
682 onNone: () =>
683 crypto.randomBytes(24).pipe(
684 Effect.map((bytes) => {
685 const token = Encoding.encodeHex(bytes);
686 return [token, Option.some(token)] as const;
687 }),
688 ),
689 }),
690 );
691​
692 // Both resolvers share the same bootstrap token: the renderer holds a
693 // single token and uses it against whichever backend it's currently
694 // talking to. Observability settings get re-read each resolve so a
695 // hot-swap of the server-settings file is picked up on the next
696 // restart cycle without having to bounce the desktop process.
697 const sharedInputs = Effect.gen(function* () {
698 const bootstrapToken = yield* getOrCreateBootstrapToken;
699 const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
700 Effect.provideService(FileSystem.FileSystem, fileSystem),
701 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
702 );
703 return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
704 });
705​
706 const buildWslPrimaryConfig = Effect.gen(function* () {
707 // wsl-only mode pipes the WSL backend through the same port the
708 // Windows primary would normally take. That way the renderer
709 // still loads from the local-only endpoint advertised by
710 // DesktopServerExposure, and primary-aware code paths (cookie
711 // auth, the env switcher's "primary" id) keep working without
712 // a parallel "secondary" registration.
713 const backendExposure = yield* serverExposure.backendConfig;
714 const persistedSettings = yield* settings.get;
715 const shared = yield* sharedInputs;
716 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
717 return yield* resolveWslStartConfig({
718 ...shared,
719 port: backendExposure.port,
720 distro: persistedSettings.wslDistro,
721 }).pipe(
722 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
723 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
724 Effect.provideService(FileSystem.FileSystem, fileSystem),
725 );
726 });
727​
728 const buildWindowsPrimaryConfig = Effect.gen(function* () {
729 const shared = yield* sharedInputs;
730 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
731 Effect.provideService(FileSystem.FileSystem, fileSystem),
732 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
733 );
734 return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
735 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
736 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
737 );
738 });
739​
740 // Single source of truth for what the primary actually runs as. Both
741 // the start-config dispatch and the renderer-facing label derive from
742 // this, so they can't disagree — e.g. the label reading "WSL" while the
743 // config silently fell back to Windows because WSL is unavailable.
744 // Dispatch happens at resolve time so toggling wsl-only between restarts
745 // is picked up on the next start cycle (the pool's primary instance is
746 // created once at layer init, but configResolve fires on each restart).
747 const describePrimary = Effect.gen(function* () {
748 const persistedSettings = yield* settings.get;
749 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
750 // Only honor wsl-only when WSL is actually usable. If the user
751 // persisted wsl-only but WSL has since become unavailable (wsl.exe
752 // removed, no distro), fall back to the Windows primary instead of
753 // looping forever on preflight failures: the Connections backend
754 // control is hidden while WSL is unavailable, so a stuck WSL primary
755 // would otherwise leave no in-app way back to Windows.
756 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
757 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
758 });
759​
760 return DesktopBackendConfiguration.of({
761 resolvePrimary: Effect.gen(function* () {
762 const { useWsl, wslRequested } = yield* describePrimary;
763 if (useWsl) {
764 return yield* buildWslPrimaryConfig;
765 }
766 if (wslRequested) {
767 yield* Effect.logWarning(
768 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
769 );
770 }
771 return yield* buildWindowsPrimaryConfig;
772 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
773 resolvePrimaryLabel: Effect.gen(function* () {
774 const { useWsl, distro } = yield* describePrimary;
775 if (!useWsl) {
776 return environment.platform === "win32" ? "Windows" : "Local environment";
777 }
778 return distro ? `WSL (${distro})` : "WSL";
779 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
780 resolveWsl: (input) =>
781 Effect.gen(function* () {
782 const shared = yield* sharedInputs;
783 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
784 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
785 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
786 Effect.provideService(FileSystem.FileSystem, fileSystem),
787 );
788 }).pipe(
789 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
790 attributes: { port: input.port, distro: input.distro ?? null },
791 }),
792 ),
793 });
794});
795​
796export const layer = Layer.effect(DesktopBackendConfiguration, make);