Desktop: parallel WSL + Windows backends with mode picker #2751
MergedJgratton24(GitHub profile, opens in a new tab)merged 170 commits into
main fromrefs/pull/2751/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/settings/ConnectionsSettings.tsx line 2399OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -2329,2 +2379,21 @@23292379 })23302380 : null;2381+ // Apply a setting change immediately. The orchestrator reconciles the2382+ // pool in the background and the primary backend is untouched, so we2383+ // don't gate this behind a confirmation dialog. After the desktop2384+ // side persists the change and nudges its orchestrator, we trigger2385+ // the renderer's reconciler so the WSL backend's saved-env-shaped2386+ // entry catches up (registers/unregisters) without a reload.2387+ const applyWslSettingChange = useCallback(2388+ async (apply: () => Promise<DesktopWslState>) => {2389+ if (!desktopBridge) return;2390+ setIsUpdatingWslBackend(true);2391+ setDesktopWslError(null);2392+ try {2393+ const next = await apply();2394+ setDesktopWslState(next);2395+ // Keep the renderer's auto-retry loop awake while the user has2396+ // WSL enabled, and let it park otherwise. Without this the2397+ // loop would never resume after a fresh desktop install where2398+ // the initial probe latched "no WSL configured".2399+ markSecondariesConfigured(next.enabled);
- apps/web/src/components/Sidebar.tsx line 837Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -674,4 +687,4 @@674687 ) : null}675688 <span className={threadMetaClassName}>676689 <span className="inline-flex items-center gap-1">677- {isRemoteThread && (690+ {isRemoteThread && !isDesktopLocalThread && (
- apps/desktop/src/backend/DesktopBackendPool.ts line 439Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +267,21 @@267+ ] as const);268+ });269+ yield* Option.match(removed, {270+ onNone: () => Effect.void,271+ onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),272+ });273+ });274+275+ return DesktopBackendPool.of({276+ get: (id) =>277+ SynchronizedRef.get(instancesRef).pipe(278+ Effect.map((instances) => Option.fromNullishOr(instances.get(id)?.instance)),279+ ),280+ list: SynchronizedRef.get(instancesRef).pipe(281+ Effect.map((instances) => Array.from(instances.values(), (entry) => entry.instance)),282+ ),283+ primary: Effect.succeed(primary),284+ register,285+ unregister,286+ });287+ }),
- apps/desktop/src/updates/DesktopUpdates.ts line 372OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -368,4 +369,4 @@368369 yield* Ref.set(updateInstallInFlightRef, true);369370370371 return yield* Effect.gen(function* () {371- yield* backendManager.stop({ timeout: Duration.seconds(5) });372+ yield* primaryBackend.stop({ timeout: Duration.seconds(5) });
- apps/desktop/src/app/DesktopApp.ts line 241OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -226,7 +234,8 @@226234 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });227235228236 const shutdown = yield* DesktopLifecycle.DesktopShutdown;229- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;237+ const pool = yield* DesktopBackendPool.DesktopBackendPool;238+ const primaryBackend = yield* pool.primary;230239231240 yield* Effect.addFinalizer(() =>232- backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),241+ primaryBackend.stop().pipe(Effect.ensuring(shutdown.markComplete)),
- apps/desktop/src/ipc/methods/window.ts line 88Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -75,3 +119,20 @@119+ targetId !== undefined &&120+ targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&121+ targetId.startsWith(WSL_INSTANCE_ID_PREFIX);122+ const settings = yield* appSettings.get;123+ // Fall back to the persisted wslDistro when the id is the124+ // "wsl:default" sentinel; the orchestrator uses the same fallback125+ // for the actual backend.126+ const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;127+ const defaultPath = useWsl128+ ? Option.fromNullishOr(129+ resolveWslPickFolderDefaultPath(130+ options,131+ { distro: wslDistro },132+ yield* wslEnvironment.listDistros,133+ Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),134+ ),135+ )136+ : environment.resolvePickFolderDefaultPath(options);75137 const selectedPath = yield* dialog.pickFolder({76138 owner: yield* electronWindow.focusedMainOrFirst,77- defaultPath: environment.resolvePickFolderDefaultPath(options),apps/desktop/src/wsl/DesktopWslBackend.ts line 243Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +178,21 @@178+ if (179+ Option.isSome(targetId) &&180+ Option.isSome(existingId) &&181+ targetId.value === existingId.value182+ ) {183+ return;184+ }185+186+ if (Option.isSome(existingId)) {187+ yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });188+ yield* stopExisting(existingId.value);189+ }190+191+ if (Option.isSome(targetId)) {192+ // Pre-warm the WSL VM before registering so the readiness probe193+ // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates194+ // distro=null (uses the WSL default) and is bounded by its own195+ // timeout, so it's safe to await unconditionally here.196+ yield* wslEnvironment.preWarm(settings.wslDistro);197+ yield* startNew({ distro: settings.wslDistro });198+ }
- apps/desktop/src/backend/DesktopBackendManager.ts line 356Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -256,2 +300,19 @@256- },257- );300+ const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));301+ const command = ChildProcess.make(options.executablePath, options.args, {302+ cwd: options.cwd,303+ env: options.env,304+ extendEnv: options.extendEnv,305+ // In Electron main, process.execPath points to the Electron binary.306+ // Run the child in Node mode so this backend process does not become a GUI app instance.307+ stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",308+ stdout: options.captureOutput ? "pipe" : "inherit",309+ stderr: options.captureOutput ? "pipe" : "inherit",310+ killSignal: "SIGTERM",311+ forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,312+ // wsl.exe drops additional file descriptors when forwarding to the Linux313+ // side, so the WSL spawn path delivers the bootstrap envelope via stdin314+ // (`--bootstrap-fd 0`) instead.315+ ...(options.bootstrapDelivery === "fd3"316+ ? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }317+ : {}),318+ });
- apps/desktop/src/backend/DesktopBackendManager.ts line 750Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -560,4 +638,4 @@560638 });561639 });562640563- const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {641+ const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
- apps/desktop/src/ipc/methods/window.ts line 87OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -57,10 +69,19 @@69+ // at a port nothing is bound to and trigger needless70+ // /api/auth/bootstrap/bearer error cycles.71+ if (Option.isSome(config.value.preflightFailure)) continue;72+ const { bootstrap, httpBaseUrl } = config.value;73+ bootstraps.push({74+ id: instance.id,75+ label: instance.label,5776 httpBaseUrl: httpBaseUrl.href,5877 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),5978 ...(bootstrap.desktopBootstrapToken6079 ? { bootstrapToken: bootstrap.desktopBootstrapToken }6180 : {}),62- }),63- });81+ });82+ }83+ return bootstraps;6484 }),6585 });668687+const WSL_INSTANCE_ID_PREFIX = "wsl:";
- apps/desktop/src/app/DesktopObservability.ts line 432Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -343,0 +399,21 @@399+400+ const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>401+ SynchronizedRef.modifyEffect(cacheRef, (cache) => {402+ // Key the cache by the resolved file path, not the raw id.403+ // Otherwise two ids that sanitize to the same filename (e.g.404+ // `wsl:default` and `wsl_default`) would each create their405+ // own RotatingLogFileWriter pointing at the same file, with406+ // independent currentSize tracking and a race on writes.407+ const cacheKey = backendLogFilePathForInstance(environment, id);408+ const cached = cache.get(cacheKey);409+ if (cached !== undefined) return Effect.succeed([cached, cache] as const);410+ return makeBackendOutputLogForInstance(environment, id).pipe(411+ Effect.provideService(FileSystem.FileSystem, fileSystem),412+ Effect.provideService(Path.Path, path),413+ Scope.provide(factoryScope),414+ Effect.map((shape) => {415+ const next = new Map(cache);416+ next.set(cacheKey, shape);417+ return [shape, next as ReadonlyMap<string, DesktopBackendOutputLogShape>] as const;418+ }),419+ );apps/desktop/src/wsl/DesktopWslBackend.ts line 214OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +194,21 @@194+ return;195+ }196+197+ if (Option.isSome(existingId)) {198+ yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });199+ yield* stopExisting(existingId.value);200+ }201+202+ if (Option.isSome(targetId)) {203+ // Pre-warm the WSL VM before registering so the readiness probe204+ // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates205+ // distro=null (uses the WSL default) and is bounded by its own206+ // timeout, so it's safe to await unconditionally here.207+ yield* wslEnvironment.preWarm(settings.wslDistro);208+ yield* startNew({ distro: settings.wslDistro });209+ }210+ });211+212+ const reconcile = reconcileMutex213+ .withPermits(1)(reconcileBody)214+ .pipe(Effect.withSpan("desktop.wslBackend.reconcile"));
- apps/desktop/src/backend/DesktopBackendPool.ts line 228OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +208,21 @@208+ // so the label needs to match. We don't try to react to runtime209+ // setting changes here: the wsl-only switch requires an app210+ // restart so the label reflects the mode the user is actually in.211+ const initialSettings = yield* settings.get;212+ const primaryLabel =213+ initialSettings.wslOnly && initialSettings.wslBackendEnabled214+ ? initialSettings.wslDistro215+ ? `WSL (${initialSettings.wslDistro})`216+ : "WSL"217+ : "Windows";218+219+ const primary = yield* DesktopBackendManager.makeBackendInstance({220+ id: DesktopBackendManager.PRIMARY_INSTANCE_ID,221+ label: primaryLabel,222+ configResolve: configuration.resolvePrimary,223+ // Window creation errors propagating out of handleBackendReady are224+ // swallowed here on purpose: they're logged by the window service225+ // and we don't want a stuck splash window to block the readiness226+ // callback (which would prevent restartAttempt from being reset).227+ onReady: (httpBaseUrl) =>228+ desktopWindow.handleBackendReady(httpBaseUrl).pipe(Effect.catch(() => Effect.void)),
- apps/desktop/src/backend/DesktopBackendConfiguration.ts line 438OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -133,6 +418,21 @@418+ args: [419+ ...distroArgs,420+ "--",421+ "node",422+ preflight.linuxEntryPath,423+ "--bootstrap-fd",424+ "0",425+ ...devUrlArgs,426+ ],427+ preflightFailure: Option.none(),428+ } satisfies DesktopBackendManager.DesktopBackendStartConfig;429+});430+133431 export const layer = Layer.effect(134432 DesktopBackendConfiguration,135433 Effect.gen(function* () {136434 const environment = yield* DesktopEnvironment.DesktopEnvironment;137435 const fileSystem = yield* FileSystem.FileSystem;138436 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;437+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;438+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
- apps/desktop/src/backend/DesktopBackendPool.ts line 298Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +220,21 @@220+ : "Windows";221+222+ const primary = yield* DesktopBackendManager.makeBackendInstance({223+ id: DesktopBackendManager.PRIMARY_INSTANCE_ID,224+ label: primaryLabel,225+ configResolve: configuration.resolvePrimary,226+ // Window creation errors propagating out of handleBackendReady must227+ // not block the readiness callback (that would prevent restartAttempt228+ // from being reset), so we absorb them here. The window service only229+ // logs on success, so log the failure here before swallowing it —230+ // otherwise a post-readiness window-open failure vanishes silently and231+ // is near-impossible to diagnose in production.232+ onReady: (httpBaseUrl) =>233+ desktopWindow.handleBackendReady(httpBaseUrl).pipe(234+ Effect.catch((error) =>235+ logBackendPoolWarning("failed to open main window after backend readiness", {236+ error: error.message,237+ }),238+ ),239+ ),240+ onShutdown: () => desktopWindow.handleBackendNotReady,
- apps/desktop/src/backend/DesktopBackendPool.ts line 220OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +200,21 @@200+ const layerScope = yield* Scope.Scope;201+ // Capture the services needed to build any future instance from the202+ // pool's layer scope. register() runs `makeBackendInstance` against203+ // a fresh child scope but reuses these services so the instance gets204+ // the same FileSystem, spawner, HTTP client and log factory the205+ // primary instance uses.206+ const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();207+208+ // Primary label is captured once per process. When wsl-only mode209+ // is active, the primary's configResolve actually returns the WSL210+ // backend config (see DesktopBackendConfiguration.resolvePrimary),211+ // so the label needs to match. We don't try to react to runtime212+ // setting changes here: the wsl-only switch requires an app213+ // restart so the label reflects the mode the user is actually in.214+ const initialSettings = yield* settings.get;215+ const primaryLabel =216+ initialSettings.wslOnly && initialSettings.wslBackendEnabled217+ ? initialSettings.wslDistro218+ ? `WSL (${initialSettings.wslDistro})`219+ : "WSL"220+ : "Windows";
- apps/desktop/src/app/DesktopObservability.ts line 311OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -293,7 +308,4 @@293308 },294309 );295310296-const backendOutputLogLayer = Layer.effect(297- DesktopBackendOutputLog,298- Effect.gen(function* () {299- const environment = yield* DesktopEnvironment.DesktopEnvironment;311+const PRIMARY_BACKEND_LOG_INSTANCE_ID = "primary";apps/desktop/src/backend/DesktopBackendManager.ts line 411OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -328,5 +408,4 @@328408 return;329409 }330410331- yield* Ref.set(desktopState.backendReady, false);332- const config = yield* configuration.resolve.pipe(411+ yield* spec.onShutdown?.() ?? Effect.void;
- apps/desktop/src/backend/DesktopBackendPool.ts line 212OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +192,21 @@192+ // instance scopes can be forked off it. Without this, instance193+ // scopes are orphaned: they only close via explicit unregister()194+ // calls, so on app shutdown the WSL backend child process gets195+ // hard-killed by the OS instead of receiving the graceful196+ // SIGTERM + grace period the instance's stop finalizer would197+ // otherwise run.198+ const layerScope = yield* Scope.Scope;199+ // Capture the services needed to build any future instance from the200+ // pool's layer scope. register() runs `makeBackendInstance` against201+ // a fresh child scope but reuses these services so the instance gets202+ // the same FileSystem, spawner, HTTP client and log factory the203+ // primary instance uses.204+ const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();205+206+ // Primary label is captured once per process. The configuration derives207+ // it from the same decision resolvePrimary makes (wsl-only + WSL actually208+ // available, else Windows), so the label always matches the backend that209+ // resolves — including the fall-back to Windows when WSL is unavailable.210+ // We don't react to runtime setting changes here: the wsl-only switch211+ // requires an app restart, so this reflects the mode the user is in.212+ const primaryLabel = yield* configuration.resolvePrimaryLabel;
- apps/desktop/src/ipc/methods/window.ts line 115Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -57,7 +70,19 @@70+ // Skip instances whose preflight failed (e.g. WSL distro71+ // missing node, the linux server entry was never built). The72+ // backend manager schedules a restart instead of actually73+ // listening, so exposing the bootstrap would point the renderer74+ // at a port nothing is bound to and trigger needless75+ // /api/auth/bootstrap/bearer error cycles.76+ if (Option.isSome(config.value.preflightFailure)) continue;77+ const { bootstrap, httpBaseUrl } = config.value;78+ bootstraps.push({79+ id: instance.id,80+ label: yield* instance.label,5781 httpBaseUrl: httpBaseUrl.href,5882 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),5983 ...(bootstrap.desktopBootstrapToken6084 ? { bootstrapToken: bootstrap.desktopBootstrapToken }6185 : {}),62- }),63- });86+ });87+ }88+ return bootstraps;
- apps/desktop/src/backend/DesktopBackendManager.ts line 621Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -424,4 +511,4 @@424511 details: `pid=${pid.value} ${reason}`,425512 });426513 }427- yield* Ref.set(desktopState.backendReady, false);514+ yield* spec.onShutdown?.() ?? Effect.void;
- apps/desktop/src/backend/DesktopBackendManager.ts line 451Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -328,5 +408,5 @@328408 return;329409 }330410331- yield* Ref.set(desktopState.backendReady, false);332- const config = yield* configuration.resolve.pipe(411+ if (current.ready || Option.isSome(current.config)) {412+ yield* spec.onShutdown?.() ?? Effect.void;
- apps/desktop/src/backend/DesktopBackendConfiguration.ts line 546OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -158,4 +530,17 @@158- );159- return yield* resolveBackendStartConfig({160- bootstrapToken,161- observabilitySettings,530+ resolvePrimary: Effect.gen(function* () {531+ const { useWsl, wslRequested } = yield* describePrimary;532+ if (useWsl) {533+ return yield* buildWslPrimaryConfig;534+ }535+ if (wslRequested) {536+ yield* Effect.logWarning(537+ "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",538+ );539+ }540+ return yield* buildWindowsPrimaryConfig;541+ }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),542+ resolvePrimaryLabel: Effect.gen(function* () {543+ const { useWsl, distro } = yield* describePrimary;544+ if (!useWsl) return "Windows";545+ return distro ? `WSL (${distro})` : "WSL";546+ }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
- apps/desktop/src/ipc/methods/wsl.ts line 101Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +49,21 @@49+ yield* appSettings.setWslBackendEnabled(enabled);50+ // Reconcile is idempotent and never fails; no need for a swap-style51+ // rollback when the WSL side has trouble coming up. With both52+ // backends running side by side, "WSL didn't start" is a transient53+ // state on one instance — the primary stays up either way.54+ yield* wslBackend.reconcile;55+ return yield* readWslState;56+ }),57+});58+59+export const setWslDistro = makeIpcMethod({60+ channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,61+ payload: Schema.NullOr(Schema.String),62+ result: DesktopWslStateSchema,63+ handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {64+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;65+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;66+ yield* appSettings.setWslDistro(distro);67+ yield* wslBackend.reconcile;68+ return yield* readWslState;69+ }),
- apps/web/src/components/settings/ConnectionsSettings.tsx lines 2620 to 2620OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -2493,0 +2600,21 @@2600+ // open threads/projects. If WSL never connected (fresh install,2601+ // toggled on then immediately off, etc.) we skip the confirmation2602+ // dialog because there's nothing to lose.2603+ const hasWslRegistrationToLose = useMemo(() => {2604+ for (const record of Object.values(savedEnvironmentsById)) {2605+ if (record.desktopLocal?.instanceId?.startsWith("wsl:")) return true;2606+ }2607+ return false;2608+ }, [savedEnvironmentsById]);2609+2610+ // Single picker for "WSL backend off" vs "running on distro X". The2611+ // dropdown maps "Off" to disable and any distro entry to enable +2612+ // run on that distro. Splitting these into a separate switch and2613+ // dropdown was confusing — they're the same decision.2614+ const handleSelectWslMode = useCallback(2615+ (value: string) => {2616+ if (!desktopBridge || !desktopWslState) return;2617+ const defaultDistroName =2618+ desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null;2619+ if (value === BACKEND_VALUE_WSL_OFF) {2620+ if (!desktopWslState.enabled) return;
- apps/desktop/src/backend/DesktopBackendConfiguration.ts line 225OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -92,0 +205,21 @@205+ });206+ if (!nodePtyResult.ok) {207+ return {208+ _tag: "Failed",209+ reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,210+ } as const;211+ }212+213+ return { _tag: "Ready", linuxEntryPath: linuxEntry.value } as const;214+});215+216+// True when the given IPv4 belongs to a Windows-side network217+// interface. In WSL2 mirrored mode the distro's eth0 IP equals the218+// host's, which is the signature we use to detect that mode and219+// switch the renderer URL to loopback.220+const isLocalHostIpv4 = (ip: string): boolean => {221+ const interfaces = NodeOS.networkInterfaces();222+ for (const list of Object.values(interfaces)) {223+ if (!list) continue;224+ for (const entry of list) {225+ if (entry.family === "IPv4" && entry.address === ip) return true;
- apps/desktop/src/backend/DesktopBackendConfiguration.ts line 106OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -54,0 +86,21 @@86+ const slashIndex = entry.indexOf("/");87+ return slashIndex === -1 ? entry : entry.slice(0, slashIndex);88+};89+90+const mergeWslEnv = (91+ existingWslEnv: string | undefined,92+ forwardedEnvNames: ReadonlyArray<string>,93+): string | undefined => {94+ const entries: string[] = [];95+ const seenNames = new Set<string>();96+97+ for (const rawEntry of existingWslEnv?.split(":") ?? []) {98+ const entry = rawEntry.trim();99+ if (entry.length === 0) continue;100+101+ const name = getWslEnvEntryName(entry);102+ if (name.length === 0 || seenNames.has(name)) continue;103+104+ seenNames.add(name);105+ entries.push(entry);106+ }apps/desktop/src/wsl/DesktopWslBackend.ts line 223Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +175,21 @@175+176+ // In wsl-only mode the pool's primary IS the WSL backend (see177+ // DesktopBackendConfiguration.resolvePrimary), so the178+ // orchestrator skips registering a parallel "wsl:<distro>"179+ // secondary. Without this skip we'd spin up two WSL processes180+ // on the same distro for users who explicitly asked for one.181+ const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;182+ const targetId = shouldRun183+ ? Option.some(resolveTargetInstanceId(settings.wslDistro))184+ : Option.none<DesktopBackendPool.BackendInstanceId>();185+186+ // No-op if the desired state already matches what's registered.187+ if (Option.isNone(targetId) && Option.isNone(existingId)) {188+ return;189+ }190+ if (191+ Option.isSome(targetId) &&192+ Option.isSome(existingId) &&193+ targetId.value === existingId.value194+ ) {195+ return;
- apps/desktop/src/backend/DesktopBackendPool.ts line 235OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +215,21 @@215+ // once the distro is fixed.216+ const handlePrimaryPreflightFailure = Effect.fn(217+ "desktop.backendPool.primaryPreflightFailed",218+ )(function* (reason: string) {219+ yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {220+ reason,221+ });222+ yield* electronDialog.showErrorBox(223+ "WSL backend couldn't start",224+ `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable "Run in WSL only" from Settings > Connections once the WSL distro is fixed.`,225+ );226+ // Persist Windows mode so the manager's next restart re-resolves the227+ // primary as Windows (describePrimary reads wslOnly) and a window opens.228+ // Swallow a write failure — we still logged and surfaced the reason.229+ yield* appSettings.setWslOnly(false).pipe(230+ Effect.catch((error) =>231+ logBackendPoolWarning("failed to persist Windows fallback after WSL preflight failure", {232+ error: error.message,233+ }),234+ ),235+ );
- apps/web/src/environments/local/index.ts lines 340 to 346OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +326,21 @@326+ wsBaseUrl: bootstrap.wsBaseUrl,327+ httpBaseUrl: bootstrap.httpBaseUrl,328+ createdAt: existing?.createdAt ?? new Date().toISOString(),329+ lastConnectedAt: new Date().toISOString(),330+ desktopLocal: { instanceId: bootstrap.id },331+ };332+333+ // Order is load-bearing: the bearer must be in the secret store334+ // before we upsert. The zustand subscriber on the registry fires a335+ // saved-env sync as soon as upsert lands, and that path reads the336+ // bearer back out via readSavedEnvironmentBearerToken; without the337+ // earlier write the sync would race ahead, find no bearer, and flip338+ // the runtime state to "requires-auth" before the explicit339+ // ensureSavedEnvironmentConnection call below runs.340+ useSavedEnvironmentRegistryStore.getState().upsert(record);341+ await ensureSavedEnvironmentConnection(record, {342+ bearerToken,343+ scopes,344+ });345+ return record;346+}
- apps/desktop/src/backend/DesktopBackendManager.ts line 515Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -354,0 +462,21 @@462+ const { reason, fatal } = preflightFailure.value;463+ if (!fatal) {464+ // Transient (WSL cold-starting, wslpath while the VM boots). Keep465+ // retrying so the backend self-heals once WSL is ready; don't count466+ // it toward the fatal cap.467+ yield* scheduleRestart(reason);468+ return;469+ }470+ const attempt = yield* Ref.modify(state, (latest) => {471+ const next = latest.preflightFailureAttempt + 1;472+ return [next, { ...latest, preflightFailureAttempt: next }] as const;473+ });474+ if (attempt > MAX_PREFLIGHT_FAILURE_ATTEMPTS) {475+ // We already surfaced and asked for the Windows fallback, yet we're476+ // still resolving the WSL primary — the fallback didn't take (e.g.477+ // the settings write failed). Stop rather than loop forever.478+ yield* logInstanceError("backend preflight still failing after fallback; stopping", {479+ reason,480+ attempt,481+ });482+ return;
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
146fe5fe-b286-4299-ae4d-3bd0e889737bYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share