feat(desktop): orchestrate the WSL backend as a second pool instance
This is the cut-over to parallel backends. The old "swap the primary
into WSL and bounce it" flow goes away; the WSL backend is now a
second instance registered with the pool, running alongside the
Windows primary. Toggling the WSL backend on/off doesn't touch the
primary at all.
New service DesktopWslBackend (apps/desktop/src/wsl/DesktopWslBackend.ts)
owns the orchestration. Its one entry point, reconcile, reads the
persisted wslBackendEnabled + wslDistro settings, looks at what's
currently registered with the pool, and brings the two in line:
- If WSL should be running and isn't, allocate a loopback port
starting one above the primary's, register a fresh instance via
pool.register({ id, label, configResolve: resolveWsl(...) }),
and kick off instance.start.
- If WSL is running with a stale distro selection, unregister the
old instance (which closes its scope and stops the child process)
before registering the new one.
- If WSL should not be running, unregister whatever wsl: instance
is registered.
reconcile never fails. Port-allocation failures, "WSL not available",
and pool-already-registered errors are logged and the call returns
having left the pool in a consistent state. The primary backend is
never affected.
Instance ids encode the user's distro selection: wsl:default when
wslDistro is null (track the WSL default) and wsl:<distro> otherwise.
These ids are what the env-id work in step 6/7 will key off, so they
stay stable across underlying-default-distro changes — picking
"track default" doesn't reshuffle env ids if the user later sets a
different WSL distro as the default.
Bootstrap call site (DesktopApp.ts) forks reconcile after the primary
start request. The WSL backend can take a moment to come up first
time (wsl.exe cold spawn, node-pty build); the fork keeps that off
the primary's critical path.
IPC surface change:
- Drop setWslBackend({mode, distro}) — the swap call with rollback
semantics — and the SWAP_READINESS_TIMEOUT / waitForReady /
in-process primary stop+start dance in apps/desktop/src/ipc/methods/wsl.ts.
- Add setWslBackendEnabled(boolean) + setWslDistro(string | null).
Each persists the setting via DesktopAppSettings and then calls
wslBackend.reconcile to bring the pool in line. No rollback path:
with both backends running, "WSL didn't come up" is transient
state on one instance, not a degraded app.
- Drop DesktopWslMode / DesktopWslModeSchema from contracts. The
DesktopWslState wire shape changes mode: "local" | "wsl" to a
plain enabled: boolean.
- New IPC channels SET_WSL_BACKEND_ENABLED_CHANNEL +
SET_WSL_DISTRO_CHANNEL.
DesktopBackendConfiguration's resolveWsl bootstrap now hardcodes
tailscaleServePort: 443 when tailscaleServeEnabled is false, because
PortSchema rejects 0. The backend only reads the port when serve is
on, so the value is inert.
Web UI (ConnectionsSettings.tsx) is wired against the new IPC. The
swap ceremony (reauth, welcome-race, suppressReconnect, 6-minute
flow timeout) goes away — toggling is fast and non-destructive now.
The dialog is still the same select-with-confirm shape; step 8 will
rework it into a proper "WSL backend: enabled + distro picker"
control. SettingsPanels.browser.tsx and localApi.test.ts pick up
the new mock shape.
This commit is contained in:
1 parent
31ce3add12
commit
627c80cbec
12 files changed
+335
-235
No files matched your search
@@ -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"));
|
||||
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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";
|
||||
@@ -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;
|
||||
}),
|
||||
});
|
||||
@@ -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(() =>
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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:<distro>` 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<void>;
|
||||
}
|
||||
|
||||
export class DesktopWslBackend extends Context.Service<DesktopWslBackend, DesktopWslBackendShape>()(
|
||||
"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<number, NetService.NetError, NetService.NetService> {
|
||||
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<number>())),
|
||||
),
|
||||
);
|
||||
|
||||
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<DesktopBackendPool.DesktopBackendInstance>())),
|
||||
),
|
||||
);
|
||||
|
||||
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<DesktopBackendPool.BackendInstanceId>();
|
||||
|
||||
// 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 });
|
||||
}),
|
||||
);
|
||||
@@ -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<string | null>(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<AdvertisedEndpoint | null>(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<void>((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<never>((_, 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<void>((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 (
|
||||
<SettingsRow
|
||||
title="Backend runtime"
|
||||
title="WSL backend"
|
||||
description={
|
||||
desktopWslState.mode === "wsl"
|
||||
? "Backend runs inside the selected WSL distro."
|
||||
: "Backend runs natively on Windows."
|
||||
desktopWslState.enabled
|
||||
? "A second backend is running inside the selected WSL distro alongside the Windows one."
|
||||
: "Run a second backend inside a WSL distro alongside the Windows one."
|
||||
}
|
||||
status={
|
||||
desktopWslError ? <span className="block text-destructive">{desktopWslError}</span> : null
|
||||
@@ -2558,7 +2475,7 @@ export function ConnectionsSettings() {
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full sm:w-56"
|
||||
aria-label="Backend runtime"
|
||||
aria-label="WSL backend"
|
||||
disabled={isUpdatingWslBackend}
|
||||
>
|
||||
<SelectValue>{currentLabel}</SelectValue>
|
||||
@@ -2585,15 +2502,15 @@ export function ConnectionsSettings() {
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{isSwitchingToWsl
|
||||
? desktopWslState.mode === "wsl"
|
||||
? desktopWslState.enabled
|
||||
? "Switch WSL distro?"
|
||||
: "Switch to WSL backend?"
|
||||
: "Switch to local backend?"}
|
||||
: "Enable WSL backend?"
|
||||
: "Disable WSL backend?"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{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."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -2612,16 +2529,12 @@ export function ConnectionsSettings() {
|
||||
{isUpdatingWslBackend ? (
|
||||
<>
|
||||
<Spinner className="size-3.5" />
|
||||
{desktopWslChangeStage === "syncing"
|
||||
? "Syncing threads…"
|
||||
: desktopWslChangeStage === "reauthenticating"
|
||||
? "Re-establishing session…"
|
||||
: "Restarting backend…"}
|
||||
Applying…
|
||||
</>
|
||||
) : isSwitchingToWsl ? (
|
||||
"Restart in WSL"
|
||||
"Enable"
|
||||
) : (
|
||||
"Restart on Windows"
|
||||
"Disable"
|
||||
)}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -221,13 +221,19 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): 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: [],
|
||||
|
||||
@@ -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<DesktopServerExposureState>;
|
||||
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;
|
||||
getWslState: () => Promise<DesktopWslState>;
|
||||
setWslBackend: (input: {
|
||||
mode: DesktopWslMode;
|
||||
distro: string | null;
|
||||
}) => Promise<DesktopWslState>;
|
||||
setWslBackendEnabled: (enabled: boolean) => Promise<DesktopWslState>;
|
||||
setWslDistro: (distro: string | null) => Promise<DesktopWslState>;
|
||||
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
setTheme: (theme: DesktopTheme) => Promise<void>;
|
||||
|
||||
Reference in new issue
Block a user