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 DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
24import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
25import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
26import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
27
28export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedError<DesktopBackendObservabilitySettingsReadError>()(
29 "DesktopBackendObservabilitySettingsReadError",
30 {
31 settingsPath: Schema.String,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
37 }
38}
39
40export class DesktopBackendConfiguration extends Context.Service<
41 DesktopBackendConfiguration,
42 {
43 // Build the Windows-native primary backend's start config. Reads the
44 // primary's port/host/exposure from DesktopServerExposure. Can fail
45 // with PlatformError because bootstrap token generation now uses
46 // crypto.randomBytes under the hood (post Effect 4 migration).
47 readonly resolvePrimary: Effect.Effect<
48 DesktopBackendManager.DesktopBackendStartConfig,
49 PlatformError.PlatformError
50 >;
51 // Build a WSL backend start config for the given distro on the given
52 // port. The WSL backend is always loopback-only (the primary owns LAN
53 // exposure when the user opts in), so this takes the port directly and
54 // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
55 // forwarded to wsl.exe with no -d flag.
56 readonly resolveWsl: (input: {
57 readonly port: number;
58 readonly distro: string | null;
59 }) => Effect.Effect<
60 DesktopBackendManager.DesktopBackendStartConfig,
61 PlatformError.PlatformError
62 >;
63 // The renderer-facing label for the primary instance, derived from the
64 // same decision resolvePrimary makes (including the WSL-availability
65 // fall-back to Windows), so the env switcher can't show "WSL" for a
66 // backend that actually resolved to Windows.
67 readonly resolvePrimaryLabel: Effect.Effect<string>;
68 // The bootstrap token the renderer should present right now. It rotates
69 // every window (derived from the secret every backend was launched with),
70 // so the renderer never holds one long-lived admin credential.
71 readonly currentBootstrapToken: Effect.Effect<string, PlatformError.PlatformError>;
72 }
73>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
74
75interface BackendObservabilitySettings {
76 readonly otlpTracesUrl: Option.Option<string>;
77 readonly otlpMetricsUrl: Option.Option<string>;
78 readonly otlpLogsUrl: Option.Option<string>;
79}
80
81const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
82 otlpTracesUrl: Option.none(),
83 otlpMetricsUrl: Option.none(),
84 otlpLogsUrl: Option.none(),
85};
86
87const DESKTOP_BACKEND_ENV_NAMES = [
88 "T3CODE_PORT",
89 "T3CODE_MODE",
90 "T3CODE_NO_BROWSER",
91 "T3CODE_HOST",
92 "T3CODE_DESKTOP_WS_URL",
93 "T3CODE_DESKTOP_LAN_ACCESS",
94 "T3CODE_DESKTOP_LAN_HOST",
95 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
96 "T3CODE_TAILSCALE_SERVE",
97 "T3CODE_TAILSCALE_SERVE_PORT",
98] as const;
99
100// Env vars that the WSL backend needs but Windows process.env won't forward
101// across the wsl.exe boundary without WSLENV. The dev-server URL travels as
102// the `--dev-url` CLI flag instead.
103const WSL_FORWARDED_ENV_NAMES = [
104 "OPENAI_API_KEY",
105 "ANTHROPIC_API_KEY",
106 "T3CODE_TELEMETRY_ENABLED",
107 // Otherwise the WSL server keeps exporting to endpoints from the bootstrap.
108 "T3CODE_OTEL_SDK_DISABLED",
109 "OTEL_SDK_DISABLED",
110 "T3CODE_OTLP_HEADERS",
111 "T3CODE_OTLP_PROTOCOL",
112 // Forwarded without a WSLENV flag, so the values arrive untranslated. The
113 // server prefers an OTEL endpoint over the bootstrap envelope, so the T3 URLs
114 // travel as variables to keep winning inside the distro as they do on Windows.
115 "T3CODE_OTLP_TRACES_URL",
116 "T3CODE_OTLP_METRICS_URL",
117 "T3CODE_OTLP_LOGS_URL",
118 "OTEL_EXPORTER_OTLP_ENDPOINT",
119 "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
120 "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
121 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
122 "OTEL_EXPORTER_OTLP_HEADERS",
123 "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
124 "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
125 "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
126 "OTEL_EXPORTER_OTLP_PROTOCOL",
127 "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL",
128 "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",
129 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
130 "OTEL_TRACES_EXPORTER",
131 "OTEL_METRICS_EXPORTER",
132 "OTEL_LOGS_EXPORTER",
133] as const;
134
135const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
136
137const nodeBinDirOf = (nodePath: string): string => {
138 const lastSlash = nodePath.lastIndexOf("/");
139 return lastSlash > 0 ? nodePath.slice(0, lastSlash) : "/usr/bin";
140};
141
142const backendChildEnvPatch = (): Record<string, string | undefined> =>
143 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
144
145const getWslEnvEntryName = (entry: string): string => {
146 const slashIndex = entry.indexOf("/");
147 return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
148};
149
150const mergeWslEnv = (
151 existingWslEnv: string | undefined,
152 forwardedEnvNames: ReadonlyArray<string>,
153): string | undefined => {
154 const existing = existingWslEnv?.trim() ?? "";
155
156 // Names already declared, so we don't forward a duplicate. We parse the
157 // existing value only for this membership test — the string itself is
158 // preserved verbatim below rather than re-serialized.
159 const seenNames = new Set(
160 existing
161 .split(":")
162 .map((entry) => getWslEnvEntryName(entry.trim()))
163 .filter((name) => name.length > 0),
164 );
165
166 const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
167
168 // Preserve the user's WSLENV exactly as Windows handed it to us — empty
169 // "::" segments and duplicate entries are harmless no-ops to WSL and not
170 // ours to normalize — and only append the secrets we need to forward
171 // across the wsl.exe boundary.
172 const parts = [existing, ...additions].filter((part) => part.length > 0);
173 return parts.length > 0 ? parts.join(":") : undefined;
174};
175
176const logBackendObservabilitySettingsReadFailure = (
177 settingsPath: string,
178 cause: PlatformError.PlatformError,
179) => {
180 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
181 return Effect.logWarning(error).pipe(
182 Effect.annotateLogs({
183 component: "desktop-backend-configuration",
184 error,
185 }),
186 );
187};
188
189function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
190 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
191}
192
193const resolveResourceMonitorPath = Effect.fn(
194 "desktop.backendConfiguration.resolveResourceMonitorPath",
195)(function* () {
196 const environment = yield* DesktopEnvironment.DesktopEnvironment;
197 const fileSystem = yield* FileSystem.FileSystem;
198 const binaryName = resourceMonitorBinaryName(environment.platform);
199 const candidates = environment.isDevelopment
200 ? [
201 environment.path.join(
202 environment.rootDir,
203 "native/resource-monitor/target/release",
204 binaryName,
205 ),
206 environment.path.join(
207 environment.rootDir,
208 "native/resource-monitor/target/debug",
209 binaryName,
210 ),
211 ]
212 : environment.isPackaged
213 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
214 : environment.resolveResourcePathCandidates(
215 environment.path.join("resource-monitor", binaryName),
216 );
217
218 for (const candidate of candidates) {
219 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
220 return Option.some(candidate);
221 }
222 }
223
224 return Option.none<string>();
225});
226
227const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
228 const fileSystem = yield* FileSystem.FileSystem;
229 const environment = yield* DesktopEnvironment.DesktopEnvironment;
230 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
231 Effect.asSome,
232 Effect.catchTags({
233 PlatformError: (cause) =>
234 cause.reason._tag === "NotFound"
235 ? Effect.succeedNone
236 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
237 Effect.as(Option.none()),
238 ),
239 }),
240 );
241 if (Option.isNone(raw)) {
242 return emptyBackendObservabilitySettings;
243 }
244
245 const parsed = parsePersistedServerObservabilitySettings(raw.value);
246 return {
247 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
248 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
249 otlpLogsUrl: Option.fromNullishOr(parsed.otlpLogsUrl),
250 };
251});
252
253// The bootstrap carries the OTLP endpoints to every backend, including a WSL
254// child that lacks the variables. The T3 URLs also travel as variables in
255// WSL_FORWARDED_ENV_NAMES so they outrank a forwarded OTEL endpoint. Env beats
256// the persisted settings file, matching the precedence resolveServerConfig and
257// DesktopObservability apply.
258const readBackendObservabilitySettings = Effect.gen(function* () {
259 const environment = yield* DesktopEnvironment.DesktopEnvironment;
260 const persisted = yield* readPersistedBackendObservabilitySettings;
261 return {
262 otlpTracesUrl: Option.orElse(environment.otlpTracesUrl, () => persisted.otlpTracesUrl),
263 otlpMetricsUrl: Option.orElse(environment.otlpMetricsUrl, () => persisted.otlpMetricsUrl),
264 otlpLogsUrl: Option.orElse(environment.otlpLogsUrl, () => persisted.otlpLogsUrl),
265 } satisfies BackendObservabilitySettings;
266});
267
268interface SharedBootstrapInput {
269 readonly bootstrapToken: string;
270 readonly bootstrapSecret: string;
271 readonly observabilitySettings: BackendObservabilitySettings;
272}
273
274// What the launch runs inside the distro. The staged runtime is the release's
275// self-contained `t3` executable (Node inside); the mounted server tree is a
276// script that needs the distro's own Node.
277type WslPreflightRuntime =
278 | {
279 readonly kind: "executable";
280 readonly entryPath: string;
281 }
282 | {
283 readonly kind: "node-script";
284 // Absolute path to the node binary the preflight validated after the
285 // shared remote resolver repaired PATH. The launch must use this exact
286 // path so it doesn't fall through to a different/old node than the one
287 // node-pty was probed with.
288 readonly nodePath: string;
289 readonly linuxEntryPath: string;
290 };
291
292interface WslPreflightSuccess {
293 readonly _tag: "Ready";
294 readonly runningDistro: string;
295 readonly windowsEntryPath: string;
296 readonly runtime: WslPreflightRuntime;
297 // PATH captured from the user's login shell. The launch forwards this value
298 // directly without a shell so the server can spawn provider CLIs by name.
299 readonly resolvedPath: string;
300 // Identifies the distro-local runtime cache selected from the packaged archive.
301 readonly runtimeId?: string;
302}
303
304interface WslPreflightFailure {
305 readonly _tag: "Failed";
306 readonly reason: string;
307 // Fatal: the WSL distro is misconfigured (no node, wrong version, missing
308 // build tools) and retrying won't help — surface it and (wsl-only) fall back
309 // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
310 // boots), with a bounded window for self-healing before fallback.
311 readonly fatal: boolean;
312 readonly retryLimit?: number;
313}
314
315const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
316const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
317const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
318const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
319
320const parseWslRuntimeArchiveHash = (value: string): string | null => {
321 const trimmed = value.trim();
322 return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
323};
324
325type FailedNodePtyResult = Extract<
326 DesktopWslEnvironment.EnsureWslNodePtyResult,
327 { readonly ok: false }
328>;
329
330const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
331 readonly distro: string | null;
332 readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;
333 readonly allowBuild: boolean;
334}): Effect.fn.Return<
335 WslPreflightSuccess | WslPreflightFailure,
336 never,
337 | DesktopEnvironment.DesktopEnvironment
338 | DesktopWslEnvironment.DesktopWslEnvironment
339 | DesktopWslServerTree.DesktopWslServerTree
340 | FileSystem.FileSystem
341> {
342 const environment = yield* DesktopEnvironment.DesktopEnvironment;
343 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
344 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
345 const fileSystem = yield* FileSystem.FileSystem;
346
347 const wslAvailable = yield* wslEnv.isAvailable;
348 if (!wslAvailable) {
349 return {
350 _tag: "Failed",
351 reason: "WSL is not available on this system",
352 fatal: false,
353 } as const;
354 }
355
356 const distroProbe = yield* wslEnv.probeDistros.pipe(
357 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
358 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
359 );
360 if (distroProbe._tag === "Failure") {
361 return {
362 _tag: "Failed",
363 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
364 fatal: false,
365 } as const;
366 }
367
368 const installedDistros = distroProbe.distros;
369 const runningDistro = input.distro
370 ? (installedDistros.find(
371 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
372 )?.name ?? null)
373 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
374 if (runningDistro === null) {
375 return {
376 _tag: "Failed",
377 reason: input.distro
378 ? `WSL distro is not installed: ${input.distro}`
379 : installedDistros.length === 0
380 ? "WSL has no installed distributions"
381 : "WSL has no default distribution",
382 fatal: true,
383 } as const;
384 }
385
386 const nodePtyOptions = {
387 allowBuild: input.allowBuild,
388 nodeEngineRange: serverPackageJson.engines.node,
389 };
390 const failedNodePty = (result: FailedNodePtyResult) =>
391 ({
392 _tag: "Failed",
393 reason: `WSL node-pty unavailable: ${result.reason}`,
394 fatal: result.fatal,
395 ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),
396 }) as const;
397
398 // The mounted server tree is the fallback runtime: the Windows-side copy the
399 // distro reads over /mnt. Slower to launch from, but always installed.
400 const resolveMountedAppRoot = Effect.gen(function* () {
401 const serverTree = yield* wslServerTree.ensure;
402 if (!serverTree.ok) {
403 return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;
404 }
405 const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");
406 const entryExists = yield* fileSystem
407 .exists(windowsEntryPath)
408 .pipe(Effect.orElseSucceed(() => false));
409 if (!entryExists) {
410 return {
411 ok: false,
412 reason: `missing server entry at ${windowsEntryPath}`,
413 fatal: true,
414 } as const;
415 }
416 const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);
417 return Option.isNone(mountedAppRoot)
418 ? ({
419 ok: false,
420 reason: `wslpath conversion failed for ${serverTree.root}`,
421 fatal: false,
422 } as const)
423 : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);
424 });
425
426 // Set once a staged runtime has been ruled out by the probe, and carried
427 // through the mounted attempt: if the mounted tree works the cache is the
428 // broken part and gets invalidated, and if the mounted tree returns its own
429 // fatal verdict the cached reason is the more actionable one to report.
430 // A transient mounted failure is neither — it rules nothing out, so it stays
431 // retryable and the staged verdict waits for an attempt that can answer.
432 let stagedFailure: { readonly runtimeId: string; readonly reason: string } | undefined;
433 const failedStaged = (failure: { readonly reason: string }) =>
434 ({
435 _tag: "Failed",
436 reason: `WSL runtime unavailable: ${failure.reason}`,
437 fatal: true,
438 }) as const;
439
440 if (input.runtimeArchive !== null) {
441 const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
442 if (runtime.ok) {
443 // The staged runtime supplies its own Node and node-pty. Provider PATH
444 // discovery must not require either dependency for runtime readiness.
445 const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
446 if (stagedProbe.ok) {
447 yield* wslServerTree.cleanupLegacy;
448 return {
449 _tag: "Ready",
450 runningDistro,
451 windowsEntryPath: environment.backendEntryPath,
452 runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
453 resolvedPath: stagedProbe.resolvedPath,
454 runtimeId: input.runtimeArchive.runtimeId,
455 } as const;
456 }
457 yield* Effect.logWarning(
458 "The staged WSL runtime did not start; retrying from the mounted server tree.",
459 { reason: stagedProbe.reason },
460 );
461 stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
462 } else {
463 yield* Effect.logWarning(
464 "Could not stage the WSL runtime; launching from the mounted server tree instead.",
465 { reason: runtime.reason },
466 );
467 }
468 }
469
470 const mounted = yield* resolveMountedAppRoot;
471 if (!mounted.ok) {
472 return stagedFailure && mounted.fatal
473 ? failedStaged(stagedFailure)
474 : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
475 }
476
477 const nodePtyResult = yield* wslEnv.ensureNodePty(
478 runningDistro,
479 mounted.linuxAppRoot,
480 nodePtyOptions,
481 );
482 if (!nodePtyResult.ok) {
483 // Substituting the staged verdict for a transient mounted failure would
484 // turn a retryable failure into a fatal one, ending the WSL attempt (and,
485 // in wsl-only mode, persisting Windows) before the slow /mnt path had a
486 // chance to answer and clear the bad cache.
487 return stagedFailure && nodePtyResult.fatal
488 ? failedStaged(stagedFailure)
489 : failedNodePty(nodePtyResult);
490 }
491
492 // The mounted tree runs what the cache could not, so the cache is the broken
493 // copy: revoke its ready marker so the next launch reinstalls it instead of
494 // reusing a tree that has already been proven unloadable.
495 if (stagedFailure) {
496 yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);
497 }
498
499 return {
500 _tag: "Ready",
501 runningDistro,
502 windowsEntryPath: mounted.windowsEntryPath,
503 runtime: {
504 kind: "node-script",
505 nodePath: nodePtyResult.nodePath,
506 linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
507 },
508 resolvedPath: nodePtyResult.resolvedPath,
509 } as const;
510});
511
512// True when the given IPv4 belongs to a Windows-side network
513// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
514// host's, which is the signature we use to detect that mode and
515// switch the renderer URL to loopback.
516const isLocalHostIpv4 = (ip: string): boolean => {
517 const interfaces = NodeOS.networkInterfaces();
518 for (const list of Object.values(interfaces)) {
519 if (!list) continue;
520 for (const entry of list) {
521 // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
522 // the Node build Electron ships (41 / Node 22, verified), but some Node
523 // builds report the numeric 4. Normalize to a string so a future runtime
524 // bump can't silently break mirrored-mode detection and leave the
525 // renderer pointed at the distro IP instead of loopback.
526 const family = String(entry.family);
527 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
528 }
529 }
530 return false;
531};
532
533const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
534 ...Option.match(observabilitySettings.otlpTracesUrl, {
535 onNone: () => ({}),
536 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
537 }),
538 ...Option.match(observabilitySettings.otlpMetricsUrl, {
539 onNone: () => ({}),
540 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
541 }),
542 ...Option.match(observabilitySettings.otlpLogsUrl, {
543 onNone: () => ({}),
544 onSome: (otlpLogsUrl) => ({ otlpLogsUrl }),
545 }),
546});
547
548const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
549 function* (
550 input: SharedBootstrapInput & {
551 readonly resourceMonitorPath: Option.Option<string>;
552 readonly cliPath: Option.Option<string>;
553 readonly shellEnvironmentPrepared: boolean;
554 },
555 ): Effect.fn.Return<
556 DesktopBackendManager.DesktopBackendStartConfig,
557 never,
558 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
559 > {
560 const environment = yield* DesktopEnvironment.DesktopEnvironment;
561 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
562 const backendExposure = yield* serverExposure.backendConfig;
563
564 const bootstrap = {
565 mode: "desktop" as const,
566 noBrowser: true,
567 port: backendExposure.port,
568 t3Home: environment.baseDir,
569 host: backendExposure.bindHost,
570 desktopBootstrapToken: input.bootstrapToken,
571 desktopBootstrapSecret: input.bootstrapSecret,
572 // Failed Windows probes leave server hydration enabled for another attempt.
573 shellEnvironmentPrepared: input.shellEnvironmentPrepared,
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 shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
846 const fileSystem = yield* FileSystem.FileSystem;
847 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
848 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
849 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
850 const settings = yield* DesktopAppSettings.DesktopAppSettings;
851 const crypto = yield* Crypto.Crypto;
852 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
853 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
854 // resolve concurrently; with a plain Ref both could observe None, generate
855 // distinct secrets, and one would overwrite the other — leaving the two
856 // backends deriving mismatched tokens and breaking the shared-token
857 // invariant the renderer relies on. modifyEffect serializes the whole
858 // get-or-create so the first caller wins and the rest reuse its secret.
859 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
860 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
861 Option.match(current, {
862 onSome: (secret) => Effect.succeed([secret, current] as const),
863 onNone: () =>
864 crypto.randomBytes(32).pipe(
865 Effect.map((bytes) => {
866 const secret = Hex.encode(bytes);
867 return [secret, Option.some(secret)] as const;
868 }),
869 ),
870 }),
871 );
872
873 // Both resolvers share the same bootstrap token: the renderer holds a
874 // single token and uses it against whichever backend it's currently
875 // talking to. Observability settings get re-read each resolve so a
876 // hot-swap of the server-settings file is picked up on the next
877 // restart cycle without having to bounce the desktop process.
878 const sharedInputs = Effect.gen(function* () {
879 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
880 const bootstrapToken = currentDesktopBootstrapToken(
881 bootstrapSecret,
882 yield* Clock.currentTimeMillis,
883 );
884 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
885 Effect.provideService(FileSystem.FileSystem, fileSystem),
886 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
887 );
888 return {
889 bootstrapToken,
890 bootstrapSecret,
891 observabilitySettings,
892 } satisfies SharedBootstrapInput;
893 });
894
895 const buildWslPrimaryConfig = Effect.gen(function* () {
896 // wsl-only mode pipes the WSL backend through the same port the
897 // Windows primary would normally take. That way the renderer
898 // still loads from the local-only endpoint advertised by
899 // DesktopServerExposure, and primary-aware code paths (cookie
900 // auth, the env switcher's "primary" id) keep working without
901 // a parallel "secondary" registration.
902 const backendExposure = yield* serverExposure.backendConfig;
903 const persistedSettings = yield* settings.get;
904 const shared = yield* sharedInputs;
905 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
906 return yield* resolveWslStartConfig({
907 ...shared,
908 port: backendExposure.port,
909 distro: persistedSettings.wslDistro,
910 }).pipe(
911 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
912 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
913 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
914 Effect.provideService(FileSystem.FileSystem, fileSystem),
915 );
916 });
917
918 const buildWindowsPrimaryConfig = Effect.gen(function* () {
919 const shared = yield* sharedInputs;
920 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
921 Effect.provideService(FileSystem.FileSystem, fileSystem),
922 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
923 );
924 const cliPath = yield* DesktopCliShim.install.pipe(
925 Effect.provideService(FileSystem.FileSystem, fileSystem),
926 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
927 );
928 const shellEnvironmentPrepared = yield* shellEnvironment.installIntoProcess;
929 return yield* resolvePrimaryStartConfig({
930 ...shared,
931 resourceMonitorPath,
932 cliPath,
933 shellEnvironmentPrepared,
934 }).pipe(
935 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
936 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
937 );
938 });
939
940 // Single source of truth for what the primary actually runs as. Both
941 // the start-config dispatch and the renderer-facing label derive from
942 // this, so they can't disagree — e.g. the label reading "WSL" while the
943 // config silently fell back to Windows because WSL is unavailable.
944 // Dispatch happens at resolve time so toggling wsl-only between restarts
945 // is picked up on the next start cycle (the pool's primary instance is
946 // created once at layer init, but configResolve fires on each restart).
947 const describePrimary = Effect.gen(function* () {
948 const persistedSettings = yield* settings.get;
949 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
950 // Only honor wsl-only when WSL is actually usable. If the user
951 // persisted wsl-only but WSL has since become unavailable (wsl.exe
952 // removed, no distro), fall back to the Windows primary instead of
953 // looping forever on preflight failures: the Connections backend
954 // control is hidden while WSL is unavailable, so a stuck WSL primary
955 // would otherwise leave no in-app way back to Windows.
956 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
957 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
958 });
959
960 const currentBootstrapToken = Effect.gen(function* () {
961 const secret = yield* getOrCreateBootstrapSecret;
962 return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
963 });
964
965 return DesktopBackendConfiguration.of({
966 currentBootstrapToken,
967 resolvePrimary: Effect.gen(function* () {
968 const { useWsl, wslRequested } = yield* describePrimary;
969 if (useWsl) {
970 return yield* buildWslPrimaryConfig;
971 }
972 if (wslRequested) {
973 yield* Effect.logWarning(
974 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
975 );
976 }
977 return yield* buildWindowsPrimaryConfig;
978 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
979 resolvePrimaryLabel: Effect.gen(function* () {
980 const { useWsl, distro } = yield* describePrimary;
981 if (!useWsl) {
982 return environment.platform === "win32" ? "Windows" : "Local environment";
983 }
984 return distro ? `WSL (${distro})` : "WSL";
985 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
986 resolveWsl: (input) =>
987 Effect.gen(function* () {
988 const shared = yield* sharedInputs;
989 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
990 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
991 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
992 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
993 Effect.provideService(FileSystem.FileSystem, fileSystem),
994 );
995 }).pipe(
996 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
997 attributes: { port: input.port, distro: input.distro ?? null },
998 }),
999 ),
1000 });
1001});
1002
1003export const layer = Layer.effect(DesktopBackendConfiguration, make);