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