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 be a /mnt/c path and share
451 // the SQLite file with the primary).
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 + node-pty (see asarUnpack in build-desktop-artifact.ts)
472 // to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
473 // already a real directory, so this is a no-op.
474 const wslAppRoot = environment.isPackaged
475 ? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
476 : environment.appRoot;
477 const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
478
479 const preflight = yield* runWslPreflight({
480 distro: input.distro,
481 windowsEntryPath: wslEntryPath,
482 windowsRepoRoot: wslAppRoot,
483 // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
484 // attached to the Windows artifact — see build-desktop-artifact.ts), so the
485 // WSL backend never needs a compiler, node-gyp, or network on first launch.
486 // Compiling from source is a dev-only convenience: a checkout has no shipped
487 // prebuilt, and developers have the toolchain. In packaged builds we instead
488 // surface a clear diagnostic if the prebuilt can't load (unsupported
489 // arch/distro), rather than silently dropping into a fragile runtime build.
490 allowBuild: !environment.isPackaged,
491 });
492
493 // Every operation after preflight uses the same concrete distro. In
494 // default-tracking mode this closes the race where the system default
495 // changes between probing and spawning the backend.
496 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
497 const distroForConfig = runningDistro ?? input.distro;
498
499 // Resolve the selected distro's IPv4 address. In mirrored mode the distro
500 // reports a host interface, so use loopback instead; a failed probe also
501 // falls back to loopback and preserves the previous behavior.
502 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
503 const usesSharedNetworkStack = Option.match(distroIp, {
504 onNone: () => false,
505 onSome: (ip) => isLocalHostIpv4(ip),
506 });
507 const rendererHost = usesSharedNetworkStack
508 ? "127.0.0.1"
509 : Option.getOrElse(distroIp, () => "127.0.0.1");
510 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
511
512 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
513 const forwardedEnv: Record<string, string> = {};
514 const forwardedEnvNames: string[] = [];
515 for (const name of WSL_FORWARDED_ENV_NAMES) {
516 const value = process.env[name];
517 if (value !== undefined && value.length > 0) {
518 forwardedEnv[name] = value;
519 forwardedEnvNames.push(name);
520 }
521 }
522
523 // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
524 // exports the Windows-side base dir for the primary; if it leaks into
525 // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
526 // /mnt/c, which means both backends read/write the same database and
527 // their env-ids collide).
528 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
529 for (const [key, value] of Object.entries(process.env)) {
530 if (key === "T3CODE_HOME") continue;
531 parentEnvWithoutT3Home[key] = value;
532 }
533 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
534
535 const baseConfig = {
536 executablePath: "wsl.exe",
537 entryPath: wslEntryPath,
538 cwd: environment.backendCwd,
539 env: {
540 ...parentEnvWithoutT3Home,
541 ...backendChildEnvPatch(),
542 ...forwardedEnv,
543 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
544 },
545 // env is already a complete process.env minus T3CODE_HOME; pass it
546 // verbatim instead of letting the spawner re-merge process.env on top.
547 extendEnv: false,
548 bootstrap,
549 bootstrapDelivery: "stdin" as const,
550 httpBaseUrl,
551 captureOutput: true,
552 ...(runningDistro !== null ? { runningDistro } : {}),
553 };
554
555 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
556 // config resolution lands in dev/ instead of userdata/. Inheriting through
557 // WSLENV is unreliable in practice (URL-shaped values with colons /
558 // slashes get translated unpredictably depending on flags), and the
559 // packaged build leaves devServerUrl as None anyway.
560 const devUrlArgs = Option.match(environment.devServerUrl, {
561 onNone: () => [] as ReadonlyArray<string>,
562 onSome: (url) => ["--dev-url", url.href],
563 });
564
565 if (preflight._tag === "Failed") {
566 const retryLimit =
567 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
568 return {
569 ...baseConfig,
570 args: [...distroArgs, "--", "node", "--version"],
571 preflightFailure: Option.some({
572 reason: preflight.reason,
573 fatal: preflight.fatal,
574 ...(retryLimit === undefined ? {} : { retryLimit }),
575 }),
576 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
577 }
578
579 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
580 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
581 // live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
582 // the process PATH, so `npm install -g ...` fails with NotFound. Pass the
583 // user PATH entries captured by the login-shell preflight. Every dynamic
584 // value is a separate argv entry under `wsl.exe --exec`; no shell command is
585 // involved, so Windows cannot mangle nested quotes and stdin remains reserved
586 // for the bootstrap envelope.
587 const lastSlash = preflight.nodePath.lastIndexOf("/");
588 const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
589 const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
590
591 return {
592 ...baseConfig,
593 args: [
594 ...distroArgs,
595 "--exec",
596 "env",
597 `PATH=${launchPath}`,
598 preflight.nodePath,
599 preflight.linuxEntryPath,
600 "--bootstrap-fd",
601 "0",
602 ...devUrlArgs,
603 ],
604 preflightFailure: Option.none(),
605 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
606});
607
608export const make = Effect.gen(function* () {
609 const environment = yield* DesktopEnvironment.DesktopEnvironment;
610 const fileSystem = yield* FileSystem.FileSystem;
611 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
612 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
613 const settings = yield* DesktopAppSettings.DesktopAppSettings;
614 const crypto = yield* Crypto.Crypto;
615 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
616 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
617 // resolve concurrently; with a plain Ref both could observe None, generate
618 // distinct tokens, and one would overwrite the other — leaving the two
619 // backends holding mismatched tokens and breaking the shared-token
620 // invariant the renderer relies on. modifyEffect serializes the whole
621 // get-or-create so the first caller wins and the rest reuse its token.
622 const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
623 const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
624 Option.match(current, {
625 onSome: (token) => Effect.succeed([token, current] as const),
626 onNone: () =>
627 crypto.randomBytes(24).pipe(
628 Effect.map((bytes) => {
629 const token = Encoding.encodeHex(bytes);
630 return [token, Option.some(token)] as const;
631 }),
632 ),
633 }),
634 );
635
636 // Both resolvers share the same bootstrap token: the renderer holds a
637 // single token and uses it against whichever backend it's currently
638 // talking to. Observability settings get re-read each resolve so a
639 // hot-swap of the server-settings file is picked up on the next
640 // restart cycle without having to bounce the desktop process.
641 const sharedInputs = Effect.gen(function* () {
642 const bootstrapToken = yield* getOrCreateBootstrapToken;
643 const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
644 Effect.provideService(FileSystem.FileSystem, fileSystem),
645 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
646 );
647 return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
648 });
649
650 const buildWslPrimaryConfig = Effect.gen(function* () {
651 // wsl-only mode pipes the WSL backend through the same port the
652 // Windows primary would normally take. That way the renderer
653 // still loads from the local-only endpoint advertised by
654 // DesktopServerExposure, and primary-aware code paths (cookie
655 // auth, the env switcher's "primary" id) keep working without
656 // a parallel "secondary" registration.
657 const backendExposure = yield* serverExposure.backendConfig;
658 const persistedSettings = yield* settings.get;
659 const shared = yield* sharedInputs;
660 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
661 return yield* resolveWslStartConfig({
662 ...shared,
663 port: backendExposure.port,
664 distro: persistedSettings.wslDistro,
665 }).pipe(
666 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
667 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
668 Effect.provideService(FileSystem.FileSystem, fileSystem),
669 );
670 });
671
672 const buildWindowsPrimaryConfig = Effect.gen(function* () {
673 const shared = yield* sharedInputs;
674 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
675 Effect.provideService(FileSystem.FileSystem, fileSystem),
676 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
677 );
678 return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
679 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
680 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
681 );
682 });
683
684 // Single source of truth for what the primary actually runs as. Both
685 // the start-config dispatch and the renderer-facing label derive from
686 // this, so they can't disagree — e.g. the label reading "WSL" while the
687 // config silently fell back to Windows because WSL is unavailable.
688 // Dispatch happens at resolve time so toggling wsl-only between restarts
689 // is picked up on the next start cycle (the pool's primary instance is
690 // created once at layer init, but configResolve fires on each restart).
691 const describePrimary = Effect.gen(function* () {
692 const persistedSettings = yield* settings.get;
693 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
694 // Only honor wsl-only when WSL is actually usable. If the user
695 // persisted wsl-only but WSL has since become unavailable (wsl.exe
696 // removed, no distro), fall back to the Windows primary instead of
697 // looping forever on preflight failures: the Connections backend
698 // control is hidden while WSL is unavailable, so a stuck WSL primary
699 // would otherwise leave no in-app way back to Windows.
700 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
701 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
702 });
703
704 return DesktopBackendConfiguration.of({
705 resolvePrimary: Effect.gen(function* () {
706 const { useWsl, wslRequested } = yield* describePrimary;
707 if (useWsl) {
708 return yield* buildWslPrimaryConfig;
709 }
710 if (wslRequested) {
711 yield* Effect.logWarning(
712 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
713 );
714 }
715 return yield* buildWindowsPrimaryConfig;
716 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
717 resolvePrimaryLabel: Effect.gen(function* () {
718 const { useWsl, distro } = yield* describePrimary;
719 if (!useWsl) {
720 return environment.platform === "win32" ? "Windows" : "Local environment";
721 }
722 return distro ? `WSL (${distro})` : "WSL";
723 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
724 resolveWsl: (input) =>
725 Effect.gen(function* () {
726 const shared = yield* sharedInputs;
727 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
728 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
729 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
730 Effect.provideService(FileSystem.FileSystem, fileSystem),
731 );
732 }).pipe(
733 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
734 attributes: { port: input.port, distro: input.distro ?? null },
735 }),
736 ),
737 });
738});
739
740export const layer = Layer.effect(DesktopBackendConfiguration, make);