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