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