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