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