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

DesktopBackendConfiguration.ts

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