diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index f948adde13..befa38167e 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -21,6 +21,7 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; import * as DesktopState from "./DesktopState.ts"; import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; +import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; const DEFAULT_DESKTOP_BACKEND_PORT = 3773; const MAX_TCP_PORT = 65_535; @@ -136,6 +137,7 @@ const bootstrap = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; + const wslBackend = yield* DesktopWslBackend.DesktopWslBackend; yield* logBootstrapInfo("bootstrap start"); if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) { @@ -181,6 +183,11 @@ const bootstrap = Effect.gen(function* () { if (!(yield* Ref.get(state.quitting))) { yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + // Bring up the WSL backend if the user previously enabled it. The + // primary is already starting; reconcile fires off the WSL register + // in parallel rather than blocking primary readiness on a possibly + // slow first wsl.exe spawn. + yield* Effect.forkScoped(wslBackend.reconcile); } }).pipe(Effect.withSpan("desktop.bootstrap")); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 40c1551670..e75be07eaf 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -300,8 +300,12 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl // the SQLite file with the primary). host: wslHost, desktopBootstrapToken: input.bootstrapToken, + // PortSchema rejects 0, so when tailscale serve is disabled we still + // need a valid number in this slot. The backend reads tailscaleServePort + // only when tailscaleServeEnabled is true, so the actual value here is + // inert. tailscaleServeEnabled: false, - tailscaleServePort: 0, + tailscaleServePort: 443, ...buildObservabilityFragment(input.observabilitySettings), }; diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 33e2acec2a..e663228961 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -41,7 +41,7 @@ import { setTheme, showContextMenu, } from "./methods/window.ts"; -import { getWslState, setWslBackend } from "./methods/wsl.ts"; +import { getWslState, setWslBackendEnabled, setWslDistro } from "./methods/wsl.ts"; export const installDesktopIpcHandlers = Effect.gen(function* () { const ipc = yield* DesktopIpc.DesktopIpc; @@ -72,7 +72,8 @@ export const installDesktopIpcHandlers = Effect.gen(function* () { yield* ipc.handle(getAdvertisedEndpoints); yield* ipc.handle(getWslState); - yield* ipc.handle(setWslBackend); + yield* ipc.handle(setWslBackendEnabled); + yield* ipc.handle(setWslDistro); yield* ipc.handle(pickFolder); yield* ipc.handle(confirm); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 098bf7cc70..8410c7d999 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -33,5 +33,6 @@ export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mod export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled"; export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints"; export const GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state"; -export const SET_WSL_BACKEND_CHANNEL = "desktop:set-wsl-backend"; +export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled"; +export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro"; export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled"; diff --git a/apps/desktop/src/ipc/methods/wsl.ts b/apps/desktop/src/ipc/methods/wsl.ts index 9990fb6dbb..25e3953b41 100644 --- a/apps/desktop/src/ipc/methods/wsl.ts +++ b/apps/desktop/src/ipc/methods/wsl.ts @@ -1,34 +1,13 @@ -import { - DesktopWslModeSchema, - DesktopWslStateSchema, - type DesktopWslState, -} from "@t3tools/contracts"; -import * as Data from "effect/Data"; -import * as Duration from "effect/Duration"; +import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as IpcChannels from "../channels.ts"; import { makeIpcMethod } from "../DesktopIpc.ts"; -// Cap how long we wait for the new backend to come up before rolling back to -// the previous mode. Generous enough to cover cold WSL boots (VM spin-up, -// initial wslhost forwarding handshake) and node-pty preparation on a fresh -// distro; tight enough that a truly stuck swap doesn't strand the user. -const SWAP_READINESS_TIMEOUT = Duration.minutes(2); - -const SetWslBackendInput = Schema.Struct({ - mode: DesktopWslModeSchema, - distro: Schema.NullOr(Schema.String), -}); - -class WslBackendSwapError extends Data.TaggedError("WslBackendSwapError")<{ - readonly message: string; -}> {} - const readWslState: Effect.Effect< DesktopWslState, never, @@ -42,7 +21,7 @@ const readWslState: Effect.Effect< // non-WSL host would spawn wsl.exe and hit the timeout for nothing. const distros = available ? yield* wslEnvironment.listDistros : []; return { - mode: settings.wslBackendEnabled ? "wsl" : "local", + enabled: settings.wslBackendEnabled, distro: settings.wslDistro, available, distros, @@ -58,55 +37,32 @@ export const getWslState = makeIpcMethod({ }), }); -export const setWslBackend = makeIpcMethod({ - channel: IpcChannels.SET_WSL_BACKEND_CHANNEL, - payload: SetWslBackendInput, +export const setWslBackendEnabled = makeIpcMethod({ + channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, + payload: Schema.Boolean, result: DesktopWslStateSchema, - handler: Effect.fn("desktop.ipc.wsl.setBackend")(function* (input) { + handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) { const appSettings = yield* DesktopAppSettings.DesktopAppSettings; - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const primaryBackend = yield* pool.primary; - const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; - - // Pre-warm the WSL VM before swapping so the new backend boot doesn't - // race wsl.exe's first-spawn cold start against the HTTP readiness probe. - if (input.mode === "wsl") { - yield* wslEnvironment.preWarm(input.distro); - } - - const previousSettings = yield* appSettings.get; - const targetEnabled = input.mode === "wsl"; - const enabledChange = yield* appSettings.setWslBackendEnabled(targetEnabled); - const distroChange = yield* appSettings.setWslDistro(input.distro); - - if (!enabledChange.changed && !distroChange.changed) { - return yield* readWslState; - } - - // In-process swap: stop the running backend, then start it again. The - // backend instance re-resolves config on start, so the new toggle picks - // up automatically. - yield* primaryBackend.stop(); - yield* primaryBackend.start; - - // Bounded readiness wait — if the new backend doesn't come up in time - // (bad distro, missing node-pty, preflight failure that scheduled - // restarts forever) revert to the previous toggle so the user isn't stuck. - const ready = yield* primaryBackend.waitForReady(SWAP_READINESS_TIMEOUT); - if (!ready) { - yield* appSettings.setWslBackendEnabled(previousSettings.wslBackendEnabled); - yield* appSettings.setWslDistro(previousSettings.wslDistro); - yield* primaryBackend.stop(); - yield* primaryBackend.start; - const rolledBack = yield* primaryBackend.waitForReady(SWAP_READINESS_TIMEOUT); - const failedTarget = targetEnabled ? "WSL backend" : "local backend"; - return yield* new WslBackendSwapError({ - message: rolledBack - ? `The ${failedTarget} didn't come up. Rolled back to the previous mode — check that the chosen distro is healthy and try again.` - : `The ${failedTarget} didn't come up, and the rollback also failed to start. The app is in a degraded state — restart T3 Code to recover.`, - }); - } - + const wslBackend = yield* DesktopWslBackend.DesktopWslBackend; + yield* appSettings.setWslBackendEnabled(enabled); + // Reconcile is idempotent and never fails; no need for a swap-style + // rollback when the WSL side has trouble coming up. With both + // backends running side by side, "WSL didn't start" is a transient + // state on one instance — the primary stays up either way. + yield* wslBackend.reconcile; + return yield* readWslState; + }), +}); + +export const setWslDistro = makeIpcMethod({ + channel: IpcChannels.SET_WSL_DISTRO_CHANNEL, + payload: Schema.NullOr(Schema.String), + result: DesktopWslStateSchema, + handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) { + const appSettings = yield* DesktopAppSettings.DesktopAppSettings; + const wslBackend = yield* DesktopWslBackend.DesktopWslBackend; + yield* appSettings.setWslDistro(distro); + yield* wslBackend.reconcile; return yield* readWslState; }), }); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9cd0fe8888..de52dce921 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -44,6 +44,7 @@ import * as DesktopSshRemoteApi from "./ssh/DesktopSshRemoteApi.ts"; import * as DesktopState from "./app/DesktopState.ts"; import * as DesktopUpdates from "./updates/DesktopUpdates.ts"; import * as DesktopWindow from "./window/DesktopWindow.ts"; +import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts"; const desktopEnvironmentLayer = Layer.unwrap( @@ -140,12 +141,19 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe( Layer.provideMerge(desktopWindowLayer), ); +// WSL orchestrator hangs off the backend layer because it needs the +// pool + configuration + serverExposure; it pulls NetService and the +// foundation services through the same provideMerge chain. +const desktopWslBackendLayer = DesktopWslBackend.layer.pipe( + Layer.provideMerge(desktopBackendLayer), +); + const desktopApplicationLayer = Layer.mergeAll( DesktopLifecycle.layer, DesktopApplicationMenu.layer, DesktopShellEnvironment.layer, desktopSshLayer, -).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer)); +).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopWslBackendLayer)); const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe( Layer.flatMap(() => diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 0361423953..72bcd71a72 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -88,7 +88,9 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input), getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL), getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL), - setWslBackend: (input) => ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_CHANNEL, input), + setWslBackendEnabled: (enabled) => + ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled), + setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro), pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options), confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message), setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme), diff --git a/apps/desktop/src/wsl/DesktopWslBackend.ts b/apps/desktop/src/wsl/DesktopWslBackend.ts new file mode 100644 index 0000000000..fe4a19714f --- /dev/null +++ b/apps/desktop/src/wsl/DesktopWslBackend.ts @@ -0,0 +1,198 @@ +// Orchestrator that keeps the WSL pool instance in sync with the user's +// settings. `reconcile` is the single entry point — bootstrap calls it +// once after the primary backend starts, and the wsl.ts IPC calls it +// after persisting a `wslBackendEnabled` or `wslDistro` change. The +// effect is idempotent and never fails: errors (WSL not available, port +// allocation failed, register failed) get logged and reconcile returns +// having left the pool in a consistent state (either the previous WSL +// instance is still running, or none is). +// +// The instance id encodes the desired distro selection — `wsl:default` +// when the user picked "track the WSL default" (settings.wslDistro is +// null) and `wsl:` otherwise. Changing the distro setting +// changes the id, so reconcile unregisters the old instance before +// registering the new one. The label that the frontend env switcher +// renders is derived from the same field. +// +// Port allocation: each WSL instance gets a freshly scanned port to +// avoid colliding with the primary or with a previously-registered WSL +// instance that's still tearing down. The scan only checks loopback +// (127.0.0.1) since the WSL backend is loopback-only — the primary +// owns LAN exposure when the user opts in. + +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as NetService from "@t3tools/shared/Net"; + +import * as DesktopObservability from "../app/DesktopObservability.ts"; +import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; +import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; +import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; +import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; +import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts"; + +const WSL_INSTANCE_ID_PREFIX = "wsl:"; +const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`; +const MAX_TCP_PORT = 65_535; + +export interface DesktopWslBackendShape { + // Bring the pool in line with the current persisted WSL settings. + // Idempotent. Never fails (errors are logged); callers can chain it + // after persisting settings without an error-handling dance. + readonly reconcile: Effect.Effect; +} + +export class DesktopWslBackend extends Context.Service()( + "t3/desktop/WslBackend", +) {} + +const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } = + DesktopObservability.makeComponentLogger("desktop-wsl-backend"); + +const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId => + DesktopBackendPool.BackendInstanceId( + distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`, + ); + +const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean => + id.startsWith(WSL_INSTANCE_ID_PREFIX); + +const buildLabel = (distro: string | null): string => + distro === null ? "WSL (default distro)" : `WSL (${distro})`; + +// Loopback-only port scan starting one above the primary's port. The +// WSL backend is reachable via 127.0.0.1 from Windows (wslhost +// auto-forwards), so we only need to verify the IPv4 loopback can bind. +const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* ( + startPort: number, +): Effect.fn.Return { + const net = yield* NetService.NetService; + for (let port = startPort; port <= MAX_TCP_PORT; port += 1) { + if (yield* net.canListenOnHost(port, "127.0.0.1")) { + return port; + } + } + return yield* new NetService.NetError({ + message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`, + }); +}); + +export const layer = Layer.effect( + DesktopWslBackend, + Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; + const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; + const appSettings = yield* DesktopAppSettings.DesktopAppSettings; + const net = yield* NetService.NetService; + + const findExistingWslInstance = pool.list.pipe( + Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))), + Effect.map(Option.fromNullishOr), + ); + + const stopExisting = (id: DesktopBackendPool.BackendInstanceId) => + pool.unregister(id).pipe( + Effect.catchTag("DesktopBackendPoolCannotUnregisterPrimaryError", (cause) => + // Should never happen — wsl: ids are not the primary id — but + // log loudly if the logic ever drifts. + logWslBackendWarning("refusing to unregister primary as wsl instance", { + id, + error: cause.message, + }), + ), + ); + + const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: { + readonly distro: string | null; + }) { + const primaryConfig = yield* serverExposure.backendConfig; + const port = yield* scanForWslPort(primaryConfig.port + 1).pipe( + Effect.provideService(NetService.NetService, net), + Effect.map((value) => Option.some(value)), + Effect.catch((error) => + logWslBackendWarning("could not allocate port for WSL backend", { + error: error.message, + }).pipe(Effect.as(Option.none())), + ), + ); + + if (Option.isNone(port)) { + return; + } + const allocatedPort = port.value; + + const targetId = resolveTargetInstanceId(input.distro); + yield* logWslBackendInfo("registering WSL backend with pool", { + id: targetId, + port: allocatedPort, + distro: input.distro ?? null, + }); + + const instance = yield* pool + .register({ + id: targetId, + label: buildLabel(input.distro), + configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }), + }) + .pipe( + Effect.map((registered) => Option.some(registered)), + Effect.catch((error) => + logWslBackendWarning("WSL backend already registered, skipping start", { + id: targetId, + error: error.message, + }).pipe(Effect.as(Option.none())), + ), + ); + + yield* Option.match(instance, { + onNone: () => Effect.void, + onSome: (registered) => registered.start, + }); + }); + + const reconcile = Effect.gen(function* () { + const settings = yield* appSettings.get; + const available = yield* wslEnvironment.isAvailable; + const existing = yield* findExistingWslInstance; + const existingId = Option.map(existing, (instance) => instance.id); + + const shouldRun = settings.wslBackendEnabled && available; + const targetId = shouldRun + ? Option.some(resolveTargetInstanceId(settings.wslDistro)) + : Option.none(); + + // No-op if the desired state already matches what's registered. + if (Option.isNone(targetId) && Option.isNone(existingId)) { + return; + } + if ( + Option.isSome(targetId) && + Option.isSome(existingId) && + targetId.value === existingId.value + ) { + return; + } + + if (Option.isSome(existingId)) { + yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value }); + yield* stopExisting(existingId.value); + } + + if (Option.isSome(targetId)) { + // Pre-warm the WSL VM before registering so the readiness probe + // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates + // distro=null (uses the WSL default) and is bounded by its own + // timeout, so it's safe to await unconditionally here. + yield* wslEnvironment.preWarm(settings.wslDistro); + yield* startNew({ distro: settings.wslDistro }); + } + }).pipe(Effect.withSpan("desktop.wslBackend.reconcile")); + + return DesktopWslBackend.of({ reconcile }); + }), +); diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 7a167d53b8..38e849dbda 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -81,14 +81,9 @@ import { revokeServerClientSession, revokeServerPairingLink, isLoopbackHostname, - reauthenticatePrimaryEnvironment, - readPrimaryEnvironmentDescriptor, type ServerClientSessionRecord, type ServerPairingLinkRecord, } from "~/environments/primary"; -import { getWelcomePayload, onWelcome } from "~/rpc/serverState"; -import { suppressReconnect } from "~/rpc/wsConnectionState"; -import { useStore } from "~/store"; import type { WsRpcClient } from "~/rpc/wsRpcClient"; import { type SavedEnvironmentRecord, @@ -1509,12 +1504,9 @@ export function ConnectionsSettings() { const [isUpdatingWslBackend, setIsUpdatingWslBackend] = useState(false); const [desktopWslError, setDesktopWslError] = useState(null); const [pendingDesktopWslSelection, setPendingDesktopWslSelection] = useState<{ - readonly mode: "local" | "wsl"; + readonly enabled: boolean; readonly distro: string | null; } | null>(null); - const [desktopWslChangeStage, setDesktopWslChangeStage] = useState< - "restarting-backend" | "reauthenticating" | "syncing" | null - >(null); const [pendingTailscaleServeEndpoint, setPendingTailscaleServeEndpoint] = useState(null); const [disableTailscaleServeDialogOpen, setDisableTailscaleServeDialogOpen] = useState(false); @@ -2369,9 +2361,9 @@ export function ConnectionsSettings() { if (!desktopWslState) return; const target = value === BACKEND_VALUE_LOCAL - ? { mode: "local" as const, distro: null } + ? { enabled: false, distro: null } : { - mode: "wsl" as const, + enabled: true, distro: value === BACKEND_VALUE_DEFAULT_WSL ? null : value, }; // The dropdown maps `state.distro: null` to the actual default distro @@ -2381,11 +2373,14 @@ export function ConnectionsSettings() { // before comparing so this is a true no-op. const defaultDistroName = desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null; - const resolvedCurrentDistro = - desktopWslState.mode === "wsl" ? (desktopWslState.distro ?? defaultDistroName) : null; - const resolvedTargetDistro = - target.mode === "wsl" ? (target.distro ?? defaultDistroName) : null; - if (target.mode === desktopWslState.mode && resolvedTargetDistro === resolvedCurrentDistro) { + const resolvedCurrentDistro = desktopWslState.enabled + ? (desktopWslState.distro ?? defaultDistroName) + : null; + const resolvedTargetDistro = target.enabled ? (target.distro ?? defaultDistroName) : null; + if ( + target.enabled === desktopWslState.enabled && + resolvedTargetDistro === resolvedCurrentDistro + ) { return; } setPendingDesktopWslSelection(target); @@ -2397,114 +2392,37 @@ export function ConnectionsSettings() { if (!desktopBridge || !pendingDesktopWslSelection) return; const target = pendingDesktopWslSelection; setIsUpdatingWslBackend(true); - setDesktopWslChangeStage("restarting-backend"); setDesktopWslError(null); - const previousPrimaryEnvId = readPrimaryEnvironmentDescriptor()?.environmentId ?? null; - - // Subscribe to welcomes BEFORE the swap so we can wait for the new - // backend's welcome before declaring the swap done. Capture the current - // welcome's env-id as the baseline instead of comparing against - // `previousPrimaryEnvId`: `onWelcome` is `immediate: true` and fires - // synchronously with the atom's current value, so if the descriptor - // hasn't loaded (`previousPrimaryEnvId === null`) any non-null payload - // would otherwise resolve the promise instantly. Using the live welcome - // atom as the baseline closes that race. - const baselineWelcomeEnvId = getWelcomePayload()?.environment.environmentId ?? null; - let resolveNewWelcome: (() => void) | null = null; - const newWelcomePromise = new Promise((resolve) => { - resolveNewWelcome = resolve; - }); - const unsubscribeWelcome = onWelcome((payload) => { - if (payload.environment.environmentId !== baselineWelcomeEnvId) { - resolveNewWelcome?.(); - } - }); - - // Global ceiling on the whole flow. The IPC handler has two stacked - // 2-minute waits worst-case (initial readiness + rollback readiness), so - // setWslBackend itself can legitimately take up to ~4 minutes before - // resolving; reauth adds another ~60s retry budget and the welcome race - // is bounded at 45s. We cap the total at 6 minutes so a true hang surfaces - // without firing prematurely while a legitimate rollback is in progress. - let aborted = false; - let flowTimeoutHandle: number | null = null; - const flowTimeout = new Promise((_, reject) => { - flowTimeoutHandle = window.setTimeout(() => { - aborted = true; - reject(new Error("Backend swap took too long. Check WSL is responsive and try again.")); - }, 360_000); - }); - - const runSwap = async () => { - const updated = await desktopBridge.setWslBackend(target); - if (aborted) return; - setDesktopWslState(updated); - - if (previousPrimaryEnvId) { - useStore.getState().removeEnvironmentState(previousPrimaryEnvId); - } - - setDesktopWslChangeStage("reauthenticating"); - // Each backend signs sessions with its own key, so the OLD cookie is - // rejected by the new backend. Re-bootstrap before any WS reconnect. - // Descriptor is the same URL across the swap, so it'll be re-fetched - // lazily by the next consumer — no need to force a refresh here. - await reauthenticatePrimaryEnvironment(); - if (aborted) return; - - // Wait for the new backend's welcome event so the modal stays open - // until threads are actually ready. Bounded by 45s. - setDesktopWslChangeStage("syncing"); - await Promise.race([ - newWelcomePromise, - new Promise((resolve) => { - window.setTimeout(resolve, 45_000); - }), - ]); - }; - - // Wrap the whole flow (incl. error recovery) in suppressReconnect so the - // catch-block reauth doesn't surface transient reconnect/offline toasts - // on top of the error toast the user is reading. + // The new IPC is non-destructive: toggling WSL on/off or switching + // distros doesn't bounce the primary. The orchestrator picks up + // settings changes and reconciles the WSL pool instance in the + // background. No reauth dance, no welcome race, no rollback are + // needed; the primary stays up either way. try { - await suppressReconnect(async () => { - try { - await Promise.race([runSwap(), flowTimeout]); - - setPendingDesktopWslSelection(null); - toastManager.add({ - type: "success", - title: "Backend restarted", - description: - target.mode === "wsl" - ? `The local backend is now running inside ${target.distro ?? "the default WSL distro"}.` - : "The local backend is now running on Windows.", - }); - } catch (error) { - const message = error instanceof Error ? error.message : "Failed to update WSL backend."; - setDesktopWslError(message); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not change backend mode", - description: message, - }), - ); - await reauthenticatePrimaryEnvironment().catch(() => undefined); - await desktopBridge - .getWslState() - .then((state) => setDesktopWslState(state)) - .catch(() => undefined); - } - }); + // Set distro first so when we flip enabled=true the orchestrator + // immediately registers the right instance. + const afterDistro = await desktopBridge.setWslDistro(target.distro); + setDesktopWslState(afterDistro); + const afterEnabled = await desktopBridge.setWslBackendEnabled(target.enabled); + setDesktopWslState(afterEnabled); + setPendingDesktopWslSelection(null); + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to update WSL backend."; + setDesktopWslError(message); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not change WSL backend", + description: message, + }), + ); + await desktopBridge + .getWslState() + .then((state) => setDesktopWslState(state)) + .catch(() => undefined); } finally { - // Clear the global timer on every path so it can't fire after the flow - // has settled and reject an unreferenced promise. - if (flowTimeoutHandle !== null) window.clearTimeout(flowTimeoutHandle); - unsubscribeWelcome(); setIsUpdatingWslBackend(false); - setDesktopWslChangeStage(null); } }, [desktopBridge, pendingDesktopWslSelection]); @@ -2518,25 +2436,24 @@ export function ConnectionsSettings() { const defaultDistroName = desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null; const wslSelectValue = desktopWslState.distro ?? defaultDistroName ?? BACKEND_VALUE_DEFAULT_WSL; - const currentValue = desktopWslState.mode === "wsl" ? wslSelectValue : BACKEND_VALUE_LOCAL; + const currentValue = desktopWslState.enabled ? wslSelectValue : BACKEND_VALUE_LOCAL; const currentLabel = currentValue === BACKEND_VALUE_LOCAL ? "Local (Windows)" : currentValue === BACKEND_VALUE_DEFAULT_WSL ? "WSL: default distro" : `WSL: ${currentValue}`; - const pendingTargetLabel = - pendingDesktopWslSelection?.mode === "wsl" - ? (pendingDesktopWslSelection.distro ?? "the default WSL distro") - : "Windows"; - const isSwitchingToWsl = pendingDesktopWslSelection?.mode === "wsl"; + const pendingTargetLabel = pendingDesktopWslSelection?.enabled + ? (pendingDesktopWslSelection.distro ?? "the default WSL distro") + : "Windows"; + const isSwitchingToWsl = pendingDesktopWslSelection?.enabled === true; return ( {desktopWslError} : null @@ -2558,7 +2475,7 @@ export function ConnectionsSettings() { > {currentLabel} @@ -2585,15 +2502,15 @@ export function ConnectionsSettings() { {isSwitchingToWsl - ? desktopWslState.mode === "wsl" + ? desktopWslState.enabled ? "Switch WSL distro?" - : "Switch to WSL backend?" - : "Switch to local backend?"} + : "Enable WSL backend?" + : "Disable WSL backend?"} {isSwitchingToWsl - ? `T3 Code will restart the local backend inside ${pendingTargetLabel}. This may take a little while. Each backend keeps its own threads — your Windows threads stay where they are and will return when you switch back.` - : "T3 Code will restart the local backend on Windows. This may take a little while. Each backend keeps its own threads — your WSL threads stay where they are and will return when you switch back."} + ? `T3 Code will bring up a backend inside ${pendingTargetLabel}. The Windows backend keeps running so projects you opened against it stay where they are.` + : "T3 Code will stop the WSL backend. The Windows backend keeps running so projects you opened against it stay where they are."} @@ -2612,16 +2529,12 @@ export function ConnectionsSettings() { {isUpdatingWslBackend ? ( <> - {desktopWslChangeStage === "syncing" - ? "Syncing threads…" - : desktopWslChangeStage === "reauthenticating" - ? "Re-establishing session…" - : "Restarting backend…"} + Applying… ) : isSwitchingToWsl ? ( - "Restart in WSL" + "Enable" ) : ( - "Restart on Windows" + "Disable" )} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 5b01c7b2e5..c06d800eac 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -445,13 +445,19 @@ const createDesktopBridgeStub = (overrides?: { })), getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []), getWslState: vi.fn().mockResolvedValue({ - mode: "local" as const, + enabled: false, distro: null, available: false, distros: [], }), - setWslBackend: vi.fn().mockResolvedValue({ - mode: "local" as const, + setWslBackendEnabled: vi.fn().mockResolvedValue({ + enabled: false, + distro: null, + available: false, + distros: [], + }), + setWslDistro: vi.fn().mockResolvedValue({ + enabled: false, distro: null, available: false, distros: [], diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 1ab7b49c61..7b4cfcdc72 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -221,13 +221,19 @@ function makeDesktopBridge(overrides: Partial = {}): DesktopBridg }), getAdvertisedEndpoints: async () => [], getWslState: async () => ({ - mode: "local", + enabled: false, distro: null, available: false, distros: [], }), - setWslBackend: async () => ({ - mode: "local", + setWslBackendEnabled: async () => ({ + enabled: false, + distro: null, + available: false, + distros: [], + }), + setWslDistro: async () => ({ + enabled: false, distro: null, available: false, distros: [], diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 39343fda55..8d306f01ac 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -369,10 +369,6 @@ export const PickFolderOptionsSchema = Schema.Struct({ initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)), }); -export type DesktopWslMode = "local" | "wsl"; - -export const DesktopWslModeSchema = Schema.Literals(["local", "wsl"]); - export interface DesktopWslDistro { name: string; isDefault: boolean; @@ -386,14 +382,18 @@ export const DesktopWslDistroSchema = Schema.Struct({ }); export interface DesktopWslState { - mode: DesktopWslMode; + // True when the user has opted the WSL backend in; the actual backend + // process is registered with the desktop pool independently of this + // flag and may take a moment to come up after the user enables it. + enabled: boolean; + // null means "track the current WSL default distro". distro: string | null; available: boolean; distros: readonly DesktopWslDistro[]; } export const DesktopWslStateSchema = Schema.Struct({ - mode: DesktopWslModeSchema, + enabled: Schema.Boolean, distro: Schema.NullOr(Schema.String), available: Schema.Boolean, distros: Schema.Array(DesktopWslDistroSchema), @@ -437,10 +437,8 @@ export interface DesktopBridge { }) => Promise; getAdvertisedEndpoints: () => Promise; getWslState: () => Promise; - setWslBackend: (input: { - mode: DesktopWslMode; - distro: string | null; - }) => Promise; + setWslBackendEnabled: (enabled: boolean) => Promise; + setWslDistro: (distro: string | null) => Promise; pickFolder: (options?: PickFolderOptions) => Promise; confirm: (message: string) => Promise; setTheme: (theme: DesktopTheme) => Promise;