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

DesktopBackendConfiguration.ts

983 lines39.9 KB

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