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

DesktopBackendConfiguration.ts

899 lines33.5 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 Crypto from "effect/Crypto";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as PlatformError from "effect/PlatformError";
14import * as Schema from "effect/Schema";
15import * as SynchronizedRef from "effect/SynchronizedRef";
16​
17import serverPackageJson from "../../../server/package.json" with { type: "json" };
18​
19import * as DesktopBackendManager from "./DesktopBackendManager.ts";
20import * as DesktopCliShim from "../app/DesktopCliShim.ts";
21import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
22import * as DesktopServerExposure from "./DesktopServerExposure.ts";
23import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
24import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
25import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
26import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
27​
28export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedError<DesktopBackendObservabilitySettingsReadError>()(
29 "DesktopBackendObservabilitySettingsReadError",
30 {
31 settingsPath: Schema.String,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
37 }
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_ACCESS",
78 "T3CODE_DESKTOP_LAN_HOST",
79 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
80 "T3CODE_TAILSCALE_SERVE",
81 "T3CODE_TAILSCALE_SERVE_PORT",
82] as const;
83​
84// Env vars that the WSL backend needs but Windows process.env won't forward
85// across the wsl.exe boundary without WSLENV.
86const WSL_FORWARDED_ENV_NAMES = [
87 "OPENAI_API_KEY",
88 "ANTHROPIC_API_KEY",
89 "T3CODE_TELEMETRY_ENABLED",
90 // Otherwise the WSL server keeps exporting to endpoints from the bootstrap.
91 "T3CODE_OTEL_SDK_DISABLED",
92 "OTEL_SDK_DISABLED",
93 "T3CODE_OTLP_HEADERS",
94 "T3CODE_OTLP_PROTOCOL",
95 // Forwarded without a WSLENV flag, so the values arrive untranslated. The
96 // server prefers an OTEL endpoint over the bootstrap envelope, so the T3 URLs
97 // travel as variables to keep winning inside the distro as they do on Windows.
98 "T3CODE_OTLP_TRACES_URL",
99 "T3CODE_OTLP_METRICS_URL",
100 "T3CODE_OTLP_LOGS_URL",
101 "OTEL_EXPORTER_OTLP_ENDPOINT",
102 "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
103 "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
104 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
105 "OTEL_EXPORTER_OTLP_HEADERS",
106 "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
107 "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
108 "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
109 "OTEL_EXPORTER_OTLP_PROTOCOL",
110 "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL",
111 "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",
112 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
113 "OTEL_TRACES_EXPORTER",
114 "OTEL_METRICS_EXPORTER",
115 "OTEL_LOGS_EXPORTER",
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 the user's WSLENV exactly as Windows handed it to us — empty
149 // "::" segments and duplicate entries are harmless no-ops to WSL and not
150 // ours to normalize — and only append the secrets we need to forward
151 // across the wsl.exe boundary.
152 const parts = [existing, ...additions].filter((part) => part.length > 0);
153 return parts.length > 0 ? parts.join(":") : undefined;
154};
155​
156const logBackendObservabilitySettingsReadFailure = (
157 settingsPath: string,
158 cause: PlatformError.PlatformError,
159) => {
160 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
161 return Effect.logWarning(error).pipe(
162 Effect.annotateLogs({
163 component: "desktop-backend-configuration",
164 error,
165 }),
166 );
167};
168​
169function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
170 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
172​
173const resolveResourceMonitorPath = Effect.fn(
174 "desktop.backendConfiguration.resolveResourceMonitorPath",
175)(function* () {
176 const environment = yield* DesktopEnvironment.DesktopEnvironment;
177 const fileSystem = yield* FileSystem.FileSystem;
178 const binaryName = resourceMonitorBinaryName(environment.platform);
179 const candidates = environment.isDevelopment
180 ? [
181 environment.path.join(
182 environment.rootDir,
183 "native/resource-monitor/target/release",
184 binaryName,
185 ),
186 environment.path.join(
187 environment.rootDir,
188 "native/resource-monitor/target/debug",
189 binaryName,
190 ),
191 ]
192 : environment.isPackaged
193 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
194 : environment.resolveResourcePathCandidates(
195 environment.path.join("resource-monitor", binaryName),
196 );
197​
198 for (const candidate of candidates) {
199 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
200 return Option.some(candidate);
201 }
202 }
203​
204 return Option.none<string>();
205});
206​
207const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
208 const fileSystem = yield* FileSystem.FileSystem;
209 const environment = yield* DesktopEnvironment.DesktopEnvironment;
210 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
211 Effect.asSome,
212 Effect.catchTags({
213 PlatformError: (cause) =>
214 cause.reason._tag === "NotFound"
215 ? Effect.succeedNone
216 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
217 Effect.as(Option.none()),
218 ),
219 }),
220 );
221 if (Option.isNone(raw)) {
222 return emptyBackendObservabilitySettings;
223 }
224​
225 const parsed = parsePersistedServerObservabilitySettings(raw.value);
226 return {
227 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
228 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
229 otlpLogsUrl: Option.fromNullishOr(parsed.otlpLogsUrl),
230 };
231});
232​
233const readBackendObservabilitySettings = Effect.gen(function* () {
234 const environment = yield* DesktopEnvironment.DesktopEnvironment;
235 const persisted = yield* readPersistedBackendObservabilitySettings;
236 return {
237 otlpTracesUrl: Option.orElse(environment.otlpTracesUrl, () => persisted.otlpTracesUrl),
238 otlpMetricsUrl: Option.orElse(environment.otlpMetricsUrl, () => persisted.otlpMetricsUrl),
239 otlpLogsUrl: Option.orElse(environment.otlpLogsUrl, () => persisted.otlpLogsUrl),
240 } satisfies BackendObservabilitySettings;
241});
242​
243interface SharedBootstrapInput {
244 readonly bootstrapToken: string;
245 readonly bootstrapSecret: string;
246 readonly observabilitySettings: BackendObservabilitySettings;
248​
249type WslPreflightRuntime =
250 | {
251 readonly kind: "executable";
252 readonly entryPath: string;
253 }
254 | {
255 readonly kind: "node-script";
256 // Absolute path to the node binary the preflight validated after the
257 // shared remote resolver repaired PATH. The launch must use this exact
258 // path so it doesn't fall through to a different/old node than the one
259 // node-pty was probed with.
260 readonly nodePath: string;
261 readonly linuxEntryPath: string;
262 };
263​
264interface WslPreflightSuccess {
265 readonly _tag: "Ready";
266 readonly runningDistro: string;
267 readonly windowsEntryPath: string;
268 readonly runtime: WslPreflightRuntime;
269 readonly resolvedPath: string;
270 readonly runtimeId?: string;
272​
273interface WslPreflightFailure {
274 readonly _tag: "Failed";
275 readonly reason: string;
276 readonly fatal: boolean;
277 readonly retryLimit?: number;
279​
280const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
281const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
282const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
283const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
284​
285const parseWslRuntimeArchiveHash = (value: string): string | null => {
286 const trimmed = value.trim();
287 return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
288};
289​
290type FailedNodePtyResult = Extract<
291 DesktopWslEnvironment.EnsureWslNodePtyResult,
292 { readonly ok: false }
293>;
294​
295const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
296 readonly distro: string | null;
297 readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;
298 readonly allowBuild: boolean;
299}): Effect.fn.Return<
300 WslPreflightSuccess | WslPreflightFailure,
301 never,
302 | DesktopEnvironment.DesktopEnvironment
303 | DesktopWslEnvironment.DesktopWslEnvironment
304 | DesktopWslServerTree.DesktopWslServerTree
305 | FileSystem.FileSystem
306> {
307 const environment = yield* DesktopEnvironment.DesktopEnvironment;
308 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
309 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
310 const fileSystem = yield* FileSystem.FileSystem;
311​
312 const wslAvailable = yield* wslEnv.isAvailable;
313 if (!wslAvailable) {
314 return {
315 _tag: "Failed",
316 reason: "WSL is not available on this system",
317 fatal: false,
318 } as const;
319 }
320​
321 const distroProbe = yield* wslEnv.probeDistros.pipe(
322 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
323 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
324 );
325 if (distroProbe._tag === "Failure") {
326 return {
327 _tag: "Failed",
328 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
329 fatal: false,
330 } as const;
331 }
332​
333 const installedDistros = distroProbe.distros;
334 const runningDistro = input.distro
335 ? (installedDistros.find(
336 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
337 )?.name ?? null)
338 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
339 if (runningDistro === null) {
340 return {
341 _tag: "Failed",
342 reason: input.distro
343 ? `WSL distro is not installed: ${input.distro}`
344 : installedDistros.length === 0
345 ? "WSL has no installed distributions"
346 : "WSL has no default distribution",
347 fatal: true,
348 } as const;
349 }
350​
351 const nodePtyOptions = {
352 allowBuild: input.allowBuild,
353 nodeEngineRange: serverPackageJson.engines.node,
354 };
355 const failedNodePty = (result: FailedNodePtyResult) =>
356 ({
357 _tag: "Failed",
358 reason: `WSL node-pty unavailable: ${result.reason}`,
359 fatal: result.fatal,
360 ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),
361 }) as const;
362​
363 const resolveMountedAppRoot = Effect.gen(function* () {
364 const serverTree = yield* wslServerTree.ensure;
365 if (!serverTree.ok) {
366 return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;
367 }
368 const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");
369 const entryExists = yield* fileSystem
370 .exists(windowsEntryPath)
371 .pipe(Effect.orElseSucceed(() => false));
372 if (!entryExists) {
373 return {
374 ok: false,
375 reason: `missing server entry at ${windowsEntryPath}`,
376 fatal: true,
377 } as const;
378 }
379 const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);
380 return Option.isNone(mountedAppRoot)
381 ? ({
382 ok: false,
383 reason: `wslpath conversion failed for ${serverTree.root}`,
384 fatal: false,
385 } as const)
386 : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);
387 });
388​
389 let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined;
390 const failedStaged = (failure: { readonly reason: string }) =>
391 ({
392 _tag: "Failed",
393 reason: `WSL runtime unavailable: ${failure.reason}`,
394 fatal: true,
395 }) as const;
396​
397 if (input.runtimeArchive !== null) {
398 const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
399 if (runtime.ok) {
400 // The staged runtime supplies its own Node and node-pty. Provider PATH
401 // discovery must not require either dependency for runtime readiness.
402 const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot);
403 if (stagedProbe.ok) {
404 yield* wslServerTree.cleanupLegacy;
405 return {
406 _tag: "Ready",
407 runningDistro,
408 windowsEntryPath: environment.backendEntryPath,
409 runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
410 resolvedPath: stagedProbe.resolvedPath,
411 runtimeId: input.runtimeArchive.runtimeId,
412 } as const;
413 }
414 yield* Effect.logWarning(
415 "The staged WSL runtime did not start; retrying from the mounted server tree.",
416 { reason: stagedProbe.reason },
417 );
418 stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
419 } else {
420 stagedFailure = { reason: runtime.reason };
421 yield* Effect.logWarning(
422 "Could not stage the WSL runtime; launching from the mounted server tree instead.",
423 { reason: runtime.reason },
424 );
425 }
426 }
427​
428 const mounted = yield* resolveMountedAppRoot;
429 if (!mounted.ok) {
430 return stagedFailure && mounted.fatal
431 ? failedStaged(stagedFailure)
432 : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
433 }
434​
435 const nodePtyResult = yield* wslEnv.ensureNodePty(
436 runningDistro,
437 mounted.linuxAppRoot,
438 nodePtyOptions,
439 );
440 if (!nodePtyResult.ok) {
441 // Substituting the staged verdict for a transient mounted failure would
442 // turn a retryable failure into a fatal one, ending the WSL attempt (and,
443 // in wsl-only mode, persisting Windows) before the slow /mnt path had a
444 // chance to answer and clear the bad cache.
445 return stagedFailure && nodePtyResult.fatal
446 ? failedStaged(stagedFailure)
447 : failedNodePty(nodePtyResult);
448 }
449​
450 if (stagedFailure?.runtimeId) {
451 yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);
452 }
453​
454 return {
455 _tag: "Ready",
456 runningDistro,
457 windowsEntryPath: mounted.windowsEntryPath,
458 runtime: {
459 kind: "node-script",
460 nodePath: nodePtyResult.nodePath,
461 linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
462 },
463 resolvedPath: nodePtyResult.resolvedPath,
464 } as const;
465});
466​
467// In WSL2 mirrored mode the distro's eth0 IP equals the host's, which is the
468// signature we use to detect that mode and switch the renderer URL to loopback.
469const isLocalHostIpv4 = (ip: string): boolean => {
470 const interfaces = NodeOS.networkInterfaces();
471 for (const list of Object.values(interfaces)) {
472 if (!list) continue;
473 for (const entry of list) {
474 // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
475 // the Node build Electron ships (41 / Node 22, verified), but some Node
476 // builds report the numeric 4.
477 const family = String(entry.family);
478 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
479 }
480 }
481 return false;
482};
483​
484const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
485 ...Option.match(observabilitySettings.otlpTracesUrl, {
486 onNone: () => ({}),
487 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
488 }),
489 ...Option.match(observabilitySettings.otlpMetricsUrl, {
490 onNone: () => ({}),
491 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
492 }),
493 ...Option.match(observabilitySettings.otlpLogsUrl, {
494 onNone: () => ({}),
495 onSome: (otlpLogsUrl) => ({ otlpLogsUrl }),
496 }),
497});
498​
499const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
500 function* (
501 input: SharedBootstrapInput & {
502 readonly resourceMonitorPath: Option.Option<string>;
503 readonly cliPath: Option.Option<string>;
504 readonly shellEnvironmentPrepared: boolean;
505 },
506 ): Effect.fn.Return<
507 DesktopBackendManager.DesktopBackendStartConfig,
508 never,
509 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
510 > {
511 const environment = yield* DesktopEnvironment.DesktopEnvironment;
512 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
513 const backendExposure = yield* serverExposure.backendConfig;
514​
515 const bootstrap = {
516 mode: "desktop" as const,
517 noBrowser: true,
518 port: backendExposure.port,
519 t3Home: environment.baseDir,
520 host: backendExposure.bindHost,
521 desktopBootstrapToken: input.bootstrapToken,
522 desktopBootstrapSecret: input.bootstrapSecret,
523 // Failed Windows probes leave server hydration enabled for another attempt.
524 shellEnvironmentPrepared: input.shellEnvironmentPrepared,
525 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
526 tailscaleServePort: backendExposure.tailscaleServePort,
527 desktopTelemetryFd: 4,
528 desktopTelemetryControlFd: 5,
529 desktopBrowserFd: 6,
530 desktopBrowserControlFd: 7,
531 ...Option.match(input.resourceMonitorPath, {
532 onNone: () => ({}),
533 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
534 }),
535 ...buildObservabilityFragment(input.observabilitySettings),
536 };
537​
538 return {
539 executablePath: process.execPath,
540 // Packaged builds only, so a dev instance never shares the cache with the
541 // prod app it is often run from. `--require` rather than NODE_COMPILE_CACHE,
542 // so the setting does not leak into the provider and terminal processes
543 // the backend starts.
544 args: [
545 ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
546 environment.backendEntryPath,
547 "--bootstrap-fd",
548 "3",
549 ],
550 entryPath: environment.backendEntryPath,
551 cwd: environment.backendCwd,
552 env: {
553 ...backendChildEnvPatch(),
554 ELECTRON_RUN_AS_NODE: "1",
555 T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
556 },
557 extendEnv: true,
558 bootstrap,
559 bootstrapDelivery: "fd3",
560 httpBaseUrl: backendExposure.httpBaseUrl,
561 captureOutput: true,
562 preflightFailure: Option.none(),
563 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
564 },
565);
566​
567const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
568 input: SharedBootstrapInput & {
569 readonly port: number;
570 readonly distro: string | null;
571 },
572): Effect.fn.Return<
573 DesktopBackendManager.DesktopBackendStartConfig,
574 never,
575 | DesktopEnvironment.DesktopEnvironment
576 | DesktopWslEnvironment.DesktopWslEnvironment
577 | DesktopWslServerTree.DesktopWslServerTree
578 | FileSystem.FileSystem
579> {
580 const environment = yield* DesktopEnvironment.DesktopEnvironment;
581 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
582 const fileSystem = yield* FileSystem.FileSystem;
583​
584 // wslhost forwarding is unreliable on some Windows hosts: the desktop's
585 // readiness probe and the renderer's saved-env-style fetch both saw "Failed
586 // to fetch" when the backend only bound to 127.0.0.1 inside WSL. Binding to
587 // 0.0.0.0 plus advertising the WSL IP as the renderer-visible URL avoids that
588 // dependency.
589 const wslBindHost = "0.0.0.0";
590​
591 const bootstrap = {
592 mode: "desktop" as const,
593 noBrowser: true,
594 port: input.port,
595 // Omit t3Home so the Linux backend uses its own home dir instead of
596 // the Windows-side baseDir (which would be a /mnt/c path and share
597 // the SQLite file with the primary).
598 host: wslBindHost,
599 desktopBootstrapToken: input.bootstrapToken,
600 desktopBootstrapSecret: input.bootstrapSecret,
601 // PortSchema rejects 0, so when tailscale serve is disabled we still need a
602 // valid number in this slot.
603 tailscaleServeEnabled: false,
604 tailscaleServePort: 443,
605 ...buildObservabilityFragment(input.observabilitySettings),
606 };
607​
608 const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);
609 const archiveHashPath = environment.path.join(
610 environment.resourcesPath,
611 WSL_RUNTIME_ARCHIVE_HASH_NAME,
612 );
613​
614 const hasArchive = environment.isPackaged
615 ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))
616 : false;
617 const archiveHash = hasArchive
618 ? yield* fileSystem.readFileString(archiveHashPath).pipe(
619 Effect.map(parseWslRuntimeArchiveHash),
620 Effect.orElseSucceed(() => null),
621 )
622 : null;
623 if (hasArchive && archiveHash === null) {
624 yield* Effect.logWarning(
625 "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",
626 { hashPath: archiveHashPath },
627 );
628 }
629​
630 const preflight = yield* runWslPreflight({
631 distro: input.distro,
632 runtimeArchive:
633 archiveHash === null
634 ? null
635 : {
636 windowsPath: archivePath,
637 runtimeId: `sha256-${archiveHash}`,
638 sha256: archiveHash,
639 },
640 allowBuild: !environment.isPackaged,
641 });
642​
643 // Every operation after preflight uses the same concrete distro. In
644 // default-tracking mode this closes the race where the system default
645 // changes between probing and spawning the backend.
646 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
647 const distroForConfig = runningDistro ?? input.distro;
648​
649 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
650 const usesSharedNetworkStack = Option.match(distroIp, {
651 onNone: () => false,
652 onSome: (ip) => isLocalHostIpv4(ip),
653 });
654 const rendererHost = usesSharedNetworkStack
655 ? "127.0.0.1"
656 : Option.getOrElse(distroIp, () => "127.0.0.1");
657 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
658​
659 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
660 const forwardedEnv: Record<string, string> = {};
661 const forwardedEnvNames: string[] = [];
662 for (const name of WSL_FORWARDED_ENV_NAMES) {
663 const value = process.env[name];
664 if (value !== undefined && value.length > 0) {
665 forwardedEnv[name] = value;
666 forwardedEnvNames.push(name);
667 }
668 }
669​
670 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
671 for (const [key, value] of Object.entries(process.env)) {
672 if (key === "T3CODE_HOME") continue;
673 parentEnvWithoutT3Home[key] = value;
674 }
675 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
676​
677 const baseConfig = {
678 executablePath: "wsl.exe",
679 entryPath:
680 preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,
681 cwd: environment.backendCwd,
682 env: {
683 ...parentEnvWithoutT3Home,
684 ...backendChildEnvPatch(),
685 ...forwardedEnv,
686 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
687 },
688 // env is already a complete process.env minus T3CODE_HOME; pass it
689 // verbatim instead of letting the spawner re-merge process.env on top.
690 extendEnv: false,
691 bootstrap,
692 bootstrapDelivery: "stdin" as const,
693 httpBaseUrl,
694 captureOutput: true,
695 ...(runningDistro !== null ? { runningDistro } : {}),
696 };
697​
698 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
699 // config resolution lands in dev/ instead of userdata/.
700 const devUrlArgs = Option.match(environment.devServerUrl, {
701 onNone: () => [] as ReadonlyArray<string>,
702 onSome: (url) => ["--dev-url", url.href],
703 });
704​
705 if (preflight._tag === "Failed") {
706 const retryLimit =
707 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
708 return {
709 ...baseConfig,
710 args: [...distroArgs, "--", "node", "--version"],
711 preflightFailure: Option.some({
712 reason: preflight.reason,
713 fatal: preflight.fatal,
714 ...(retryLimit === undefined ? {} : { retryLimit }),
715 }),
716 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
717 }
718​
719 // The WSL server spawns commands its providers reference by name — `npm`/`npx`
720 // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
721 // live on the user's login-shell PATH, which `wsl.exe --exec` does NOT put on
722 // the process PATH, so `npm install -g ...` fails with NotFound.
723 const runtime = preflight.runtime;
724 const launchPath =
725 runtime.kind === "executable"
726 ? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
727 : `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
728 const command =
729 runtime.kind === "executable"
730 ? [runtime.entryPath]
731 : [runtime.nodePath, runtime.linuxEntryPath];
732​
733 return {
734 ...baseConfig,
735 args: [
736 ...distroArgs,
737 "--exec",
738 "env",
739 `PATH=${launchPath}`,
740 ...command,
741 "--bootstrap-fd",
742 "0",
743 ...devUrlArgs,
744 ],
745 preflightFailure: Option.none(),
746 ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),
747 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
748});
749​
750/** @public Service construction is part of the canonical Effect module API. */
751export const make = Effect.gen(function* () {
752 const environment = yield* DesktopEnvironment.DesktopEnvironment;
753 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
754 const fileSystem = yield* FileSystem.FileSystem;
755 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
756 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
757 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
758 const settings = yield* DesktopAppSettings.DesktopAppSettings;
759 const crypto = yield* Crypto.Crypto;
760 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
761 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
762 // resolve concurrently; with a plain Ref both could observe None, generate
763 // distinct secrets, and one would overwrite the other — leaving the two
764 // backends deriving mismatched tokens and breaking the shared-token invariant
765 // the renderer relies on.
766 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
767 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
768 Option.match(current, {
769 onSome: (secret) => Effect.succeed([secret, current] as const),
770 onNone: () =>
771 crypto.randomBytes(32).pipe(
772 Effect.map((bytes) => {
773 const secret = Hex.encode(bytes);
774 return [secret, Option.some(secret)] as const;
775 }),
776 ),
777 }),
778 );
779​
780 const sharedInputs = Effect.gen(function* () {
781 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
782 const bootstrapToken = currentDesktopBootstrapToken(
783 bootstrapSecret,
784 yield* Clock.currentTimeMillis,
785 );
786 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
787 Effect.provideService(FileSystem.FileSystem, fileSystem),
788 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
789 );
790 return {
791 bootstrapToken,
792 bootstrapSecret,
793 observabilitySettings,
794 } satisfies SharedBootstrapInput;
795 });
796​
797 const buildWslPrimaryConfig = Effect.gen(function* () {
798 const backendExposure = yield* serverExposure.backendConfig;
799 const persistedSettings = yield* settings.get;
800 const shared = yield* sharedInputs;
801 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
802 return yield* resolveWslStartConfig({
803 ...shared,
804 port: backendExposure.port,
805 distro: persistedSettings.wslDistro,
806 }).pipe(
807 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
808 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
809 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
810 Effect.provideService(FileSystem.FileSystem, fileSystem),
811 );
812 });
813​
814 const buildWindowsPrimaryConfig = Effect.gen(function* () {
815 const shared = yield* sharedInputs;
816 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
817 Effect.provideService(FileSystem.FileSystem, fileSystem),
818 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
819 );
820 const cliPath = yield* DesktopCliShim.install.pipe(
821 Effect.provideService(FileSystem.FileSystem, fileSystem),
822 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
823 );
824 const shellEnvironmentPrepared = yield* shellEnvironment.installIntoProcess;
825 return yield* resolvePrimaryStartConfig({
826 ...shared,
827 resourceMonitorPath,
828 cliPath,
829 shellEnvironmentPrepared,
830 }).pipe(
831 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
832 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
833 );
834 });
835​
836 // Dispatch happens at resolve time so toggling wsl-only between restarts
837 // is picked up on the next start cycle (the pool's primary instance is
838 // created once at layer init, but configResolve fires on each restart).
839 const describePrimary = Effect.gen(function* () {
840 const persistedSettings = yield* settings.get;
841 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
842 // Only honor wsl-only when WSL is actually usable. If the user
843 // persisted wsl-only but WSL has since become unavailable (wsl.exe
844 // removed, no distro), fall back to the Windows primary instead of
845 // looping forever on preflight failures: the Connections backend
846 // control is hidden while WSL is unavailable, so a stuck WSL primary
847 // would otherwise leave no in-app way back to Windows.
848 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
849 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
850 });
851​
852 const currentBootstrapToken = Effect.gen(function* () {
853 const secret = yield* getOrCreateBootstrapSecret;
854 return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
855 });
856​
857 return DesktopBackendConfiguration.of({
858 currentBootstrapToken,
859 resolvePrimary: Effect.gen(function* () {
860 const { useWsl, wslRequested } = yield* describePrimary;
861 if (useWsl) {
862 return yield* buildWslPrimaryConfig;
863 }
864 if (wslRequested) {
865 yield* Effect.logWarning(
866 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
867 );
868 }
869 return yield* buildWindowsPrimaryConfig;
870 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
871 resolvePrimaryLabel: Effect.gen(function* () {
872 const { useWsl, distro } = yield* describePrimary;
873 if (!useWsl) {
874 return environment.platform === "win32" ? "Windows" : "Local environment";
875 }
876 return distro ? `WSL (${distro})` : "WSL";
877 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
878 // The span options depend on each request's port and distro.
879 resolveWsl: Effect.fnUntraced(
880 function* (input) {
881 const shared = yield* sharedInputs;
882 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
883 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
884 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
885 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
886 Effect.provideService(FileSystem.FileSystem, fileSystem),
887 );
888 },
889 (effect, input) =>
890 effect.pipe(
891 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
892 attributes: { port: input.port, distro: input.distro ?? null },
893 }),
894 ),
895 ),
896 });
897});
898​
899export const layer = Layer.effect(DesktopBackendConfiguration, make);