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