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

DesktopBackendConfiguration.ts

981 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 ...Option.match(input.resourceMonitorPath, {
572 onNone: () => ({}),
573 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
574 }),
575 ...buildObservabilityFragment(input.observabilitySettings),
576 };
577​
578 return {
579 executablePath: process.execPath,
580 // Packaged builds only, so a dev instance never shares the cache with the
581 // prod app it is often run from. `--require` rather than NODE_COMPILE_CACHE,
582 // so the setting does not leak into the provider and terminal processes
583 // the backend starts.
584 args: [
585 ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
586 environment.backendEntryPath,
587 "--bootstrap-fd",
588 "3",
589 ],
590 entryPath: environment.backendEntryPath,
591 cwd: environment.backendCwd,
592 env: {
593 ...backendChildEnvPatch(),
594 ELECTRON_RUN_AS_NODE: "1",
595 },
596 // Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
597 extendEnv: true,
598 bootstrap,
599 bootstrapDelivery: "fd3",
600 httpBaseUrl: backendExposure.httpBaseUrl,
601 captureOutput: true,
602 preflightFailure: Option.none(),
603 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
604 },
605);
606​
607const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
608 input: SharedBootstrapInput & {
609 readonly port: number;
610 readonly distro: string | null;
611 },
612): Effect.fn.Return<
613 DesktopBackendManager.DesktopBackendStartConfig,
614 never,
615 | DesktopEnvironment.DesktopEnvironment
616 | DesktopWslEnvironment.DesktopWslEnvironment
617 | DesktopWslServerTree.DesktopWslServerTree
618 | FileSystem.FileSystem
619> {
620 const environment = yield* DesktopEnvironment.DesktopEnvironment;
621 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
622 const fileSystem = yield* FileSystem.FileSystem;
623​
624 // Bind to 0.0.0.0 inside WSL so the backend is reachable both via
625 // WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
626 // -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
627 // Windows. wslhost forwarding is unreliable on some Windows hosts:
628 // the desktop's readiness probe and the renderer's saved-env-style
629 // fetch both saw "Failed to fetch" when the backend only bound to
630 // 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
631 // WSL IP as the renderer-visible URL avoids that dependency.
632 // Security-wise this is acceptable for the local-only WSL backend:
633 // the network it exposes on is the WSL-vEthernet network, not the
634 // LAN; the primary owns LAN exposure when the user opts in.
635 const wslBindHost = "0.0.0.0";
636​
637 const bootstrap = {
638 mode: "desktop" as const,
639 noBrowser: true,
640 port: input.port,
641 // Omit t3Home so the Linux backend uses its own home dir instead of
642 // the Windows-side baseDir (which would be a /mnt/c path and share
643 // the SQLite file with the primary).
644 host: wslBindHost,
645 desktopBootstrapToken: input.bootstrapToken,
646 desktopBootstrapSecret: input.bootstrapSecret,
647 // PortSchema rejects 0, so when tailscale serve is disabled we still
648 // need a valid number in this slot. The backend reads tailscaleServePort
649 // only when tailscaleServeEnabled is true, so the actual value here is
650 // inert.
651 tailscaleServeEnabled: false,
652 tailscaleServePort: 443,
653 // The packaged sidecar is a Windows executable and cannot run inside the
654 // Linux WSL backend. Keep the field absent instead of passing an unusable
655 // `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
656 // See docs/internals/resource-telemetry.md.
657 ...buildObservabilityFragment(input.observabilitySettings),
658 };
659​
660 // The archive is the primary packaged WSL path: it installs directly into
661 // the distro's ext4 filesystem. The server.asar extraction service is only
662 // consulted lazily if the archive is unavailable or cannot be staged.
663 const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);
664 const archiveHashPath = environment.path.join(
665 environment.resourcesPath,
666 WSL_RUNTIME_ARCHIVE_HASH_NAME,
667 );
668​
669 const hasArchive = environment.isPackaged
670 ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))
671 : false;
672 const archiveHash = hasArchive
673 ? yield* fileSystem.readFileString(archiveHashPath).pipe(
674 Effect.map(parseWslRuntimeArchiveHash),
675 Effect.orElseSucceed(() => null),
676 )
677 : null;
678 if (hasArchive && archiveHash === null) {
679 yield* Effect.logWarning(
680 "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",
681 { hashPath: archiveHashPath },
682 );
683 }
684​
685 const preflight = yield* runWslPreflight({
686 distro: input.distro,
687 runtimeArchive:
688 archiveHash === null
689 ? null
690 : {
691 windowsPath: archivePath,
692 // The verified archive bytes are the cache identity. Release builds
693 // embed the release version and pnpm install metadata, so the
694 // archive changes on every update even when application logic does
695 // not. Later launches of that update still reuse this directory.
696 runtimeId: `sha256-${archiveHash}`,
697 sha256: archiveHash,
698 },
699 // Packaged builds run the self-contained Linux runtime and, on fallback,
700 // whatever Linux node-pty the mounted tree carries, so the WSL backend never
701 // needs a compiler, node-gyp, or network on first launch. Compiling from
702 // source is a dev-only convenience: a checkout has no Linux binary, and
703 // developers have the toolchain. In packaged builds we instead surface a
704 // clear diagnostic if the binary can't load (unsupported arch/distro),
705 // rather than silently dropping into a fragile runtime build.
706 allowBuild: !environment.isPackaged,
707 });
708​
709 // Every operation after preflight uses the same concrete distro. In
710 // default-tracking mode this closes the race where the system default
711 // changes between probing and spawning the backend.
712 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
713 const distroForConfig = runningDistro ?? input.distro;
714​
715 // Resolve the selected distro's IPv4 address. In mirrored mode the distro
716 // reports a host interface, so use loopback instead; a failed probe also
717 // falls back to loopback and preserves the previous behavior.
718 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
719 const usesSharedNetworkStack = Option.match(distroIp, {
720 onNone: () => false,
721 onSome: (ip) => isLocalHostIpv4(ip),
722 });
723 const rendererHost = usesSharedNetworkStack
724 ? "127.0.0.1"
725 : Option.getOrElse(distroIp, () => "127.0.0.1");
726 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
727​
728 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
729 const forwardedEnv: Record<string, string> = {};
730 const forwardedEnvNames: string[] = [];
731 for (const name of WSL_FORWARDED_ENV_NAMES) {
732 const value = process.env[name];
733 if (value !== undefined && value.length > 0) {
734 forwardedEnv[name] = value;
735 forwardedEnvNames.push(name);
736 }
737 }
738​
739 // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
740 // exports the Windows-side base dir for the primary; if it leaks into
741 // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
742 // /mnt/c, which means both backends read/write the same database and
743 // their env-ids collide).
744 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
745 for (const [key, value] of Object.entries(process.env)) {
746 if (key === "T3CODE_HOME") continue;
747 parentEnvWithoutT3Home[key] = value;
748 }
749 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
750​
751 const baseConfig = {
752 executablePath: "wsl.exe",
753 entryPath:
754 preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,
755 cwd: environment.backendCwd,
756 env: {
757 ...parentEnvWithoutT3Home,
758 ...backendChildEnvPatch(),
759 ...forwardedEnv,
760 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
761 },
762 // env is already a complete process.env minus T3CODE_HOME; pass it
763 // verbatim instead of letting the spawner re-merge process.env on top.
764 extendEnv: false,
765 bootstrap,
766 bootstrapDelivery: "stdin" as const,
767 httpBaseUrl,
768 captureOutput: true,
769 ...(runningDistro !== null ? { runningDistro } : {}),
770 };
771​
772 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
773 // config resolution lands in dev/ instead of userdata/. The packaged build
774 // leaves devServerUrl as None.
775 const devUrlArgs = Option.match(environment.devServerUrl, {
776 onNone: () => [] as ReadonlyArray<string>,
777 onSome: (url) => ["--dev-url", url.href],
778 });
779​
780 if (preflight._tag === "Failed") {
781 const retryLimit =
782 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
783 return {
784 ...baseConfig,
785 args: [...distroArgs, "--", "node", "--version"],
786 preflightFailure: Option.some({
787 reason: preflight.reason,
788 fatal: preflight.fatal,
789 ...(retryLimit === undefined ? {} : { retryLimit }),
790 }),
791 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
792 }
793​
794 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
795 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
796 // live on the user's login-shell PATH, which `wsl.exe --exec` does NOT put on
797 // the process PATH, so `npm install -g ...` fails with NotFound. Pass the
798 // user PATH entries captured by the preflight. Every dynamic value is a
799 // separate argv entry under `wsl.exe --exec`; no shell command is involved,
800 // so Windows cannot mangle nested quotes and stdin remains reserved for the
801 // bootstrap envelope. A node-script runtime additionally leads with the
802 // probed Node's bin dir so the server cannot pick up a different node than
803 // the one node-pty was probed with.
804 const runtime = preflight.runtime;
805 const launchPath =
806 runtime.kind === "executable"
807 ? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
808 : `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
809 const command =
810 runtime.kind === "executable"
811 ? [runtime.entryPath]
812 : [runtime.nodePath, runtime.linuxEntryPath];
813​
814 return {
815 ...baseConfig,
816 args: [
817 ...distroArgs,
818 "--exec",
819 "env",
820 `PATH=${launchPath}`,
821 ...command,
822 "--bootstrap-fd",
823 "0",
824 ...devUrlArgs,
825 ],
826 preflightFailure: Option.none(),
827 ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),
828 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
829});
830​
831/** @public Service construction is part of the canonical Effect module API. */
832export const make = Effect.gen(function* () {
833 const environment = yield* DesktopEnvironment.DesktopEnvironment;
834 const fileSystem = yield* FileSystem.FileSystem;
835 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
836 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
837 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
838 const settings = yield* DesktopAppSettings.DesktopAppSettings;
839 const crypto = yield* Crypto.Crypto;
840 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
841 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
842 // resolve concurrently; with a plain Ref both could observe None, generate
843 // distinct secrets, and one would overwrite the other — leaving the two
844 // backends deriving mismatched tokens and breaking the shared-token
845 // invariant the renderer relies on. modifyEffect serializes the whole
846 // get-or-create so the first caller wins and the rest reuse its secret.
847 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
848 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
849 Option.match(current, {
850 onSome: (secret) => Effect.succeed([secret, current] as const),
851 onNone: () =>
852 crypto.randomBytes(32).pipe(
853 Effect.map((bytes) => {
854 const secret = Hex.encode(bytes);
855 return [secret, Option.some(secret)] as const;
856 }),
857 ),
858 }),
859 );
860​
861 // Both resolvers share the same bootstrap token: the renderer holds a
862 // single token and uses it against whichever backend it's currently
863 // talking to. Observability settings get re-read each resolve so a
864 // hot-swap of the server-settings file is picked up on the next
865 // restart cycle without having to bounce the desktop process.
866 const sharedInputs = Effect.gen(function* () {
867 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
868 const bootstrapToken = currentDesktopBootstrapToken(
869 bootstrapSecret,
870 yield* Clock.currentTimeMillis,
871 );
872 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
873 Effect.provideService(FileSystem.FileSystem, fileSystem),
874 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
875 );
876 return {
877 bootstrapToken,
878 bootstrapSecret,
879 observabilitySettings,
880 } satisfies SharedBootstrapInput;
881 });
882​
883 const buildWslPrimaryConfig = Effect.gen(function* () {
884 // wsl-only mode pipes the WSL backend through the same port the
885 // Windows primary would normally take. That way the renderer
886 // still loads from the local-only endpoint advertised by
887 // DesktopServerExposure, and primary-aware code paths (cookie
888 // auth, the env switcher's "primary" id) keep working without
889 // a parallel "secondary" registration.
890 const backendExposure = yield* serverExposure.backendConfig;
891 const persistedSettings = yield* settings.get;
892 const shared = yield* sharedInputs;
893 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
894 return yield* resolveWslStartConfig({
895 ...shared,
896 port: backendExposure.port,
897 distro: persistedSettings.wslDistro,
898 }).pipe(
899 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
900 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
901 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
902 Effect.provideService(FileSystem.FileSystem, fileSystem),
903 );
904 });
905​
906 const buildWindowsPrimaryConfig = Effect.gen(function* () {
907 const shared = yield* sharedInputs;
908 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
909 Effect.provideService(FileSystem.FileSystem, fileSystem),
910 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
911 );
912 return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
913 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
914 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
915 );
916 });
917​
918 // Single source of truth for what the primary actually runs as. Both
919 // the start-config dispatch and the renderer-facing label derive from
920 // this, so they can't disagree — e.g. the label reading "WSL" while the
921 // config silently fell back to Windows because WSL is unavailable.
922 // Dispatch happens at resolve time so toggling wsl-only between restarts
923 // is picked up on the next start cycle (the pool's primary instance is
924 // created once at layer init, but configResolve fires on each restart).
925 const describePrimary = Effect.gen(function* () {
926 const persistedSettings = yield* settings.get;
927 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
928 // Only honor wsl-only when WSL is actually usable. If the user
929 // persisted wsl-only but WSL has since become unavailable (wsl.exe
930 // removed, no distro), fall back to the Windows primary instead of
931 // looping forever on preflight failures: the Connections backend
932 // control is hidden while WSL is unavailable, so a stuck WSL primary
933 // would otherwise leave no in-app way back to Windows.
934 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
935 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
936 });
937​
938 const currentBootstrapToken = Effect.gen(function* () {
939 const secret = yield* getOrCreateBootstrapSecret;
940 return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
941 });
942​
943 return DesktopBackendConfiguration.of({
944 currentBootstrapToken,
945 resolvePrimary: Effect.gen(function* () {
946 const { useWsl, wslRequested } = yield* describePrimary;
947 if (useWsl) {
948 return yield* buildWslPrimaryConfig;
949 }
950 if (wslRequested) {
951 yield* Effect.logWarning(
952 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
953 );
954 }
955 return yield* buildWindowsPrimaryConfig;
956 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
957 resolvePrimaryLabel: Effect.gen(function* () {
958 const { useWsl, distro } = yield* describePrimary;
959 if (!useWsl) {
960 return environment.platform === "win32" ? "Windows" : "Local environment";
961 }
962 return distro ? `WSL (${distro})` : "WSL";
963 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
964 resolveWsl: (input) =>
965 Effect.gen(function* () {
966 const shared = yield* sharedInputs;
967 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
968 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
969 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
970 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
971 Effect.provideService(FileSystem.FileSystem, fileSystem),
972 );
973 }).pipe(
974 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
975 attributes: { port: input.port, distro: input.distro ?? null },
976 }),
977 ),
978 });
979});
980​
981export const layer = Layer.effect(DesktopBackendConfiguration, make);