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