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

DesktopBackendConfiguration.ts

866 lines31.3 KB

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