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