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

DesktopBackendConfiguration.ts

821 lines33.3 KB

1import * as NodeOS from "node:os";
2​
3import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as Encoding from "effect/Encoding";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as SynchronizedRef from "effect/SynchronizedRef";
14​
15import serverPackageJson from "../../../server/package.json" with { type: "json" };
16​
17import * as DesktopBackendManager from "./DesktopBackendManager.ts";
18import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
19import * as DesktopServerExposure from "./DesktopServerExposure.ts";
20import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
21import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
22​
23export type WslBackendPortStrategy = "fixed" | "wsl-auto";
24​
25export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
26 "DesktopBackendObservabilitySettingsReadError",
27 {
28 settingsPath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
34 }
36​
37export class DesktopBackendConfiguration extends Context.Service<
38 DesktopBackendConfiguration,
39 {
40 // Build the Windows-native primary backend's start config. Reads the
41 // primary's port/host/exposure from DesktopServerExposure. Can fail
42 // with PlatformError because bootstrap token generation now uses
43 // crypto.randomBytes under the hood (post Effect 4 migration).
44 readonly resolvePrimary: Effect.Effect<
45 DesktopBackendManager.DesktopBackendStartConfig,
46 PlatformError.PlatformError
47 >;
48 // Build a WSL backend start config for the given distro on the given
49 // port. The WSL backend is private to the desktop app: WSL2 NAT mode binds
50 // only the distro's concrete IPv4 address, while mirrored/fallback mode
51 // binds loopback. It never binds every Linux interface. Distro=null means
52 // "WSL default distro" and is resolved to one concrete distro in preflight.
53 readonly resolveWsl: (input: {
54 readonly port: number;
55 readonly distro: string | null;
56 // `fixed` is used by the WSL-only primary because the production
57 // desktop protocol is registered against the configured primary port.
58 // `wsl-auto` is used by dual-mode secondary backends: the preferred
59 // number is tested inside Linux and WSL may fall back to a kernel-chosen
60 // ephemeral port when it is occupied there.
61 readonly portStrategy?: WslBackendPortStrategy;
62 }) => Effect.Effect<
63 DesktopBackendManager.DesktopBackendStartConfig,
64 PlatformError.PlatformError
65 >;
66 // The renderer-facing label for the primary instance, derived from the
67 // same decision resolvePrimary makes (including the WSL-availability
68 // fall-back to Windows), so the env switcher can't show "WSL" for a
69 // backend that actually resolved to Windows.
70 readonly resolvePrimaryLabel: Effect.Effect<string>;
71 }
72>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
73​
74interface BackendObservabilitySettings {
75 readonly otlpTracesUrl: Option.Option<string>;
76 readonly otlpMetricsUrl: Option.Option<string>;
78​
79const emptyBackendObservabilitySettings: BackendObservabilitySettings = {
80 otlpTracesUrl: Option.none(),
81 otlpMetricsUrl: Option.none(),
82};
83​
84const DESKTOP_BACKEND_ENV_NAMES = [
85 "T3CODE_PORT",
86 "T3CODE_MODE",
87 "T3CODE_NO_BROWSER",
88 "T3CODE_HOST",
89 "T3CODE_DESKTOP_WS_URL",
90 "T3CODE_DESKTOP_LAN_ACCESS",
91 "T3CODE_DESKTOP_LAN_HOST",
92 "T3CODE_DESKTOP_HTTPS_ENDPOINTS",
93 "T3CODE_TAILSCALE_SERVE",
94 "T3CODE_TAILSCALE_SERVE_PORT",
95] as const;
96​
97// Sensitive env vars that the WSL backend needs but Windows process.env won't
98// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
99// handled separately via a `--dev-url` CLI flag because WSLENV translation of
100// URL-shaped values (colons / slashes) is unreliable.
101const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
102​
103const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
104​
105const backendChildEnvPatch = (): Record<string, string | undefined> =>
106 Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
107​
108const getWslEnvEntryName = (entry: string): string => {
109 const slashIndex = entry.indexOf("/");
110 return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
111};
112​
113const mergeWslEnv = (
114 existingWslEnv: string | undefined,
115 forwardedEnvNames: ReadonlyArray<string>,
116): string | undefined => {
117 const existing = existingWslEnv?.trim() ?? "";
118​
119 // Names already declared, so we don't forward a duplicate. We parse the
120 // existing value only for this membership test — the string itself is
121 // preserved verbatim below rather than re-serialized.
122 const seenNames = new Set(
123 existing
124 .split(":")
125 .map((entry) => getWslEnvEntryName(entry.trim()))
126 .filter((name) => name.length > 0),
127 );
128​
129 const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
130​
131 // Preserve the user's WSLENV exactly as Windows handed it to us — empty
132 // "::" segments and duplicate entries are harmless no-ops to WSL and not
133 // ours to normalize — and only append the secrets we need to forward
134 // across the wsl.exe boundary.
135 const parts = [existing, ...additions].filter((part) => part.length > 0);
136 return parts.length > 0 ? parts.join(":") : undefined;
137};
138​
139const logBackendObservabilitySettingsReadFailure = (
140 settingsPath: string,
141 cause: PlatformError.PlatformError,
142) => {
143 const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
144 return Effect.logWarning(error).pipe(
145 Effect.annotateLogs({
146 component: "desktop-backend-configuration",
147 error,
148 }),
149 );
150};
151​
152function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
153 return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
155​
156const resolveResourceMonitorPath = Effect.fn(
157 "desktop.backendConfiguration.resolveResourceMonitorPath",
158)(function* () {
159 const environment = yield* DesktopEnvironment.DesktopEnvironment;
160 const fileSystem = yield* FileSystem.FileSystem;
161 const binaryName = resourceMonitorBinaryName(environment.platform);
162 const candidates = environment.isDevelopment
163 ? [
164 environment.path.join(
165 environment.rootDir,
166 "native/resource-monitor/target/release",
167 binaryName,
168 ),
169 environment.path.join(
170 environment.rootDir,
171 "native/resource-monitor/target/debug",
172 binaryName,
173 ),
174 ]
175 : environment.isPackaged
176 ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)]
177 : environment.resolveResourcePathCandidates(
178 environment.path.join("resource-monitor", binaryName),
179 );
180​
181 for (const candidate of candidates) {
182 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
183 return Option.some(candidate);
184 }
185 }
186​
187 return Option.none<string>();
188});
189​
190const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
191 const fileSystem = yield* FileSystem.FileSystem;
192 const environment = yield* DesktopEnvironment.DesktopEnvironment;
193 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
194 Effect.map(Option.some),
195 Effect.catchTags({
196 PlatformError: (cause) =>
197 cause.reason._tag === "NotFound"
198 ? Effect.succeed(Option.none())
199 : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
200 Effect.as(Option.none()),
201 ),
202 }),
203 );
204 if (Option.isNone(raw)) {
205 return emptyBackendObservabilitySettings;
206 }
207​
208 const parsed = parsePersistedServerObservabilitySettings(raw.value);
209 return {
210 otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl),
211 otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl),
212 };
213});
214​
215interface SharedBootstrapInput {
216 readonly bootstrapToken: string;
217 readonly observabilitySettings: BackendObservabilitySettings;
219​
220interface WslPreflightSuccess {
221 readonly _tag: "Ready";
222 readonly runningDistro: string;
223 readonly linuxEntryPath: string;
224 // Absolute path to the node binary the preflight validated after the shared
225 // remote resolver repaired PATH. The launch must use this exact path so it
226 // doesn't fall through to a different/old node than the one node-pty was
227 // built against.
228 readonly nodePath: string;
229 // PATH captured from the same login shell after the shared resolver loaded
230 // version managers. The launch forwards this value directly without a shell.
231 readonly resolvedPath: string;
233​
234interface WslPreflightFailure {
235 readonly _tag: "Failed";
236 readonly reason: string;
237 // Fatal: the WSL distro is misconfigured (no node, wrong version, missing
238 // build tools) and retrying won't help — surface it and (wsl-only) fall back
239 // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
240 // boots), with a bounded window for self-healing before fallback.
241 readonly fatal: boolean;
242 readonly retryLimit?: number;
244​
245const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
246const WSL_PORT_ALLOCATION_RETRY_LIMIT = 3;
247​
248const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
249 readonly distro: string | null;
250 readonly windowsEntryPath: string;
251 readonly windowsRepoRoot: string;
252 readonly allowBuild: boolean;
253 readonly bundledNodeWindowsPath?: string | null;
254}): Effect.fn.Return<
255 WslPreflightSuccess | WslPreflightFailure,
256 never,
257 DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
258> {
259 const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
260 const fileSystem = yield* FileSystem.FileSystem;
261​
262 const wslAvailable = yield* wslEnv.isAvailable;
263 if (!wslAvailable) {
264 return {
265 _tag: "Failed",
266 reason: "WSL is not available on this system",
267 fatal: false,
268 } as const;
269 }
270​
271 const distroProbe = yield* wslEnv.probeDistros.pipe(
272 Effect.map((distros) => ({ _tag: "Success", distros }) as const),
273 Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
274 );
275 if (distroProbe._tag === "Failure") {
276 return {
277 _tag: "Failed",
278 reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
279 fatal: false,
280 } as const;
281 }
282​
283 const installedDistros = distroProbe.distros;
284 const runningDistroRecord = input.distro
285 ? (installedDistros.find(
286 (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
287 ) ?? null)
288 : (installedDistros.find((installed) => installed.isDefault) ?? null);
289 if (runningDistroRecord === null) {
290 return {
291 _tag: "Failed",
292 reason: input.distro
293 ? `WSL distro is not installed: ${input.distro}`
294 : installedDistros.length === 0
295 ? "WSL has no installed distributions"
296 : "WSL has no default distribution",
297 fatal: true,
298 } as const;
299 }
300​
301 // The desktop transport below relies on WSL2 networking semantics. WSL1
302 // shares the Windows network stack differently and does not provide the
303 // distro-address contract used for direct host-to-guest backend access.
304 // Fail closed before touching paths or native modules so a WSL1 install
305 // never enters a half-working/restart-loop state.
306 if (runningDistroRecord.version !== 2) {
307 return {
308 _tag: "Failed",
309 reason: `WSL distro "${runningDistroRecord.name}" is using WSL 1, which T3 Code does not support. Convert it to WSL 2 with \`wsl.exe --set-version "${runningDistroRecord.name}" 2\`, then retry.`,
310 fatal: true,
311 } as const;
312 }
313 const runningDistro = runningDistroRecord.name;
314​
315 const entryExists = yield* fileSystem
316 .exists(input.windowsEntryPath)
317 .pipe(Effect.orElseSucceed(() => false));
318 if (!entryExists) {
319 return {
320 _tag: "Failed",
321 reason: `missing server entry at ${input.windowsEntryPath}`,
322 fatal: true,
323 } as const;
324 }
325​
326 if (input.bundledNodeWindowsPath) {
327 const bundledNodeExists = yield* fileSystem
328 .exists(input.bundledNodeWindowsPath)
329 .pipe(Effect.orElseSucceed(() => false));
330 if (!bundledNodeExists) {
331 return {
332 _tag: "Failed",
333 reason: `missing packaged WSL Node runtime at ${input.bundledNodeWindowsPath}`,
334 fatal: true,
335 } as const;
336 }
337 }
338​
339 const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
340 if (Option.isNone(linuxEntry)) {
341 return {
342 _tag: "Failed",
343 reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
344 fatal: false,
345 } as const;
346 }
347​
348 const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
349 allowBuild: input.allowBuild,
350 nodeEngineRange: serverPackageJson.engines.node,
351 bundledNodeWindowsPath: input.bundledNodeWindowsPath,
352 });
353 if (!nodePtyResult.ok) {
354 return {
355 _tag: "Failed",
356 reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
357 fatal: nodePtyResult.fatal,
358 ...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
359 } as const;
360 }
361​
362 return {
363 _tag: "Ready",
364 runningDistro,
365 linuxEntryPath: linuxEntry.value,
366 nodePath: nodePtyResult.nodePath,
367 resolvedPath: nodePtyResult.resolvedPath,
368 } as const;
369});
370​
371// True when the given IPv4 belongs to a Windows-side network
372// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
373// host's, which is the signature we use to detect that mode and
374// switch the renderer URL to loopback.
375const isLocalHostIpv4 = (ip: string): boolean => {
376 const interfaces = NodeOS.networkInterfaces();
377 for (const list of Object.values(interfaces)) {
378 if (!list) continue;
379 for (const entry of list) {
380 // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
381 // the Node build Electron ships (41 / Node 22, verified), but some Node
382 // builds report the numeric 4. Normalize to a string so a future runtime
383 // bump can't silently break mirrored-mode detection and leave the
384 // renderer pointed at the distro IP instead of loopback.
385 const family = String(entry.family);
386 if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
387 }
388 }
389 return false;
390};
391​
392const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
393 ...Option.match(observabilitySettings.otlpTracesUrl, {
394 onNone: () => ({}),
395 onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
396 }),
397 ...Option.match(observabilitySettings.otlpMetricsUrl, {
398 onNone: () => ({}),
399 onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
400 }),
401});
402​
403const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
404 function* (
405 input: SharedBootstrapInput & {
406 readonly resourceMonitorPath: Option.Option<string>;
407 },
408 ): Effect.fn.Return<
409 DesktopBackendManager.DesktopBackendStartConfig,
410 never,
411 DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
412 > {
413 const environment = yield* DesktopEnvironment.DesktopEnvironment;
414 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
415 const backendExposure = yield* serverExposure.backendConfig;
416​
417 const bootstrap = {
418 mode: "desktop" as const,
419 noBrowser: true,
420 port: backendExposure.port,
421 t3Home: environment.baseDir,
422 host: backendExposure.bindHost,
423 desktopBootstrapToken: input.bootstrapToken,
424 tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
425 tailscaleServePort: backendExposure.tailscaleServePort,
426 desktopTelemetryFd: 4,
427 desktopTelemetryControlFd: 5,
428 ...Option.match(input.resourceMonitorPath, {
429 onNone: () => ({}),
430 onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
431 }),
432 ...buildObservabilityFragment(input.observabilitySettings),
433 };
434​
435 return {
436 executablePath: process.execPath,
437 args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
438 entryPath: environment.backendEntryPath,
439 cwd: environment.backendCwd,
440 env: {
441 ...backendChildEnvPatch(),
442 ELECTRON_RUN_AS_NODE: "1",
443 },
444 // Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
445 extendEnv: true,
446 bootstrap,
447 bootstrapDelivery: "fd3",
448 httpBaseUrl: backendExposure.httpBaseUrl,
449 captureOutput: true,
450 preflightFailure: Option.none(),
451 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
452 },
453);
454​
455const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
456 input: SharedBootstrapInput & {
457 readonly port: number;
458 readonly distro: string | null;
459 readonly portStrategy?: WslBackendPortStrategy;
460 },
461): Effect.fn.Return<
462 DesktopBackendManager.DesktopBackendStartConfig,
463 never,
464 | DesktopEnvironment.DesktopEnvironment
465 | DesktopWslEnvironment.DesktopWslEnvironment
466 | FileSystem.FileSystem
467> {
468 const environment = yield* DesktopEnvironment.DesktopEnvironment;
469 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
470​
471 // In packaged builds environment.appRoot is .../resources/app.asar — an
472 // archive FILE. The Windows primary reads its entry through
473 // ELECTRON_RUN_AS_NODE (asar-aware), but processes launched through WSL cannot
474 // read inside an asar. electron-builder therefore unpacks the server bundle +
475 // node_modules to the app.asar.unpacked sibling; the Linux Node executable is
476 // staged separately under resources/wsl-node and cached into the distro during
477 // preflight. In dev appRoot is already a real directory, so this is a no-op.
478 const wslAppRoot = environment.isPackaged
479 ? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
480 : environment.appRoot;
481 const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
482 const bundledNodeWindowsPath = environment.isPackaged
483 ? environment.path.join(environment.resourcesPath, "wsl-node", "bin", "node")
484 : null;
485​
486 const preflight = yield* runWslPreflight({
487 distro: input.distro,
488 windowsEntryPath: wslEntryPath,
489 windowsRepoRoot: wslAppRoot,
490 // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
491 // attached to the Windows artifact — see build-desktop-artifact.ts), so the
492 // WSL backend never needs a compiler, node-gyp, or network on first launch.
493 // Compiling from source is a dev-only convenience: a checkout has no shipped
494 // prebuilt, and developers have the toolchain. In packaged builds we instead
495 // surface a clear diagnostic if the prebuilt can't load (unsupported
496 // arch/distro), rather than silently dropping into a fragile runtime build.
497 allowBuild: !environment.isPackaged,
498 bundledNodeWindowsPath,
499 });
500​
501 // Every operation after preflight uses the same concrete distro. In
502 // default-tracking mode this closes the race where the system default
503 // changes between probing and spawning the backend.
504 const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
505 const distroForConfig = runningDistro ?? input.distro;
506​
507 // Resolve the selected distro's IPv4 address only after a successful WSL2
508 // preflight. In NAT mode Windows can reach that concrete distro address, so
509 // bind exactly that interface rather than 0.0.0.0. In mirrored mode the
510 // distro reports a Windows-owned address; bind loopback because both sides
511 // share localhost semantics. If address probing fails, fall back to loopback
512 // instead of broadening exposure to every Linux interface.
513 const distroIp =
514 preflight._tag === "Ready"
515 ? yield* wslEnvironment.getDistroIp(preflight.runningDistro)
516 : Option.none<string>();
517 const usesSharedNetworkStack = Option.match(distroIp, {
518 onNone: () => false,
519 onSome: (ip) => isLocalHostIpv4(ip),
520 });
521 const wslPrivateHost = usesSharedNetworkStack
522 ? "127.0.0.1"
523 : Option.getOrElse(distroIp, () => "127.0.0.1");
524 const portStrategy = input.portStrategy ?? "fixed";
525 const portAllocation =
526 preflight._tag === "Ready"
527 ? yield* wslEnvironment.allocateTcpPort({
528 distro: preflight.runningDistro,
529 nodePath: preflight.nodePath,
530 host: wslPrivateHost,
531 preferredPort: input.port,
532 fallbackToEphemeral: portStrategy === "wsl-auto",
533 })
534 : null;
535 const effectivePort = portAllocation?.ok === true ? portAllocation.port : input.port;
536 const httpBaseUrl = new URL(`http://${wslPrivateHost}:${effectivePort}`);
537​
538 const bootstrap = {
539 mode: "desktop" as const,
540 noBrowser: true,
541 port: effectivePort,
542 // Omit t3Home so the Linux backend uses its own home dir instead of
543 // the Windows-side baseDir (which would be a /mnt/c path and share
544 // the SQLite file with the primary).
545 host: wslPrivateHost,
546 desktopBootstrapToken: input.bootstrapToken,
547 // PortSchema rejects 0, so when tailscale serve is disabled we still
548 // need a valid number in this slot. The backend reads tailscaleServePort
549 // only when tailscaleServeEnabled is true, so the actual value here is
550 // inert.
551 tailscaleServeEnabled: false,
552 tailscaleServePort: 443,
553 // The packaged sidecar is a Windows executable and cannot run inside the
554 // Linux WSL backend. Keep the field absent instead of passing an unusable
555 // `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
556 // See docs/architecture/resource-telemetry.md.
557 ...buildObservabilityFragment(input.observabilitySettings),
558 };
559​
560 const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
561 const forwardedEnv: Record<string, string> = {};
562 const forwardedEnvNames: string[] = [];
563 for (const name of WSL_FORWARDED_ENV_NAMES) {
564 const value = process.env[name];
565 if (value !== undefined && value.length > 0) {
566 forwardedEnv[name] = value;
567 forwardedEnvNames.push(name);
568 }
569 }
570​
571 // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
572 // exports the Windows-side base dir for the primary; if it leaks into
573 // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
574 // /mnt/c, which means both backends read/write the same database and
575 // their env-ids collide).
576 const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
577 for (const [key, value] of Object.entries(process.env)) {
578 if (key === "T3CODE_HOME") continue;
579 parentEnvWithoutT3Home[key] = value;
580 }
581 const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
582​
583 const baseConfig = {
584 executablePath: "wsl.exe",
585 entryPath: wslEntryPath,
586 cwd: environment.backendCwd,
587 env: {
588 ...parentEnvWithoutT3Home,
589 ...backendChildEnvPatch(),
590 ...forwardedEnv,
591 ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
592 },
593 // env is already a complete process.env minus T3CODE_HOME; pass it
594 // verbatim instead of letting the spawner re-merge process.env on top.
595 extendEnv: false,
596 bootstrap,
597 bootstrapDelivery: "stdin" as const,
598 httpBaseUrl,
599 captureOutput: true,
600 ...(runningDistro !== null ? { runningDistro } : {}),
601 ...(preflight._tag === "Ready" ? { wslNodePath: preflight.nodePath } : {}),
602 };
603​
604 // Forward the dev-server URL as an explicit CLI flag so the WSL backend's
605 // config resolution lands in dev/ instead of userdata/. Inheriting through
606 // WSLENV is unreliable in practice (URL-shaped values with colons /
607 // slashes get translated unpredictably depending on flags), and the
608 // packaged build leaves devServerUrl as None anyway.
609 const devUrlArgs = Option.match(environment.devServerUrl, {
610 onNone: () => [] as ReadonlyArray<string>,
611 onSome: (url) => ["--dev-url", url.href],
612 });
613​
614 if (preflight._tag === "Failed") {
615 const retryLimit =
616 preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
617 return {
618 ...baseConfig,
619 args: [...distroArgs, "--", "node", "--version"],
620 preflightFailure: Option.some({
621 reason: preflight.reason,
622 fatal: preflight.fatal,
623 ...(retryLimit === undefined ? {} : { retryLimit }),
624 }),
625 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
626 }
627​
628 if (portAllocation?.ok === false) {
629 const fixedPortHint =
630 portStrategy === "fixed"
631 ? ` The required WSL-only primary port ${input.port} must be free inside ${preflight.runningDistro}; stop the Linux process using it or switch back to the Windows backend.`
632 : "";
633 return {
634 ...baseConfig,
635 args: [...distroArgs, "--", "node", "--version"],
636 preflightFailure: Option.some({
637 reason: `WSL backend could not allocate TCP port ${input.port} on ${wslPrivateHost} inside ${preflight.runningDistro}: ${portAllocation.reason}${fixedPortHint}`,
638 fatal: false,
639 retryLimit: WSL_PORT_ALLOCATION_RETRY_LIMIT,
640 }),
641 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
642 }
643​
644 if (portAllocation?.ok === true && portAllocation.usedEphemeralFallback) {
645 yield* Effect.logInfo("WSL backend preferred port was occupied inside Linux; using ephemeral port", {
646 distro: preflight.runningDistro,
647 preferredPort: input.port,
648 allocatedPort: portAllocation.port,
649 host: wslPrivateHost,
650 });
651 }
652​
653 // The WSL server spawns commands its providers reference by name. Put the exact
654 // preflight Node runtime first — packaged builds use T3 Code's per-distro cached
655 // Linux Node, while development can still use a version-manager Node — then add
656 // the distro system/login PATH for user-installed package managers/provider CLIs.
657 // Bundling Node removes the server-start dependency on distro Node; npm/pnpm/bun
658 // remain provider-tooling concerns and are intentionally resolved from user PATH.
659 // Every dynamic
660 // value is a separate argv entry under `wsl.exe --exec`; no shell command is
661 // involved, so Windows cannot mangle nested quotes and stdin remains reserved
662 // for the bootstrap envelope.
663 const lastSlash = preflight.nodePath.lastIndexOf("/");
664 const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
665 const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
666​
667 return {
668 ...baseConfig,
669 args: [
670 ...distroArgs,
671 "--exec",
672 "env",
673 `PATH=${launchPath}`,
674 preflight.nodePath,
675 preflight.linuxEntryPath,
676 "--bootstrap-fd",
677 "0",
678 ...devUrlArgs,
679 ],
680 preflightFailure: Option.none(),
681 } satisfies DesktopBackendManager.DesktopBackendStartConfig;
682});
683​
684export const make = Effect.gen(function* () {
685 const environment = yield* DesktopEnvironment.DesktopEnvironment;
686 const fileSystem = yield* FileSystem.FileSystem;
687 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
688 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
689 const settings = yield* DesktopAppSettings.DesktopAppSettings;
690 const crypto = yield* Crypto.Crypto;
691 // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
692 // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
693 // resolve concurrently; with a plain Ref both could observe None, generate
694 // distinct tokens, and one would overwrite the other — leaving the two
695 // backends holding mismatched tokens and breaking the shared-token
696 // invariant the renderer relies on. modifyEffect serializes the whole
697 // get-or-create so the first caller wins and the rest reuse its token.
698 const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
699 const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
700 Option.match(current, {
701 onSome: (token) => Effect.succeed([token, current] as const),
702 onNone: () =>
703 crypto.randomBytes(24).pipe(
704 Effect.map((bytes) => {
705 const token = Encoding.encodeHex(bytes);
706 return [token, Option.some(token)] as const;
707 }),
708 ),
709 }),
710 );
711​
712 // Both resolvers share the same bootstrap token: the renderer holds a
713 // single token and uses it against whichever backend it's currently
714 // talking to. Observability settings get re-read each resolve so a
715 // hot-swap of the server-settings file is picked up on the next
716 // restart cycle without having to bounce the desktop process.
717 const sharedInputs = Effect.gen(function* () {
718 const bootstrapToken = yield* getOrCreateBootstrapToken;
719 const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
720 Effect.provideService(FileSystem.FileSystem, fileSystem),
721 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
722 );
723 return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
724 });
725​
726 const buildWslPrimaryConfig = Effect.gen(function* () {
727 // wsl-only mode pipes the WSL backend through the same port the
728 // Windows primary would normally take. That way the renderer
729 // still loads from the local-only endpoint advertised by
730 // DesktopServerExposure, and primary-aware code paths (cookie
731 // auth, the env switcher's "primary" id) keep working without
732 // a parallel "secondary" registration.
733 const backendExposure = yield* serverExposure.backendConfig;
734 const persistedSettings = yield* settings.get;
735 const shared = yield* sharedInputs;
736 yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
737 return yield* resolveWslStartConfig({
738 ...shared,
739 port: backendExposure.port,
740 distro: persistedSettings.wslDistro,
741 portStrategy: "fixed",
742 }).pipe(
743 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
744 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
745 Effect.provideService(FileSystem.FileSystem, fileSystem),
746 );
747 });
748​
749 const buildWindowsPrimaryConfig = Effect.gen(function* () {
750 const shared = yield* sharedInputs;
751 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
752 Effect.provideService(FileSystem.FileSystem, fileSystem),
753 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
754 );
755 return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
756 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
757 Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
758 );
759 });
760​
761 // Single source of truth for what the primary actually runs as. Both
762 // the start-config dispatch and the renderer-facing label derive from
763 // this, so they can't disagree — e.g. the label reading "WSL" while the
764 // config silently fell back to Windows because WSL is unavailable.
765 // Dispatch happens at resolve time so toggling wsl-only between restarts
766 // is picked up on the next start cycle (the pool's primary instance is
767 // created once at layer init, but configResolve fires on each restart).
768 const describePrimary = Effect.gen(function* () {
769 const persistedSettings = yield* settings.get;
770 const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
771 // Only honor wsl-only when WSL is actually usable. If the user
772 // persisted wsl-only but WSL has since become unavailable (wsl.exe
773 // removed, no distro), fall back to the Windows primary instead of
774 // looping forever on preflight failures: the Connections backend
775 // control is hidden while WSL is unavailable, so a stuck WSL primary
776 // would otherwise leave no in-app way back to Windows.
777 const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
778 return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
779 });
780​
781 return DesktopBackendConfiguration.of({
782 resolvePrimary: Effect.gen(function* () {
783 const { useWsl, wslRequested } = yield* describePrimary;
784 if (useWsl) {
785 return yield* buildWslPrimaryConfig;
786 }
787 if (wslRequested) {
788 yield* Effect.logWarning(
789 "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
790 );
791 }
792 return yield* buildWindowsPrimaryConfig;
793 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
794 resolvePrimaryLabel: Effect.gen(function* () {
795 const { useWsl, distro } = yield* describePrimary;
796 if (!useWsl) {
797 return environment.platform === "win32" ? "Windows" : "Local environment";
798 }
799 return distro ? `WSL (${distro})` : "WSL";
800 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
801 resolveWsl: (input) =>
802 Effect.gen(function* () {
803 const shared = yield* sharedInputs;
804 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
805 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
806 Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
807 Effect.provideService(FileSystem.FileSystem, fileSystem),
808 );
809 }).pipe(
810 Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
811 attributes: {
812 port: input.port,
813 portStrategy: input.portStrategy ?? "fixed",
814 distro: input.distro ?? null,
815 },
816 }),
817 ),
818 });
819});
820​
821export const layer = Layer.effect(DesktopBackendConfiguration, make);