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

DesktopBackendConfiguration.ts

908 lines33.1 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;
246 readonly hostScope: string;
248​
249// Matches the server's DESKTOP_HOST_SCOPE_ENV.
250const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE";
251const HOST_SCOPE_FILE_NAME = "desktop-host-scope";
252const HOST_SCOPE_PATTERN = /^[0-9a-f]{32}$/;
253​
254/**
255 * Not a credential: it only tells this install's Windows and WSL servers that
256 * they run on one machine, so usage both read from one Windows directory counts
257 * once. Persisted so summaries from earlier launches still match.
258 */
259const readOrCreateHostScope = Effect.gen(function* () {
260 const fileSystem = yield* FileSystem.FileSystem;
261 const environment = yield* DesktopEnvironment.DesktopEnvironment;
262 const random = yield* SecureRandom.SecureRandom;
263 const scopePath = environment.path.join(environment.stateDir, HOST_SCOPE_FILE_NAME);
264 const existing = (yield* fileSystem
265 .readFileString(scopePath)
266 .pipe(Effect.orElseSucceed(() => ""))).trim();
267 if (HOST_SCOPE_PATTERN.test(existing)) return existing;
268 const scope = Hex.encode(yield* random.randomBytes(16).pipe(Effect.orDie));
269 yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }).pipe(
270 Effect.andThen(fileSystem.writeFileString(scopePath, scope)),
271 Effect.catch((cause) =>
272 Effect.logWarning("Could not persist the desktop host scope.", { cause }),
273 ),
274 );
275 return scope;
276});
277​
278type WslPreflightRuntime =
279 | {
280 readonly kind: "executable";
281 readonly entryPath: string;
282 }
283 | {
284 readonly kind: "node-script";
285 // Launch the exact Node path probed with node-pty, even if later PATH lookup would resolve another version.
286 readonly nodePath: string;
287 readonly linuxEntryPath: string;
288 };
289​
290interface WslPreflightSuccess {
291 readonly _tag: "Ready";
292 readonly runningDistro: string;
293 readonly windowsEntryPath: string;
294 readonly runtime: WslPreflightRuntime;
295 readonly resolvedPath: string;
296 readonly runtimeId?: string;
298​
299interface WslPreflightFailure {
300 readonly _tag: "Failed";
301 readonly reason: string;
302 readonly fatal: boolean;
303 readonly retryLimit?: number;
305​
306const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
307const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
308const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
309const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i;
310​
311const parseWslRuntimeArchiveHash = (value: string): string | null => {
312 const trimmed = value.trim();
313 return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
314};
315​
316type FailedNodePtyResult = Extract<
317 DesktopWslEnvironment.EnsureWslNodePtyResult,
318 { readonly ok: false }
319>;
320​
321const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
322 readonly distro: string | null;
323 readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null;
324 readonly allowBuild: boolean;
325}): Effect.fn.Return<
326 WslPreflightSuccess | WslPreflightFailure,
327 never,
328 | DesktopEnvironment.DesktopEnvironment
329 | DesktopWslEnvironment.DesktopWslEnvironment
330 | DesktopWslServerTree.DesktopWslServerTree
331 | FileSystem.FileSystem
332> {
333 const environment = yield* DesktopEnvironment.DesktopEnvironment;
334 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
335 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
336 const fileSystem = yield* FileSystem.FileSystem;
337​
338 const wslAvailable = yield* wslEnv.isAvailable;
339 if (!wslAvailable) {
340 return {
341 _tag: "Failed",
342 reason: "WSL is not available on this system",
343 fatal: false,
344 } as const;
345 }
346​
347 const distroProbe = yield* wslEnv.probeDistros.pipe(
348 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
349 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
350 );
351 if (distroProbe._tag === "Failure") {
352 return {
353 _tag: "Failed",
354 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
355 fatal: false,
356 } as const;
357 }
358​
359 const installedDistros = distroProbe.distros;
360 const runningDistro = input.distro
361 ? (installedDistros.find(
362 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
363 )?.name ?? null)
364 : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
365 if (runningDistro === null) {
366 return {
367 _tag: "Failed",
368 reason: input.distro
369 ? `WSL distro is not installed: ${input.distro}`
370 : installedDistros.length === 0
371 ? "WSL has no installed distributions"
372 : "WSL has no default distribution",
373 fatal: true,
374 } as const;
375 }
376​
377 const nodePtyOptions = {
378 allowBuild: input.allowBuild,
379 nodeEngineRange: serverPackageJson.engines.node,
380 };
381 const failedNodePty = (result: FailedNodePtyResult) =>
382 ({
383 _tag: "Failed",
384 reason: `WSL node-pty unavailable: ${result.reason}`,
385 fatal: result.fatal,
386 ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }),
387 }) as const;
388​
389 const resolveMountedAppRoot = Effect.gen(function* () {
390 const serverTree = yield* wslServerTree.ensure;
391 if (!serverTree.ok) {
392 return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const;
393 }
394 const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs");
395 const entryExists = yield* fileSystem
396 .exists(windowsEntryPath)
397 .pipe(Effect.orElseSucceed(() => false));
398 if (!entryExists) {
399 return {
400 ok: false,
401 reason: `missing server entry at ${windowsEntryPath}`,
402 fatal: true,
403 } as const;
404 }
405 const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root);
406 return Option.isNone(mountedAppRoot)
407 ? ({
408 ok: false,
409 reason: `wslpath conversion failed for ${serverTree.root}`,
410 fatal: false,
411 } as const)
412 : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const);
413 });
414​
415 let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined;
416 const failedStaged = (failure: { readonly reason: string }) =>
417 ({
418 _tag: "Failed",
419 reason: `WSL runtime unavailable: ${failure.reason}`,
420 fatal: true,
421 }) as const;
422​
423 if (input.runtimeArchive !== null) {
424 const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive);
425 if (runtime.ok) {
426 // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them.
427 const stagedProbe = yield* wslEnv.probeRuntime(runningDistro);
428 if (stagedProbe.ok) {
429 yield* wslServerTree.cleanupLegacy;
430 return {
431 _tag: "Ready",
432 runningDistro,
433 windowsEntryPath: environment.backendEntryPath,
434 runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` },
435 resolvedPath: stagedProbe.resolvedPath,
436 runtimeId: input.runtimeArchive.runtimeId,
437 } as const;
438 }
439 yield* Effect.logWarning(
440 "The staged WSL runtime probe failed; retrying from the mounted server tree.",
441 { reason: stagedProbe.reason },
442 );
443 stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason };
444 } else {
445 stagedFailure = { reason: runtime.reason };
446 yield* Effect.logWarning(
447 "Could not stage the WSL runtime; launching from the mounted server tree instead.",
448 { reason: runtime.reason },
449 );
450 }
451 }
452​
453 const mounted = yield* resolveMountedAppRoot;
454 if (!mounted.ok) {
455 return stagedFailure && mounted.fatal
456 ? failedStaged(stagedFailure)
457 : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const);
458 }
459​
460 const nodePtyResult = yield* wslEnv.ensureNodePty(
461 runningDistro,
462 mounted.linuxAppRoot,
463 nodePtyOptions,
464 );
465 if (!nodePtyResult.ok) {
466 // Only substitute a staged failure for a fatal mounted failure; transient /mnt failures must remain retryable.
467 return stagedFailure && nodePtyResult.fatal
468 ? failedStaged(stagedFailure)
469 : failedNodePty(nodePtyResult);
470 }
471​
472 if (stagedFailure?.runtimeId) {
473 yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId);
474 }
475​
476 return {
477 _tag: "Ready",
478 runningDistro,
479 windowsEntryPath: mounted.windowsEntryPath,
480 runtime: {
481 kind: "node-script",
482 nodePath: nodePtyResult.nodePath,
483 linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`,
484 },
485 resolvedPath: nodePtyResult.resolvedPath,
486 } as const;
487});
488​
489// In WSL2 mirrored mode, eth0 matches a host IP; use loopback for the renderer.
490const isLocalHostIpv4 = (ip: string): boolean => {
491 const interfaces = NodeOS.networkInterfaces();
492 for (const list of Object.values(interfaces)) {
493 if (!list) continue;
494 for (const entry of list) {
495 const family = String(entry.family);
496 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
497 }
498 }
499 return false;
500};
501​
502const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
503 ...Option.match(observabilitySettings.otlpTracesUrl, {
504 onNone: () => ({}),
505 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
506 }),
507 ...Option.match(observabilitySettings.otlpMetricsUrl, {
508 onNone: () => ({}),
509 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
510 }),
511 ...Option.match(observabilitySettings.otlpLogsUrl, {
512 onNone: () => ({}),
513 onSome: (otlpLogsUrl) => ({ otlpLogsUrl }),
514 }),
515});
516​
517const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
518 function* (
519 input: SharedBootstrapInput & {
520 readonly resourceMonitorPath: Option.Option<string>;
521 readonly cliPath: Option.Option<string>;
522 readonly shellEnvironmentPrepared: boolean;
523 readonly desktopAppUpdate: boolean;
524 },
525 ): Effect.fn.Return<
526 DesktopBackendManager.DesktopBackendStartConfig,
527 never,
528 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
529 > {
530 const environment = yield* DesktopEnvironment.DesktopEnvironment;
531 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
532 const backendExposure = yield* serverExposure.backendConfig;
533​
534 const bootstrap = {
535 mode: "desktop" as const,
536 noBrowser: true,
537 port: backendExposure.port,
538 t3Home: environment.baseDir,
539 host: backendExposure.bindHost,
540 desktopBootstrapToken: input.bootstrapToken,
541 desktopBootstrapSecret: input.bootstrapSecret,
542 shellEnvironmentPrepared: input.shellEnvironmentPrepared,
543 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
544 tailscaleServePort: backendExposure.tailscaleServePort,
545 desktopTelemetryFd: 4,
546 desktopTelemetryControlFd: 5,
547 desktopAppUpdate: input.desktopAppUpdate,
548 desktopBrowserFd: 6,
549 desktopBrowserControlFd: 7,
550 ...Option.match(input.resourceMonitorPath, {
551 onNone: () => ({}),
552 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
553 }),
554 ...buildObservabilityFragment(input.observabilitySettings),
555 };
556​
557 return {
558 executablePath: process.execPath,
559 // Packaged builds have a separate cache; --require prevents cache settings leaking to provider subprocesses.
560 args: [
561 ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []),
562 environment.backendEntryPath,
563 "--bootstrap-fd",
564 "3",
565 ],
566 entryPath: environment.backendEntryPath,
567 cwd: environment.backendCwd,
568 env: {
569 ...backendChildEnvPatch(),
570 ELECTRON_RUN_AS_NODE: "1",
571 T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
572 T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
573 [DESKTOP_HOST_SCOPE_ENV]: input.hostScope,
574 },
575 extendEnv: true,
576 bootstrap,
577 bootstrapDelivery: "fd3",
578 httpBaseUrl: backendExposure.httpBaseUrl,
579 captureOutput: true,
580 preflightFailure: Option.none(),
581 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
582 },
583);
584​
585const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
586 input: SharedBootstrapInput & {
587 readonly port: number;
588 readonly distro: string | null;
589 },
590): Effect.fn.Return<
591 DesktopBackendManager.DesktopBackendStartConfig,
592 never,
593 | DesktopEnvironment.DesktopEnvironment
594 | DesktopWslEnvironment.DesktopWslEnvironment
595 | DesktopWslServerTree.DesktopWslServerTree
596 | FileSystem.FileSystem
597> {
598 const environment = yield* DesktopEnvironment.DesktopEnvironment;
599 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
600 const fileSystem = yield* FileSystem.FileSystem;
601 const env = yield* HostProcess.Environment;
602​
603 // wslhost loopback forwarding is unreliable on some Windows hosts; advertise the WSL IP instead.
604 const wslBindHost = "0.0.0.0";
605​
606 const bootstrap = {
607 mode: "desktop" as const,
608 noBrowser: true,
609 port: input.port,
610 // Omit t3Home to keep the Linux backend from sharing the primary's Windows SQLite file.
611 host: wslBindHost,
612 desktopBootstrapToken: input.bootstrapToken,
613 desktopBootstrapSecret: input.bootstrapSecret,
614 // PortSchema rejects 0 even when Tailscale Serve is disabled.
615 tailscaleServeEnabled: false,
616 tailscaleServePort: 443,
617 ...buildObservabilityFragment(input.observabilitySettings),
618 };
619​
620 const archivePath = environment.path.join(environment.resourcesPath, WSL_RUNTIME_ARCHIVE_NAME);
621 const archiveHashPath = environment.path.join(
622 environment.resourcesPath,
623 WSL_RUNTIME_ARCHIVE_HASH_NAME,
624 );
625​
626 const hasArchive = environment.isPackaged
627 ? yield* fileSystem.exists(archivePath).pipe(Effect.orElseSucceed(() => false))
628 : false;
629 const archiveHash = hasArchive
630 ? yield* fileSystem.readFileString(archiveHashPath).pipe(
631 Effect.map(parseWslRuntimeArchiveHash),
632 Effect.orElseSucceed(() => null),
633 )
634 : null;
635 if (hasArchive && archiveHash === null) {
636 yield* Effect.logWarning(
637 "Ignoring the WSL runtime archive because its SHA-256 identity is missing or invalid; launching from the mounted server tree instead.",
638 { hashPath: archiveHashPath },
639 );
640 }
641​
642 const preflight = yield* runWslPreflight({
643 distro: input.distro,
644 runtimeArchive:
645 archiveHash === null
646 ? null
647 : {
648 windowsPath: archivePath,
649 runtimeId: `sha256-${archiveHash}`,
650 sha256: archiveHash,
651 },
652 allowBuild: !environment.isPackaged,
653 });
654​
655 // Pin the preflight distro so a default change cannot race backend startup.
656 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
657 const distroForConfig = runningDistro ?? input.distro;
658​
659 const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
660 const usesSharedNetworkStack = Option.match(distroIp, {
661 onNone: () => false,
662 onSome: (ip) => isLocalHostIpv4(ip),
663 });
664 const rendererHost = usesSharedNetworkStack
665 ? "127.0.0.1"
666 : Option.getOrElse(distroIp, () => "127.0.0.1");
667 const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
668​
669 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
670 const forwardedEnv: Record<string, string> = { [DESKTOP_HOST_SCOPE_ENV]: input.hostScope };
671 const forwardedEnvNames: string[] = [DESKTOP_HOST_SCOPE_ENV];
672 for (const name of WSL_FORWARDED_ENV_NAMES) {
673 const value = env[name];
674 if (value !== undefined && value.length > 0) {
675 forwardedEnv[name] = value;
676 forwardedEnvNames.push(name);
677 }
678 }
679​
680 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
681 for (const [key, value] of Object.entries(env)) {
682 if (key === "T3CODE_HOME") continue;
683 parentEnvWithoutT3Home[key] = value;
684 }
685 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
686​
687 const baseConfig = {
688 executablePath: "wsl.exe",
689 entryPath:
690 preflight._tag === "Ready" ? preflight.windowsEntryPath : environment.backendEntryPath,
691 cwd: environment.backendCwd,
692 env: {
693 ...parentEnvWithoutT3Home,
694 ...backendChildEnvPatch(),
695 ...forwardedEnv,
696 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
697 },
698 // env already excludes T3CODE_HOME; merging the host env would restore it.
699 extendEnv: false,
700 bootstrap,
701 bootstrapDelivery: "stdin" as const,
702 httpBaseUrl,
703 captureOutput: true,
704 ...(runningDistro !== null ? { runningDistro } : {}),
705 };
706​
707 // Explicit --dev-url keeps WSL state in dev/ rather than userdata/.
708 const devUrlArgs = Option.match(environment.devServerUrl, {
709 onNone: () => [] as ReadonlyArray<string>,
710 onSome: (url) => ["--dev-url", url.href],
711 });
712​
713 if (preflight._tag === "Failed") {
714 const retryLimit =
715 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
716 return {
717 ...baseConfig,
718 args: [...distroArgs, "--", "node", "--version"],
719 preflightFailure: Option.some({
720 reason: preflight.reason,
721 fatal: preflight.fatal,
722 ...(retryLimit === undefined ? {} : { retryLimit }),
723 }),
724 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
725 }
726​
727 // wsl.exe --exec omits the login-shell PATH needed to find provider CLIs and npm.
728 const runtime = preflight.runtime;
729 const launchPath =
730 runtime.kind === "executable"
731 ? `${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`
732 : `${nodeBinDirOf(runtime.nodePath)}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
733 const command =
734 runtime.kind === "executable"
735 ? [runtime.entryPath]
736 : [runtime.nodePath, runtime.linuxEntryPath];
737​
738 return {
739 ...baseConfig,
740 args: [
741 ...distroArgs,
742 // WSL otherwise inherits the Windows-mounted desktop working directory.
743 "--cd",
744 "~",
745 "--exec",
746 "env",
747 `PATH=${launchPath}`,
748 ...command,
749 "--bootstrap-fd",
750 "0",
751 ...devUrlArgs,
752 ],
753 preflightFailure: Option.none(),
754 ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }),
755 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
756});
757​
758/** @public */
759export const make = Effect.gen(function* () {
760 const environment = yield* DesktopEnvironment.DesktopEnvironment;
761 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
762 const fileSystem = yield* FileSystem.FileSystem;
763 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
764 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
765 const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
766 const settings = yield* DesktopAppSettings.DesktopAppSettings;
767 const desktopState = yield* DesktopState.DesktopState;
768 const mac = yield* Mac.Mac;
769 const random = yield* SecureRandom.SecureRandom;
770 // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.
771 const secretRef = yield* SynchronizedRef.make(Option.none<string>());
772 const hostScope = yield* Effect.cached(
773 readOrCreateHostScope.pipe(
774 Effect.provideService(FileSystem.FileSystem, fileSystem),
775 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
776 Effect.provideService(SecureRandom.SecureRandom, random),
777 ),
778 );
779 const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
780 Option.match(current, {
781 onSome: (secret) => Effect.succeed([secret, current] as const),
782 onNone: () =>
783 random.randomBytes(32).pipe(
784 Effect.map((bytes) => {
785 const secret = Hex.encode(bytes);
786 return [secret, Option.some(secret)] as const;
787 }),
788 ),
789 }),
790 );
791​
792 const sharedInputs = Effect.gen(function* () {
793 const bootstrapSecret = yield* getOrCreateBootstrapSecret;
794 const bootstrapToken = yield* currentDesktopBootstrapToken(
795 bootstrapSecret,
796 yield* Clock.currentTimeMillis,
797 ).pipe(Effect.provideService(Mac.Mac, mac));
798 const observabilitySettings = yield* readBackendObservabilitySettings.pipe(
799 Effect.provideService(FileSystem.FileSystem, fileSystem),
800 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
801 );
802 return {
803 bootstrapToken,
804 bootstrapSecret,
805 observabilitySettings,
806 hostScope: yield* hostScope,
807 } satisfies SharedBootstrapInput;
808 });
809​
810 const buildWslPrimaryConfig = Effect.gen(function* () {
811 const backendExposure = yield* serverExposure.backendConfig;
812 const persistedSettings = yield* settings.get;
813 const shared = yield* sharedInputs;
814 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
815 return yield* resolveWslStartConfig({
816 ...shared,
817 port: backendExposure.port,
818 distro: persistedSettings.wslDistro,
819 }).pipe(
820 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
821 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
822 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
823 Effect.provideService(FileSystem.FileSystem, fileSystem),
824 );
825 });
826​
827 const buildWindowsPrimaryConfig = Effect.gen(function* () {
828 const shared = yield* sharedInputs;
829 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
830 Effect.provideService(FileSystem.FileSystem, fileSystem),
831 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
832 );
833 const cliPath = yield* DesktopCliShim.install.pipe(
834 Effect.provideService(FileSystem.FileSystem, fileSystem),
835 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
836 );
837 const shellEnvironmentPrepared = yield* shellEnvironment.installIntoProcess;
838 return yield* resolvePrimaryStartConfig({
839 ...shared,
840 resourceMonitorPath,
841 cliPath,
842 shellEnvironmentPrepared,
843 desktopAppUpdate: yield* Ref.get(desktopState.canInstallUpdates),
844 }).pipe(
845 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
846 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
847 );
848 });
849​
850 // Resolve on each restart so toggling wsl-only takes effect without recreating the pool.
851 const describePrimary = Effect.gen(function* () {
852 const persistedSettings = yield* settings.get;
853 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
854 // When WSL is unavailable its controls are hidden; fall back to Windows to keep recovery possible.
855 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
856 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
857 });
858​
859 const currentBootstrapToken = Effect.gen(function* () {
860 const secret = yield* getOrCreateBootstrapSecret;
861 return yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe(
862 Effect.provideService(Mac.Mac, mac),
863 );
864 });
865​
866 return DesktopBackendConfiguration.of({
867 currentBootstrapToken,
868 resolvePrimary: Effect.gen(function* () {
869 const { useWsl, wslRequested } = yield* describePrimary;
870 if (useWsl) {
871 return yield* buildWslPrimaryConfig;
872 }
873 if (wslRequested) {
874 yield* Effect.logWarning(
875 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
876 );
877 }
878 return yield* buildWindowsPrimaryConfig;
879 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
880 resolvePrimaryLabel: Effect.gen(function* () {
881 const { useWsl, distro } = yield* describePrimary;
882 if (!useWsl) {
883 return environment.platform === "win32" ? "Windows" : "Local environment";
884 }
885 return distro ? `WSL (${distro})` : "WSL";
886 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
887 // The span options depend on each request's port and distro.
888 resolveWsl: Effect.fnUntraced(
889 function* (input) {
890 const shared = yield* sharedInputs;
891 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
892 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
893 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
894 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
895 Effect.provideService(FileSystem.FileSystem, fileSystem),
896 );
897 },
898 (effect, input) =>
899 effect.pipe(
900 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
901 attributes: { port: input.port, distro: input.distro ?? null },
902 }),
903 ),
904 ),
905 });
906});
907​
908export const layer = Layer.effect(DesktopBackendConfiguration, make);