import * as NodeOS from "node:os"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";import * as Context from "effect/Context";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as Encoding from "effect/Encoding";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as PlatformError from "effect/PlatformError";import * as Schema from "effect/Schema";import * as SynchronizedRef from "effect/SynchronizedRef"; import serverPackageJson from "../../../server/package.json" with { type: "json" }; import * as DesktopBackendManager from "./DesktopBackendManager.ts";import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";import * as DesktopServerExposure from "./DesktopServerExposure.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts"; export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedError<DesktopBackendObservabilitySettingsReadError>()( "DesktopBackendObservabilitySettingsReadError", { settingsPath: Schema.String, cause: Schema.Defect(), },) { override get message(): string { return `Failed to read persisted backend observability settings at ${this.settingsPath}.`; }} export class DesktopBackendConfiguration extends Context.Service< DesktopBackendConfiguration, { // Build the Windows-native primary backend's start config. Reads the // primary's port/host/exposure from DesktopServerExposure. Can fail // with PlatformError because bootstrap token generation now uses // crypto.randomBytes under the hood (post Effect 4 migration). readonly resolvePrimary: Effect.Effect< DesktopBackendManager.DesktopBackendStartConfig, PlatformError.PlatformError >; // Build a WSL backend start config for the given distro on the given // port. The WSL backend is always loopback-only (the primary owns LAN // exposure when the user opts in), so this takes the port directly and // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is // forwarded to wsl.exe with no -d flag. readonly resolveWsl: (input: { readonly port: number; readonly distro: string | null; }) => Effect.Effect< DesktopBackendManager.DesktopBackendStartConfig, PlatformError.PlatformError >; // The renderer-facing label for the primary instance, derived from the // same decision resolvePrimary makes (including the WSL-availability // fall-back to Windows), so the env switcher can't show "WSL" for a // backend that actually resolved to Windows. readonly resolvePrimaryLabel: Effect.Effect<string>; }>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {} interface BackendObservabilitySettings { readonly otlpTracesUrl: Option.Option<string>; readonly otlpMetricsUrl: Option.Option<string>;} const emptyBackendObservabilitySettings: BackendObservabilitySettings = { otlpTracesUrl: Option.none(), otlpMetricsUrl: Option.none(),}; const DESKTOP_BACKEND_ENV_NAMES = [ "T3CODE_PORT", "T3CODE_MODE", "T3CODE_NO_BROWSER", "T3CODE_HOST", "T3CODE_DESKTOP_WS_URL", "T3CODE_DESKTOP_LAN_ACCESS", "T3CODE_DESKTOP_LAN_HOST", "T3CODE_DESKTOP_HTTPS_ENDPOINTS", "T3CODE_TAILSCALE_SERVE", "T3CODE_TAILSCALE_SERVE_PORT",] as const; // Sensitive env vars that the WSL backend needs but Windows process.env won't// forward across the wsl.exe boundary without WSLENV. The dev-server URL is// handled separately via a `--dev-url` CLI flag because WSLENV translation of// URL-shaped values (colons / slashes) is unreliable.const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const; const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; const backendChildEnvPatch = (): Record<string, string | undefined> => Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined])); const getWslEnvEntryName = (entry: string): string => { const slashIndex = entry.indexOf("/"); return slashIndex === -1 ? entry : entry.slice(0, slashIndex);}; const mergeWslEnv = ( existingWslEnv: string | undefined, forwardedEnvNames: ReadonlyArray<string>,): string | undefined => { const existing = existingWslEnv?.trim() ?? ""; // Names already declared, so we don't forward a duplicate. We parse the // existing value only for this membership test — the string itself is // preserved verbatim below rather than re-serialized. const seenNames = new Set( existing .split(":") .map((entry) => getWslEnvEntryName(entry.trim())) .filter((name) => name.length > 0), ); const additions = forwardedEnvNames.filter((name) => !seenNames.has(name)); // Preserve the user's WSLENV exactly as Windows handed it to us — empty // "::" segments and duplicate entries are harmless no-ops to WSL and not // ours to normalize — and only append the secrets we need to forward // across the wsl.exe boundary. const parts = [existing, ...additions].filter((part) => part.length > 0); return parts.length > 0 ? parts.join(":") : undefined;}; const logBackendObservabilitySettingsReadFailure = ( settingsPath: string, cause: PlatformError.PlatformError,) => { const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause }); return Effect.logWarning(error).pipe( Effect.annotateLogs({ component: "desktop-backend-configuration", error, }), );}; function resourceMonitorBinaryName(platform: NodeJS.Platform): string { return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";} const resolveResourceMonitorPath = Effect.fn( "desktop.backendConfiguration.resolveResourceMonitorPath",)(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const binaryName = resourceMonitorBinaryName(environment.platform); const candidates = environment.isDevelopment ? [ environment.path.join( environment.rootDir, "native/resource-monitor/target/release", binaryName, ), environment.path.join( environment.rootDir, "native/resource-monitor/target/debug", binaryName, ), ] : environment.isPackaged ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)] : environment.resolveResourcePathCandidates( environment.path.join("resource-monitor", binaryName), ); for (const candidate of candidates) { if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { return Option.some(candidate); } } return Option.none<string>();}); const readPersistedBackendObservabilitySettings = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const environment = yield* DesktopEnvironment.DesktopEnvironment; const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe( Effect.map(Option.some), Effect.catchTags({ PlatformError: (cause) => cause.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe( Effect.as(Option.none()), ), }), ); if (Option.isNone(raw)) { return emptyBackendObservabilitySettings; } const parsed = parsePersistedServerObservabilitySettings(raw.value); return { otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl), otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl), };}); interface SharedBootstrapInput { readonly bootstrapToken: string; readonly observabilitySettings: BackendObservabilitySettings;} interface WslPreflightSuccess { readonly _tag: "Ready"; readonly runningDistro: string; readonly windowsEntryPath: string; readonly linuxEntryPath: string; // Absolute path to the node binary the preflight validated after the shared // remote resolver repaired PATH. The launch must use this exact path so it // doesn't fall through to a different/old node than the one node-pty was // built against. readonly nodePath: string; // PATH captured from the same login shell after the shared resolver loaded // version managers. The launch forwards this value directly without a shell. readonly resolvedPath: string; // Identifies the distro-local runtime cache selected from the packaged archive. readonly runtimeId?: string;} interface WslPreflightFailure { readonly _tag: "Failed"; readonly reason: string; // Fatal: the WSL distro is misconfigured (no node, wrong version, missing // build tools) and retrying won't help — surface it and (wsl-only) fall back // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it // boots), with a bounded window for self-healing before fallback. readonly fatal: boolean; readonly retryLimit?: number;} const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i; const parseWslRuntimeArchiveHash = (value: string): string | null => { const trimmed = value.trim(); return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;}; type FailedNodePtyResult = Extract< DesktopWslEnvironment.EnsureWslNodePtyResult, { readonly ok: false }>; const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: { readonly distro: string | null; readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null; readonly allowBuild: boolean;}): Effect.fn.Return< WslPreflightSuccess | WslPreflightFailure, never, | DesktopEnvironment.DesktopEnvironment | DesktopWslEnvironment.DesktopWslEnvironment | DesktopWslServerTree.DesktopWslServerTree | FileSystem.FileSystem> { const environment = yield* DesktopEnvironment.DesktopEnvironment; const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment; const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const fileSystem = yield* FileSystem.FileSystem; const wslAvailable = yield* wslEnv.isAvailable; if (!wslAvailable) { return { _tag: "Failed", reason: "WSL is not available on this system", fatal: false, } as const; } const distroProbe = yield* wslEnv.probeDistros.pipe( Effect.map((distros) => ({ _tag: "Success", distros }) as const), Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)), ); if (distroProbe._tag === "Failure") { return { _tag: "Failed", reason: `Unable to list WSL distributions: ${distroProbe.error.message}`, fatal: false, } as const; } const installedDistros = distroProbe.distros; const runningDistro = input.distro ? (installedDistros.find( (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(), )?.name ?? null) : (installedDistros.find((installed) => installed.isDefault)?.name ?? null); if (runningDistro === null) { return { _tag: "Failed", reason: input.distro ? `WSL distro is not installed: ${input.distro}` : installedDistros.length === 0 ? "WSL has no installed distributions" : "WSL has no default distribution", fatal: true, } as const; } const nodePtyOptions = { allowBuild: input.allowBuild, nodeEngineRange: serverPackageJson.engines.node, }; const failedNodePty = (result: FailedNodePtyResult) => ({ _tag: "Failed", reason: `WSL node-pty unavailable: ${result.reason}`, fatal: result.fatal, ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }), }) as const; // The mounted server tree is the fallback runtime: the Windows-side copy the // distro reads over /mnt. Slower to launch from, but always installed. const resolveMountedAppRoot = Effect.gen(function* () { const serverTree = yield* wslServerTree.ensure; if (!serverTree.ok) { return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const; } const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs"); const entryExists = yield* fileSystem .exists(windowsEntryPath) .pipe(Effect.orElseSucceed(() => false)); if (!entryExists) { return { ok: false, reason: `missing server entry at ${windowsEntryPath}`, fatal: true, } as const; } const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root); return Option.isNone(mountedAppRoot) ? ({ ok: false, reason: `wslpath conversion failed for ${serverTree.root}`, fatal: false, } as const) : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const); }); // Set once a staged runtime has been ruled out by the probe, and carried // through the mounted attempt: if the mounted tree works the cache is the // broken part and gets invalidated, and if the mounted tree returns its own // fatal verdict the cached reason is the more actionable one to report. // A transient mounted failure is neither — it rules nothing out, so it stays // retryable and the staged verdict waits for an attempt that can answer. let stagedFailure: | { readonly runtimeId: string; readonly nodePty: FailedNodePtyResult } | undefined; if (input.runtimeArchive !== null) { const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { const stagedNodePty = yield* wslEnv.ensureNodePty( runningDistro, runtime.linuxAppRoot, nodePtyOptions, ); if (stagedNodePty.ok) { yield* wslServerTree.cleanupLegacy; return { _tag: "Ready", runningDistro, windowsEntryPath: environment.backendEntryPath, linuxEntryPath: `${runtime.linuxAppRoot}/apps/server/dist/bin.mjs`, nodePath: stagedNodePty.nodePath, resolvedPath: stagedNodePty.resolvedPath, runtimeId: input.runtimeArchive.runtimeId, } as const; } // A transport failure says nothing about the staged tree, so it is // retried against the same cache rather than spending a second probe on // the mounted tree and risking a needless reinstall. if (!stagedNodePty.fatal) return failedNodePty(stagedNodePty); yield* Effect.logWarning( "The staged WSL runtime could not load node-pty; retrying from the mounted server tree.", { reason: stagedNodePty.reason }, ); stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, nodePty: stagedNodePty }; } else { yield* Effect.logWarning( "Could not stage the WSL runtime; launching from the mounted server tree instead.", { reason: runtime.reason }, ); } } const mounted = yield* resolveMountedAppRoot; if (!mounted.ok) { return stagedFailure && mounted.fatal ? failedNodePty(stagedFailure.nodePty) : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const); } const nodePtyResult = yield* wslEnv.ensureNodePty( runningDistro, mounted.linuxAppRoot, nodePtyOptions, ); if (!nodePtyResult.ok) { // Substituting the staged verdict for a transient mounted failure would // turn a retryable failure into a fatal one, ending the WSL attempt (and, // in wsl-only mode, persisting Windows) before the slow /mnt path had a // chance to answer and clear the bad cache. return failedNodePty( stagedFailure && nodePtyResult.fatal ? stagedFailure.nodePty : nodePtyResult, ); } // The mounted tree runs what the cache could not, so the cache is the broken // copy: revoke its ready marker so the next launch reinstalls it instead of // reusing a tree that has already been proven unloadable. if (stagedFailure) { yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); } return { _tag: "Ready", runningDistro, windowsEntryPath: mounted.windowsEntryPath, linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`, nodePath: nodePtyResult.nodePath, resolvedPath: nodePtyResult.resolvedPath, } as const;}); // True when the given IPv4 belongs to a Windows-side network// interface. In WSL2 mirrored mode the distro's eth0 IP equals the// host's, which is the signature we use to detect that mode and// switch the renderer URL to loopback.const isLocalHostIpv4 = (ip: string): boolean => { const interfaces = NodeOS.networkInterfaces(); for (const list of Object.values(interfaces)) { if (!list) continue; for (const entry of list) { // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on // the Node build Electron ships (41 / Node 22, verified), but some Node // builds report the numeric 4. Normalize to a string so a future runtime // bump can't silently break mirrored-mode detection and leave the // renderer pointed at the distro IP instead of loopback. const family = String(entry.family); if ((family === "IPv4" || family === "4") && entry.address === ip) return true; } } return false;}; const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({ ...Option.match(observabilitySettings.otlpTracesUrl, { onNone: () => ({}), onSome: (otlpTracesUrl) => ({ otlpTracesUrl }), }), ...Option.match(observabilitySettings.otlpMetricsUrl, { onNone: () => ({}), onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }), }),}); const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")( function* ( input: SharedBootstrapInput & { readonly resourceMonitorPath: Option.Option<string>; }, ): Effect.fn.Return< DesktopBackendManager.DesktopBackendStartConfig, never, DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure > { const environment = yield* DesktopEnvironment.DesktopEnvironment; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const backendExposure = yield* serverExposure.backendConfig; const bootstrap = { mode: "desktop" as const, noBrowser: true, port: backendExposure.port, t3Home: environment.baseDir, host: backendExposure.bindHost, desktopBootstrapToken: input.bootstrapToken, tailscaleServeEnabled: backendExposure.tailscaleServeEnabled, tailscaleServePort: backendExposure.tailscaleServePort, desktopTelemetryFd: 4, desktopTelemetryControlFd: 5, ...Option.match(input.resourceMonitorPath, { onNone: () => ({}), onSome: (resourceMonitorPath) => ({ resourceMonitorPath }), }), ...buildObservabilityFragment(input.observabilitySettings), };Lines 1–500 of 876. Load more
import * as NodeOS from "node:os"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as SynchronizedRef from "effect/SynchronizedRef"; import serverPackageJson from "../../../server/package.json" with { type: "json" }; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts"; export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedError<DesktopBackendObservabilitySettingsReadError>()( "DesktopBackendObservabilitySettingsReadError", { settingsPath: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { return `Failed to read persisted backend observability settings at ${this.settingsPath}.`; } } export class DesktopBackendConfiguration extends Context.Service< DesktopBackendConfiguration, { // Build the Windows-native primary backend's start config. Reads the // primary's port/host/exposure from DesktopServerExposure. Can fail // with PlatformError because bootstrap token generation now uses // crypto.randomBytes under the hood (post Effect 4 migration). readonly resolvePrimary: Effect.Effect< DesktopBackendManager.DesktopBackendStartConfig, PlatformError.PlatformError >; // Build a WSL backend start config for the given distro on the given // port. The WSL backend is always loopback-only (the primary owns LAN // exposure when the user opts in), so this takes the port directly and // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is // forwarded to wsl.exe with no -d flag. readonly resolveWsl: (input: { readonly port: number; readonly distro: string | null; }) => Effect.Effect< DesktopBackendManager.DesktopBackendStartConfig, PlatformError.PlatformError >; // The renderer-facing label for the primary instance, derived from the // same decision resolvePrimary makes (including the WSL-availability // fall-back to Windows), so the env switcher can't show "WSL" for a // backend that actually resolved to Windows. readonly resolvePrimaryLabel: Effect.Effect<string>; } >()("@t3tools/desktop/backend/DesktopBackendConfiguration") {} interface BackendObservabilitySettings { readonly otlpTracesUrl: Option.Option<string>; readonly otlpMetricsUrl: Option.Option<string>; } const emptyBackendObservabilitySettings: BackendObservabilitySettings = { otlpTracesUrl: Option.none(), otlpMetricsUrl: Option.none(), }; const DESKTOP_BACKEND_ENV_NAMES = [ "T3CODE_PORT", "T3CODE_MODE", "T3CODE_NO_BROWSER", "T3CODE_HOST", "T3CODE_DESKTOP_WS_URL", "T3CODE_DESKTOP_LAN_ACCESS", "T3CODE_DESKTOP_LAN_HOST", "T3CODE_DESKTOP_HTTPS_ENDPOINTS", "T3CODE_TAILSCALE_SERVE", "T3CODE_TAILSCALE_SERVE_PORT", ] as const; // Sensitive env vars that the WSL backend needs but Windows process.env won't // forward across the wsl.exe boundary without WSLENV. The dev-server URL is // handled separately via a `--dev-url` CLI flag because WSLENV translation of // URL-shaped values (colons / slashes) is unreliable. const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const; const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; const backendChildEnvPatch = (): Record<string, string | undefined> => Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined])); const getWslEnvEntryName = (entry: string): string => { const slashIndex = entry.indexOf("/"); return slashIndex === -1 ? entry : entry.slice(0, slashIndex); }; const mergeWslEnv = ( existingWslEnv: string | undefined, forwardedEnvNames: ReadonlyArray<string>, ): string | undefined => { const existing = existingWslEnv?.trim() ?? ""; // Names already declared, so we don't forward a duplicate. We parse the // existing value only for this membership test — the string itself is // preserved verbatim below rather than re-serialized. const seenNames = new Set( existing .split(":") .map((entry) => getWslEnvEntryName(entry.trim())) .filter((name) => name.length > 0), ); const additions = forwardedEnvNames.filter((name) => !seenNames.has(name)); // Preserve the user's WSLENV exactly as Windows handed it to us — empty // "::" segments and duplicate entries are harmless no-ops to WSL and not // ours to normalize — and only append the secrets we need to forward // across the wsl.exe boundary. const parts = [existing, ...additions].filter((part) => part.length > 0); return parts.length > 0 ? parts.join(":") : undefined; }; const logBackendObservabilitySettingsReadFailure = ( settingsPath: string, cause: PlatformError.PlatformError, ) => { const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause }); return Effect.logWarning(error).pipe( Effect.annotateLogs({ component: "desktop-backend-configuration", error, }), ); }; function resourceMonitorBinaryName(platform: NodeJS.Platform): string { return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor"; } const resolveResourceMonitorPath = Effect.fn( "desktop.backendConfiguration.resolveResourceMonitorPath", )(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const binaryName = resourceMonitorBinaryName(environment.platform); const candidates = environment.isDevelopment ? [ environment.path.join( environment.rootDir, "native/resource-monitor/target/release", binaryName, ), environment.path.join( environment.rootDir, "native/resource-monitor/target/debug", binaryName, ), ] : environment.isPackaged ? [environment.path.join(environment.resourcesPath, "resource-monitor", binaryName)] : environment.resolveResourcePathCandidates( environment.path.join("resource-monitor", binaryName), ); for (const candidate of candidates) { if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { return Option.some(candidate); } } return Option.none<string>(); }); const readPersistedBackendObservabilitySettings = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const environment = yield* DesktopEnvironment.DesktopEnvironment; const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe( Effect.map(Option.some), Effect.catchTags({ PlatformError: (cause) => cause.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe( Effect.as(Option.none()), ), }), ); if (Option.isNone(raw)) { return emptyBackendObservabilitySettings; } const parsed = parsePersistedServerObservabilitySettings(raw.value); return { otlpTracesUrl: Option.fromNullishOr(parsed.otlpTracesUrl), otlpMetricsUrl: Option.fromNullishOr(parsed.otlpMetricsUrl), }; }); interface SharedBootstrapInput { readonly bootstrapToken: string; readonly observabilitySettings: BackendObservabilitySettings; } interface WslPreflightSuccess { readonly _tag: "Ready"; readonly runningDistro: string; readonly windowsEntryPath: string; readonly linuxEntryPath: string; // Absolute path to the node binary the preflight validated after the shared // remote resolver repaired PATH. The launch must use this exact path so it // doesn't fall through to a different/old node than the one node-pty was // built against. readonly nodePath: string; // PATH captured from the same login shell after the shared resolver loaded // version managers. The launch forwards this value directly without a shell. readonly resolvedPath: string; // Identifies the distro-local runtime cache selected from the packaged archive. readonly runtimeId?: string; } interface WslPreflightFailure { readonly _tag: "Failed"; readonly reason: string; // Fatal: the WSL distro is misconfigured (no node, wrong version, missing // build tools) and retrying won't help — surface it and (wsl-only) fall back // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it // boots), with a bounded window for self-healing before fallback. readonly fatal: boolean; readonly retryLimit?: number; } const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12; const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz"; const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`; const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/i; const parseWslRuntimeArchiveHash = (value: string): string | null => { const trimmed = value.trim(); return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null; }; type FailedNodePtyResult = Extract< DesktopWslEnvironment.EnsureWslNodePtyResult, { readonly ok: false } >; const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: { readonly distro: string | null; readonly runtimeArchive: DesktopWslEnvironment.WslRuntimeArchive | null; readonly allowBuild: boolean; }): Effect.fn.Return< WslPreflightSuccess | WslPreflightFailure, never, | DesktopEnvironment.DesktopEnvironment | DesktopWslEnvironment.DesktopWslEnvironment | DesktopWslServerTree.DesktopWslServerTree | FileSystem.FileSystem > { const environment = yield* DesktopEnvironment.DesktopEnvironment; const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment; const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const fileSystem = yield* FileSystem.FileSystem; const wslAvailable = yield* wslEnv.isAvailable; if (!wslAvailable) { return { _tag: "Failed", reason: "WSL is not available on this system", fatal: false, } as const; } const distroProbe = yield* wslEnv.probeDistros.pipe( Effect.map((distros) => ({ _tag: "Success", distros }) as const), Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)), ); if (distroProbe._tag === "Failure") { return { _tag: "Failed", reason: `Unable to list WSL distributions: ${distroProbe.error.message}`, fatal: false, } as const; } const installedDistros = distroProbe.distros; const runningDistro = input.distro ? (installedDistros.find( (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(), )?.name ?? null) : (installedDistros.find((installed) => installed.isDefault)?.name ?? null); if (runningDistro === null) { return { _tag: "Failed", reason: input.distro ? `WSL distro is not installed: ${input.distro}` : installedDistros.length === 0 ? "WSL has no installed distributions" : "WSL has no default distribution", fatal: true, } as const; } const nodePtyOptions = { allowBuild: input.allowBuild, nodeEngineRange: serverPackageJson.engines.node, }; const failedNodePty = (result: FailedNodePtyResult) => ({ _tag: "Failed", reason: `WSL node-pty unavailable: ${result.reason}`, fatal: result.fatal, ...(result.retryLimit === undefined ? {} : { retryLimit: result.retryLimit }), }) as const; // The mounted server tree is the fallback runtime: the Windows-side copy the // distro reads over /mnt. Slower to launch from, but always installed. const resolveMountedAppRoot = Effect.gen(function* () { const serverTree = yield* wslServerTree.ensure; if (!serverTree.ok) { return { ok: false, reason: serverTree.reason, fatal: serverTree.fatal } as const; } const windowsEntryPath = environment.path.join(serverTree.root, "apps/server/dist/bin.mjs"); const entryExists = yield* fileSystem .exists(windowsEntryPath) .pipe(Effect.orElseSucceed(() => false)); if (!entryExists) { return { ok: false, reason: `missing server entry at ${windowsEntryPath}`, fatal: true, } as const; } const mountedAppRoot = yield* wslEnv.windowsToWslPath(runningDistro, serverTree.root); return Option.isNone(mountedAppRoot) ? ({ ok: false, reason: `wslpath conversion failed for ${serverTree.root}`, fatal: false, } as const) : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const); }); // Set once a staged runtime has been ruled out by the probe, and carried // through the mounted attempt: if the mounted tree works the cache is the // broken part and gets invalidated, and if the mounted tree returns its own // fatal verdict the cached reason is the more actionable one to report. // A transient mounted failure is neither — it rules nothing out, so it stays // retryable and the staged verdict waits for an attempt that can answer. let stagedFailure: | { readonly runtimeId: string; readonly nodePty: FailedNodePtyResult } | undefined; if (input.runtimeArchive !== null) { const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { const stagedNodePty = yield* wslEnv.ensureNodePty( runningDistro, runtime.linuxAppRoot, nodePtyOptions, ); if (stagedNodePty.ok) { yield* wslServerTree.cleanupLegacy; return { _tag: "Ready", runningDistro, windowsEntryPath: environment.backendEntryPath, linuxEntryPath: `${runtime.linuxAppRoot}/apps/server/dist/bin.mjs`, nodePath: stagedNodePty.nodePath, resolvedPath: stagedNodePty.resolvedPath, runtimeId: input.runtimeArchive.runtimeId, } as const; } // A transport failure says nothing about the staged tree, so it is // retried against the same cache rather than spending a second probe on // the mounted tree and risking a needless reinstall. if (!stagedNodePty.fatal) return failedNodePty(stagedNodePty); yield* Effect.logWarning( "The staged WSL runtime could not load node-pty; retrying from the mounted server tree.", { reason: stagedNodePty.reason }, ); stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, nodePty: stagedNodePty }; } else { yield* Effect.logWarning( "Could not stage the WSL runtime; launching from the mounted server tree instead.", { reason: runtime.reason }, ); } } const mounted = yield* resolveMountedAppRoot; if (!mounted.ok) { return stagedFailure && mounted.fatal ? failedNodePty(stagedFailure.nodePty) : ({ _tag: "Failed", reason: mounted.reason, fatal: mounted.fatal } as const); } const nodePtyResult = yield* wslEnv.ensureNodePty( runningDistro, mounted.linuxAppRoot, nodePtyOptions, ); if (!nodePtyResult.ok) { // Substituting the staged verdict for a transient mounted failure would // turn a retryable failure into a fatal one, ending the WSL attempt (and, // in wsl-only mode, persisting Windows) before the slow /mnt path had a // chance to answer and clear the bad cache. return failedNodePty( stagedFailure && nodePtyResult.fatal ? stagedFailure.nodePty : nodePtyResult, ); } // The mounted tree runs what the cache could not, so the cache is the broken // copy: revoke its ready marker so the next launch reinstalls it instead of // reusing a tree that has already been proven unloadable. if (stagedFailure) { yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); } return { _tag: "Ready", runningDistro, windowsEntryPath: mounted.windowsEntryPath, linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`, nodePath: nodePtyResult.nodePath, resolvedPath: nodePtyResult.resolvedPath, } as const; }); // True when the given IPv4 belongs to a Windows-side network // interface. In WSL2 mirrored mode the distro's eth0 IP equals the // host's, which is the signature we use to detect that mode and // switch the renderer URL to loopback. const isLocalHostIpv4 = (ip: string): boolean => { const interfaces = NodeOS.networkInterfaces(); for (const list of Object.values(interfaces)) { if (!list) continue; for (const entry of list) { // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on // the Node build Electron ships (41 / Node 22, verified), but some Node // builds report the numeric 4. Normalize to a string so a future runtime // bump can't silently break mirrored-mode detection and leave the // renderer pointed at the distro IP instead of loopback. const family = String(entry.family); if ((family === "IPv4" || family === "4") && entry.address === ip) return true; } } return false; }; const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({ ...Option.match(observabilitySettings.otlpTracesUrl, { onNone: () => ({}), onSome: (otlpTracesUrl) => ({ otlpTracesUrl }), }), ...Option.match(observabilitySettings.otlpMetricsUrl, { onNone: () => ({}), onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }), }), }); const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")( function* ( input: SharedBootstrapInput & { readonly resourceMonitorPath: Option.Option<string>; }, ): Effect.fn.Return< DesktopBackendManager.DesktopBackendStartConfig, never, DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure > { const environment = yield* DesktopEnvironment.DesktopEnvironment; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const backendExposure = yield* serverExposure.backendConfig; const bootstrap = { mode: "desktop" as const, noBrowser: true, port: backendExposure.port, t3Home: environment.baseDir, host: backendExposure.bindHost, desktopBootstrapToken: input.bootstrapToken, tailscaleServeEnabled: backendExposure.tailscaleServeEnabled, tailscaleServePort: backendExposure.tailscaleServePort, desktopTelemetryFd: 4, desktopTelemetryControlFd: 5, ...Option.match(input.resourceMonitorPath, { onNone: () => ({}), onSome: (resourceMonitorPath) => ({ resourceMonitorPath }), }), ...buildObservabilityFragment(input.observabilitySettings), };