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