The best way to control Claude Code, Codex and more from any computer or phone

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