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 readonly resolvePrimary: Effect.Effect<
44 DesktopBackendManager.DesktopBackendStartConfig,
45 PlatformError.PlatformError
46 >;
47 readonly resolveWsl: (input: {
48 readonly port: number;
49 readonly distro: string | null;
50 }) => Effect.Effect<
51 DesktopBackendManager.DesktopBackendStartConfig,
52 PlatformError.PlatformError
53 >;
54 readonly resolvePrimaryLabel: Effect.Effect<string>;
55 readonly currentBootstrapToken: Effect.Effect<string, PlatformError.PlatformError>;
56 }
57>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
58
59interface BackendObservabilitySettings {
60 readonly otlpTracesUrl: Option.Option<string>;
61 readonly otlpMetricsUrl: Option.Option<string>;
62 readonly otlpLogsUrl: Option.Option<string>;
63}
64
65const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
66 otlpTracesUrl: Option.none(),
67 otlpMetricsUrl: Option.none(),
68 otlpLogsUrl: Option.none(),
69};
70
71const DESKTOP_BACKEND_ENV_NAMES = [
72 "T3CODE_PORT",
73 "T3CODE_MODE",
74 "T3CODE_NO_BROWSER",
75 "T3CODE_HOST",
76 "T3CODE_DESKTOP_WS_URL",
77 "T3CODE_DESKTOP_LAN_ACCESS",
78 "T3CODE_DESKTOP_LAN_HOST",
79 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
80 "T3CODE_TAILSCALE_SERVE",
81 "T3CODE_TAILSCALE_SERVE_PORT",
82] as const;
83
84// Env vars that the WSL backend needs but Windows process.env won't forward
85// across the wsl.exe boundary without WSLENV.
86const WSL_FORWARDED_ENV_NAMES = [
87 "OPENAI_API_KEY",
88 "ANTHROPIC_API_KEY",
89 "T3CODE_TELEMETRY_ENABLED",
90 // Otherwise the WSL server keeps exporting to endpoints from the bootstrap.
91 "T3CODE_OTEL_SDK_DISABLED",
92 "OTEL_SDK_DISABLED",
93 "T3CODE_OTLP_HEADERS",
94 "T3CODE_OTLP_PROTOCOL",
95 // Forwarded without a WSLENV flag, so the values arrive untranslated. The
96 // server prefers an OTEL endpoint over the bootstrap envelope, so the T3 URLs
97 // travel as variables to keep winning inside the distro as they do on Windows.
98 "T3CODE_OTLP_TRACES_URL",
99 "T3CODE_OTLP_METRICS_URL",
100 "T3CODE_OTLP_LOGS_URL",
101 "OTEL_EXPORTER_OTLP_ENDPOINT",
102 "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
103 "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
104 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
105 "OTEL_EXPORTER_OTLP_HEADERS",
106 "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
107 "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
108 "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
109 "OTEL_EXPORTER_OTLP_PROTOCOL",
110 "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL",
111 "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",
112 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
113 "OTEL_TRACES_EXPORTER",
114 "OTEL_METRICS_EXPORTER",
115 "OTEL_LOGS_EXPORTER",
116] as const;
117
118const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
119
120const nodeBinDirOf = (nodePath: string): string => {
121 const lastSlash = nodePath.lastIndexOf("/");
122 return lastSlash > 0 ? nodePath.slice(0, lastSlash) : "/usr/bin";
123};
124
125const backendChildEnvPatch = (): Record<string, string | undefined> =>
126 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
127
128const getWslEnvEntryName = (entry: string): string => {
129 const slashIndex = entry.indexOf("/");
130 return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
131};
132
133const mergeWslEnv = (
134 existingWslEnv: string | undefined,
135 forwardedEnvNames: ReadonlyArray<string>,
136): string | undefined => {
137 const existing = existingWslEnv?.trim() ?? "";
138
139 const seenNames = new Set(
140 existing
141 .split(":")
142 .map((entry) => getWslEnvEntryName(entry.trim()))
143 .filter((name) => name.length > 0),
144 );
145
146 const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
147
148 // Preserve the user's WSLENV exactly as Windows handed it to us — empty
149 // "::" segments and duplicate entries are harmless no-ops to WSL and not
150 // ours to normalize — and only append the secrets we need to forward
151 // across the wsl.exe boundary.
152 const parts = [existing, ...additions].filter((part) => part.length > 0);
153 return parts.length > 0 ? parts.join(":") : undefined;
154};
155
156const logBackendObservabilitySettingsReadFailure = (
157 settingsPath: string,
158 cause: PlatformError.PlatformError,
159) => {
160 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
161 return Effect.logWarning(error).pipe(
162 Effect.annotateLogs({
163 component: "desktop-backend-configuration",
164 error,
165 }),
166 );
167};
168
169function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
170 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
171}
172
173const resolveResourceMonitorPath = Effect.fn(
174 "desktop.backendConfiguration.resolveResourceMonitorPath",
175)(function* () {
176 const environment = yield* DesktopEnvironment.DesktopEnvironment;
177 const fileSystem = yield* FileSystem.FileSystem;
178 const binaryName = resourceMonitorBinaryName(environment.platform);
179 const candidates = environment.isDevelopment
180 ? [
181 environment.path.join(
182 environment.rootDir,
183 "native/resource-monitor/target/release",
184 binaryName,
185 ),
186 environment.path.join(
187 environment.rootDir,
188 "native/resource-monitor/target/debug",
189 binaryName,
190 ),
191 ]
192 : environment.isPackaged
193 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
194 : environment.resolveResourcePathCandidates(
195 environment.path.join("resource-monitor", binaryName),
196 );
197
198 for (const candidate of candidates) {
199 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
200 return Option.some(candidate);
201 }
202 }
203
204 return Option.none<string>();
205});
206
207const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
208 const fileSystem = yield* FileSystem.FileSystem;
209 const environment = yield* DesktopEnvironment.DesktopEnvironment;
210 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
211 Effect.asSome,
212 Effect.catchTags({
213 PlatformError: (cause) =>
214 cause.reason._tag === "NotFound"
215 ? Effect.succeedNone
216 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
217 Effect.as(Option.none()),
218 ),
219 }),
220 );
221 if (Option.isNone(raw)) {
222 return emptyBackendObservabilitySettings;
223 }
224
225 const parsed = parsePersistedServerObservabilitySettings(raw.value);
226 return {
227 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
228 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
229 otlpLogsUrl: Option.fromNullishOr(parsed.otlpLogsUrl),
230 };
231});
232
233const readBackendObservabilitySettings = Effect.gen(function* () {
234 const environment = yield* DesktopEnvironment.DesktopEnvironment;
235 const persisted = yield* readPersistedBackendObservabilitySettings;
236 return {
237 otlpTracesUrl: Option.orElse(environment.otlpTracesUrl, () => persisted.otlpTracesUrl),
238 otlpMetricsUrl: Option.orElse(environment.otlpMetricsUrl, () => persisted.otlpMetricsUrl),
239 otlpLogsUrl: Option.orElse(environment.otlpLogsUrl, () => persisted.otlpLogsUrl),
240 } satisfies BackendObservabilitySettings;
241});
242
243interface SharedBootstrapInput {
244 readonly bootstrapToken: string;
245 readonly bootstrapSecret: string;
246 readonly observabilitySettings: BackendObservabilitySettings;
247}
248
249type WslPreflightRuntime =
250 | {
251 readonly kind: "executable";
252 readonly entryPath: string;
253 }
254 | {
255 readonly kind: "node-script";
256 // Absolute path to the node binary the preflight validated after the
257 // shared remote resolver repaired PATH. The launch must use this exact
258 // path so it doesn't fall through to a different/old node than the one
259 // node-pty was probed with.
260 readonly nodePath: string;
261 readonly linuxEntryPath: string;
262 };
263
264interface WslPreflightSuccess {
265 readonly _tag: "Ready";
266 readonly runningDistro: string;
267 readonly windowsEntryPath: string;
268 readonly runtime: WslPreflightRuntime;
269 readonly resolvedPath: string;
270 readonly runtimeId?: string;
271}
272
273interface WslPreflightFailure {
274 readonly _tag: "Failed";
275 readonly reason: string;
276 readonly fatal: boolean;
277 readonly retryLimit?: number;
278}
279
280const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
281const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
282const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
283const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
284
285const parseWslRuntimeArchiveHash = (value: string): string | null => {
286 const trimmed = value.trim();
287 return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
288};
289
290type FailedNodePtyResult = Extract<
291 DesktopWslEnvironment.EnsureWslNodePtyResult,
292 { readonly ok: false }
293>;
294
295const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
296 readonly distro: string | null;
297 readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;
298 readonly allowBuild: boolean;
299}): Effect.fn.Return<
300 WslPreflightSuccess | WslPreflightFailure,
301 never,
302 | DesktopEnvironment.DesktopEnvironment
303 | DesktopWslEnvironment.DesktopWslEnvironment
304 | DesktopWslServerTree.DesktopWslServerTree
305 | FileSystem.FileSystem
306> {
307 const environment = yield* DesktopEnvironment.DesktopEnvironment;
308 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
309 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
310 const fileSystem = yield* FileSystem.FileSystem;
311
312 const wslAvailable = yield* wslEnv.isAvailable;
313 if (!wslAvailable) {
314 return {
315 _tag: "Failed",
316 reason: "WSL is not available on this system",
317 fatal: false,
318 } as const;
319 }
320
321 const distroProbe = yield* wslEnv.probeDistros.pipe(
322 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
323 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
324 );
325 if (distroProbe._tag === "Failure") {
326 return {
327 _tag: "Failed",
328 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
329 fatal: false,
330 } as const;
331 }
332
333 const installedDistros = distroProbe.distros;
334 const runningDistro = input.distro
335 ? (installedDistros.find(
336 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
337 )?.name ?? null)
338 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
339 if (runningDistro === null) {
340 return {
341 _tag: "Failed",
342 reason: input.distro
343 ? `WSL distro is not installed: ${input.distro}`
344 : installedDistros.length === 0
345 ? "WSL has no installed distributions"
346 : "WSL has no default distribution",
347 fatal: true,
348 } as const;
349 }
350
351 const nodePtyOptions = {
352 allowBuild: input.allowBuild,
353 nodeEngineRange: serverPackageJson.engines.node,
354 };
355 const failedNodePty = (result: FailedNodePtyResult) =>
356 ({
357 _tag: "Failed",
358 reason: `WSL node-pty unavailable: ${result.reason}`,
359 fatal: result.fatal,
360 ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),
361 }) as const;
362
363 const resolveMountedAppRoot = Effect.gen(function* () {
364 const serverTree = yield* wslServerTree.ensure;
365 if (!serverTree.ok) {
366 return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;
367 }
368 const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");
369 const entryExists = yield* fileSystem
370 .exists(windowsEntryPath)
371 .pipe(Effect.orElseSucceed(() => false));
372 if (!entryExists) {
373 return {
374 ok: false,
375 reason: `missing server entry at ${windowsEntryPath}`,
376 fatal: true,
377 } as const;
378 }
379 const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);
380 return Option.isNone(mountedAppRoot)
381 ? ({
382 ok: false,
383 reason: `wslpath conversion failed for ${serverTree.root}`,
384 fatal: false,
385 } as const)
386 : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);
387 });
388
389 let stagedFailure: { readonly runtimeId: string; readonly reason: string } | undefined;
390 const failedStaged = (failure: { readonly reason: string }) =>
391 ({
392 _tag: "Failed",
393 reason: `WSL runtime unavailable: ${failure.reason}`,
394 fatal: true,
395 }) as const;
396
397 if (input.runtimeArchive !== null) {
398 const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
399 if (runtime.ok) {
400 // The staged runtime supplies its own Node and node-pty. Provider PATH
401 // discovery must not require either dependency for runtime readiness.
402 const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
403 if (stagedProbe.ok) {
404 yield* wslServerTree.cleanupLegacy;
405 return {
406 _tag: "Ready",
407 runningDistro,
408 windowsEntryPath: environment.backendEntryPath,
409 runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
410 resolvedPath: stagedProbe.resolvedPath,
411 runtimeId: input.runtimeArchive.runtimeId,
412 } as const;
413 }
414 yield* Effect.logWarning(
415 "The staged WSL runtime did not start; retrying from the mounted server tree.",
416 { reason: stagedProbe.reason },
417 );
418 stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
419 } else {
420 yield* Effect.logWarning(
421 "Could not stage the WSL runtime; launching from the mounted server tree instead.",
422 { reason: runtime.reason },
423 );
424 }
425 }
426
427 const mounted = yield* resolveMountedAppRoot;
428 if (!mounted.ok) {
429 return stagedFailure && mounted.fatal
430 ? failedStaged(stagedFailure)
431 : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
432 }
433
434 const nodePtyResult = yield* wslEnv.ensureNodePty(
435 runningDistro,
436 mounted.linuxAppRoot,
437 nodePtyOptions,
438 );
439 if (!nodePtyResult.ok) {
440 // Substituting the staged verdict for a transient mounted failure would
441 // turn a retryable failure into a fatal one, ending the WSL attempt (and,
442 // in wsl-only mode, persisting Windows) before the slow /mnt path had a
443 // chance to answer and clear the bad cache.
444 return stagedFailure && nodePtyResult.fatal
445 ? failedStaged(stagedFailure)
446 : failedNodePty(nodePtyResult);
447 }
448
449 if (stagedFailure) {
450 yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);
451 }
452
453 return {
454 _tag: "Ready",
455 runningDistro,
456 windowsEntryPath: mounted.windowsEntryPath,
457 runtime: {
458 kind: "node-script",
459 nodePath: nodePtyResult.nodePath,
460 linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
461 },
462 resolvedPath: nodePtyResult.resolvedPath,
463 } as const;
464});
465
466// In WSL2 mirrored mode the distro's eth0 IP equals the host's, which is the
467// signature we use to detect that mode and switch the renderer URL to loopback.
468const isLocalHostIpv4 = (ip: string): boolean => {
469 const interfaces = NodeOS.networkInterfaces();
470 for (const list of Object.values(interfaces)) {
471 if (!list) continue;
472 for (const entry of list) {
473 // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
474 // the Node build Electron ships (41 / Node 22, verified), but some Node
475 // builds report the numeric 4.
476 const family = String(entry.family);
477 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
478 }
479 }
480 return false;
481};
482
483const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
484 ...Option.match(observabilitySettings.otlpTracesUrl, {
485 onNone: () => ({}),
486 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
487 }),
488 ...Option.match(observabilitySettings.otlpMetricsUrl, {
489 onNone: () => ({}),
490 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
491 }),
492 ...Option.match(observabilitySettings.otlpLogsUrl, {
493 onNone: () => ({}),
494 onSome: (otlpLogsUrl) => ({ otlpLogsUrl }),
495 }),
496});
497
498const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
499 function* (
500 input: SharedBootstrapInput & {
501 readonly resourceMonitorPath: Option.Option<string>;
502 readonly cliPath: Option.Option<string>;
503 readonly shellEnvironmentPrepared: boolean;
504 },
505 ): Effect.fn.Return<
506 DesktopBackendManager.DesktopBackendStartConfig,
507 never,
508 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
509 > {
510 const environment = yield* DesktopEnvironment.DesktopEnvironment;
511 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
512 const backendExposure = yield* serverExposure.backendConfig;
513
514 const bootstrap = {
515 mode: "desktop" as const,
516 noBrowser: true,
517 port: backendExposure.port,
518 t3Home: environment.baseDir,
519 host: backendExposure.bindHost,
520 desktopBootstrapToken: input.bootstrapToken,
521 desktopBootstrapSecret: input.bootstrapSecret,
522 // Failed Windows probes leave server hydration enabled for another attempt.
523 shellEnvironmentPrepared: input.shellEnvironmentPrepared,
524 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
525 tailscaleServePort: backendExposure.tailscaleServePort,
526 desktopTelemetryFd: 4,
527 desktopTelemetryControlFd: 5,
528 desktopBrowserFd: 6,
529 desktopBrowserControlFd: 7,
530 ...Option.match(input.resourceMonitorPath, {
531 onNone: () => ({}),
532 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
533 }),
534 ...buildObservabilityFragment(input.observabilitySettings),
535 };
536
537 return {
538 executablePath: process.execPath,
539 // Packaged builds only, so a dev instance never shares the cache with the
540 // prod app it is often run from. `--require` rather than NODE_COMPILE_CACHE,
541 // so the setting does not leak into the provider and terminal processes
542 // the backend starts.
543 args: [
544 ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
545 environment.backendEntryPath,
546 "--bootstrap-fd",
547 "3",
548 ],
549 entryPath: environment.backendEntryPath,
550 cwd: environment.backendCwd,
551 env: {
552 ...backendChildEnvPatch(),
553 ELECTRON_RUN_AS_NODE: "1",
554 T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
555 },
556 extendEnv: true,
557 bootstrap,
558 bootstrapDelivery: "fd3",
559 httpBaseUrl: backendExposure.httpBaseUrl,
560 captureOutput: true,
561 preflightFailure: Option.none(),
562 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
563 },
564);
565
566const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
567 input: SharedBootstrapInput & {
568 readonly port: number;
569 readonly distro: string | null;
570 },
571): Effect.fn.Return<
572 DesktopBackendManager.DesktopBackendStartConfig,
573 never,
574 | DesktopEnvironment.DesktopEnvironment
575 | DesktopWslEnvironment.DesktopWslEnvironment
576 | DesktopWslServerTree.DesktopWslServerTree
577 | FileSystem.FileSystem
578> {
579 const environment = yield* DesktopEnvironment.DesktopEnvironment;
580 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
581 const fileSystem = yield* FileSystem.FileSystem;
582
583 // wslhost forwarding is unreliable on some Windows hosts: the desktop's
584 // readiness probe and the renderer's saved-env-style fetch both saw "Failed
585 // to fetch" when the backend only bound to 127.0.0.1 inside WSL. Binding to
586 // 0.0.0.0 plus advertising the WSL IP as the renderer-visible URL avoids that
587 // dependency.
588 const wslBindHost = "0.0.0.0";
589
590 const bootstrap = {
591 mode: "desktop" as const,
592 noBrowser: true,
593 port: input.port,
594 // Omit t3Home so the Linux backend uses its own home dir instead of
595 // the Windows-side baseDir (which would be a /mnt/c path and share
596 // the SQLite file with the primary).
597 host: wslBindHost,
598 desktopBootstrapToken: input.bootstrapToken,
599 desktopBootstrapSecret: input.bootstrapSecret,
600 // PortSchema rejects 0, so when tailscale serve is disabled we still need a
601 // valid number in this slot.
602 tailscaleServeEnabled: false,
603 tailscaleServePort: 443,
604 ...buildObservabilityFragment(input.observabilitySettings),
605 };
606
607 const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);
608 const archiveHashPath = environment.path.join(
609 environment.resourcesPath,
610 WSL_RUNTIME_ARCHIVE_HASH_NAME,
611 );
612
613 const hasArchive = environment.isPackaged
614 ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))
615 : false;
616 const archiveHash = hasArchive
617 ? yield* fileSystem.readFileString(archiveHashPath).pipe(
618 Effect.map(parseWslRuntimeArchiveHash),
619 Effect.orElseSucceed(() => null),
620 )
621 : null;
622 if (hasArchive && archiveHash === null) {
623 yield* Effect.logWarning(
624 "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",
625 { hashPath: archiveHashPath },
626 );
627 }
628
629 const preflight = yield* runWslPreflight({
630 distro: input.distro,
631 runtimeArchive:
632 archiveHash === null
633 ? null
634 : {
635 windowsPath: archivePath,
636 runtimeId: `sha256-${archiveHash}`,
637 sha256: archiveHash,
638 },
639 allowBuild: !environment.isPackaged,
640 });
641
642 // Every operation after preflight uses the same concrete distro. In
643 // default-tracking mode this closes the race where the system default
644 // changes between probing and spawning the backend.
645 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
646 const distroForConfig = runningDistro ?? input.distro;
647
648 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
649 const usesSharedNetworkStack = Option.match(distroIp, {
650 onNone: () => false,
651 onSome: (ip) => isLocalHostIpv4(ip),
652 });
653 const rendererHost = usesSharedNetworkStack
654 ? "127.0.0.1"
655 : Option.getOrElse(distroIp, () => "127.0.0.1");
656 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
657
658 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
659 const forwardedEnv: Record<string, string> = {};
660 const forwardedEnvNames: string[] = [];
661 for (const name of WSL_FORWARDED_ENV_NAMES) {
662 const value = process.env[name];
663 if (value !== undefined && value.length > 0) {
664 forwardedEnv[name] = value;
665 forwardedEnvNames.push(name);
666 }
667 }
668
669 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
670 for (const [key, value] of Object.entries(process.env)) {
671 if (key === "T3CODE_HOME") continue;
672 parentEnvWithoutT3Home[key] = value;
673 }
674 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
675
676 const baseConfig = {
677 executablePath: "wsl.exe",
678 entryPath:
679 preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,
680 cwd: environment.backendCwd,
681 env: {
682 ...parentEnvWithoutT3Home,
683 ...backendChildEnvPatch(),
684 ...forwardedEnv,
685 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
686 },
687 // env is already a complete process.env minus T3CODE_HOME; pass it
688 // verbatim instead of letting the spawner re-merge process.env on top.
689 extendEnv: false,
690 bootstrap,
691 bootstrapDelivery: "stdin" as const,
692 httpBaseUrl,
693 captureOutput: true,
694 ...(runningDistro !== null ? { runningDistro } : {}),
695 };
696
697 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
698 // config resolution lands in dev/ instead of userdata/.
699 const devUrlArgs = Option.match(environment.devServerUrl, {
700 onNone: () => [] as ReadonlyArray<string>,
701 onSome: (url) => ["--dev-url", url.href],
702 });
703
704 if (preflight._tag === "Failed") {
705 const retryLimit =
706 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
707 return {
708 ...baseConfig,
709 args: [...distroArgs, "--", "node", "--version"],
710 preflightFailure: Option.some({
711 reason: preflight.reason,
712 fatal: preflight.fatal,
713 ...(retryLimit === undefined ? {} : { retryLimit }),
714 }),
715 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
716 }
717
718 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
719 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
720 // live on the user's login-shell PATH, which `wsl.exe --exec` does NOT put on
721 // the process PATH, so `npm install -g ...` fails with NotFound.
722 const runtime = preflight.runtime;
723 const launchPath =
724 runtime.kind === "executable"
725 ? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
726 : `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
727 const command =
728 runtime.kind === "executable"
729 ? [runtime.entryPath]
730 : [runtime.nodePath, runtime.linuxEntryPath];
731
732 return {
733 ...baseConfig,
734 args: [
735 ...distroArgs,
736 "--exec",
737 "env",
738 `PATH=${launchPath}`,
739 ...command,
740 "--bootstrap-fd",
741 "0",
742 ...devUrlArgs,
743 ],
744 preflightFailure: Option.none(),
745 ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),
746 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
747});
748
749/** @public Service construction is part of the canonical Effect module API. */
750export const make = Effect.gen(function* () {
751 const environment = yield* DesktopEnvironment.DesktopEnvironment;
752 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
753 const fileSystem = yield* FileSystem.FileSystem;
754 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
755 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
756 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
757 const settings = yield* DesktopAppSettings.DesktopAppSettings;
758 const crypto = yield* Crypto.Crypto;
759 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
760 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
761 // resolve concurrently; with a plain Ref both could observe None, generate
762 // distinct secrets, and one would overwrite the other — leaving the two
763 // backends deriving mismatched tokens and breaking the shared-token invariant
764 // the renderer relies on.
765 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
766 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
767 Option.match(current, {
768 onSome: (secret) => Effect.succeed([secret, current] as const),
769 onNone: () =>
770 crypto.randomBytes(32).pipe(
771 Effect.map((bytes) => {
772 const secret = Hex.encode(bytes);
773 return [secret, Option.some(secret)] as const;
774 }),
775 ),
776 }),
777 );
778
779 const sharedInputs = Effect.gen(function* () {
780 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
781 const bootstrapToken = currentDesktopBootstrapToken(
782 bootstrapSecret,
783 yield* Clock.currentTimeMillis,
784 );
785 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
786 Effect.provideService(FileSystem.FileSystem, fileSystem),
787 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
788 );
789 return {
790 bootstrapToken,
791 bootstrapSecret,
792 observabilitySettings,
793 } satisfies SharedBootstrapInput;
794 });
795
796 const buildWslPrimaryConfig = Effect.gen(function* () {
797 const backendExposure = yield* serverExposure.backendConfig;
798 const persistedSettings = yield* settings.get;
799 const shared = yield* sharedInputs;
800 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
801 return yield* resolveWslStartConfig({
802 ...shared,
803 port: backendExposure.port,
804 distro: persistedSettings.wslDistro,
805 }).pipe(
806 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
807 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
808 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
809 Effect.provideService(FileSystem.FileSystem, fileSystem),
810 );
811 });
812
813 const buildWindowsPrimaryConfig = Effect.gen(function* () {
814 const shared = yield* sharedInputs;
815 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
816 Effect.provideService(FileSystem.FileSystem, fileSystem),
817 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
818 );
819 const cliPath = yield* DesktopCliShim.install.pipe(
820 Effect.provideService(FileSystem.FileSystem, fileSystem),
821 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
822 );
823 const shellEnvironmentPrepared = yield* shellEnvironment.installIntoProcess;
824 return yield* resolvePrimaryStartConfig({
825 ...shared,
826 resourceMonitorPath,
827 cliPath,
828 shellEnvironmentPrepared,
829 }).pipe(
830 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
831 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
832 );
833 });
834
835 // Dispatch happens at resolve time so toggling wsl-only between restarts
836 // is picked up on the next start cycle (the pool's primary instance is
837 // created once at layer init, but configResolve fires on each restart).
838 const describePrimary = Effect.gen(function* () {
839 const persistedSettings = yield* settings.get;
840 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
841 // Only honor wsl-only when WSL is actually usable. If the user
842 // persisted wsl-only but WSL has since become unavailable (wsl.exe
843 // removed, no distro), fall back to the Windows primary instead of
844 // looping forever on preflight failures: the Connections backend
845 // control is hidden while WSL is unavailable, so a stuck WSL primary
846 // would otherwise leave no in-app way back to Windows.
847 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
848 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
849 });
850
851 const currentBootstrapToken = Effect.gen(function* () {
852 const secret = yield* getOrCreateBootstrapSecret;
853 return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
854 });
855
856 return DesktopBackendConfiguration.of({
857 currentBootstrapToken,
858 resolvePrimary: Effect.gen(function* () {
859 const { useWsl, wslRequested } = yield* describePrimary;
860 if (useWsl) {
861 return yield* buildWslPrimaryConfig;
862 }
863 if (wslRequested) {
864 yield* Effect.logWarning(
865 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
866 );
867 }
868 return yield* buildWindowsPrimaryConfig;
869 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
870 resolvePrimaryLabel: Effect.gen(function* () {
871 const { useWsl, distro } = yield* describePrimary;
872 if (!useWsl) {
873 return environment.platform === "win32" ? "Windows" : "Local environment";
874 }
875 return distro ? `WSL (${distro})` : "WSL";
876 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
877 resolveWsl: (input) =>
878 Effect.gen(function* () {
879 const shared = yield* sharedInputs;
880 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
881 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
882 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
883 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
884 Effect.provideService(FileSystem.FileSystem, fileSystem),
885 );
886 }).pipe(
887 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
888 attributes: { port: input.port, distro: input.distro ?? null },
889 }),
890 ),
891 });
892});
893
894export const layer = Layer.effect(DesktopBackendConfiguration, make);