Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendConfiguration.ts

854 lines30.7 KB

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