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

DesktopBackendConfiguration.ts

876 lines35.9 KB

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