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

DesktopBackendConfiguration.ts

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