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

DesktopBackendConfiguration.ts

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