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

DesktopBackendConfiguration.ts

757 lines30.8 KB

1import * as NodeOS from "node:os";
2​
3import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
4import type { CuaDriverMcpConfiguration } from "@t3tools/contracts";
5import * as Context from "effect/Context";
6import * as Crypto from "effect/Crypto";
7import * as Effect from "effect/Effect";
8import * as Encoding from "effect/Encoding";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import * as SynchronizedRef from "effect/SynchronizedRef";
15​
16import serverPackageJson from "../../../server/package.json" with { type: "json" };
17​
18import * as DesktopBackendManager from "./DesktopBackendManager.ts";
19import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
20import * as DesktopServerExposure from "./DesktopServerExposure.ts";
21import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
22import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
23import * as DesktopCuaDriver from "../cua/DesktopCuaDriver.ts";
24​
25export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
26 "DesktopBackendObservabilitySettingsReadError",
27 {
28 settingsPath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
34 }
36​
37export class DesktopBackendConfiguration extends Context.Service<
38 DesktopBackendConfiguration,
39 {
40 // Build the Windows-native primary backend's start config. Reads the
41 // primary's port/host/exposure from DesktopServerExposure. Can fail
42 // with PlatformError because bootstrap token generation now uses
43 // crypto.randomBytes under the hood (post Effect 4 migration).
44 readonly resolvePrimary: Effect.Effect<
45 DesktopBackendManager.DesktopBackendStartConfig,
46 PlatformError.PlatformError
47 >;
48 // Build a WSL backend start config for the given distro on the given
49 // port. The WSL backend is always loopback-only (the primary owns LAN
50 // exposure when the user opts in), so this takes the port directly and
51 // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
52 // forwarded to wsl.exe with no -d flag.
53 readonly resolveWsl: (input: {
54 readonly port: number;
55 readonly distro: string | null;
56 }) => Effect.Effect<
57 DesktopBackendManager.DesktopBackendStartConfig,
58 PlatformError.PlatformError
59 >;
60 // The renderer-facing label for the primary instance, derived from the
61 // same decision resolvePrimary makes (including the WSL-availability
62 // fall-back to Windows), so the env switcher can't show "WSL" for a
63 // backend that actually resolved to Windows.
64 readonly resolvePrimaryLabel: Effect.Effect<string>;
65 }
66>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
67​
68interface BackendObservabilitySettings {
69 readonly otlpTracesUrl: Option.Option<string>;
70 readonly otlpMetricsUrl: Option.Option<string>;
72​
73const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
74 otlpTracesUrl: Option.none(),
75 otlpMetricsUrl: Option.none(),
76};
77​
78const DESKTOP_BACKEND_ENV_NAMES = [
79 "T3CODE_PORT",
80 "T3CODE_MODE",
81 "T3CODE_NO_BROWSER",
82 "T3CODE_HOST",
83 "T3CODE_DESKTOP_WS_URL",
84 "T3CODE_DESKTOP_LAN_ACCESS",
85 "T3CODE_DESKTOP_LAN_HOST",
86 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
87 "T3CODE_TAILSCALE_SERVE",
88 "T3CODE_TAILSCALE_SERVE_PORT",
89 // Desktop owns its embedded daemon. Never let inherited development
90 // variables make a local or WSL backend start a second daemon.
91 "T3CODE_CUA_DRIVER_PATH",
92 "T3CODE_CUA_DRIVER_HOST_BUNDLE_ID",
93 "T3CODE_CUA_DRIVER_MODULE_URL",
94] as const;
95​
96// Sensitive env vars that the WSL backend needs but Windows process.env won't
97// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
98// handled separately via a `--dev-url` CLI flag because WSLENV translation of
99// URL-shaped values (colons / slashes) is unreliable.
100const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] 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";
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;
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;
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;
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 readonly cuaDriverMcp: Option.Option<CuaDriverMcpConfiguration>;
377 },
378 ): Effect.fn.Return<
379 DesktopBackendManager.DesktopBackendStartConfig,
380 never,
381 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
382 > {
383 const environment = yield* DesktopEnvironment.DesktopEnvironment;
384 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
385 const backendExposure = yield* serverExposure.backendConfig;
386​
387 const bootstrap = {
388 mode: "desktop" as const,
389 noBrowser: true,
390 port: backendExposure.port,
391 t3Home: environment.baseDir,
392 host: backendExposure.bindHost,
393 desktopBootstrapToken: input.bootstrapToken,
394 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
395 tailscaleServePort: backendExposure.tailscaleServePort,
396 desktopTelemetryFd: 4,
397 desktopTelemetryControlFd: 5,
398 ...Option.match(input.resourceMonitorPath, {
399 onNone: () => ({}),
400 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
401 }),
402 ...Option.match(input.cuaDriverMcp, {
403 onNone: () => ({}),
404 onSome: (cuaDriverMcp) => ({ cuaDriverMcp }),
405 }),
406 ...buildObservabilityFragment(input.observabilitySettings),
407 };
408​
409 return {
410 executablePath: process.execPath,
411 args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
412 entryPath: environment.backendEntryPath,
413 cwd: environment.backendCwd,
414 env: {
415 ...backendChildEnvPatch(),
416 ELECTRON_RUN_AS_NODE: "1",
417 },
418 // Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
419 extendEnv: true,
420 bootstrap,
421 bootstrapDelivery: "fd3",
422 httpBaseUrl: backendExposure.httpBaseUrl,
423 captureOutput: true,
424 preflightFailure: Option.none(),
425 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
426 },
427);
428​
429const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
430 input: SharedBootstrapInput & {
431 readonly port: number;
432 readonly distro: string | null;
433 },
434): Effect.fn.Return<
435 DesktopBackendManager.DesktopBackendStartConfig,
436 never,
437 | DesktopEnvironment.DesktopEnvironment
438 | DesktopWslEnvironment.DesktopWslEnvironment
439 | FileSystem.FileSystem
440> {
441 const environment = yield* DesktopEnvironment.DesktopEnvironment;
442 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
443​
444 // Bind to 0.0.0.0 inside WSL so the backend is reachable both via
445 // WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
446 // -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
447 // Windows. wslhost forwarding is unreliable on some Windows hosts:
448 // the desktop's readiness probe and the renderer's saved-env-style
449 // fetch both saw "Failed to fetch" when the backend only bound to
450 // 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
451 // WSL IP as the renderer-visible URL avoids that dependency.
452 // Security-wise this is acceptable for the local-only WSL backend:
453 // the network it exposes on is the WSL-vEthernet network, not the
454 // LAN; the primary owns LAN exposure when the user opts in.
455 const wslBindHost = "0.0.0.0";
456​
457 const bootstrap = {
458 mode: "desktop" as const,
459 noBrowser: true,
460 port: input.port,
461 // Omit t3Home so the Linux backend uses its own home dir instead of
462 // the Windows-side baseDir (which would be a /mnt/c path and share
463 // the SQLite file with the primary).
464 host: wslBindHost,
465 desktopBootstrapToken: input.bootstrapToken,
466 // PortSchema rejects 0, so when tailscale serve is disabled we still
467 // need a valid number in this slot. The backend reads tailscaleServePort
468 // only when tailscaleServeEnabled is true, so the actual value here is
469 // inert.
470 tailscaleServeEnabled: false,
471 tailscaleServePort: 443,
472 // The packaged sidecar is a Windows executable and cannot run inside the
473 // Linux WSL backend. Keep the field absent instead of passing an unusable
474 // `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
475 // See docs/architecture/resource-telemetry.md.
476 ...buildObservabilityFragment(input.observabilitySettings),
477 };
478​
479 // In packaged builds environment.appRoot is .../resources/app.asar — an
480 // archive FILE. The Windows primary reads its entry through
481 // ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
482 // `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
483 // the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
484 // to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
485 // already a real directory, so this is a no-op.
486 const wslAppRoot = environment.isPackaged
487 ? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
488 : environment.appRoot;
489 const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
490​
491 const preflight = yield* runWslPreflight({
492 distro: input.distro,
493 windowsEntryPath: wslEntryPath,
494 windowsRepoRoot: wslAppRoot,
495 // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
496 // attached to the Windows artifact — see build-desktop-artifact.ts), so the
497 // WSL backend never needs a compiler, node-gyp, or network on first launch.
498 // Compiling from source is a dev-only convenience: a checkout has no shipped
499 // prebuilt, and developers have the toolchain. In packaged builds we instead
500 // surface a clear diagnostic if the prebuilt can't load (unsupported
501 // arch/distro), rather than silently dropping into a fragile runtime build.
502 allowBuild: !environment.isPackaged,
503 });
504​
505 // Every operation after preflight uses the same concrete distro. In
506 // default-tracking mode this closes the race where the system default
507 // changes between probing and spawning the backend.
508 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
509 const distroForConfig = runningDistro ?? input.distro;
510​
511 // Resolve the selected distro's IPv4 address. In mirrored mode the distro
512 // reports a host interface, so use loopback instead; a failed probe also
513 // falls back to loopback and preserves the previous behavior.
514 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
515 const usesSharedNetworkStack = Option.match(distroIp, {
516 onNone: () => false,
517 onSome: (ip) => isLocalHostIpv4(ip),
518 });
519 const rendererHost = usesSharedNetworkStack
520 ? "127.0.0.1"
521 : Option.getOrElse(distroIp, () => "127.0.0.1");
522 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
523​
524 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
525 const forwardedEnv: Record<string, string> = {};
526 const forwardedEnvNames: string[] = [];
527 for (const name of WSL_FORWARDED_ENV_NAMES) {
528 const value = process.env[name];
529 if (value !== undefined && value.length > 0) {
530 forwardedEnv[name] = value;
531 forwardedEnvNames.push(name);
532 }
533 }
534​
535 // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
536 // exports the Windows-side base dir for the primary; if it leaks into
537 // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
538 // /mnt/c, which means both backends read/write the same database and
539 // their env-ids collide).
540 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
541 for (const [key, value] of Object.entries(process.env)) {
542 if (key === "T3CODE_HOME") continue;
543 parentEnvWithoutT3Home[key] = value;
544 }
545 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
546​
547 const baseConfig = {
548 executablePath: "wsl.exe",
549 entryPath: wslEntryPath,
550 cwd: environment.backendCwd,
551 env: {
552 ...parentEnvWithoutT3Home,
553 ...backendChildEnvPatch(),
554 ...forwardedEnv,
555 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
556 },
557 // env is already a complete process.env minus T3CODE_HOME; pass it
558 // verbatim instead of letting the spawner re-merge process.env on top.
559 extendEnv: false,
560 bootstrap,
561 bootstrapDelivery: "stdin" as const,
562 httpBaseUrl,
563 captureOutput: true,
564 ...(runningDistro !== null ? { runningDistro } : {}),
565 };
566​
567 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
568 // config resolution lands in dev/ instead of userdata/. Inheriting through
569 // WSLENV is unreliable in practice (URL-shaped values with colons /
570 // slashes get translated unpredictably depending on flags), and the
571 // packaged build leaves devServerUrl as None anyway.
572 const devUrlArgs = Option.match(environment.devServerUrl, {
573 onNone: () => [] as ReadonlyArray<string>,
574 onSome: (url) => ["--dev-url", url.href],
575 });
576​
577 if (preflight._tag === "Failed") {
578 const retryLimit =
579 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
580 return {
581 ...baseConfig,
582 args: [...distroArgs, "--", "node", "--version"],
583 preflightFailure: Option.some({
584 reason: preflight.reason,
585 fatal: preflight.fatal,
586 ...(retryLimit === undefined ? {} : { retryLimit }),
587 }),
588 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
589 }
590​
591 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
592 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
593 // live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
594 // the process PATH, so `npm install -g ...` fails with NotFound. Pass the
595 // user PATH entries captured by the login-shell preflight. Every dynamic
596 // value is a separate argv entry under `wsl.exe --exec`; no shell command is
597 // involved, so Windows cannot mangle nested quotes and stdin remains reserved
598 // for the bootstrap envelope.
599 const lastSlash = preflight.nodePath.lastIndexOf("/");
600 const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
601 const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
602​
603 return {
604 ...baseConfig,
605 args: [
606 ...distroArgs,
607 "--exec",
608 "env",
609 `PATH=${launchPath}`,
610 preflight.nodePath,
611 preflight.linuxEntryPath,
612 "--bootstrap-fd",
613 "0",
614 ...devUrlArgs,
615 ],
616 preflightFailure: Option.none(),
617 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
618});
619​
620export const make = Effect.gen(function* () {
621 const environment = yield* DesktopEnvironment.DesktopEnvironment;
622 const fileSystem = yield* FileSystem.FileSystem;
623 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
624 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
625 const settings = yield* DesktopAppSettings.DesktopAppSettings;
626 const crypto = yield* Crypto.Crypto;
627 const cuaDriver = yield* Effect.serviceOption(DesktopCuaDriver.DesktopCuaDriver);
628 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
629 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
630 // resolve concurrently; with a plain Ref both could observe None, generate
631 // distinct tokens, and one would overwrite the other — leaving the two
632 // backends holding mismatched tokens and breaking the shared-token
633 // invariant the renderer relies on. modifyEffect serializes the whole
634 // get-or-create so the first caller wins and the rest reuse its token.
635 const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
636 const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
637 Option.match(current, {
638 onSome: (token) => Effect.succeed([token, current] as const),
639 onNone: () =>
640 crypto.randomBytes(24).pipe(
641 Effect.map((bytes) => {
642 const token = Encoding.encodeHex(bytes);
643 return [token, Option.some(token)] as const;
644 }),
645 ),
646 }),
647 );
648​
649 // Both resolvers share the same bootstrap token: the renderer holds a
650 // single token and uses it against whichever backend it's currently
651 // talking to. Observability settings get re-read each resolve so a
652 // hot-swap of the server-settings file is picked up on the next
653 // restart cycle without having to bounce the desktop process.
654 const sharedInputs = Effect.gen(function* () {
655 const bootstrapToken = yield* getOrCreateBootstrapToken;
656 const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
657 Effect.provideService(FileSystem.FileSystem, fileSystem),
658 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
659 );
660 return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
661 });
662​
663 const buildWslPrimaryConfig = Effect.gen(function* () {
664 // wsl-only mode pipes the WSL backend through the same port the
665 // Windows primary would normally take. That way the renderer
666 // still loads from the local-only endpoint advertised by
667 // DesktopServerExposure, and primary-aware code paths (cookie
668 // auth, the env switcher's "primary" id) keep working without
669 // a parallel "secondary" registration.
670 const backendExposure = yield* serverExposure.backendConfig;
671 const persistedSettings = yield* settings.get;
672 const shared = yield* sharedInputs;
673 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
674 return yield* resolveWslStartConfig({
675 ...shared,
676 port: backendExposure.port,
677 distro: persistedSettings.wslDistro,
678 }).pipe(
679 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
680 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
681 Effect.provideService(FileSystem.FileSystem, fileSystem),
682 );
683 });
684​
685 const buildWindowsPrimaryConfig = Effect.gen(function* () {
686 const shared = yield* sharedInputs;
687 const cuaDriverMcp = yield* Option.match(cuaDriver, {
688 onNone: () => Effect.succeed(Option.none()),
689 onSome: (service) => service.mcpConfiguration,
690 });
691 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
692 Effect.provideService(FileSystem.FileSystem, fileSystem),
693 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
694 );
695 return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath, cuaDriverMcp }).pipe(
696 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
697 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
698 );
699 });
700​
701 // Single source of truth for what the primary actually runs as. Both
702 // the start-config dispatch and the renderer-facing label derive from
703 // this, so they can't disagree — e.g. the label reading "WSL" while the
704 // config silently fell back to Windows because WSL is unavailable.
705 // Dispatch happens at resolve time so toggling wsl-only between restarts
706 // is picked up on the next start cycle (the pool's primary instance is
707 // created once at layer init, but configResolve fires on each restart).
708 const describePrimary = Effect.gen(function* () {
709 const persistedSettings = yield* settings.get;
710 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
711 // Only honor wsl-only when WSL is actually usable. If the user
712 // persisted wsl-only but WSL has since become unavailable (wsl.exe
713 // removed, no distro), fall back to the Windows primary instead of
714 // looping forever on preflight failures: the Connections backend
715 // control is hidden while WSL is unavailable, so a stuck WSL primary
716 // would otherwise leave no in-app way back to Windows.
717 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
718 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
719 });
720​
721 return DesktopBackendConfiguration.of({
722 resolvePrimary: Effect.gen(function* () {
723 const { useWsl, wslRequested } = yield* describePrimary;
724 if (useWsl) {
725 return yield* buildWslPrimaryConfig;
726 }
727 if (wslRequested) {
728 yield* Effect.logWarning(
729 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
730 );
731 }
732 return yield* buildWindowsPrimaryConfig;
733 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
734 resolvePrimaryLabel: Effect.gen(function* () {
735 const { useWsl, distro } = yield* describePrimary;
736 if (!useWsl) {
737 return environment.platform === "win32" ? "Windows" : "Local environment";
738 }
739 return distro ? `WSL (${distro})` : "WSL";
740 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
741 resolveWsl: (input) =>
742 Effect.gen(function* () {
743 const shared = yield* sharedInputs;
744 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
745 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
746 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
747 Effect.provideService(FileSystem.FileSystem, fileSystem),
748 );
749 }).pipe(
750 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
751 attributes: { port: input.port, distro: input.distro ?? null },
752 }),
753 ),
754 });
755});
756​
757export const layer = Layer.effect(DesktopBackendConfiguration, make);