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

DesktopBackendConfiguration.ts

947 lines34.6 KB

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