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

DesktopBackendConfiguration.ts

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