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

DesktopBackendConfiguration.ts

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