feat(desktop): add WSL backend mode
Lets the desktop app launch the local backend inside a WSL distro instead of natively on Windows. Adds: - Backend plumbing (apps/desktop/src/wsl): pure path parsing utilities, a DesktopWslEnvironment Effect service wrapping wsl.exe operations (listDistros, preWarm, windowsToWslPath, ensureNodePty, isAvailable), and an explicit preflight that checks for missing node / build tools before spawning so the failure message names the actual problem. - Spawn path: DesktopBackendConfiguration branches on the new wslMode setting and assembles "wsl.exe -d <distro> -- node <linux-entry> --bootstrap-fd 0" with the bootstrap envelope on stdin (wsl.exe drops additional file descriptors). Sensitive env vars forward via WSLENV; --dev-url is passed as a CLI flag so the WSL dev backend lands in dev/ instead of userdata/ deterministi- cally. The Windows-side T3CODE_HOME is scrubbed and extendEnv is disabled for WSL so the WSL backend cannot accidentally share a baseDir with the local backend via /mnt/c/... - Settings: wslMode + wslDistro on DesktopAppSettings, with validation that drops distro names containing control or shell meta characters. Contracts get DesktopWslMode / DesktopWslDistro / DesktopWslState schemas. - IPC: getWslState and setWslBackend on the desktop bridge. The setter pre-warms the WSL VM, persists settings, then drives an in-process backend stop + start with a 2-minute readiness wait and a rollback path that reverts to the previous mode if the new backend never reports ready. pickFolder defaults to the WSL home UNC path when wslMode is "wsl". - Web UI: backend-runtime selector in Connection Settings with a three-stage swap modal (restarting / re-establishing session / syncing) that suppresses the WS reconnect toast for the duration of the swap, waits for the new backend's welcome event before closing, and clears the previous env's store state so the side- bar does not render stale threads. New suppressReconnect helper on the connection-status atom plus exports for the descriptor refresh and reauth used by the swap flow.
This commit is contained in:
1 parent
f83d73b6fe
commit
0ae9a14c40
28 files changed
+1712
-53
No files matched your search
@@ -9,6 +9,8 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -89,6 +91,8 @@ const withHarness = <A, E, R>(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -181,6 +185,8 @@ describe("DesktopBackendConfiguration", () => {
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
isPackaged: false,
|
||||
|
||||
@@ -7,10 +7,14 @@ import * as Option from "effect/Option";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import serverPackageJson from "../../../server/package.json" with { type: "json" };
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
@@ -44,6 +48,17 @@ const DESKTOP_BACKEND_ENV_NAMES = [
|
||||
"T3CODE_TAILSCALE_SERVE_PORT",
|
||||
] as const;
|
||||
|
||||
// Sensitive env vars that the WSL backend needs but Windows process.env won't
|
||||
// forward across the wsl.exe boundary without WSLENV. VITE_DEV_SERVER_URL is
|
||||
// included so the WSL backend can tell it is running in dev mode and use the
|
||||
// `dev/` subdir instead of `userdata/` for its state — otherwise the dev
|
||||
// build collides with the user's daily-driver packaged WSL backend.
|
||||
const WSL_FORWARDED_ENV_NAMES = [
|
||||
"OPENAI_API_KEY",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
] as const;
|
||||
|
||||
const backendChildEnvPatch = (): Record<string, string | undefined> =>
|
||||
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
|
||||
|
||||
@@ -97,48 +112,211 @@ const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootst
|
||||
},
|
||||
);
|
||||
|
||||
interface ResolveBackendStartConfigInput {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
readonly wslMode: "local" | "wsl";
|
||||
readonly wslDistro: string | null;
|
||||
}
|
||||
|
||||
interface WslPreflightOutcome {
|
||||
readonly _tag: "Ready";
|
||||
readonly linuxEntryPath: string;
|
||||
}
|
||||
|
||||
interface WslPreflightFailure {
|
||||
readonly _tag: "Failed";
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
|
||||
readonly distro: string | null;
|
||||
readonly windowsEntryPath: string;
|
||||
readonly windowsRepoRoot: string;
|
||||
readonly allowBuild: boolean;
|
||||
}): Effect.fn.Return<
|
||||
WslPreflightOutcome | WslPreflightFailure,
|
||||
never,
|
||||
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
|
||||
> {
|
||||
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const wslAvailable = yield* wslEnv.isAvailable;
|
||||
if (!wslAvailable) {
|
||||
return { _tag: "Failed", reason: "WSL is not available on this system" } as const;
|
||||
}
|
||||
|
||||
const entryExists = yield* fileSystem
|
||||
.exists(input.windowsEntryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!entryExists) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `missing server entry at ${input.windowsEntryPath}`,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const linuxEntry = yield* wslEnv.windowsToWslPath(input.distro, input.windowsEntryPath);
|
||||
if (Option.isNone(linuxEntry)) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const nodePtyResult = yield* wslEnv.ensureNodePty(input.distro, input.windowsRepoRoot, {
|
||||
allowBuild: input.allowBuild,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
});
|
||||
if (!nodePtyResult.ok) {
|
||||
return {
|
||||
_tag: "Failed",
|
||||
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
|
||||
} as const;
|
||||
}
|
||||
|
||||
return { _tag: "Ready", linuxEntryPath: linuxEntry.value } as const;
|
||||
});
|
||||
|
||||
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
}): Effect.fn.Return<
|
||||
function* (
|
||||
input: ResolveBackendStartConfigInput,
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const backendExposure = yield* serverExposure.backendConfig;
|
||||
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
const useWsl = input.wslMode === "wsl" && environment.platform === "win32";
|
||||
|
||||
const bootstrap = {
|
||||
mode: "desktop" as const,
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
// Omit t3Home for WSL mode so the Linux backend uses its own home dir
|
||||
// instead of the Windows-side baseDir (which would be a /mnt/c path).
|
||||
...(useWsl ? {} : { t3Home: environment.baseDir }),
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
};
|
||||
|
||||
if (!useWsl) {
|
||||
return {
|
||||
executablePath: process.execPath,
|
||||
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
// Local mode wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
|
||||
extendEnv: true,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "fd3",
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.wslDistro,
|
||||
windowsEntryPath: environment.backendEntryPath,
|
||||
windowsRepoRoot: environment.appRoot,
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
const distroArgs = input.wslDistro ? ["-d", input.wslDistro] : [];
|
||||
const forwardedEnv: Record<string, string> = {};
|
||||
const forwardedEnvNames: string[] = [];
|
||||
for (const name of WSL_FORWARDED_ENV_NAMES) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined && value.length > 0) {
|
||||
forwardedEnv[name] = value;
|
||||
forwardedEnvNames.push(name);
|
||||
}
|
||||
}
|
||||
const wslEnvNames = [...new Set(forwardedEnvNames)];
|
||||
|
||||
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
|
||||
// exports the Windows-side base dir for the local backend; if it leaks
|
||||
// into the WSL backend the Linux side ends up sharing C:\Users\...\.t3
|
||||
// via /mnt/c, which means both backends are reading/writing the same
|
||||
// database and the env-id never differs across the swap).
|
||||
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "T3CODE_HOME") continue;
|
||||
parentEnvWithoutT3Home[key] = value;
|
||||
}
|
||||
|
||||
const baseConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
entryPath: environment.backendEntryPath,
|
||||
cwd: environment.backendCwd,
|
||||
env: {
|
||||
...parentEnvWithoutT3Home,
|
||||
...backendChildEnvPatch(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
bootstrap: {
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendExposure.port,
|
||||
t3Home: environment.baseDir,
|
||||
host: backendExposure.bindHost,
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
|
||||
}),
|
||||
...forwardedEnv,
|
||||
...(wslEnvNames.length > 0 ? { WSLENV: wslEnvNames.join(":") } : {}),
|
||||
},
|
||||
// env is already a complete process.env minus T3CODE_HOME; pass it
|
||||
// verbatim instead of letting the spawner re-merge process.env on top.
|
||||
extendEnv: false,
|
||||
bootstrap,
|
||||
bootstrapDelivery: "stdin" as const,
|
||||
httpBaseUrl: backendExposure.httpBaseUrl,
|
||||
captureOutput: true,
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
const devUrlArgs = Option.match(environment.devServerUrl, {
|
||||
onNone: () => [] as ReadonlyArray<string>,
|
||||
onSome: (url) => ["--dev-url", url.href],
|
||||
});
|
||||
|
||||
if (preflight._tag === "Failed") {
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [...distroArgs, "--", "node", "--version"],
|
||||
preflightFailure: Option.some(preflight.reason),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}
|
||||
|
||||
return {
|
||||
...baseConfig,
|
||||
args: [
|
||||
...distroArgs,
|
||||
"--",
|
||||
"node",
|
||||
preflight.linuxEntryPath,
|
||||
"--bootstrap-fd",
|
||||
"0",
|
||||
...devUrlArgs,
|
||||
],
|
||||
preflightFailure: Option.none(),
|
||||
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -148,6 +326,8 @@ export const layer = Layer.effect(
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
@@ -157,12 +337,17 @@ export const layer = Layer.effect(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
const settings = yield* appSettings.get;
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
wslMode: settings.wslMode,
|
||||
wslDistro: settings.wslDistro,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
|
||||
@@ -31,6 +31,7 @@ const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
|
||||
entryPath: "/server/bin.mjs",
|
||||
cwd: "/server",
|
||||
env: { ELECTRON_RUN_AS_NODE: "1" },
|
||||
@@ -44,8 +45,11 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
},
|
||||
bootstrapDelivery: "fd3",
|
||||
extendEnv: true,
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
preflightFailure: Option.none(),
|
||||
};
|
||||
|
||||
const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
|
||||
@@ -43,14 +43,23 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
|
||||
readonly extendEnv: boolean;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
readonly preflightFailure: Option.Option<string>;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
@@ -111,6 +120,10 @@ export interface DesktopBackendManagerShape {
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
// Polls desiredRunning + ready until the backend reports ready, or the
|
||||
// timeout elapses. Returns true on ready, false on timeout. Used by the
|
||||
// WSL backend swap to drive its rollback path.
|
||||
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
@@ -233,28 +246,25 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
{
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: true,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const command = ChildProcess.make(options.executablePath, options.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
extendEnv: options.extendEnv,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
|
||||
stdout: options.captureOutput ? "pipe" : "inherit",
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
@@ -342,6 +352,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
config: Option.some(config),
|
||||
}));
|
||||
|
||||
if (Option.isSome(config.preflightFailure)) {
|
||||
yield* scheduleRestart(config.preflightFailure.value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
|
||||
return;
|
||||
@@ -583,6 +598,20 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
});
|
||||
|
||||
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
|
||||
Effect.gen(function* () {
|
||||
const ready = yield* Ref.get(desktopState.backendReady);
|
||||
if (ready) return true;
|
||||
return false;
|
||||
}).pipe(
|
||||
Effect.repeat({
|
||||
until: (ready) => ready,
|
||||
schedule: Schedule.spaced(Duration.millis(100)),
|
||||
}),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse(() => false)),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() => stop());
|
||||
|
||||
return DesktopBackendManager.of({
|
||||
@@ -590,6 +619,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
stop,
|
||||
currentConfig,
|
||||
snapshot,
|
||||
waitForReady,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
import { getWslState, setWslBackend } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
const ipc = yield* DesktopIpc.DesktopIpc;
|
||||
@@ -70,6 +71,9 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(setTailscaleServeEnabled);
|
||||
yield* ipc.handle(getAdvertisedEndpoints);
|
||||
|
||||
yield* ipc.handle(getWslState);
|
||||
yield* ipc.handle(setWslBackend);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
|
||||
@@ -32,4 +32,6 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
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 SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
@@ -11,6 +11,8 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
@@ -18,6 +20,7 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
|
||||
import { resolveWslPickFolderDefaultPath } from "../../wsl/wslPathParsing.ts";
|
||||
|
||||
const ContextMenuPosition = Schema.Struct({
|
||||
x: Schema.Number,
|
||||
@@ -72,9 +75,23 @@ export const pickFolder = makeIpcMethod({
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* appSettings.get;
|
||||
const wslAvailable = yield* wslEnvironment.isAvailable;
|
||||
const useWsl = settings.wslMode === "wsl" && wslAvailable;
|
||||
const defaultPath = useWsl
|
||||
? Option.fromNullishOr(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
options,
|
||||
{ enabled: true, distro: settings.wslDistro },
|
||||
yield* wslEnvironment.listDistros,
|
||||
),
|
||||
)
|
||||
: environment.resolvePickFolderDefaultPath(options);
|
||||
const selectedPath = yield* dialog.pickFolder({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath: environment.resolvePickFolderDefaultPath(options),
|
||||
defaultPath,
|
||||
});
|
||||
return Option.getOrNull(selectedPath);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
DesktopWslModeSchema,
|
||||
DesktopWslStateSchema,
|
||||
type DesktopWslState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.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,
|
||||
DesktopAppSettings.DesktopAppSettings | DesktopWslEnvironment.DesktopWslEnvironment
|
||||
> = Effect.gen(function* () {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const settings = yield* appSettings.get;
|
||||
const available = yield* wslEnvironment.isAvailable;
|
||||
// Only enumerate distros when WSL is actually available — listDistros on a
|
||||
// non-WSL host would spawn wsl.exe and hit the timeout for nothing.
|
||||
const distros = available ? yield* wslEnvironment.listDistros : [];
|
||||
return {
|
||||
mode: settings.wslMode,
|
||||
distro: settings.wslDistro,
|
||||
available,
|
||||
distros,
|
||||
};
|
||||
});
|
||||
|
||||
export const getWslState = makeIpcMethod({
|
||||
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
|
||||
return yield* readWslState;
|
||||
}),
|
||||
});
|
||||
|
||||
export const setWslBackend = makeIpcMethod({
|
||||
channel: IpcChannels.SET_WSL_BACKEND_CHANNEL,
|
||||
payload: SetWslBackendInput,
|
||||
result: DesktopWslStateSchema,
|
||||
handler: Effect.fn("desktop.ipc.wsl.setBackend")(function* (input) {
|
||||
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
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 change = yield* appSettings.setWslMode({ mode: input.mode, distro: input.distro });
|
||||
|
||||
if (!change.changed) {
|
||||
return yield* readWslState;
|
||||
}
|
||||
|
||||
// In-process swap: stop the running backend, then start it again. The
|
||||
// backend manager re-resolves config on start, so the new wslMode picks
|
||||
// up automatically.
|
||||
yield* backendManager.stop();
|
||||
yield* backendManager.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 mode so the user isn't stuck.
|
||||
const ready = yield* backendManager.waitForReady(SWAP_READINESS_TIMEOUT);
|
||||
if (!ready) {
|
||||
yield* appSettings.setWslMode({
|
||||
mode: previousSettings.wslMode,
|
||||
distro: previousSettings.wslDistro,
|
||||
});
|
||||
yield* backendManager.stop();
|
||||
yield* backendManager.start;
|
||||
yield* backendManager.waitForReady(SWAP_READINESS_TIMEOUT);
|
||||
return yield* new WslBackendSwapError({
|
||||
message:
|
||||
input.mode === "wsl"
|
||||
? "The WSL backend didn't come up. Rolled back to the previous mode — check that the chosen distro is healthy and try again."
|
||||
: "The local backend didn't come up. Rolled back to the previous mode.",
|
||||
});
|
||||
}
|
||||
|
||||
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 DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -130,6 +131,7 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopSe
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -87,6 +87,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
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),
|
||||
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),
|
||||
|
||||
@@ -21,6 +21,8 @@ const DesktopSettingsPatch = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
|
||||
@@ -95,6 +97,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
});
|
||||
|
||||
@@ -116,6 +120,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
@@ -195,6 +201,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
),
|
||||
@@ -234,6 +242,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -256,6 +266,8 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
@@ -277,8 +289,47 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
} satisfies DesktopSettingsValue);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists wsl mode and normalizes invalid distro names", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const enable = yield* settings.setWslMode({ mode: "wsl", distro: "Ubuntu-22.04" });
|
||||
assert.isTrue(enable.changed);
|
||||
assert.equal(enable.settings.wslMode, "wsl");
|
||||
assert.equal(enable.settings.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reloaded = yield* settings.load;
|
||||
assert.equal(reloaded.wslMode, "wsl");
|
||||
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
|
||||
|
||||
const reject = yield* settings.setWslMode({ mode: "wsl", distro: "bad name!" });
|
||||
assert.equal(reject.settings.wslDistro, null);
|
||||
|
||||
const noop = yield* settings.setWslMode({ mode: "wsl", distro: null });
|
||||
assert.isFalse(noop.changed);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops invalid persisted wsl distro values on load", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
wslMode: "wsl",
|
||||
wslDistro: "bad/name",
|
||||
});
|
||||
const loaded = yield* settings.load;
|
||||
assert.equal(loaded.wslMode, "wsl");
|
||||
assert.equal(loaded.wslDistro, null);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import {
|
||||
DesktopServerExposureModeSchema,
|
||||
DesktopUpdateChannelSchema,
|
||||
DesktopWslModeSchema,
|
||||
type DesktopServerExposureMode,
|
||||
type DesktopUpdateChannel,
|
||||
type DesktopWslMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -19,6 +21,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -26,6 +29,8 @@ export interface DesktopSettings {
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
readonly wslMode: DesktopWslMode;
|
||||
readonly wslDistro: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopSettingsChange {
|
||||
@@ -41,6 +46,8 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
wslMode: "local",
|
||||
wslDistro: null,
|
||||
};
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
@@ -49,6 +56,8 @@ const DesktopSettingsDocument = Schema.Struct({
|
||||
tailscaleServePort: Schema.optionalKey(Schema.Number),
|
||||
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
|
||||
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
|
||||
wslMode: Schema.optionalKey(DesktopWslModeSchema),
|
||||
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
|
||||
@@ -84,6 +93,10 @@ export interface DesktopAppSettingsShape {
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setWslMode: (input: {
|
||||
readonly mode: DesktopWslMode;
|
||||
readonly distro: string | null;
|
||||
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
}
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
@@ -104,6 +117,10 @@ function normalizeTailscaleServePort(value: unknown): number {
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
function normalizeWslDistro(value: unknown): string | null {
|
||||
return typeof value === "string" && isValidDistroName(value) ? value : null;
|
||||
}
|
||||
|
||||
function normalizeDesktopSettingsDocument(
|
||||
parsed: DesktopSettingsDocument,
|
||||
appVersion: string,
|
||||
@@ -124,6 +141,8 @@ function normalizeDesktopSettingsDocument(
|
||||
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
wslMode: parsed.wslMode === "wsl" ? "wsl" : "local",
|
||||
wslDistro: normalizeWslDistro(parsed.wslDistro),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -148,6 +167,12 @@ function toDesktopSettingsDocument(
|
||||
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
|
||||
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
|
||||
}
|
||||
if (settings.wslMode !== defaults.wslMode) {
|
||||
document.wslMode = settings.wslMode;
|
||||
}
|
||||
if (settings.wslDistro !== defaults.wslDistro) {
|
||||
document.wslDistro = settings.wslDistro;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
@@ -194,6 +219,20 @@ function setUpdateChannel(
|
||||
};
|
||||
}
|
||||
|
||||
function setWslMode(
|
||||
settings: DesktopSettings,
|
||||
input: { readonly mode: DesktopWslMode; readonly distro: string | null },
|
||||
): DesktopSettings {
|
||||
const distro = normalizeWslDistro(input.distro);
|
||||
return settings.wslMode === input.mode && settings.wslDistro === distro
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
wslMode: input.mode,
|
||||
wslDistro: distro,
|
||||
};
|
||||
}
|
||||
|
||||
function readSettings(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
@@ -285,6 +324,12 @@ export const layer = Layer.effect(
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
setWslMode: (input) =>
|
||||
persist((settings) => setWslMode(settings, input)).pipe(
|
||||
Effect.withSpan("desktop.settings.setWslMode", {
|
||||
attributes: { mode: input.mode, distro: input.distro ?? null },
|
||||
}),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -313,6 +358,7 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
|
||||
update((settings) => setServerExposureMode(settings, mode)),
|
||||
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
|
||||
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
|
||||
setWslMode: (input) => update((settings) => setWslMode(settings, input)),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -112,6 +112,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { formatMissingToolsReason, parseToolchainReport } from "./DesktopWslEnvironment.ts";
|
||||
|
||||
describe("parseToolchainReport", () => {
|
||||
it("returns no missing tools and no node version on empty output", () => {
|
||||
expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
|
||||
});
|
||||
|
||||
it("collects all missing: lines", () => {
|
||||
const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["make", "g++"],
|
||||
nodeVersion: "24.10.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores blank lines and trims whitespace", () => {
|
||||
const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
|
||||
expect(parseToolchainReport(stdout)).toEqual({
|
||||
missingTools: ["python3"],
|
||||
nodeVersion: "v22.16.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null node version when value after prefix is empty", () => {
|
||||
expect(parseToolchainReport("nodeVersion:")).toEqual({
|
||||
missingTools: [],
|
||||
nodeVersion: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMissingToolsReason", () => {
|
||||
it("returns null when everything is present and node is in range", () => {
|
||||
expect(
|
||||
formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when range is not specified and tools are present", () => {
|
||||
expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("flags missing node first", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["node", "make"], nodeVersion: null },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("node");
|
||||
expect(reason).toContain("^24.10");
|
||||
expect(reason).toContain("make");
|
||||
expect(reason).toContain("nvm");
|
||||
});
|
||||
|
||||
it("flags an out-of-range node version with the actual version surfaced", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: [], nodeVersion: "20.0.0" },
|
||||
"^24.10 || ^22.16",
|
||||
);
|
||||
expect(reason).toContain("node 20.0.0");
|
||||
expect(reason).toContain("requires ^24.10 || ^22.16");
|
||||
});
|
||||
|
||||
it("flags missing build tools without node when node is fine", () => {
|
||||
const reason = formatMissingToolsReason(
|
||||
{ missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
|
||||
"^24.10",
|
||||
);
|
||||
expect(reason).toContain("g++");
|
||||
expect(reason).toContain("python3");
|
||||
expect(reason).toContain("build-essential");
|
||||
expect(reason).not.toContain("nvm");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,453 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { satisfiesSemverRange } from "@t3tools/shared/semver";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
|
||||
|
||||
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
|
||||
const LIST_TIMEOUT = Duration.seconds(8);
|
||||
const PRE_WARM_TIMEOUT = Duration.seconds(10);
|
||||
const WSLPATH_TIMEOUT = Duration.seconds(10);
|
||||
const PROBE_TIMEOUT = Duration.seconds(10);
|
||||
const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
|
||||
const BUILD_TIMEOUT = Duration.minutes(5);
|
||||
|
||||
export interface EnsureWslNodePtyOptions {
|
||||
readonly allowBuild?: boolean;
|
||||
readonly nodeEngineRange?: string | null;
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| { readonly ok: true }
|
||||
| { readonly ok: false; readonly reason: string };
|
||||
|
||||
export interface DesktopWslEnvironmentShape {
|
||||
readonly isAvailable: Effect.Effect<boolean>;
|
||||
readonly listDistros: Effect.Effect<readonly WslDistro[]>;
|
||||
readonly preWarm: (distro: string | null) => Effect.Effect<void>;
|
||||
readonly windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>;
|
||||
readonly ensureNodePty: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => Effect.Effect<EnsureWslNodePtyResult>;
|
||||
}
|
||||
|
||||
export class DesktopWslEnvironment extends Context.Service<
|
||||
DesktopWslEnvironment,
|
||||
DesktopWslEnvironmentShape
|
||||
>()("t3/desktop/WslEnvironment") {}
|
||||
|
||||
const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
|
||||
distro ? ["-d", distro] : [];
|
||||
|
||||
const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
|
||||
let totalLength = 0;
|
||||
for (const arr of arrays) totalLength += arr.byteLength;
|
||||
const out = new Uint8Array(totalLength);
|
||||
let offset = 0;
|
||||
for (const arr of arrays) {
|
||||
out.set(arr, offset);
|
||||
offset += arr.byteLength;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
|
||||
|
||||
interface ShellResult {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
const TIMEOUT_RESULT: ShellResult = { exitCode: 124, stdout: "", stderr: "\n[timeout]" };
|
||||
|
||||
// wsl.exe re-escapes args before forwarding them to the Linux side, which
|
||||
// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
|
||||
// avoid passing it on the command line at all.
|
||||
const runWslShell = (
|
||||
distro: string | null,
|
||||
bashScript: string,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const spawner = ChildProcessSpawner.ChildProcessSpawner;
|
||||
// -l so nvm/profile-managed tools (node, node-gyp) are on PATH;
|
||||
// -s so bash reads the script from stdin instead of the command line.
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
|
||||
{
|
||||
stdin: Stream.encodeText(Stream.make(bashScript)),
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawnerService = yield* spawner;
|
||||
const handle = yield* spawnerService.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const stderrBytes = yield* Stream.runCollect(handle.stderr);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
return {
|
||||
exitCode: exitCode as unknown as number,
|
||||
stdout: decodeUtf8(concatChunks(stdoutBytes)),
|
||||
stderr: decodeUtf8(concatChunks(stderrBytes)),
|
||||
} satisfies ShellResult;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed<ShellResult>({
|
||||
exitCode: 127,
|
||||
stdout: "",
|
||||
stderr: `\n${error.message}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
const expected = {
|
||||
arch: process.arch,
|
||||
modules: process.versions.modules,
|
||||
nodePtyVersion: require("node-pty/package.json").version,
|
||||
};
|
||||
const marker = path.join(pkgDir, "prebuilds", "linux-" + process.arch, "t3code-wsl-node-pty.json");
|
||||
require("node-pty");
|
||||
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
|
||||
for (const key of Object.keys(expected)) {
|
||||
if (actual[key] !== expected[key]) process.exit(2);
|
||||
}
|
||||
NODE`;
|
||||
|
||||
const TOOLCHAIN_CHECK_SCRIPT = [
|
||||
"for tool in node make g++ python3; do",
|
||||
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
|
||||
"done",
|
||||
"if command -v node >/dev/null 2>&1; then",
|
||||
` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
|
||||
' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
|
||||
"fi",
|
||||
].join("\n");
|
||||
|
||||
const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
|
||||
[
|
||||
"set -e",
|
||||
`cd ${shellQuote(linuxServerDir)}`,
|
||||
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
|
||||
`arch=$(node -p "process.arch")`,
|
||||
`modules=$(node -p "process.versions.modules")`,
|
||||
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
|
||||
`cd "$pkg_dir"`,
|
||||
"npx --yes node-gyp rebuild",
|
||||
`prebuild_dir="prebuilds/linux-$arch"`,
|
||||
`mkdir -p "$prebuild_dir"`,
|
||||
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
|
||||
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
|
||||
`node -e 'require("node-pty")'`,
|
||||
].join("\n");
|
||||
|
||||
export interface ToolchainReport {
|
||||
readonly missingTools: ReadonlyArray<string>;
|
||||
readonly nodeVersion: string | null;
|
||||
}
|
||||
|
||||
export const parseToolchainReport = (stdout: string): ToolchainReport => {
|
||||
const lines = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
const missingTools = lines
|
||||
.filter((line) => line.startsWith("missing:"))
|
||||
.map((line) => line.slice("missing:".length));
|
||||
const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
|
||||
const nodeVersion = nodeVersionLine
|
||||
? nodeVersionLine.slice("nodeVersion:".length).trim() || null
|
||||
: null;
|
||||
return { missingTools, nodeVersion };
|
||||
};
|
||||
|
||||
export const formatMissingToolsReason = (
|
||||
report: ToolchainReport,
|
||||
requiredRange: string | null,
|
||||
): string | null => {
|
||||
const nodeMissing = report.missingTools.includes("node");
|
||||
const nodeOutOfRange =
|
||||
!nodeMissing &&
|
||||
requiredRange !== null &&
|
||||
report.nodeVersion !== null &&
|
||||
!satisfiesSemverRange(report.nodeVersion, requiredRange);
|
||||
const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
|
||||
|
||||
if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const issues: string[] = [];
|
||||
const remediations: string[] = [];
|
||||
|
||||
if (nodeMissing) {
|
||||
issues.push("node");
|
||||
remediations.push(
|
||||
`Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
|
||||
);
|
||||
} else if (nodeOutOfRange) {
|
||||
issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
|
||||
remediations.push(
|
||||
`a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (buildToolsMissing.length > 0) {
|
||||
issues.push(...buildToolsMissing);
|
||||
remediations.push(
|
||||
"the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
|
||||
);
|
||||
}
|
||||
|
||||
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
|
||||
};
|
||||
|
||||
const ensureNodePtyImpl = (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
windowsToWslPath: (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
) => Effect.Effect<Option.Option<string>>,
|
||||
options: EnsureWslNodePtyOptions = {},
|
||||
): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.gen(function* () {
|
||||
const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
|
||||
if (Option.isNone(linuxRepoRootOption)) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: `wslpath conversion failed for ${windowsRepoRoot}`,
|
||||
} as const;
|
||||
}
|
||||
const linuxRepoRoot = linuxRepoRootOption.value;
|
||||
// node-pty lives in the apps/server workspace's node_modules; resolve from
|
||||
// there rather than the monorepo root, where Bun's hoist layout omits it.
|
||||
const linuxServerDir = `${linuxRepoRoot}/apps/server`;
|
||||
|
||||
const probe = yield* runWslShell(distro, NODE_PTY_PROBE_SCRIPT(linuxServerDir), PROBE_TIMEOUT);
|
||||
if (probe.exitCode === 0) return { ok: true } as const;
|
||||
|
||||
// Run the toolchain check before the allowBuild branch so a missing
|
||||
// node binary (or an out-of-range version, or missing build tools)
|
||||
// surfaces as a specific, actionable message in both dev and packaged
|
||||
// builds. Without this, packaged users with no node in their WSL distro
|
||||
// saw a generic "node-pty is not prepared" error pointing at a script
|
||||
// that itself would have failed for the same reason.
|
||||
const toolchainCheck = yield* runWslShell(distro, TOOLCHAIN_CHECK_SCRIPT, TOOLCHAIN_TIMEOUT);
|
||||
const report = parseToolchainReport(toolchainCheck.stdout);
|
||||
const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
|
||||
if (missingReason !== null) {
|
||||
return { ok: false, reason: missingReason } as const;
|
||||
}
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
"node-pty is not prepared for this WSL Node runtime. Run `bun run prepare:wsl` from this checkout, then restart the desktop app.",
|
||||
} as const;
|
||||
}
|
||||
|
||||
const build = yield* runWslShell(distro, NODE_PTY_BUILD_SCRIPT(linuxServerDir), BUILD_TIMEOUT);
|
||||
if (build.exitCode === 0) return { ok: true } as const;
|
||||
const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
|
||||
return {
|
||||
ok: false,
|
||||
reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
|
||||
} as const;
|
||||
});
|
||||
|
||||
const listDistrosImpl: Effect.Effect<
|
||||
readonly WslDistro[],
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return [] as readonly WslDistro[];
|
||||
}
|
||||
return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(LIST_TIMEOUT),
|
||||
Effect.map(Option.getOrElse((): readonly WslDistro[] => [])),
|
||||
Effect.catch(() => Effect.succeed<readonly WslDistro[]>([])),
|
||||
);
|
||||
|
||||
const preWarmImpl = (
|
||||
distro: string | null,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
});
|
||||
const handle = yield* spawner.spawn(command);
|
||||
yield* handle.exitCode;
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(PRE_WARM_TIMEOUT),
|
||||
Effect.asVoid,
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
|
||||
const windowsToWslPathImpl = (
|
||||
distro: string | null,
|
||||
windowsPath: string,
|
||||
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
// wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
|
||||
const normalized = windowsPath.replaceAll("\\", "/");
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(
|
||||
"wsl.exe",
|
||||
[...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "ignore",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: PROCESS_TERMINATE_GRACE,
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
|
||||
const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
|
||||
return converted.length > 0 ? Option.some(converted) : Option.none<string>();
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeoutOption(WSLPATH_TIMEOUT),
|
||||
Effect.map(Option.flatten),
|
||||
Effect.catch(() => Effect.succeed(Option.none<string>())),
|
||||
);
|
||||
};
|
||||
|
||||
const makeIsAvailable = (
|
||||
platform: NodeJS.Platform,
|
||||
windir: string,
|
||||
): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
if (platform !== "win32") return false;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const wslExePath = path.join(windir, "System32", "wsl.exe");
|
||||
return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
|
||||
});
|
||||
|
||||
export interface DesktopWslEnvironmentTestStub {
|
||||
readonly isAvailable?: boolean;
|
||||
readonly distros?: ReadonlyArray<WslDistro>;
|
||||
readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
|
||||
readonly ensureNodePty?: (
|
||||
distro: string | null,
|
||||
windowsRepoRoot: string,
|
||||
options?: EnsureWslNodePtyOptions,
|
||||
) => EnsureWslNodePtyResult;
|
||||
}
|
||||
|
||||
export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) =>
|
||||
Layer.succeed(
|
||||
DesktopWslEnvironment,
|
||||
DesktopWslEnvironment.of({
|
||||
isAvailable: Effect.succeed(stub.isAvailable ?? false),
|
||||
listDistros: Effect.succeed(stub.distros ?? []),
|
||||
preWarm: () => Effect.void,
|
||||
windowsToWslPath: (distro, windowsPath) =>
|
||||
Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
Effect.succeed(
|
||||
stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
|
||||
ok: false,
|
||||
reason: "ensureNodePty stub not configured",
|
||||
},
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopWslEnvironment,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const windir = process.env.WINDIR ?? "C:\\Windows";
|
||||
|
||||
const provideSpawner = <A, E>(
|
||||
effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
|
||||
): Effect.Effect<A, E> =>
|
||||
effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
|
||||
|
||||
const isAvailable = makeIsAvailable(environment.platform, windir).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, environment.path),
|
||||
Effect.withSpan("desktop.wsl.isAvailable"),
|
||||
);
|
||||
|
||||
const windowsToWslPath = (distro: string | null, windowsPath: string) =>
|
||||
provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
|
||||
Effect.withSpan("desktop.wsl.windowsToWslPath"),
|
||||
);
|
||||
|
||||
return DesktopWslEnvironment.of({
|
||||
isAvailable,
|
||||
listDistros: provideSpawner(listDistrosImpl).pipe(Effect.withSpan("desktop.wsl.listDistros")),
|
||||
preWarm: (distro) =>
|
||||
provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
|
||||
windowsToWslPath,
|
||||
ensureNodePty: (distro, windowsRepoRoot, options) =>
|
||||
provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
|
||||
Effect.withSpan("desktop.wsl.ensureNodePty"),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import {
|
||||
DISTRO_NAME_PATTERN,
|
||||
extractDistroFromUncPath,
|
||||
isValidDistroName,
|
||||
parseWslDistroList,
|
||||
resolveWslHomeUncPath,
|
||||
resolveWslPickFolderDefaultPath,
|
||||
} from "./wslPathParsing.ts";
|
||||
|
||||
function makeUtf16LeBuffer(text: string): Buffer {
|
||||
return Buffer.from("" + text, "utf16le");
|
||||
}
|
||||
|
||||
describe("parseWslDistroList", () => {
|
||||
it("parses standard output with default distro marked", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" Debian Stopped 2",
|
||||
" Ubuntu-22.04 Running 1",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
{ name: "Ubuntu-22.04", isDefault: false, version: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty array for empty buffer", () => {
|
||||
expect(parseWslDistroList(Buffer.alloc(0))).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns empty array for header-only output", () => {
|
||||
const output = makeUtf16LeBuffer(" NAME STATE VERSION\r\n");
|
||||
expect(parseWslDistroList(output)).toEqual([]);
|
||||
});
|
||||
|
||||
it("skips malformed lines", () => {
|
||||
const output = makeUtf16LeBuffer(
|
||||
[
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
" bad line",
|
||||
"",
|
||||
" Debian Stopped 2",
|
||||
].join("\r\n"),
|
||||
);
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([
|
||||
{ name: "Ubuntu", isDefault: true, version: 2 },
|
||||
{ name: "Debian", isDefault: false, version: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles output without BOM", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Ubuntu Running 2",
|
||||
].join("\r\n");
|
||||
const output = Buffer.from(text, "utf16le");
|
||||
const distros = parseWslDistroList(output);
|
||||
expect(distros).toEqual([{ name: "Ubuntu", isDefault: true, version: 2 }]);
|
||||
});
|
||||
|
||||
it("handles UTF-8 output", () => {
|
||||
const text = [
|
||||
" NAME STATE VERSION",
|
||||
"* Debian Running 2",
|
||||
].join("\r\n");
|
||||
const distros = parseWslDistroList(Buffer.from(text, "utf8"));
|
||||
expect(distros).toEqual([{ name: "Debian", isDefault: true, version: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractDistroFromUncPath", () => {
|
||||
it("extracts the distro from \\\\wsl.localhost UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh")).toBe(
|
||||
"Ubuntu-22.04",
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts the distro from the legacy \\\\wsl$ UNC paths", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl$\\Debian\\home\\josh")).toBe("Debian");
|
||||
});
|
||||
|
||||
it("returns null for non-UNC Windows paths", () => {
|
||||
expect(extractDistroFromUncPath("C:\\Users\\Josh\\project")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the segment is not a valid distro name", () => {
|
||||
expect(extractDistroFromUncPath("\\\\wsl.localhost\\bad name!\\home")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslHomeUncPath", () => {
|
||||
const distros = [
|
||||
{ name: "Debian", isDefault: true, version: 2 as const },
|
||||
{ name: "Ubuntu", isDefault: false, version: 2 as const },
|
||||
];
|
||||
|
||||
it("uses the configured distro when one is selected", () => {
|
||||
expect(resolveWslHomeUncPath({ enabled: true, distro: "Ubuntu" }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Ubuntu\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the actual default distro when config uses the WSL default", () => {
|
||||
expect(resolveWslHomeUncPath({ enabled: true, distro: null }, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the default path when no default distro is known", () => {
|
||||
expect(resolveWslHomeUncPath({ enabled: true, distro: null }, [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWslPickFolderDefaultPath", () => {
|
||||
const config = { enabled: true, distro: null };
|
||||
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
|
||||
|
||||
it("uses WSL home when no initial path is provided", () => {
|
||||
expect(resolveWslPickFolderDefaultPath(undefined, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps Linux initial paths to WSL UNC paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath({ initialPath: "/home/josh/project" }, config, distros),
|
||||
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
|
||||
});
|
||||
|
||||
it("maps tilde initial paths under the WSL home UNC path", () => {
|
||||
expect(resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros)).toBe(
|
||||
"\\\\wsl.localhost\\Debian\\home\\project",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves existing UNC initial paths", () => {
|
||||
expect(
|
||||
resolveWslPickFolderDefaultPath(
|
||||
{ initialPath: "\\\\wsl.localhost\\Ubuntu\\home\\josh" },
|
||||
config,
|
||||
distros,
|
||||
),
|
||||
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\josh");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
|
||||
it("accepts common distro names", () => {
|
||||
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
|
||||
expect(isValidDistroName(name)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names with trailing whitespace, hyphen, or dot", () => {
|
||||
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects names containing control or shell-meta characters", () => {
|
||||
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
|
||||
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
export interface WslDistro {
|
||||
readonly name: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly version: 1 | 2;
|
||||
}
|
||||
|
||||
export interface WslConfig {
|
||||
readonly enabled: boolean;
|
||||
readonly distro: string | null;
|
||||
}
|
||||
|
||||
export const DEFAULT_WSL_CONFIG: WslConfig = { enabled: false, distro: null };
|
||||
|
||||
// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
|
||||
// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
|
||||
export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
|
||||
|
||||
export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
|
||||
const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
|
||||
const likelyUtf16Le =
|
||||
hasUtf16Bom ||
|
||||
Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
|
||||
(byte, index) => index % 2 === 1 && byte === 0,
|
||||
).length > 10;
|
||||
let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
|
||||
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
||||
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
const distros: WslDistro[] = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
const isDefault = line.startsWith("*");
|
||||
const cleaned = isDefault ? line.slice(1).trim() : line.trim();
|
||||
const fields = cleaned.split(/\s{2,}/);
|
||||
if (fields.length < 3) continue;
|
||||
const name = fields[0]!.trim();
|
||||
const versionNum = parseInt(fields[2]!, 10);
|
||||
if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
|
||||
distros.push({ name, isDefault, version: versionNum as 1 | 2 });
|
||||
}
|
||||
return distros;
|
||||
}
|
||||
|
||||
// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\... so
|
||||
// `wslpath` can be invoked inside the distro that actually owns the path,
|
||||
// rather than whichever distro is configured for the desktop backend.
|
||||
export function extractDistroFromUncPath(windowsPath: string): string | null {
|
||||
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)/i.exec(windowsPath);
|
||||
if (!match) return null;
|
||||
const candidate = match[1]!;
|
||||
return DISTRO_NAME_PATTERN.test(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
export function resolveWslHomeUncPath(
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
): string | null {
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
|
||||
}
|
||||
|
||||
export function resolveWslPickFolderDefaultPath(
|
||||
rawOptions: unknown,
|
||||
config: WslConfig,
|
||||
distros: readonly WslDistro[],
|
||||
): string | null {
|
||||
const homePath = resolveWslHomeUncPath(config, distros);
|
||||
if (typeof rawOptions !== "object" || rawOptions === null) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const { initialPath } = rawOptions as { initialPath?: unknown };
|
||||
if (typeof initialPath !== "string") {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const trimmedPath = initialPath.trim();
|
||||
if (trimmedPath.length === 0) {
|
||||
return homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("\\\\")) {
|
||||
return trimmedPath;
|
||||
}
|
||||
|
||||
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
|
||||
if (!distroName) {
|
||||
return homePath;
|
||||
}
|
||||
|
||||
const toUncPath = (linuxPath: string) =>
|
||||
`\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
|
||||
|
||||
if (trimmedPath === "~") {
|
||||
return homePath;
|
||||
}
|
||||
if (trimmedPath.startsWith("~/")) {
|
||||
return homePath ? `${homePath}\\${trimmedPath.slice(2).replaceAll("/", "\\")}` : null;
|
||||
}
|
||||
if (trimmedPath.startsWith("/")) {
|
||||
return toUncPath(trimmedPath);
|
||||
}
|
||||
|
||||
return homePath;
|
||||
}
|
||||
|
||||
export function isValidDistroName(value: string): boolean {
|
||||
return DISTRO_NAME_PATTERN.test(value);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionSt
|
||||
reconnectMaxAttempts: 8,
|
||||
reconnectPhase: "idle",
|
||||
socketUrl: null,
|
||||
suppressed: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -271,9 +271,16 @@ export function WebSocketConnectionCoordinator() {
|
||||
const uiState = getWsConnectionUiState(status);
|
||||
const previousUiState = previousUiStateRef.current;
|
||||
const previousDisconnectedAt = previousDisconnectedAtRef.current;
|
||||
const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting";
|
||||
const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null;
|
||||
const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted";
|
||||
// Skip ALL connection-state toasts while a known backend swap is in
|
||||
// flight — the caller is rendering its own modal and the transient
|
||||
// reconnect / error states from stopping the old backend would just
|
||||
// compete with it.
|
||||
const shouldShowReconnectToast =
|
||||
!status.suppressed && status.hasConnected && uiState === "reconnecting";
|
||||
const shouldShowOfflineToast =
|
||||
!status.suppressed && uiState === "offline" && status.disconnectedAt !== null;
|
||||
const shouldShowExhaustedToast =
|
||||
!status.suppressed && status.hasConnected && status.reconnectPhase === "exhausted";
|
||||
|
||||
if (
|
||||
toastResetTimerRef.current !== null &&
|
||||
@@ -336,6 +343,7 @@ export function WebSocketConnectionCoordinator() {
|
||||
}
|
||||
|
||||
if (
|
||||
!status.suppressed &&
|
||||
uiState === "connected" &&
|
||||
(previousUiState === "offline" || previousUiState === "reconnecting") &&
|
||||
previousDisconnectedAt !== null
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type DesktopDiscoveredSshHost,
|
||||
type DesktopSshEnvironmentTarget,
|
||||
type DesktopServerExposureState,
|
||||
type DesktopWslState,
|
||||
type EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -54,6 +55,7 @@ import {
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { QRCodeSvg } from "../ui/qr-code";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -79,9 +81,14 @@ import {
|
||||
revokeServerClientSession,
|
||||
revokeServerPairingLink,
|
||||
isLoopbackHostname,
|
||||
reauthenticatePrimaryEnvironment,
|
||||
readPrimaryEnvironmentDescriptor,
|
||||
type ServerClientSessionRecord,
|
||||
type ServerPairingLinkRecord,
|
||||
} from "~/environments/primary";
|
||||
import { onWelcome } from "~/rpc/serverState";
|
||||
import { suppressReconnect } from "~/rpc/wsConnectionState";
|
||||
import { useStore } from "~/store";
|
||||
import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
import {
|
||||
type SavedEnvironmentRecord,
|
||||
@@ -1492,6 +1499,16 @@ export function ConnectionsSettings() {
|
||||
const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
|
||||
const [isDesktopServerExposureDialogOpen, setIsDesktopServerExposureDialogOpen] = useState(false);
|
||||
const [isUpdatingTailscaleServe, setIsUpdatingTailscaleServe] = useState(false);
|
||||
const [desktopWslState, setDesktopWslState] = useState<DesktopWslState | null>(null);
|
||||
const [isUpdatingWslBackend, setIsUpdatingWslBackend] = useState(false);
|
||||
const [desktopWslError, setDesktopWslError] = useState<string | null>(null);
|
||||
const [pendingDesktopWslSelection, setPendingDesktopWslSelection] = useState<{
|
||||
readonly mode: "local" | "wsl";
|
||||
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);
|
||||
@@ -2037,10 +2054,23 @@ export function ConnectionsSettings() {
|
||||
error instanceof Error ? error.message : "Failed to load reachable endpoints.";
|
||||
setDesktopServerExposureError(message);
|
||||
});
|
||||
void desktopBridge
|
||||
.getWslState()
|
||||
.then((state) => {
|
||||
if (cancelled) return;
|
||||
setDesktopWslState(state);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
const message = error instanceof Error ? error.message : "Failed to load WSL state.";
|
||||
setDesktopWslError(message);
|
||||
});
|
||||
} else {
|
||||
setDesktopServerExposureState(null);
|
||||
setDesktopAdvertisedEndpoints([]);
|
||||
setDesktopServerExposureError(null);
|
||||
setDesktopWslState(null);
|
||||
setDesktopWslError(null);
|
||||
}
|
||||
|
||||
return () => {
|
||||
@@ -2328,6 +2358,234 @@ export function ConnectionsSettings() {
|
||||
);
|
||||
})
|
||||
: null;
|
||||
const handleWslSelectionChange = useCallback(
|
||||
(value: string) => {
|
||||
if (!desktopWslState) return;
|
||||
const target =
|
||||
value === "__local__"
|
||||
? { mode: "local" as const, distro: null }
|
||||
: { mode: "wsl" as const, distro: value === "__default__" ? null : value };
|
||||
if (target.mode === desktopWslState.mode && target.distro === desktopWslState.distro) {
|
||||
return;
|
||||
}
|
||||
setPendingDesktopWslSelection(target);
|
||||
},
|
||||
[desktopWslState],
|
||||
);
|
||||
|
||||
const handleConfirmDesktopWslChange = useCallback(async () => {
|
||||
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 (env-id !== previous) before declaring the swap done.
|
||||
let resolveNewWelcome: (() => void) | null = null;
|
||||
const newWelcomePromise = new Promise<void>((resolve) => {
|
||||
resolveNewWelcome = resolve;
|
||||
});
|
||||
const unsubscribeWelcome = onWelcome((payload) => {
|
||||
if (payload.environment.environmentId !== previousPrimaryEnvId) {
|
||||
resolveNewWelcome?.();
|
||||
}
|
||||
});
|
||||
|
||||
// Global ceiling on the whole flow — the IPC waits up to 2 minutes for
|
||||
// the backend to come up (cold WSL boots + node-pty prep can be slow),
|
||||
// the welcome wait is 45s after that, and reauth has its own retry loop.
|
||||
// Cap the total so a hung step can't strand the modal forever.
|
||||
const flowTimeout = new Promise<never>((_, reject) => {
|
||||
window.setTimeout(
|
||||
() => reject(new Error("Backend swap took too long. Check WSL is responsive and try again.")),
|
||||
180_000,
|
||||
);
|
||||
});
|
||||
|
||||
const runSwap = async () => {
|
||||
const updated = await desktopBridge.setWslBackend(target);
|
||||
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();
|
||||
|
||||
// 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);
|
||||
}),
|
||||
]);
|
||||
|
||||
if (previousPrimaryEnvId) {
|
||||
useStore.getState().removeEnvironmentState(previousPrimaryEnvId);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await suppressReconnect(() => 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);
|
||||
} finally {
|
||||
unsubscribeWelcome();
|
||||
setIsUpdatingWslBackend(false);
|
||||
setDesktopWslChangeStage(null);
|
||||
}
|
||||
}, [desktopBridge, pendingDesktopWslSelection]);
|
||||
|
||||
const renderWslRow = () => {
|
||||
if (!desktopWslState || !desktopWslState.available) return null;
|
||||
const currentValue =
|
||||
desktopWslState.mode === "wsl" ? (desktopWslState.distro ?? "__default__") : "__local__";
|
||||
const currentLabel =
|
||||
currentValue === "__local__"
|
||||
? "Local (Windows)"
|
||||
: currentValue === "__default__"
|
||||
? "WSL: default distro"
|
||||
: `WSL: ${currentValue}`;
|
||||
const pendingTargetLabel =
|
||||
pendingDesktopWslSelection?.mode === "wsl"
|
||||
? (pendingDesktopWslSelection.distro ?? "the default WSL distro")
|
||||
: "Windows";
|
||||
const isSwitchingToWsl = pendingDesktopWslSelection?.mode === "wsl";
|
||||
return (
|
||||
<SettingsRow
|
||||
title="Backend runtime"
|
||||
description={
|
||||
desktopWslState.mode === "wsl"
|
||||
? "Backend runs inside the selected WSL distro."
|
||||
: "Backend runs natively on Windows."
|
||||
}
|
||||
status={
|
||||
desktopWslError ? <span className="block text-destructive">{desktopWslError}</span> : null
|
||||
}
|
||||
control={
|
||||
<AlertDialog
|
||||
open={pendingDesktopWslSelection !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (isUpdatingWslBackend) return;
|
||||
if (!open) setPendingDesktopWslSelection(null);
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
value={currentValue}
|
||||
onValueChange={(value) => {
|
||||
if (typeof value !== "string") return;
|
||||
handleWslSelectionChange(value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full sm:w-56"
|
||||
aria-label="Backend runtime"
|
||||
disabled={isUpdatingWslBackend}
|
||||
>
|
||||
<SelectValue>{currentLabel}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="__local__">
|
||||
Local (Windows)
|
||||
</SelectItem>
|
||||
{desktopWslState.distros.length === 0 ? (
|
||||
<SelectItem hideIndicator value="__default__">
|
||||
WSL: default distro
|
||||
</SelectItem>
|
||||
) : (
|
||||
desktopWslState.distros.map((distro) => (
|
||||
<SelectItem hideIndicator key={distro.name} value={distro.name}>
|
||||
WSL: {distro.name}
|
||||
{distro.isDefault ? " (default)" : ""}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{isSwitchingToWsl
|
||||
? desktopWslState.mode === "wsl"
|
||||
? "Switch WSL distro?"
|
||||
: "Switch to WSL backend?"
|
||||
: "Switch to local 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."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose
|
||||
disabled={isUpdatingWslBackend}
|
||||
render={<Button variant="outline" disabled={isUpdatingWslBackend} />}
|
||||
>
|
||||
Cancel
|
||||
</AlertDialogClose>
|
||||
<Button
|
||||
onClick={() => {
|
||||
void handleConfirmDesktopWslChange();
|
||||
}}
|
||||
disabled={pendingDesktopWslSelection === null || isUpdatingWslBackend}
|
||||
>
|
||||
{isUpdatingWslBackend ? (
|
||||
<>
|
||||
<Spinner className="size-3.5" />
|
||||
{desktopWslChangeStage === "syncing"
|
||||
? "Syncing threads…"
|
||||
: desktopWslChangeStage === "reauthenticating"
|
||||
? "Re-establishing session…"
|
||||
: "Restarting backend…"}
|
||||
</>
|
||||
) : isSwitchingToWsl ? (
|
||||
"Restart in WSL"
|
||||
) : (
|
||||
"Restart on Windows"
|
||||
)}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const renderTailscaleRow = () => (
|
||||
<SettingsRow
|
||||
title="Tailscale HTTPS"
|
||||
@@ -2463,6 +2721,7 @@ export function ConnectionsSettings() {
|
||||
{renderNetworkAccessRow()}
|
||||
{renderEndpointRows("endpoint-rail")}
|
||||
{renderTailscaleRow()}
|
||||
{renderWslRow()}
|
||||
</>
|
||||
) : (
|
||||
renderDisabledNetworkAccessRow()
|
||||
|
||||
@@ -444,6 +444,18 @@ const createDesktopBridgeStub = (overrides?: {
|
||||
tailscaleServePort: input.port ?? 443,
|
||||
})),
|
||||
getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []),
|
||||
getWslState: vi.fn().mockResolvedValue({
|
||||
mode: "local" as const,
|
||||
distro: null,
|
||||
available: false,
|
||||
distros: [],
|
||||
}),
|
||||
setWslBackend: vi.fn().mockResolvedValue({
|
||||
mode: "local" as const,
|
||||
distro: null,
|
||||
available: false,
|
||||
distros: [],
|
||||
}),
|
||||
pickFolder: vi.fn().mockResolvedValue(null),
|
||||
confirm: vi.fn().mockResolvedValue(false),
|
||||
setTheme: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -402,6 +402,16 @@ export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGat
|
||||
});
|
||||
}
|
||||
|
||||
// Used by the WSL backend swap: invalidate the cached authenticated state
|
||||
// (the new backend signs sessions with a different key) and re-bootstrap
|
||||
// against the desktop bootstrap credential so the next WS reconnect doesn't
|
||||
// hit 401 and start a reauth loop in the renderer.
|
||||
export async function reauthenticatePrimaryEnvironment(): Promise<ServerAuthGateState> {
|
||||
resolvedAuthenticatedGateState = null;
|
||||
bootstrapPromise = null;
|
||||
return resolveInitialServerAuthGateState();
|
||||
}
|
||||
|
||||
export function __resetServerAuthBootstrapForTests() {
|
||||
bootstrapPromise = null;
|
||||
resolvedAuthenticatedGateState = null;
|
||||
|
||||
@@ -109,6 +109,18 @@ export function resolveInitialPrimaryEnvironmentDescriptor(): Promise<ExecutionE
|
||||
});
|
||||
}
|
||||
|
||||
// Used by the WSL backend swap: bypass the cached descriptor and re-fetch
|
||||
// against the (potentially new) backend at the same URL.
|
||||
export function refreshPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironmentDescriptor> {
|
||||
const nextPromise = fetchPrimaryEnvironmentDescriptor();
|
||||
primaryEnvironmentDescriptorPromise = nextPromise;
|
||||
return nextPromise.finally(() => {
|
||||
if (primaryEnvironmentDescriptorPromise === nextPromise) {
|
||||
primaryEnvironmentDescriptorPromise = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function __resetPrimaryEnvironmentBootstrapForTests(): void {
|
||||
primaryEnvironmentDescriptorPromise = null;
|
||||
usePrimaryEnvironmentBootstrapStore.getState().reset();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export {
|
||||
getPrimaryKnownEnvironment,
|
||||
readPrimaryEnvironmentDescriptor,
|
||||
refreshPrimaryEnvironmentDescriptor,
|
||||
resetPrimaryEnvironmentDescriptorForTests,
|
||||
resolveInitialPrimaryEnvironmentDescriptor,
|
||||
usePrimaryEnvironmentId,
|
||||
@@ -20,6 +21,7 @@ export {
|
||||
listServerClientSessions,
|
||||
listServerPairingLinks,
|
||||
peekPairingTokenFromUrl,
|
||||
reauthenticatePrimaryEnvironment,
|
||||
resolveInitialServerAuthGateState,
|
||||
revokeOtherServerClientSessions,
|
||||
revokeServerClientSession,
|
||||
|
||||
@@ -220,6 +220,18 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
|
||||
tailscaleServePort: input.port ?? 443,
|
||||
}),
|
||||
getAdvertisedEndpoints: async () => [],
|
||||
getWslState: async () => ({
|
||||
mode: "local",
|
||||
distro: null,
|
||||
available: false,
|
||||
distros: [],
|
||||
}),
|
||||
setWslBackend: async () => ({
|
||||
mode: "local",
|
||||
distro: null,
|
||||
available: false,
|
||||
distros: [],
|
||||
}),
|
||||
pickFolder: async () => null,
|
||||
confirm: async () => true,
|
||||
setTheme: async () => undefined,
|
||||
|
||||
@@ -29,6 +29,10 @@ export interface WsConnectionStatus {
|
||||
readonly reconnectMaxAttempts: number;
|
||||
readonly reconnectPhase: WsReconnectPhase;
|
||||
readonly socketUrl: string | null;
|
||||
// True while an intentional backend swap (e.g. WSL mode change) is in
|
||||
// progress and the connection surface should stay silent rather than
|
||||
// surfacing the transient reconnect/error states the swap causes.
|
||||
readonly suppressed: boolean;
|
||||
}
|
||||
|
||||
const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
|
||||
@@ -48,6 +52,7 @@ const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
|
||||
reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "idle",
|
||||
socketUrl: null,
|
||||
suppressed: false,
|
||||
});
|
||||
|
||||
export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
|
||||
@@ -183,6 +188,34 @@ export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
|
||||
}));
|
||||
}
|
||||
|
||||
export function setWsConnectionSuppressed(suppressed: boolean): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
suppressed,
|
||||
}));
|
||||
}
|
||||
|
||||
let suppressDepth = 0;
|
||||
|
||||
// Run `operation` with the WS connection surface silenced. Reentrant — only
|
||||
// the outermost caller resets the flag, so nested helpers (descriptor
|
||||
// refresh, reauth) won't prematurely re-arm reconnect toasts in the middle
|
||||
// of a swap.
|
||||
export async function suppressReconnect<T>(operation: () => Promise<T>): Promise<T> {
|
||||
suppressDepth += 1;
|
||||
if (suppressDepth === 1) {
|
||||
setWsConnectionSuppressed(true);
|
||||
}
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
suppressDepth -= 1;
|
||||
if (suppressDepth === 0) {
|
||||
setWsConnectionSuppressed(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function resetWsReconnectBackoff(): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
|
||||
@@ -6,7 +6,10 @@ export const DesktopBackendBootstrap = Schema.Struct({
|
||||
mode: Schema.Literal("desktop"),
|
||||
noBrowser: Schema.Boolean,
|
||||
port: PortSchema,
|
||||
t3Home: Schema.String,
|
||||
// Omitted when the desktop launches the backend inside WSL, since the
|
||||
// Windows-side baseDir maps to /mnt/c/... and the Linux side should use its
|
||||
// own home directory instead.
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
host: Schema.String,
|
||||
desktopBootstrapToken: Schema.String,
|
||||
tailscaleServeEnabled: Schema.Boolean,
|
||||
|
||||
@@ -369,6 +369,36 @@ 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;
|
||||
version: 1 | 2;
|
||||
}
|
||||
|
||||
export const DesktopWslDistroSchema = Schema.Struct({
|
||||
name: Schema.String,
|
||||
isDefault: Schema.Boolean,
|
||||
version: Schema.Literals([1, 2]),
|
||||
});
|
||||
|
||||
export interface DesktopWslState {
|
||||
mode: DesktopWslMode;
|
||||
distro: string | null;
|
||||
available: boolean;
|
||||
distros: readonly DesktopWslDistro[];
|
||||
}
|
||||
|
||||
export const DesktopWslStateSchema = Schema.Struct({
|
||||
mode: DesktopWslModeSchema,
|
||||
distro: Schema.NullOr(Schema.String),
|
||||
available: Schema.Boolean,
|
||||
distros: Schema.Array(DesktopWslDistroSchema),
|
||||
});
|
||||
|
||||
export interface DesktopBridge {
|
||||
getAppBranding: () => DesktopAppBranding | null;
|
||||
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
|
||||
@@ -406,6 +436,11 @@ export interface DesktopBridge {
|
||||
readonly port?: number;
|
||||
}) => Promise<DesktopServerExposureState>;
|
||||
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;
|
||||
getWslState: () => Promise<DesktopWslState>;
|
||||
setWslBackend: (input: {
|
||||
mode: DesktopWslMode;
|
||||
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