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