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// Windows forwards these variables into WSL only through WSLENV.
85const WSL_FORWARDED_ENV_NAMES = [
86 "OPENAI_API_KEY",
87 "ANTHROPIC_API_KEY",
88 "T3CODE_TELEMETRY_ENABLED",
89 // Otherwise the WSL server keeps exporting to endpoints from the bootstrap.
90 "T3CODE_OTEL_SDK_DISABLED",
91 "OTEL_SDK_DISABLED",
92 "T3CODE_OTLP_HEADERS",
93 "T3CODE_OTLP_PROTOCOL",
94 // Untranslated T3 URLs must override bootstrap endpoints inside WSL, as they do on Windows.
95 "T3CODE_OTLP_TRACES_URL",
96 "T3CODE_OTLP_METRICS_URL",
97 "T3CODE_OTLP_LOGS_URL",
98 "OTEL_EXPORTER_OTLP_ENDPOINT",
99 "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
100 "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
101 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
102 "OTEL_EXPORTER_OTLP_HEADERS",
103 "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
104 "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
105 "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
106 "OTEL_EXPORTER_OTLP_PROTOCOL",
107 "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL",
108 "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",
109 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
110 "OTEL_TRACES_EXPORTER",
111 "OTEL_METRICS_EXPORTER",
112 "OTEL_LOGS_EXPORTER",
113 "OTEL_RESOURCE_ATTRIBUTES",
114] as const;
115
116const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
117
118const nodeBinDirOf = (nodePath: string): string => {
119 const lastSlash = nodePath.lastIndexOf("/");
120 return lastSlash > 0 ? nodePath.slice(0, lastSlash) : "/usr/bin";
121};
122
123const backendChildEnvPatch = (): Record<string, string | undefined> =>
124 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
125
126const getWslEnvEntryName = (entry: string): string => {
127 const slashIndex = entry.indexOf("/");
128 return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
129};
130
131const mergeWslEnv = (
132 existingWslEnv: string | undefined,
133 forwardedEnvNames: ReadonlyArray<string>,
134): string | undefined => {
135 const existing = existingWslEnv?.trim() ?? "";
136
137 const seenNames = new Set(
138 existing
139 .split(":")
140 .map((entry) => getWslEnvEntryName(entry.trim()))
141 .filter((name) => name.length > 0),
142 );
143
144 const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
145
146 // Preserve empty segments and duplicates in the user's WSLENV; only append required variables.
147 const parts = [existing, ...additions].filter((part) => part.length > 0);
148 return parts.length > 0 ? parts.join(":") : undefined;
149};
150
151const logBackendObservabilitySettingsReadFailure = (
152 settingsPath: string,
153 cause: PlatformError.PlatformError,
154) => {
155 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
156 return Effect.logWarning(error).pipe(
157 Effect.annotateLogs({
158 component: "desktop-backend-configuration",
159 error,
160 }),
161 );
162};
163
164function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
165 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
166}
167
168const resolveResourceMonitorPath = Effect.fn(
169 "desktop.backendConfiguration.resolveResourceMonitorPath",
170)(function* () {
171 const environment = yield* DesktopEnvironment.DesktopEnvironment;
172 const fileSystem = yield* FileSystem.FileSystem;
173 const binaryName = resourceMonitorBinaryName(environment.platform);
174 const candidates = environment.isDevelopment
175 ? [
176 environment.path.join(
177 environment.rootDir,
178 "native/resource-monitor/target/release",
179 binaryName,
180 ),
181 environment.path.join(
182 environment.rootDir,
183 "native/resource-monitor/target/debug",
184 binaryName,
185 ),
186 ]
187 : environment.isPackaged
188 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
189 : environment.resolveResourcePathCandidates(
190 environment.path.join("resource-monitor", binaryName),
191 );
192
193 for (const candidate of candidates) {
194 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
195 return Option.some(candidate);
196 }
197 }
198
199 return Option.none<string>();
200});
201
202const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
203 const fileSystem = yield* FileSystem.FileSystem;
204 const environment = yield* DesktopEnvironment.DesktopEnvironment;
205 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
206 Effect.asSome,
207 Effect.catchTags({
208 PlatformError: (cause) =>
209 cause.reason._tag === "NotFound"
210 ? Effect.succeedNone
211 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
212 Effect.as(Option.none()),
213 ),
214 }),
215 );
216 if (Option.isNone(raw)) {
217 return emptyBackendObservabilitySettings;
218 }
219
220 const parsed = parsePersistedServerObservabilitySettings(raw.value);
221 return {
222 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
223 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
224 otlpLogsUrl: Option.fromNullishOr(parsed.otlpLogsUrl),
225 };
226});
227
228const readBackendObservabilitySettings = Effect.gen(function* () {
229 const environment = yield* DesktopEnvironment.DesktopEnvironment;
230 const persisted = yield* readPersistedBackendObservabilitySettings;
231 return {
232 otlpTracesUrl: Option.orElse(environment.otlpTracesUrl, () => persisted.otlpTracesUrl),
233 otlpMetricsUrl: Option.orElse(environment.otlpMetricsUrl, () => persisted.otlpMetricsUrl),
234 otlpLogsUrl: Option.orElse(environment.otlpLogsUrl, () => persisted.otlpLogsUrl),
235 } satisfies BackendObservabilitySettings;
236});
237
238interface SharedBootstrapInput {
239 readonly bootstrapToken: string;
240 readonly bootstrapSecret: string;
241 readonly observabilitySettings: BackendObservabilitySettings;
242}
243
244type WslPreflightRuntime =
245 | {
246 readonly kind: "executable";
247 readonly entryPath: string;
248 }
249 | {
250 readonly kind: "node-script";
251 // Launch the exact Node path probed with node-pty, even if later PATH lookup would resolve another version.
252 readonly nodePath: string;
253 readonly linuxEntryPath: string;
254 };
255
256interface WslPreflightSuccess {
257 readonly _tag: "Ready";
258 readonly runningDistro: string;
259 readonly windowsEntryPath: string;
260 readonly runtime: WslPreflightRuntime;
261 readonly resolvedPath: string;
262 readonly runtimeId?: string;
263}
264
265interface WslPreflightFailure {
266 readonly _tag: "Failed";
267 readonly reason: string;
268 readonly fatal: boolean;
269 readonly retryLimit?: number;
270}
271
272const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
273const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
274const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
275const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
276
277const parseWslRuntimeArchiveHash = (value: string): string | null => {
278 const trimmed = value.trim();
279 return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
280};
281
282type FailedNodePtyResult = Extract<
283 DesktopWslEnvironment.EnsureWslNodePtyResult,
284 { readonly ok: false }
285>;
286
287const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
288 readonly distro: string | null;
289 readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;
290 readonly allowBuild: boolean;
291}): Effect.fn.Return<
292 WslPreflightSuccess | WslPreflightFailure,
293 never,
294 | DesktopEnvironment.DesktopEnvironment
295 | DesktopWslEnvironment.DesktopWslEnvironment
296 | DesktopWslServerTree.DesktopWslServerTree
297 | FileSystem.FileSystem
298> {
299 const environment = yield* DesktopEnvironment.DesktopEnvironment;
300 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
301 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
302 const fileSystem = yield* FileSystem.FileSystem;
303
304 const wslAvailable = yield* wslEnv.isAvailable;
305 if (!wslAvailable) {
306 return {
307 _tag: "Failed",
308 reason: "WSL is not available on this system",
309 fatal: false,
310 } as const;
311 }
312
313 const distroProbe = yield* wslEnv.probeDistros.pipe(
314 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
315 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
316 );
317 if (distroProbe._tag === "Failure") {
318 return {
319 _tag: "Failed",
320 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
321 fatal: false,
322 } as const;
323 }
324
325 const installedDistros = distroProbe.distros;
326 const runningDistro = input.distro
327 ? (installedDistros.find(
328 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
329 )?.name ?? null)
330 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
331 if (runningDistro === null) {
332 return {
333 _tag: "Failed",
334 reason: input.distro
335 ? `WSL distro is not installed: ${input.distro}`
336 : installedDistros.length === 0
337 ? "WSL has no installed distributions"
338 : "WSL has no default distribution",
339 fatal: true,
340 } as const;
341 }
342
343 const nodePtyOptions = {
344 allowBuild: input.allowBuild,
345 nodeEngineRange: serverPackageJson.engines.node,
346 };
347 const failedNodePty = (result: FailedNodePtyResult) =>
348 ({
349 _tag: "Failed",
350 reason: `WSL node-pty unavailable: ${result.reason}`,
351 fatal: result.fatal,
352 ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),
353 }) as const;
354
355 const resolveMountedAppRoot = Effect.gen(function* () {
356 const serverTree = yield* wslServerTree.ensure;
357 if (!serverTree.ok) {
358 return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;
359 }
360 const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");
361 const entryExists = yield* fileSystem
362 .exists(windowsEntryPath)
363 .pipe(Effect.orElseSucceed(() => false));
364 if (!entryExists) {
365 return {
366 ok: false,
367 reason: `missing server entry at ${windowsEntryPath}`,
368 fatal: true,
369 } as const;
370 }
371 const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);
372 return Option.isNone(mountedAppRoot)
373 ? ({
374 ok: false,
375 reason: `wslpath conversion failed for ${serverTree.root}`,
376 fatal: false,
377 } as const)
378 : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);
379 });
380
381 let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined;
382 const failedStaged = (failure: { readonly reason: string }) =>
383 ({
384 _tag: "Failed",
385 reason: `WSL runtime unavailable: ${failure.reason}`,
386 fatal: true,
387 }) as const;
388
389 if (input.runtimeArchive !== null) {
390 const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
391 if (runtime.ok) {
392 // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them.
393 const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
394 if (stagedProbe.ok) {
395 yield* wslServerTree.cleanupLegacy;
396 return {
397 _tag: "Ready",
398 runningDistro,
399 windowsEntryPath: environment.backendEntryPath,
400 runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
401 resolvedPath: stagedProbe.resolvedPath,
402 runtimeId: input.runtimeArchive.runtimeId,
403 } as const;
404 }
405 yield* Effect.logWarning(
406 "The staged WSL runtime did not start; retrying from the mounted server tree.",
407 { reason: stagedProbe.reason },
408 );
409 stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
410 } else {
411 stagedFailure = { reason: runtime.reason };
412 yield* Effect.logWarning(
413 "Could not stage the WSL runtime; launching from the mounted server tree instead.",
414 { reason: runtime.reason },
415 );
416 }
417 }
418
419 const mounted = yield* resolveMountedAppRoot;
420 if (!mounted.ok) {
421 return stagedFailure && mounted.fatal
422 ? failedStaged(stagedFailure)
423 : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
424 }
425
426 const nodePtyResult = yield* wslEnv.ensureNodePty(
427 runningDistro,
428 mounted.linuxAppRoot,
429 nodePtyOptions,
430 );
431 if (!nodePtyResult.ok) {
432 // Only substitute a staged failure for a fatal mounted failure; transient /mnt failures must remain retryable.
433 return stagedFailure && nodePtyResult.fatal
434 ? failedStaged(stagedFailure)
435 : failedNodePty(nodePtyResult);
436 }
437
438 if (stagedFailure?.runtimeId) {
439 yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);
440 }
441
442 return {
443 _tag: "Ready",
444 runningDistro,
445 windowsEntryPath: mounted.windowsEntryPath,
446 runtime: {
447 kind: "node-script",
448 nodePath: nodePtyResult.nodePath,
449 linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
450 },
451 resolvedPath: nodePtyResult.resolvedPath,
452 } as const;
453});
454
455// In WSL2 mirrored mode, eth0 matches a host IP; use loopback for the renderer.
456const isLocalHostIpv4 = (ip: string): boolean => {
457 const interfaces = NodeOS.networkInterfaces();
458 for (const list of Object.values(interfaces)) {
459 if (!list) continue;
460 for (const entry of list) {
461 const family = String(entry.family);
462 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
463 }
464 }
465 return false;
466};
467
468const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
469 ...Option.match(observabilitySettings.otlpTracesUrl, {
470 onNone: () => ({}),
471 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
472 }),
473 ...Option.match(observabilitySettings.otlpMetricsUrl, {
474 onNone: () => ({}),
475 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
476 }),
477 ...Option.match(observabilitySettings.otlpLogsUrl, {
478 onNone: () => ({}),
479 onSome: (otlpLogsUrl) => ({ otlpLogsUrl }),
480 }),
481});
482
483const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
484 function* (
485 input: SharedBootstrapInput & {
486 readonly resourceMonitorPath: Option.Option<string>;
487 readonly cliPath: Option.Option<string>;
488 readonly shellEnvironmentPrepared: boolean;
489 },
490 ): Effect.fn.Return<
491 DesktopBackendManager.DesktopBackendStartConfig,
492 never,
493 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
494 > {
495 const environment = yield* DesktopEnvironment.DesktopEnvironment;
496 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
497 const backendExposure = yield* serverExposure.backendConfig;
498
499 const bootstrap = {
500 mode: "desktop" as const,
501 noBrowser: true,
502 port: backendExposure.port,
503 t3Home: environment.baseDir,
504 host: backendExposure.bindHost,
505 desktopBootstrapToken: input.bootstrapToken,
506 desktopBootstrapSecret: input.bootstrapSecret,
507 shellEnvironmentPrepared: input.shellEnvironmentPrepared,
508 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
509 tailscaleServePort: backendExposure.tailscaleServePort,
510 desktopTelemetryFd: 4,
511 desktopTelemetryControlFd: 5,
512 desktopBrowserFd: 6,
513 desktopBrowserControlFd: 7,
514 ...Option.match(input.resourceMonitorPath, {
515 onNone: () => ({}),
516 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
517 }),
518 ...buildObservabilityFragment(input.observabilitySettings),
519 };
520
521 return {
522 executablePath: process.execPath,
523 // Packaged builds have a separate cache; --require prevents cache settings leaking to provider subprocesses.
524 args: [
525 ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
526 environment.backendEntryPath,
527 "--bootstrap-fd",
528 "3",
529 ],
530 entryPath: environment.backendEntryPath,
531 cwd: environment.backendCwd,
532 env: {
533 ...backendChildEnvPatch(),
534 ELECTRON_RUN_AS_NODE: "1",
535 T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
536 },
537 extendEnv: true,
538 bootstrap,
539 bootstrapDelivery: "fd3",
540 httpBaseUrl: backendExposure.httpBaseUrl,
541 captureOutput: true,
542 preflightFailure: Option.none(),
543 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
544 },
545);
546
547const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
548 input: SharedBootstrapInput & {
549 readonly port: number;
550 readonly distro: string | null;
551 },
552): Effect.fn.Return<
553 DesktopBackendManager.DesktopBackendStartConfig,
554 never,
555 | DesktopEnvironment.DesktopEnvironment
556 | DesktopWslEnvironment.DesktopWslEnvironment
557 | DesktopWslServerTree.DesktopWslServerTree
558 | FileSystem.FileSystem
559> {
560 const environment = yield* DesktopEnvironment.DesktopEnvironment;
561 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
562 const fileSystem = yield* FileSystem.FileSystem;
563
564 // wslhost loopback forwarding is unreliable on some Windows hosts; advertise the WSL IP instead.
565 const wslBindHost = "0.0.0.0";
566
567 const bootstrap = {
568 mode: "desktop" as const,
569 noBrowser: true,
570 port: input.port,
571 // Omit t3Home to keep the Linux backend from sharing the primary's Windows SQLite file.
572 host: wslBindHost,
573 desktopBootstrapToken: input.bootstrapToken,
574 desktopBootstrapSecret: input.bootstrapSecret,
575 // PortSchema rejects 0 even when Tailscale Serve is disabled.
576 tailscaleServeEnabled: false,
577 tailscaleServePort: 443,
578 ...buildObservabilityFragment(input.observabilitySettings),
579 };
580
581 const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);
582 const archiveHashPath = environment.path.join(
583 environment.resourcesPath,
584 WSL_RUNTIME_ARCHIVE_HASH_NAME,
585 );
586
587 const hasArchive = environment.isPackaged
588 ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))
589 : false;
590 const archiveHash = hasArchive
591 ? yield* fileSystem.readFileString(archiveHashPath).pipe(
592 Effect.map(parseWslRuntimeArchiveHash),
593 Effect.orElseSucceed(() => null),
594 )
595 : null;
596 if (hasArchive && archiveHash === null) {
597 yield* Effect.logWarning(
598 "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",
599 { hashPath: archiveHashPath },
600 );
601 }
602
603 const preflight = yield* runWslPreflight({
604 distro: input.distro,
605 runtimeArchive:
606 archiveHash === null
607 ? null
608 : {
609 windowsPath: archivePath,
610 runtimeId: `sha256-${archiveHash}`,
611 sha256: archiveHash,
612 },
613 allowBuild: !environment.isPackaged,
614 });
615
616 // Pin the preflight distro so a default change cannot race backend startup.
617 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
618 const distroForConfig = runningDistro ?? input.distro;
619
620 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
621 const usesSharedNetworkStack = Option.match(distroIp, {
622 onNone: () => false,
623 onSome: (ip) => isLocalHostIpv4(ip),
624 });
625 const rendererHost = usesSharedNetworkStack
626 ? "127.0.0.1"
627 : Option.getOrElse(distroIp, () => "127.0.0.1");
628 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
629
630 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
631 const forwardedEnv: Record<string, string> = {};
632 const forwardedEnvNames: string[] = [];
633 for (const name of WSL_FORWARDED_ENV_NAMES) {
634 const value = process.env[name];
635 if (value !== undefined && value.length > 0) {
636 forwardedEnv[name] = value;
637 forwardedEnvNames.push(name);
638 }
639 }
640
641 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
642 for (const [key, value] of Object.entries(process.env)) {
643 if (key === "T3CODE_HOME") continue;
644 parentEnvWithoutT3Home[key] = value;
645 }
646 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
647
648 const baseConfig = {
649 executablePath: "wsl.exe",
650 entryPath:
651 preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,
652 cwd: environment.backendCwd,
653 env: {
654 ...parentEnvWithoutT3Home,
655 ...backendChildEnvPatch(),
656 ...forwardedEnv,
657 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
658 },
659 // env already excludes T3CODE_HOME; merging process.env would restore it.
660 extendEnv: false,
661 bootstrap,
662 bootstrapDelivery: "stdin" as const,
663 httpBaseUrl,
664 captureOutput: true,
665 ...(runningDistro !== null ? { runningDistro } : {}),
666 };
667
668 // Explicit --dev-url keeps WSL state in dev/ rather than userdata/.
669 const devUrlArgs = Option.match(environment.devServerUrl, {
670 onNone: () => [] as ReadonlyArray<string>,
671 onSome: (url) => ["--dev-url", url.href],
672 });
673
674 if (preflight._tag === "Failed") {
675 const retryLimit =
676 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
677 return {
678 ...baseConfig,
679 args: [...distroArgs, "--", "node", "--version"],
680 preflightFailure: Option.some({
681 reason: preflight.reason,
682 fatal: preflight.fatal,
683 ...(retryLimit === undefined ? {} : { retryLimit }),
684 }),
685 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
686 }
687
688 // wsl.exe --exec omits the login-shell PATH needed to find provider CLIs and npm.
689 const runtime = preflight.runtime;
690 const launchPath =
691 runtime.kind === "executable"
692 ? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
693 : `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
694 const command =
695 runtime.kind === "executable"
696 ? [runtime.entryPath]
697 : [runtime.nodePath, runtime.linuxEntryPath];
698
699 return {
700 ...baseConfig,
701 args: [
702 ...distroArgs,
703 "--exec",
704 "env",
705 `PATH=${launchPath}`,
706 ...command,
707 "--bootstrap-fd",
708 "0",
709 ...devUrlArgs,
710 ],
711 preflightFailure: Option.none(),
712 ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),
713 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
714});
715
716/** @public */
717export const make = Effect.gen(function* () {
718 const environment = yield* DesktopEnvironment.DesktopEnvironment;
719 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
720 const fileSystem = yield* FileSystem.FileSystem;
721 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
722 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
723 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
724 const settings = yield* DesktopAppSettings.DesktopAppSettings;
725 const crypto = yield* Crypto.Crypto;
726 // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.
727 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
728 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
729 Option.match(current, {
730 onSome: (secret) => Effect.succeed([secret, current] as const),
731 onNone: () =>
732 crypto.randomBytes(32).pipe(
733 Effect.map((bytes) => {
734 const secret = Hex.encode(bytes);
735 return [secret, Option.some(secret)] as const;
736 }),
737 ),
738 }),
739 );
740
741 const sharedInputs = Effect.gen(function* () {
742 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
743 const bootstrapToken = currentDesktopBootstrapToken(
744 bootstrapSecret,
745 yield* Clock.currentTimeMillis,
746 );
747 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
748 Effect.provideService(FileSystem.FileSystem, fileSystem),
749 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
750 );
751 return {
752 bootstrapToken,
753 bootstrapSecret,
754 observabilitySettings,
755 } satisfies SharedBootstrapInput;
756 });
757
758 const buildWslPrimaryConfig = Effect.gen(function* () {
759 const backendExposure = yield* serverExposure.backendConfig;
760 const persistedSettings = yield* settings.get;
761 const shared = yield* sharedInputs;
762 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
763 return yield* resolveWslStartConfig({
764 ...shared,
765 port: backendExposure.port,
766 distro: persistedSettings.wslDistro,
767 }).pipe(
768 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
769 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
770 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
771 Effect.provideService(FileSystem.FileSystem, fileSystem),
772 );
773 });
774
775 const buildWindowsPrimaryConfig = Effect.gen(function* () {
776 const shared = yield* sharedInputs;
777 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
778 Effect.provideService(FileSystem.FileSystem, fileSystem),
779 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
780 );
781 const cliPath = yield* DesktopCliShim.install.pipe(
782 Effect.provideService(FileSystem.FileSystem, fileSystem),
783 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
784 );
785 const shellEnvironmentPrepared = yield* shellEnvironment.installIntoProcess;
786 return yield* resolvePrimaryStartConfig({
787 ...shared,
788 resourceMonitorPath,
789 cliPath,
790 shellEnvironmentPrepared,
791 }).pipe(
792 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
793 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
794 );
795 });
796
797 // Resolve on each restart so toggling wsl-only takes effect without recreating the pool.
798 const describePrimary = Effect.gen(function* () {
799 const persistedSettings = yield* settings.get;
800 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
801 // When WSL is unavailable its controls are hidden; fall back to Windows to keep recovery possible.
802 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
803 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
804 });
805
806 const currentBootstrapToken = Effect.gen(function* () {
807 const secret = yield* getOrCreateBootstrapSecret;
808 return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
809 });
810
811 return DesktopBackendConfiguration.of({
812 currentBootstrapToken,
813 resolvePrimary: Effect.gen(function* () {
814 const { useWsl, wslRequested } = yield* describePrimary;
815 if (useWsl) {
816 return yield* buildWslPrimaryConfig;
817 }
818 if (wslRequested) {
819 yield* Effect.logWarning(
820 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
821 );
822 }
823 return yield* buildWindowsPrimaryConfig;
824 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
825 resolvePrimaryLabel: Effect.gen(function* () {
826 const { useWsl, distro } = yield* describePrimary;
827 if (!useWsl) {
828 return environment.platform === "win32" ? "Windows" : "Local environment";
829 }
830 return distro ? `WSL (${distro})` : "WSL";
831 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
832 // The span options depend on each request's port and distro.
833 resolveWsl: Effect.fnUntraced(
834 function* (input) {
835 const shared = yield* sharedInputs;
836 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
837 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
838 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
839 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
840 Effect.provideService(FileSystem.FileSystem, fileSystem),
841 );
842 },
843 (effect, input) =>
844 effect.pipe(
845 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
846 attributes: { port: input.port, distro: input.distro ?? null },
847 }),
848 ),
849 ),
850 });
851});
852
853export const layer = Layer.effect(DesktopBackendConfiguration, make);