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