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