diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index eee2aef34d..4a781c3f1d 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -110,14 +110,14 @@ const withHarness = ( }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); describe("DesktopBackendConfiguration", () => { - it.effect("resolves backend start config with a stable scoped bootstrap token", () => + it.effect("resolvePrimary produces a stable scoped bootstrap token", () => withHarness( Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const first = yield* configuration.resolve; - const second = yield* configuration.resolve; + const first = yield* configuration.resolvePrimary; + const second = yield* configuration.resolvePrimary; assert.equal(first.executablePath, process.execPath); assert.equal(first.entryPath, environment.backendEntryPath); @@ -141,7 +141,20 @@ describe("DesktopBackendConfiguration", () => { ), ); - it.effect("includes persisted backend observability endpoints when present", () => + it.effect("resolveWsl reuses the primary's bootstrap token", () => + withHarness( + Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + + const primary = yield* configuration.resolvePrimary; + const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null }); + + assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken); + }), + ), + ); + + it.effect("resolvePrimary surfaces persisted backend observability endpoints", () => withHarness( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -161,18 +174,18 @@ describe("DesktopBackendConfiguration", () => { }), ); - const config = yield* configuration.resolve; + const config = yield* configuration.resolvePrimary; assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces"); assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics"); }), ), ); - it.effect("omits backend observability endpoints when settings are missing", () => + it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () => withHarness( Effect.gen(function* () { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolve; + const config = yield* configuration.resolvePrimary; assert.isUndefined(config.bootstrap.otlpTracesUrl); assert.isUndefined(config.bootstrap.otlpMetricsUrl); @@ -180,7 +193,7 @@ describe("DesktopBackendConfiguration", () => { ), ); - it.effect("captures backend output in development so child process logs can be persisted", () => + it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -189,7 +202,7 @@ describe("DesktopBackendConfiguration", () => { yield* Effect.gen(function* () { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolve; + const config = yield* configuration.resolvePrimary; assert.equal(config.captureOutput, true); }).pipe( Effect.provide( @@ -209,7 +222,7 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("preserves existing WSLENV entries when forwarding WSL backend secrets", () => + it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -226,9 +239,13 @@ describe("DesktopBackendConfiguration", () => { yield* Effect.gen(function* () { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolve; + const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); assert.equal(config.executablePath, "wsl.exe"); + assert.equal(config.bootstrap.port, 5050); + assert.equal(config.bootstrap.host, "127.0.0.1"); + assert.equal(config.bootstrap.tailscaleServeEnabled, false); + assert.equal(config.httpBaseUrl.href, "http://127.0.0.1:5050/"); assert.equal(config.env.OPENAI_API_KEY, "openai-key"); assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); assert.equal( @@ -239,12 +256,7 @@ describe("DesktopBackendConfiguration", () => { Effect.provide( DesktopBackendConfiguration.layer.pipe( Layer.provideMerge(serverExposureLayer), - Layer.provideMerge( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: true, - }), - ), + Layer.provideMerge(DesktopAppSettings.layerTest()), Layer.provideMerge( DesktopWslEnvironment.layerTest({ isAvailable: true, diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 0041e9767e..40c1551670 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -13,11 +13,21 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopServerExposure from "./DesktopServerExposure.ts"; -import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; export interface DesktopBackendConfigurationShape { - readonly resolve: Effect.Effect; + // Build the Windows-native primary backend's start config. Reads the + // primary's port/host/exposure from DesktopServerExposure. + readonly resolvePrimary: Effect.Effect; + // 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; } export class DesktopBackendConfiguration extends Context.Service< @@ -140,11 +150,9 @@ const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootst }, ); -interface ResolveBackendStartConfigInput { +interface SharedBootstrapInput { readonly bootstrapToken: string; readonly observabilitySettings: BackendObservabilitySettings; - readonly wslBackendEnabled: boolean; - readonly wslDistro: string | null; } interface WslPreflightOutcome { @@ -207,177 +215,222 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f return { _tag: "Ready", linuxEntryPath: linuxEntry.value } as const; }); -const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")( +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: ResolveBackendStartConfigInput, + input: SharedBootstrapInput, ): Effect.fn.Return< DesktopBackendManager.DesktopBackendStartConfig, never, - | DesktopEnvironment.DesktopEnvironment - | DesktopServerExposure.DesktopServerExposure - | DesktopWslEnvironment.DesktopWslEnvironment - | FileSystem.FileSystem + DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure > { const environment = yield* DesktopEnvironment.DesktopEnvironment; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const backendExposure = yield* serverExposure.backendConfig; - const useWsl = input.wslBackendEnabled && environment.platform === "win32"; - const bootstrap = { mode: "desktop" as const, noBrowser: true, port: backendExposure.port, - // Omit t3Home for WSL mode so the Linux backend uses its own home dir - // instead of the Windows-side baseDir (which would be a /mnt/c path). - ...(useWsl ? {} : { t3Home: environment.baseDir }), + t3Home: environment.baseDir, host: backendExposure.bindHost, desktopBootstrapToken: input.bootstrapToken, tailscaleServeEnabled: backendExposure.tailscaleServeEnabled, tailscaleServePort: backendExposure.tailscaleServePort, - ...Option.match(input.observabilitySettings.otlpTracesUrl, { - onNone: () => ({}), - onSome: (otlpTracesUrl) => ({ otlpTracesUrl }), - }), - ...Option.match(input.observabilitySettings.otlpMetricsUrl, { - onNone: () => ({}), - onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }), - }), + ...buildObservabilityFragment(input.observabilitySettings), }; - if (!useWsl) { - return { - executablePath: process.execPath, - args: [environment.backendEntryPath, "--bootstrap-fd", "3"], - entryPath: environment.backendEntryPath, - cwd: environment.backendCwd, - env: { - ...backendChildEnvPatch(), - ELECTRON_RUN_AS_NODE: "1", - }, - // Local mode wants process.env (PATH, dev-runner's T3CODE_HOME, etc.). - extendEnv: true, - bootstrap, - bootstrapDelivery: "fd3", - httpBaseUrl: backendExposure.httpBaseUrl, - captureOutput: true, - preflightFailure: Option.none(), - } satisfies DesktopBackendManager.DesktopBackendStartConfig; - } - - const preflight = yield* runWslPreflight({ - distro: input.wslDistro, - windowsEntryPath: environment.backendEntryPath, - windowsRepoRoot: environment.appRoot, - allowBuild: !environment.isPackaged, - }); - - const distroArgs = input.wslDistro ? ["-d", input.wslDistro] : []; - const forwardedEnv: Record = {}; - const forwardedEnvNames: string[] = []; - for (const name of WSL_FORWARDED_ENV_NAMES) { - const value = process.env[name]; - if (value !== undefined && value.length > 0) { - forwardedEnv[name] = value; - forwardedEnvNames.push(name); - } - } - - // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner - // exports the Windows-side base dir for the local backend; if it leaks - // into the WSL backend the Linux side ends up sharing C:\Users\...\.t3 - // via /mnt/c, which means both backends are reading/writing the same - // database and the env-id never differs across the swap). - const parentEnvWithoutT3Home: Record = {}; - for (const [key, value] of Object.entries(process.env)) { - if (key === "T3CODE_HOME") continue; - parentEnvWithoutT3Home[key] = value; - } - const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames); - - const baseConfig = { - executablePath: "wsl.exe", + return { + executablePath: process.execPath, + args: [environment.backendEntryPath, "--bootstrap-fd", "3"], entryPath: environment.backendEntryPath, cwd: environment.backendCwd, env: { - ...parentEnvWithoutT3Home, ...backendChildEnvPatch(), - ...forwardedEnv, - ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}), + ELECTRON_RUN_AS_NODE: "1", }, - // env is already a complete process.env minus T3CODE_HOME; pass it - // verbatim instead of letting the spawner re-merge process.env on top. - extendEnv: false, + // Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.). + extendEnv: true, bootstrap, - bootstrapDelivery: "stdin" as const, + bootstrapDelivery: "fd3", httpBaseUrl: backendExposure.httpBaseUrl, captureOutput: true, - }; - - // Forward the dev-server URL as an explicit CLI flag so the WSL backend's - // config resolution lands in dev/ instead of userdata/. Inheriting through - // WSLENV is unreliable in practice (URL-shaped values with colons / - // slashes get translated unpredictably depending on flags), and the - // packaged build leaves devServerUrl as None anyway. - const devUrlArgs = Option.match(environment.devServerUrl, { - onNone: () => [] as ReadonlyArray, - onSome: (url) => ["--dev-url", url.href], - }); - - if (preflight._tag === "Failed") { - return { - ...baseConfig, - args: [...distroArgs, "--", "node", "--version"], - preflightFailure: Option.some(preflight.reason), - } satisfies DesktopBackendManager.DesktopBackendStartConfig; - } - - return { - ...baseConfig, - args: [ - ...distroArgs, - "--", - "node", - preflight.linuxEntryPath, - "--bootstrap-fd", - "0", - ...devUrlArgs, - ], preflightFailure: Option.none(), } satisfies DesktopBackendManager.DesktopBackendStartConfig; }, ); +const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* ( + input: SharedBootstrapInput & { + readonly port: number; + readonly distro: string | null; + }, +): Effect.fn.Return< + DesktopBackendManager.DesktopBackendStartConfig, + never, + | DesktopEnvironment.DesktopEnvironment + | DesktopWslEnvironment.DesktopWslEnvironment + | FileSystem.FileSystem +> { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + + // WSL backend is always loopback-only; the primary owns LAN exposure + // when the user opts in. Hardcode 127.0.0.1 + drop the tailscale flags + // so a second tailscale serve forwarder doesn't try to bind the same + // port from inside WSL. + const wslHost = "127.0.0.1"; + const httpBaseUrl = new URL(`http://${wslHost}:${input.port}`); + + const bootstrap = { + mode: "desktop" as const, + noBrowser: true, + port: input.port, + // Omit t3Home so the Linux backend uses its own home dir instead of + // the Windows-side baseDir (which would be a /mnt/c path and share + // the SQLite file with the primary). + host: wslHost, + desktopBootstrapToken: input.bootstrapToken, + tailscaleServeEnabled: false, + tailscaleServePort: 0, + ...buildObservabilityFragment(input.observabilitySettings), + }; + + const preflight = yield* runWslPreflight({ + distro: input.distro, + windowsEntryPath: environment.backendEntryPath, + windowsRepoRoot: environment.appRoot, + allowBuild: !environment.isPackaged, + }); + + const distroArgs = input.distro ? ["-d", input.distro] : []; + const forwardedEnv: Record = {}; + const forwardedEnvNames: string[] = []; + for (const name of WSL_FORWARDED_ENV_NAMES) { + const value = process.env[name]; + if (value !== undefined && value.length > 0) { + forwardedEnv[name] = value; + forwardedEnvNames.push(name); + } + } + + // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner + // exports the Windows-side base dir for the primary; if it leaks into + // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via + // /mnt/c, which means both backends read/write the same database and + // their env-ids collide). + const parentEnvWithoutT3Home: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key === "T3CODE_HOME") continue; + parentEnvWithoutT3Home[key] = value; + } + const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames); + + const baseConfig = { + executablePath: "wsl.exe", + entryPath: environment.backendEntryPath, + cwd: environment.backendCwd, + env: { + ...parentEnvWithoutT3Home, + ...backendChildEnvPatch(), + ...forwardedEnv, + ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}), + }, + // env is already a complete process.env minus T3CODE_HOME; pass it + // verbatim instead of letting the spawner re-merge process.env on top. + extendEnv: false, + bootstrap, + bootstrapDelivery: "stdin" as const, + httpBaseUrl, + captureOutput: true, + }; + + // Forward the dev-server URL as an explicit CLI flag so the WSL backend's + // config resolution lands in dev/ instead of userdata/. Inheriting through + // WSLENV is unreliable in practice (URL-shaped values with colons / + // slashes get translated unpredictably depending on flags), and the + // packaged build leaves devServerUrl as None anyway. + const devUrlArgs = Option.match(environment.devServerUrl, { + onNone: () => [] as ReadonlyArray, + onSome: (url) => ["--dev-url", url.href], + }); + + if (preflight._tag === "Failed") { + return { + ...baseConfig, + args: [...distroArgs, "--", "node", "--version"], + preflightFailure: Option.some(preflight.reason), + } satisfies DesktopBackendManager.DesktopBackendStartConfig; + } + + return { + ...baseConfig, + args: [ + ...distroArgs, + "--", + "node", + preflight.linuxEntryPath, + "--bootstrap-fd", + "0", + ...devUrlArgs, + ], + preflightFailure: Option.none(), + } satisfies DesktopBackendManager.DesktopBackendStartConfig; +}); + export const layer = Layer.effect( DesktopBackendConfiguration, Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const tokenRef = yield* Ref.make(Option.none()); + // Both resolvers share the same bootstrap token: the renderer holds a + // single token and uses it against whichever backend it's currently + // talking to. Observability settings get re-read each resolve so a + // hot-swap of the server-settings file is picked up on the next + // restart cycle without having to bounce the desktop process. + const sharedInputs = Effect.gen(function* () { + const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef); + const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), + ); + return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput; + }); + return DesktopBackendConfiguration.of({ - resolve: Effect.gen(function* () { - const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef); - const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), - ); - const settings = yield* appSettings.get; - return yield* resolveBackendStartConfig({ - bootstrapToken, - observabilitySettings, - wslBackendEnabled: settings.wslBackendEnabled, - wslDistro: settings.wslDistro, - }).pipe( + resolvePrimary: Effect.gen(function* () { + const shared = yield* sharedInputs; + return yield* resolvePrimaryStartConfig(shared).pipe( Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure), - Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment), - Effect.provideService(FileSystem.FileSystem, fileSystem), ); - }).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")), + }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")), + resolveWsl: (input) => + Effect.gen(function* () { + const shared = yield* sharedInputs; + return yield* resolveWslStartConfig({ ...shared, ...input }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), + Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment), + Effect.provideService(FileSystem.FileSystem, fileSystem), + ); + }).pipe( + Effect.withSpan("desktop.backendConfiguration.resolveWsl", { + attributes: { port: input.port, distro: input.distro ?? null }, + }), + ), }); }), ); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index c04c8babbb..161856d254 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -11,9 +11,10 @@ // // Singleton couplings that the legacy service held inline are now // parameterized via the spec: -// - configResolve replaces `DesktopBackendConfiguration.resolve` so each -// instance can resolve its own start config (Windows-native, WSL via -// wsl.exe, etc.). +// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve` +// so each instance can resolve its own start config — the primary wires +// `configuration.resolvePrimary`, the WSL orchestrator wires a +// `configuration.resolveWsl({ port, distro })` closure. // - onReady / onShutdown drive UI side effects (window auto-open, // readiness latch) only for instances that want them — the primary's // spec passes the window's handleBackendReady/handleBackendNotReady, diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 14aea24bd7..9380ca9550 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -168,7 +168,7 @@ export const layer = Layer.effect( const primary = yield* DesktopBackendManager.makeBackendInstance({ id: DesktopBackendManager.PRIMARY_INSTANCE_ID, label: "Windows", - configResolve: configuration.resolve, + configResolve: configuration.resolvePrimary, // Window creation errors propagating out of handleBackendReady are // swallowed here on purpose: they're logged by the window service // and we don't want a stuck splash window to block the readiness