Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Desktop: parallel WSL + Windows backends with mode picker (#2751)

Jgratton24a9b1190a1127
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 168c000c3..12ac0370c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -252,10 +252,64 @@ jobs:
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
+ # node-pty publishes no Linux prebuilt and the WSL backend runs under the
+ # distro's own (Linux) Node, which can't load the Windows/Electron binary. We
+ # build the Linux pty.node here, on Linux, and hand it to the Windows packaging
+ # job — the Windows artifact then ships a ready WSL backend binary with no
+ # cross-compiling and no first-launch compiler/node-gyp/network on the user's
+ # machine. node-pty is N-API, so one binary works across all WSL Node versions.
+ build_wsl_node_pty:
+ name: Build WSL node-pty (linux-x64)
+ needs: [preflight]
+ if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
+ runs-on: blacksmith-8vcpu-ubuntu-2404
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+ with:
+ ref: ${{ needs.preflight.outputs.ref }}
+ fetch-depth: 0
+
+ - name: Setup Vite+
+ uses: voidzero-dev/setup-vp@v1
+ with:
+ node-version-file: package.json
+ cache: true
+ run-install: true
+
+ - name: Build node-pty linux-x64 prebuild
+ shell: bash
+ run: |
+ set -euo pipefail
+ # Resolve node-pty from apps/server (where it's a dependency) and build
+ # its native binary from source for Linux. node-addon-api resolves from
+ # node-pty's own dependency tree, so node-gyp has everything it needs.
+ pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
+ pty_dir="$(dirname "$pty_pkg")"
+ ( cd "$pty_dir" && npx --yes node-gyp rebuild )
+ mkdir -p wsl-prebuild
+ cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
+ file wsl-prebuild/pty.node
+
+ - name: Upload node-pty linux-x64 prebuild
+ uses: actions/upload-artifact@v7
+ with:
+ name: wsl-node-pty-x64
+ path: wsl-prebuild/pty.node
+ if-no-files-found: error
+
build:
name: Build ${{ matrix.label }}
- needs: [preflight, relay_public_config]
- if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
+ # build_wsl_node_pty stays in `needs` so it runs first and its artifact is
+ # available to download, but only the Windows matrix entry consumes it. We
+ # therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
+ # build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
+ # builds. `!cancelled()` (not `!failure()`) lets the job run even when
+ # build_wsl_node_pty failed; the Windows-only download step below then fails
+ # that single platform if the prebuild is missing.
+ needs: [preflight, relay_public_config, build_wsl_node_pty]
+ if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
@@ -323,6 +377,13 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
+ - name: Download WSL node-pty prebuild
+ if: matrix.platform == 'win'
+ uses: actions/download-artifact@v7
+ with:
+ name: wsl-node-pty-x64
+ path: wsl-prebuild
+
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
@@ -476,6 +537,10 @@ jobs:
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
+ # Bundle the Linux node-pty binary built by the build_wsl_node_pty job
+ # so the packaged WSL backend ships a ready binary (no first-launch
+ # compile). Required for a working WSL backend on Windows.
+ args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts
index 214fd383e..fd86c5f05 100644
--- a/apps/desktop/src/app/DesktopApp.ts
+++ b/apps/desktop/src/app/DesktopApp.ts
@@ -13,7 +13,8 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
-import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
+import * as DesktopWindow from "../window/DesktopWindow.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
@@ -23,6 +24,7 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
+import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
@@ -135,11 +137,14 @@ const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
const bootstrap = Effect.gen(function* () {
- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const primaryBackend = yield* pool.primary;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* logBootstrapInfo("bootstrap start");
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
@@ -193,8 +198,20 @@ const bootstrap = Effect.gen(function* () {
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
- yield* backendManager.start;
+ // In wsl-only mode the renderer is served by the WSL backend, which can be
+ // slow to cold-boot — show a "Connecting to WSL" splash immediately so the
+ // app feels responsive instead of presenting no window until WSL is ready.
+ // (Dual mode opens fast off the Windows primary, so no splash there.)
+ if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
+ yield* desktopWindow.showConnectingSplash;
+ }
+ yield* primaryBackend.start;
yield* logBootstrapInfo("bootstrap backend start requested");
+ // Bring up the WSL backend if the user previously enabled it. The
+ // primary is already starting; reconcile fires off the WSL register
+ // in parallel rather than blocking primary readiness on a possibly
+ // slow first wsl.exe spawn.
+ yield* Effect.forkScoped(wslBackend.reconcile);
}
}).pipe(Effect.withSpan("desktop.bootstrap"));
@@ -241,10 +258,20 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
- backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
+ Effect.gen(function* () {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ // Stop every backend in the pool, not just the primary. The
+ // electronApp.quit() path can race ahead of the layer-scope
+ // cascade, so leaving the WSL instance for its parent scope
+ // finalizer means it gets hard-killed by the OS instead of
+ // receiving SIGTERM + grace. Stops run concurrently.
+ const instances = yield* pool.list;
+ yield* Effect.forEach(instances, (instance) => instance.stop(), {
+ concurrency: "unbounded",
+ });
+ }).pipe(Effect.ensuring(shutdown.markComplete)),
);
yield* startup;
diff --git a/apps/desktop/src/app/DesktopBackendOutputLog.test.ts b/apps/desktop/src/app/DesktopBackendOutputLog.test.ts
deleted file mode 100644
index 18bba9486..000000000
--- a/apps/desktop/src/app/DesktopBackendOutputLog.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { assert, describe, it } from "@effect/vitest";
-import * as Effect from "effect/Effect";
-import * as FileSystem from "effect/FileSystem";
-import * as Layer from "effect/Layer";
-import * as Logger from "effect/Logger";
-import * as Path from "effect/Path";
-import * as PlatformError from "effect/PlatformError";
-
-import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
-import * as DesktopConfig from "./DesktopConfig.ts";
-import * as DesktopEnvironment from "./DesktopEnvironment.ts";
-
-const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
-
-const environmentLayer = DesktopEnvironment.layer({
- dirname: "/repo/apps/desktop/dist-electron",
- homeDirectory: "/Users/alice",
- platform: "darwin",
- processArch: "arm64",
- appVersion: "1.2.3",
- appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
- isPackaged: true,
- resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
- runningUnderArm64Translation: false,
-}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
-
-const withOutputLog = <A, E, R>(
- effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
- fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
- messages: Array<ReadonlyArray<unknown>>,
-) => {
- const logger = Logger.make(({ message }) => {
- messages.push(Array.isArray(message) ? message : [message]);
- });
- const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
- Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
- Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
- );
- return effect.pipe(Effect.provide(outputLogLayer));
-};
-
-const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
- messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
- ?.error;
-
-describe("DesktopBackendOutputLog", () => {
- it.effect("logs setup failures with the log path and exact cause", () => {
- const messages: Array<ReadonlyArray<unknown>> = [];
- const cause = PlatformError.systemError({
- _tag: "PermissionDenied",
- module: "FileSystem",
- method: "makeDirectory",
- pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
- description: "private setup diagnostic",
- });
- const fileSystemLayer = FileSystem.layerNoop({
- makeDirectory: () => Effect.fail(cause),
- });
-
- return withOutputLog(
- Effect.gen(function* () {
- const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
- yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
-
- const error = loggedError(messages);
- assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
- assert.equal(error.logFilePath, LOG_FILE_PATH);
- assert.strictEqual(error.cause, cause);
- assert.equal(
- error.message,
- `Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
- );
- assert.notInclude(error.message, "private setup diagnostic");
- }),
- fileSystemLayer,
- messages,
- );
- });
-
- it.effect("logs record write failures with the operation and exact cause", () => {
- const messages: Array<ReadonlyArray<unknown>> = [];
- const missingCause = PlatformError.systemError({
- _tag: "NotFound",
- module: "FileSystem",
- method: "stat",
- pathOrDescriptor: LOG_FILE_PATH,
- });
- const writeCause = PlatformError.systemError({
- _tag: "PermissionDenied",
- module: "FileSystem",
- method: "writeFile",
- pathOrDescriptor: LOG_FILE_PATH,
- description: "private write diagnostic",
- });
- const fileSystemLayer = FileSystem.layerNoop({
- makeDirectory: () => Effect.void,
- stat: () => Effect.fail(missingCause),
- readDirectory: () => Effect.succeed([]),
- writeFile: () => Effect.fail(writeCause),
- });
-
- return withOutputLog(
- Effect.gen(function* () {
- const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
- yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
-
- const error = loggedError(messages);
- assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
- assert.equal(error.operation, "write-record");
- assert.equal(error.logFilePath, LOG_FILE_PATH);
- assert.strictEqual(error.cause, writeCause);
- assert.equal(
- error.message,
- `Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
- );
- assert.notInclude(error.message, "private write diagnostic");
- }),
- fileSystemLayer,
- messages,
- );
- });
-});
diff --git a/apps/desktop/src/app/DesktopBackendOutputLog.ts b/apps/desktop/src/app/DesktopBackendOutputLog.ts
deleted file mode 100644
index cad83229d..000000000
--- a/apps/desktop/src/app/DesktopBackendOutputLog.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-import * as Context from "effect/Context";
-import * as DateTime from "effect/DateTime";
-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 PlatformError from "effect/PlatformError";
-import * as References from "effect/References";
-import * as Ref from "effect/Ref";
-import * as Schema from "effect/Schema";
-import * as Semaphore from "effect/Semaphore";
-
-import * as DesktopEnvironment from "./DesktopEnvironment.ts";
-
-export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
-export const DESKTOP_LOG_FILE_MAX_FILES = 10;
-
-const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
-
-interface RotatingLogFileWriter {
- readonly filePath: string;
- readonly writeBytes: (
- chunk: Uint8Array,
- ) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
- readonly writeText: (
- chunk: string,
- ) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
-}
-
-class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
- "DesktopLogFileWriterConfigurationError",
- {
- option: Schema.Literals(["maxBytes", "maxFiles"]),
- value: Schema.Number,
- },
-) {
- override get message(): string {
- return `${this.option} must be >= 1 (received ${this.value})`;
- }
-}
-
-class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
- "DesktopLogFileWriterRecoveryError",
- {
- logFilePath: Schema.String,
- cause: Schema.Defect(),
- recoveryCause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
- }
-}
-
-export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
- "DesktopBackendOutputLogSetupError",
- {
- logFilePath: Schema.String,
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
- }
-}
-
-export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
- "DesktopBackendOutputLogWriteError",
- {
- operation: Schema.Literals(["encode-record", "write-record"]),
- logFilePath: Schema.String,
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
- }
-}
-
-export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
- "DesktopBackendConsoleWriteError",
- {
- streamName: Schema.Literals(["stdout", "stderr"]),
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to mirror desktop backend output to ${this.streamName}.`;
- }
-}
-
-export class DesktopBackendOutputLog extends Context.Service<
- DesktopBackendOutputLog,
- {
- readonly writeSessionBoundary: (input: {
- readonly phase: "START" | "END";
- readonly details: string;
- }) => Effect.Effect<void>;
- readonly writeOutputChunk: (
- streamName: "stdout" | "stderr",
- chunk: Uint8Array,
- ) => Effect.Effect<void>;
- }
->()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
-
-type DesktopLogFileWriterError =
- | DesktopLogFileWriterConfigurationError
- | PlatformError.PlatformError;
-
-const DesktopBackendChildLogRecord = Schema.Struct({
- message: Schema.String,
- level: Schema.Literals(["INFO", "ERROR"]),
- timestamp: Schema.String,
- annotations: Schema.Record(Schema.String, Schema.Unknown),
- spans: Schema.Record(Schema.String, Schema.Unknown),
- fiberId: Schema.String,
-});
-
-const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
- Schema.fromJsonString(DesktopBackendChildLogRecord),
-);
-
-const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
- writeSessionBoundary: () => Effect.void,
- writeOutputChunk: () => Effect.void,
-};
-
-const textEncoder = new TextEncoder();
-const textDecoder = new TextDecoder();
-
-const currentDesktopRunId = Effect.gen(function* () {
- const annotations = yield* References.CurrentLogAnnotations;
- const runId = annotations.runId;
- return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
-});
-
-const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
-
-const refreshFileSize = (
- fileSystem: FileSystem.FileSystem,
- filePath: string,
-): Effect.Effect<number, PlatformError.PlatformError> =>
- fileSystem.stat(filePath).pipe(
- Effect.map((stat) => Number(stat.size)),
- Effect.catchTags({
- PlatformError: (error) =>
- error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
- }),
- );
-
-const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
- readonly filePath: string;
- readonly maxBytes?: number;
- readonly maxFiles?: number;
-}): Effect.fn.Return<
- RotatingLogFileWriter,
- DesktopLogFileWriterError,
- FileSystem.FileSystem | Path.Path
-> {
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
- const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
- const directory = path.dirname(input.filePath);
- const baseName = path.basename(input.filePath);
-
- if (maxBytes < 1) {
- return yield* new DesktopLogFileWriterConfigurationError({
- option: "maxBytes",
- value: maxBytes,
- });
- }
- if (maxFiles < 1) {
- return yield* new DesktopLogFileWriterConfigurationError({
- option: "maxFiles",
- value: maxFiles,
- });
- }
-
- yield* fileSystem.makeDirectory(directory, { recursive: true });
-
- const withSuffix = (index: number) => `${input.filePath}.${index}`;
- const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
- const mutex = yield* Semaphore.make(1);
-
- const recoverCurrentSize = (
- cause: PlatformError.PlatformError,
- ): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
- refreshFileSize(fileSystem, input.filePath).pipe(
- Effect.matchEffect({
- onFailure: (recoveryCause) =>
- Effect.fail(
- new DesktopLogFileWriterRecoveryError({
- logFilePath: input.filePath,
- cause,
- recoveryCause,
- }),
- ),
- onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
- }),
- );
-
- const pruneOverflowBackups = Effect.gen(function* () {
- const entries = yield* fileSystem.readDirectory(directory);
- for (const entry of entries) {
- if (!entry.startsWith(`${baseName}.`)) continue;
- const suffix = Number(entry.slice(baseName.length + 1));
- if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
- yield* fileSystem.remove(path.join(directory, entry), { force: true });
- }
- });
-
- const rotate = Effect.gen(function* () {
- yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
- for (let index = maxFiles - 1; index >= 1; index -= 1) {
- const source = withSuffix(index);
- const sourceExists = yield* fileSystem.exists(source);
- if (sourceExists) {
- yield* fileSystem.rename(source, withSuffix(index + 1));
- }
- }
- const currentExists = yield* fileSystem.exists(input.filePath);
- if (currentExists) {
- yield* fileSystem.rename(input.filePath, withSuffix(1));
- }
- yield* Ref.set(currentSize, 0);
- });
-
- const writeBytes = (
- chunk: Uint8Array,
- ): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
- if (chunk.byteLength === 0) return Effect.void;
-
- return mutex.withPermits(1)(
- Effect.gen(function* () {
- const beforeSize = yield* Ref.get(currentSize);
- if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
- yield* rotate;
- }
-
- yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
- const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
- yield* Ref.set(currentSize, afterSize);
-
- if (afterSize > maxBytes) {
- yield* rotate;
- }
- }).pipe(
- Effect.catchTags({
- PlatformError: recoverCurrentSize,
- }),
- ),
- );
- };
-
- yield* pruneOverflowBackups;
-
- return {
- filePath: input.filePath,
- writeBytes,
- writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
- } satisfies RotatingLogFileWriter;
-});
-
-const writeDevelopmentConsoleOutput = (
- streamName: "stdout" | "stderr",
- chunk: Uint8Array,
-): Effect.Effect<void> =>
- Effect.try({
- try: () => {
- const output = streamName === "stderr" ? process.stderr : process.stdout;
- output.write(chunk);
- },
- catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
- }).pipe(
- Effect.catchTags({
- DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
- }),
- );
-
-const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
- function* (
- logFile: RotatingLogFileWriter,
- input: {
- readonly message: string;
- readonly level: "INFO" | "ERROR";
- readonly annotations: Record<string, unknown>;
- },
- ): Effect.fn.Return<void> {
- return yield* Effect.gen(function* () {
- const timestamp = DateTime.formatIso(yield* DateTime.now);
- const encoded = yield* encodeDesktopBackendChildLogRecord({
- message: input.message,
- level: input.level,
- timestamp,
- annotations: input.annotations,
- spans: {},
- fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
- }).pipe(
- Effect.mapError(
- (cause) =>
- new DesktopBackendOutputLogWriteError({
- operation: "encode-record",
- logFilePath: logFile.filePath,
- cause,
- }),
- ),
- );
- yield* logFile.writeText(`${encoded}\n`).pipe(
- Effect.mapError(
- (cause) =>
- new DesktopBackendOutputLogWriteError({
- operation: "write-record",
- logFilePath: logFile.filePath,
- cause,
- }),
- ),
- );
- }).pipe(
- Effect.catchTags({
- DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
- }),
- );
- },
-);
-
-export const make = Effect.gen(function* () {
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
- const logFilePath = environment.path.join(environment.logDir, "server-child.log");
- const writer = yield* makeRotatingLogFileWriter({
- filePath: logFilePath,
- }).pipe(
- Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
- Effect.map(Option.some),
- Effect.catchTags({
- DesktopBackendOutputLogSetupError: (error) =>
- Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
- }),
- );
-
- const service = Option.match(writer, {
- onNone: () => DesktopBackendOutputLogNoop,
- onSome: (logFile) =>
- ({
- writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
- function* ({ phase, details }) {
- const runId = yield* currentDesktopRunId;
- yield* writeBackendChildLogRecord(logFile, {
- message: `backend child process session ${phase.toLowerCase()}`,
- level: "INFO",
- annotations: {
- component: "desktop-backend-child",
- runId,
- phase,
- details: sanitizeLogValue(details),
- },
- });
- },
- ),
- writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
- function* (streamName, chunk) {
- if (environment.isDevelopment) {
- yield* writeDevelopmentConsoleOutput(streamName, chunk);
- }
- const runId = yield* currentDesktopRunId;
- yield* writeBackendChildLogRecord(logFile, {
- message: "backend child process output",
- level: streamName === "stderr" ? "ERROR" : "INFO",
- annotations: {
- component: "desktop-backend-child",
- runId,
- stream: streamName,
- text: textDecoder.decode(chunk),
- },
- });
- },
- ),
- }) satisfies DesktopBackendOutputLog["Service"],
- });
-
- return DesktopBackendOutputLog.of(service);
-});
-
-export const layer = Layer.effect(DesktopBackendOutputLog, make);
diff --git a/apps/desktop/src/app/DesktopObservability.test.ts b/apps/desktop/src/app/DesktopObservability.test.ts
index a78de48d5..9438175f6 100644
--- a/apps/desktop/src/app/DesktopObservability.test.ts
+++ b/apps/desktop/src/app/DesktopObservability.test.ts
@@ -125,7 +125,8 @@ describe("DesktopObservability", () => {
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
- const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
+ const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
+ const outputLog = yield* factory.forInstance("primary");
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
@@ -145,6 +146,7 @@ describe("DesktopObservability", () => {
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
+ assert.equal(boundary.annotations.instanceId, "primary");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
@@ -152,6 +154,7 @@ describe("DesktopObservability", () => {
assert.equal(output.level, "INFO");
assert.equal(output.annotations.component, "desktop-backend-child");
assert.equal(output.annotations.runId, "test-run");
+ assert.equal(output.annotations.instanceId, "primary");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
}).pipe(
diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts
index 21dd27ba2..42451e45d 100644
--- a/apps/desktop/src/app/DesktopObservability.ts
+++ b/apps/desktop/src/app/DesktopObservability.ts
@@ -1,20 +1,65 @@
+import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
+import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
+import * as Ref from "effect/Ref";
+import * as Schema from "effect/Schema";
+import * as Scope from "effect/Scope";
+import * as Semaphore from "effect/Semaphore";
+import * as SynchronizedRef from "effect/SynchronizedRef";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
-import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
+const DESKTOP_LOG_FILE_MAX_FILES = 10;
+const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
-export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
+export interface RotatingLogFileWriter {
+ readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
+ readonly writeText: (chunk: string) => Effect.Effect<void>;
+}
+
+export interface DesktopBackendOutputLogShape {
+ readonly writeSessionBoundary: (input: {
+ readonly phase: "START" | "END";
+ readonly details: string;
+ }) => Effect.Effect<void>;
+ readonly writeOutputChunk: (
+ streamName: "stdout" | "stderr",
+ chunk: Uint8Array,
+ ) => Effect.Effect<void>;
+}
+
+// Factory for per-instance backend output logs. `forInstance(id)` returns
+// a writer that targets a distinct rotating log file — the primary
+// instance keeps `server-child.log` so the historical path stays stable
+// for ops; other instances get `server-child-<sanitized-id>.log`.
+//
+// Writers are cached per id within a single factory instance so repeated
+// `forInstance` calls (e.g. during a backend restart that re-resolves
+// services) reuse the same rotating writer rather than racing each other
+// on the same file.
+export class DesktopBackendOutputLogFactory extends Context.Service<
+ DesktopBackendOutputLogFactory,
+ {
+ readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
+ }
+>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
+
+const textEncoder = new TextEncoder();
+const textDecoder = new TextDecoder();
export type DesktopLogAnnotations = Record<string, unknown>;
@@ -50,7 +95,166 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
-const readPersistedOtlpTracesUrl = Effect.gen(function* () {
+class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
+ "DesktopLogFileWriterConfigurationError",
+ {
+ option: Schema.Literals(["maxBytes", "maxFiles"]),
+ value: Schema.Number,
+ },
+) {
+ override get message() {
+ return `${this.option} must be >= 1 (received ${this.value})`;
+ }
+}
+
+type DesktopLogFileWriterError =
+ | DesktopLogFileWriterConfigurationError
+ | PlatformError.PlatformError;
+
+const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
+
+const DesktopBackendChildLogRecord = Schema.Struct({
+ message: Schema.String,
+ level: Schema.Literals(["INFO", "ERROR"]),
+ timestamp: Schema.String,
+ annotations: Schema.Record(Schema.String, Schema.Unknown),
+ spans: Schema.Record(Schema.String, Schema.Unknown),
+ fiberId: Schema.String,
+});
+
+const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
+ Schema.fromJsonString(DesktopBackendChildLogRecord),
+);
+
+const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
+ writeSessionBoundary: () => Effect.void,
+ writeOutputChunk: () => Effect.void,
+};
+
+const currentDesktopRunId = Effect.gen(function* () {
+ const annotations = yield* References.CurrentLogAnnotations;
+ const runId = annotations.runId;
+ return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
+});
+
+const refreshFileSize = (
+ fileSystem: FileSystem.FileSystem,
+ filePath: string,
+): Effect.Effect<number, never> =>
+ fileSystem.stat(filePath).pipe(
+ Effect.map((stat) => Number(stat.size)),
+ Effect.orElseSucceed(() => 0),
+ );
+
+const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
+ readonly filePath: string;
+ readonly maxBytes?: number;
+ readonly maxFiles?: number;
+}): Effect.fn.Return<
+ RotatingLogFileWriter,
+ DesktopLogFileWriterError,
+ FileSystem.FileSystem | Path.Path
+> {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
+ const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
+ const directory = path.dirname(input.filePath);
+ const baseName = path.basename(input.filePath);
+
+ if (maxBytes < 1) {
+ return yield* new DesktopLogFileWriterConfigurationError({
+ option: "maxBytes",
+ value: maxBytes,
+ });
+ }
+ if (maxFiles < 1) {
+ return yield* new DesktopLogFileWriterConfigurationError({
+ option: "maxFiles",
+ value: maxFiles,
+ });
+ }
+
+ yield* fileSystem.makeDirectory(directory, { recursive: true });
+
+ const withSuffix = (index: number) => `${input.filePath}.${index}`;
+ const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
+ const mutex = yield* Semaphore.make(1);
+
+ const pruneOverflowBackups = Effect.gen(function* () {
+ const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
+ for (const entry of entries) {
+ if (!entry.startsWith(`${baseName}.`)) continue;
+ const suffix = Number(entry.slice(baseName.length + 1));
+ if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
+ yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
+ }
+ });
+
+ const rotate = Effect.gen(function* () {
+ yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
+ for (let index = maxFiles - 1; index >= 1; index -= 1) {
+ const source = withSuffix(index);
+ const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
+ if (sourceExists) {
+ yield* fileSystem.rename(source, withSuffix(index + 1));
+ }
+ }
+ const currentExists = yield* fileSystem
+ .exists(input.filePath)
+ .pipe(Effect.orElseSucceed(() => false));
+ if (currentExists) {
+ yield* fileSystem.rename(input.filePath, withSuffix(1));
+ }
+ yield* Ref.set(currentSize, 0);
+ }).pipe(
+ Effect.catch(() =>
+ refreshFileSize(fileSystem, input.filePath).pipe(
+ Effect.flatMap((size) => Ref.set(currentSize, size)),
+ ),
+ ),
+ );
+
+ const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
+ if (chunk.byteLength === 0) return Effect.void;
+
+ return mutex.withPermits(1)(
+ Effect.gen(function* () {
+ const beforeSize = yield* Ref.get(currentSize);
+ if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
+ yield* rotate;
+ }
+
+ yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
+ const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
+ yield* Ref.set(currentSize, afterSize);
+
+ if (afterSize > maxBytes) {
+ yield* rotate;
+ }
+ }).pipe(
+ Effect.catch(() =>
+ refreshFileSize(fileSystem, input.filePath).pipe(
+ Effect.flatMap((size) => Ref.set(currentSize, size)),
+ ),
+ ),
+ ),
+ );
+ };
+
+ yield* pruneOverflowBackups;
+
+ return {
+ writeBytes,
+ writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
+ } satisfies RotatingLogFileWriter;
+});
+
+const readPersistedOtlpTracesUrl: Effect.Effect<
+ Option.Option<string>,
+ never,
+ FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
+> = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -70,6 +274,170 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
return yield* readPersistedOtlpTracesUrl;
});
+const writeDevelopmentConsoleOutput = (
+ streamName: "stdout" | "stderr",
+ chunk: Uint8Array,
+): Effect.Effect<void> =>
+ Effect.sync(() => {
+ const output = streamName === "stderr" ? process.stderr : process.stdout;
+ output.write(chunk);
+ }).pipe(Effect.ignore);
+
+const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
+ function* (
+ logFile: RotatingLogFileWriter,
+ input: {
+ readonly message: string;
+ readonly level: "INFO" | "ERROR";
+ readonly annotations: Record<string, unknown>;
+ },
+ ): Effect.fn.Return<void> {
+ return yield* Effect.gen(function* () {
+ const timestamp = DateTime.formatIso(yield* DateTime.now);
+ const encoded = yield* encodeDesktopBackendChildLogRecord({
+ message: input.message,
+ level: input.level,
+ timestamp,
+ annotations: input.annotations,
+ spans: {},
+ fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
+ });
+ yield* logFile.writeText(`${encoded}\n`);
+ }).pipe(Effect.ignore({ log: true }));
+ },
+);
+
+const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
+
+const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
+
+const backendLogFilePathForInstance = (
+ environment: DesktopEnvironment.DesktopEnvironment["Service"],
+ id: string,
+): string => {
+ // Primary keeps the historical "server-child.log" path so ops scripts
+ // and packaged-build log inspection still find it where it always lived.
+ if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
+ return environment.path.join(environment.logDir, "server-child.log");
+ }
+ const sanitized = sanitizeInstanceIdForFileName(id);
+ return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
+};
+
+// Just the IO sink. Cacheable by resolved file path so two ids that
+// sanitize to the same filename share a single RotatingLogFileWriter
+// (no race on currentSize tracking). Splitting the sink off from the
+// per-call shape lets the shape annotate writes with the *caller's*
+// id rather than whatever id created the cached writer first.
+const makeBackendOutputSinkForInstance = (
+ environment: DesktopEnvironment.DesktopEnvironment["Service"],
+ id: string,
+): Effect.Effect<
+ Option.Option<RotatingLogFileWriter>,
+ never,
+ FileSystem.FileSystem | Path.Path | Scope.Scope
+> =>
+ makeRotatingLogFileWriter({
+ filePath: backendLogFilePathForInstance(environment, id),
+ }).pipe(Effect.option);
+
+const makeBackendOutputLogShape = (
+ environment: DesktopEnvironment.DesktopEnvironment["Service"],
+ id: string,
+ sink: Option.Option<RotatingLogFileWriter>,
+): DesktopBackendOutputLogShape =>
+ Option.match(sink, {
+ onNone: () => DesktopBackendOutputLogNoop,
+ onSome: (logFile) =>
+ ({
+ writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
+ function* ({ phase, details }) {
+ const runId = yield* currentDesktopRunId;
+ yield* writeBackendChildLogRecord(logFile, {
+ message: `backend child process session ${phase.toLowerCase()}`,
+ level: "INFO",
+ annotations: {
+ component: "desktop-backend-child",
+ runId,
+ instanceId: id,
+ phase,
+ details: sanitizeLogValue(details),
+ },
+ });
+ },
+ ),
+ writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
+ function* (streamName, chunk) {
+ if (environment.isDevelopment) {
+ yield* writeDevelopmentConsoleOutput(streamName, chunk);
+ }
+ const runId = yield* currentDesktopRunId;
+ yield* writeBackendChildLogRecord(logFile, {
+ message: "backend child process output",
+ level: streamName === "stderr" ? "ERROR" : "INFO",
+ annotations: {
+ component: "desktop-backend-child",
+ runId,
+ instanceId: id,
+ stream: streamName,
+ text: textDecoder.decode(chunk),
+ },
+ });
+ },
+ ),
+ }) satisfies DesktopBackendOutputLogShape,
+ });
+
+const backendOutputLogFactoryLayer = Layer.effect(
+ DesktopBackendOutputLogFactory,
+ Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const factoryScope = yield* Scope.Scope;
+ // Per-file-path cache of the IO sink only. The per-call shape
+ // wraps the sink with the caller's instance id so a cache hit on
+ // a path collision (e.g. "wsl:default" and "wsl_default" both
+ // resolve to server-child-wsl_default.log) doesn't attribute the
+ // second caller's writes to the first caller's id. Each sink pins
+ // itself to the factory's scope so all log resources tear down
+ // together at app exit. Mutex serializes concurrent first-time
+ // lookups for the same file path.
+ const cacheRef = yield* SynchronizedRef.make<
+ ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
+ >(new Map());
+
+ const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
+ SynchronizedRef.modifyEffect(cacheRef, (cache) => {
+ const cacheKey = backendLogFilePathForInstance(environment, id);
+ const cached = cache.get(cacheKey);
+ if (cached !== undefined) {
+ return Effect.succeed([
+ makeBackendOutputLogShape(environment, id, cached),
+ cache,
+ ] as const);
+ }
+ return makeBackendOutputSinkForInstance(environment, id).pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(Path.Path, path),
+ Scope.provide(factoryScope),
+ Effect.map((sink) => {
+ const next = new Map(cache);
+ next.set(cacheKey, sink);
+ return [
+ makeBackendOutputLogShape(environment, id, sink),
+ next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
+ ] as const;
+ }),
+ );
+ });
+
+ return DesktopBackendOutputLogFactory.of({
+ forInstance: (id) => makeForId(id),
+ });
+ }),
+);
+
const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
@@ -82,8 +450,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
- maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
- maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
+ maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
+ maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
@@ -101,8 +469,8 @@ const tracerLayer = Layer.unwrap(
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
- maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
- maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
+ maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
+ maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
@@ -113,7 +481,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
- DesktopBackendOutputLogModule.layer,
+ backendOutputLogFactoryLayer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index 43e77a0c4..24c90943e 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -4,13 +4,19 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
+import * as ManagedRuntime from "effect/ManagedRuntime";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
+import { ChildProcessSpawner } from "effect/unstable/process";
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({
@@ -45,19 +51,22 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
function makeEnvironmentLayer(
baseDir: string,
options?: {
+ readonly appPath?: string;
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
+ readonly platform?: NodeJS.Platform;
+ readonly resourcesPath?: string;
},
) {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
- platform: "darwin",
+ platform: options?.platform ?? "darwin",
processArch: "x64",
appVersion: "1.2.3",
- appPath: "/repo",
+ appPath: options?.appPath ?? "/repo",
isPackaged: options?.isPackaged ?? true,
- resourcesPath: "/missing/resources",
+ resourcesPath: options?.resourcesPath ?? "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
@@ -75,6 +84,14 @@ function makeEnvironmentLayer(
);
}
+const restoreEnv = (name: string, value: string | undefined) => {
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+};
+
const withHarness = <A, E, R>(
effect: Effect.Effect<
A,
@@ -95,6 +112,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)),
),
),
@@ -102,14 +121,14 @@ const withHarness = <A, E, R>(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
describe("DesktopBackendConfiguration", () => {
- it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
+ it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- const first = yield* configuration.resolve;
- const second = yield* configuration.resolve;
+ const first = yield* configuration.resolvePrimary;
+ const second = yield* configuration.resolvePrimary;
assert.equal(first.executablePath, process.execPath);
assert.equal(first.entryPath, environment.backendEntryPath);
@@ -133,7 +152,167 @@ describe("DesktopBackendConfiguration", () => {
),
);
- it.effect("includes persisted backend observability endpoints when present", () =>
+ it.effect("resolveWsl reuses the primary's bootstrap token", () =>
+ withHarness(
+ Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+
+ const primary = yield* configuration.resolvePrimary;
+ const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
+
+ assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
+ }),
+ ),
+ );
+
+ it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+ const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
+ yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
+ yield* fileSystem.writeFileString(entryPath, "");
+
+ const observedDistros: Array<string | null> = [];
+ const config = yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ return yield* configuration.resolveWsl({ port: 5000, distro: null });
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distros: [
+ { name: "Debian", isDefault: false, version: 2 },
+ { name: "Ubuntu", isDefault: true, version: 2 },
+ ],
+ windowsToWslPath: (distro) => {
+ observedDistros.push(distro);
+ return Option.some("/repo/apps/server/dist/bin.mjs");
+ },
+ ensureNodePty: (distro) => {
+ observedDistros.push(distro);
+ return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
+ },
+ getDistroIp: (distro) => {
+ observedDistros.push(distro);
+ return Option.some("172.27.0.99");
+ },
+ }),
+ ),
+ Layer.provideMerge(
+ makeEnvironmentLayer(baseDir, {
+ appPath: baseDir,
+ platform: "win32",
+ resourcesPath: baseDir,
+ }),
+ ),
+ ),
+ ),
+ );
+
+ assert.equal(config.runningDistro, "Ubuntu");
+ assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
+ assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
+ assert.isTrue(Option.isNone(config.preflightFailure));
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect(
+ "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+ const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
+ yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
+ yield* fileSystem.writeFileString(entryPath, "");
+
+ const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
+ const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
+ const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
+ const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
+ const config = yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
+ windowsToWslPath: () => Option.some(linuxEntryPath),
+ ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
+ getDistroIp: () => Option.some("172.27.0.99"),
+ }),
+ ),
+ Layer.provideMerge(
+ makeEnvironmentLayer(baseDir, {
+ appPath: baseDir,
+ devServerUrl,
+ isPackaged: true,
+ platform: "win32",
+ resourcesPath: baseDir,
+ }),
+ ),
+ ),
+ ),
+ );
+
+ assert.equal(config.bootstrapDelivery, "stdin");
+ assert.deepEqual(config.args, [
+ "-d",
+ "Ubuntu",
+ "--exec",
+ "env",
+ "PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
+ nodePath,
+ linuxEntryPath,
+ "--bootstrap-fd",
+ "0",
+ "--dev-url",
+ devServerUrl,
+ ]);
+ assert.notInclude(config.args, "bash");
+ assert.notInclude(config.args, "/bin/sh");
+ assert.notInclude(config.args, "-c");
+ assert.isTrue(Option.isNone(config.preflightFailure));
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
+ withHarness(
+ Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+
+ // Resolve both before any token is cached, concurrently, so the
+ // generate step (a yield point) can interleave. The atomic
+ // get-or-create must still hand both the same token; a non-atomic
+ // Ref would let each generate its own and break the shared-token
+ // invariant.
+ const [primary, wsl] = yield* Effect.all(
+ [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
+ { concurrency: "unbounded" },
+ );
+
+ assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
+ }),
+ ),
+ );
+
+ it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
withHarness(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -153,18 +332,18 @@ describe("DesktopBackendConfiguration", () => {
}),
);
- const config = yield* configuration.resolve;
+ const config = yield* configuration.resolvePrimary;
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
}),
),
);
- it.effect("omits backend observability endpoints when settings are missing", () =>
+ it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- const config = yield* configuration.resolve;
+ const config = yield* configuration.resolvePrimary;
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
@@ -175,10 +354,11 @@ describe("DesktopBackendConfiguration", () => {
it.effect("logs structured context when persisted observability settings cannot be read", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
- const settingsPath = `${baseDir}/userdata/settings.json`;
+ const settingsPath = path.join(baseDir, "userdata", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -198,12 +378,14 @@ describe("DesktopBackendConfiguration", () => {
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- return yield* configuration.resolve;
+ return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
@@ -228,7 +410,7 @@ describe("DesktopBackendConfiguration", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
- it.effect("captures backend output in development so child process logs can be persisted", () =>
+ it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -237,12 +419,14 @@ describe("DesktopBackendConfiguration", () => {
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- const config = yield* configuration.resolve;
+ const config = yield* configuration.resolvePrimary;
assert.equal(config.captureOutput, true);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
isPackaged: false,
@@ -254,4 +438,362 @@ describe("DesktopBackendConfiguration", () => {
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+
+ it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ const previousWslEnv = process.env.WSLENV;
+ const previousOpenAiKey = process.env.OPENAI_API_KEY;
+ const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
+ try {
+ process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
+ process.env.OPENAI_API_KEY = "openai-key";
+ process.env.ANTHROPIC_API_KEY = "anthropic-key";
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
+
+ assert.equal(config.executablePath, "wsl.exe");
+ assert.equal(config.bootstrap.port, 5050);
+ // Binds to 0.0.0.0 inside WSL so the backend is reachable via
+ // both wslhost-forwarded localhost and the distro's eth0 IP.
+ assert.equal(config.bootstrap.host, "0.0.0.0");
+ assert.equal(config.bootstrap.tailscaleServeEnabled, false);
+ // httpBaseUrl uses the resolved distro IP from the test stub,
+ // not localhost — the renderer reaches the backend directly to
+ // avoid relying on wslhost forwarding.
+ assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
+ assert.equal(config.env.OPENAI_API_KEY, "openai-key");
+ assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
+ // The existing WSLENV is preserved byte-for-byte (note the empty
+ // "::" segment survives — WSL ignores it, so we don't normalize
+ // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
+ // already declared, so it isn't forwarded twice.
+ assert.equal(
+ config.env.WSLENV,
+ "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
+ );
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
+ getDistroIp: () => Option.some("172.27.0.99"),
+ }),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ } finally {
+ restoreEnv("WSLENV", previousWslEnv);
+ restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
+ restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
+ }
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect(
+ "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolvePrimary;
+
+ // wsl-only is persisted but WSL is unavailable, so the primary must
+ // not spawn wsl.exe (which would loop on preflight failures while the
+ // Connections backend control is hidden). Resolve the Windows primary.
+ assert.equal(config.executablePath, process.execPath);
+ assert.equal(config.bootstrap.t3Home, environment.baseDir);
+ assert.isTrue(Option.isNone(config.preflightFailure));
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: true,
+ }),
+ ),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect(
+ "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolvePrimary;
+ const failure = Option.getOrThrow(config.preflightFailure);
+
+ assert.equal(config.executablePath, "wsl.exe");
+ assert.isTrue(failure.fatal);
+ assert.include(failure.reason, "Removed-Distro");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: true,
+ wslDistro: "Removed-Distro",
+ }),
+ ),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
+ }),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
+ const failure = Option.getOrThrow(config.preflightFailure);
+
+ assert.isFalse(failure.fatal);
+ assert.equal(failure.retryLimit, 12);
+ assert.include(failure.reason, "timed out");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
+ reason: "wsl.exe --list --verbose timed out",
+ }),
+ }),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
+ const failure = Option.getOrThrow(config.preflightFailure);
+
+ assert.isTrue(failure.fatal);
+ assert.include(failure.reason, "missing server entry");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
+ }),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
+ const failure = Option.getOrThrow(config.preflightFailure);
+
+ assert.isTrue(failure.fatal);
+ assert.include(failure.reason, "Removed-Distro");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(
+ DesktopWslEnvironment.layerTest({
+ isAvailable: true,
+ distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
+ }),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const label = yield* configuration.resolvePrimaryLabel;
+ assert.equal(label, "WSL (Ubuntu)");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: true,
+ wslDistro: "Ubuntu",
+ }),
+ ),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
+ withHarness(
+ Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const label = yield* configuration.resolvePrimaryLabel;
+ assert.equal(label, "Local environment");
+ }),
+ ),
+ );
+
+ it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-backend-config-test-",
+ });
+
+ yield* Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ // Mirrors the resolvePrimary fall-back: the label must follow the
+ // backend that actually resolves, not the persisted preference, so the
+ // env switcher can't show "WSL" for a Windows backend.
+ const label = yield* configuration.resolvePrimaryLabel;
+ assert.equal(label, "Windows");
+ }).pipe(
+ Effect.provide(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: true,
+ wslDistro: "Ubuntu",
+ }),
+ ),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
+ Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
+ ),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
+ it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
+ // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
+ // primary instance's lazy label through Effect.runSync. The label chains
+ // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
+ // That probe must run once at layer build and expose a resolved value, not
+ // a live async effect — otherwise runSync throws in the handler. Build the
+ // real WSL layer (not the sync test stub) and resolve the label with a
+ // top-level runSync, exactly as the handler does.
+ // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
+ const runtime = ManagedRuntime.make(
+ DesktopBackendConfiguration.layer.pipe(
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
+ Layer.provideMerge(DesktopWslEnvironment.layer),
+ // isAvailable on win32 only touches the filesystem, never the spawner,
+ // so a die-stub is enough to satisfy the layer's deps.
+ Layer.provideMerge(
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.die("spawner should not be used while probing WSL availability"),
+ ),
+ ),
+ ),
+ Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
+ Layer.provide(NodeServices.layer),
+ ),
+ );
+ try {
+ const configuration = await runtime.runPromise(
+ DesktopBackendConfiguration.DesktopBackendConfiguration,
+ );
+ // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
+ const label = Effect.runSync(configuration.resolvePrimaryLabel);
+ assert.equal(typeof label, "string");
+ } finally {
+ await runtime.dispose();
+ }
+ });
});
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
index d8bd1a13d..2559b69e6 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -1,3 +1,5 @@
+import * as NodeOS from "node:os";
+
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -7,12 +9,16 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
-import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
+import * as SynchronizedRef from "effect/SynchronizedRef";
+
+import serverPackageJson from "../../../server/package.json" with { type: "json" };
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
@@ -29,10 +35,31 @@ export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedE
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
- readonly resolve: Effect.Effect<
+ // Build the Windows-native primary backend's start config. Reads the
+ // primary's port/host/exposure from DesktopServerExposure. Can fail
+ // with PlatformError because bootstrap token generation now uses
+ // crypto.randomBytes under the hood (post Effect 4 migration).
+ readonly resolvePrimary: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
+ // Build a WSL backend start config for the given distro on the given
+ // port. The WSL backend is always loopback-only (the primary owns LAN
+ // exposure when the user opts in), so this takes the port directly and
+ // hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
+ // forwarded to wsl.exe with no -d flag.
+ readonly resolveWsl: (input: {
+ readonly port: number;
+ readonly distro: string | null;
+ }) => Effect.Effect<
+ DesktopBackendManager.DesktopBackendStartConfig,
+ PlatformError.PlatformError
+ >;
+ // The renderer-facing label for the primary instance, derived from the
+ // same decision resolvePrimary makes (including the WSL-availability
+ // fall-back to Windows), so the env switcher can't show "WSL" for a
+ // backend that actually resolved to Windows.
+ readonly resolvePrimaryLabel: Effect.Effect<string>;
}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
@@ -59,9 +86,48 @@ 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. The dev-server URL is
+// handled separately via a `--dev-url` CLI flag because WSLENV translation of
+// URL-shaped values (colons / slashes) is unreliable.
+const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
+
+const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
+
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
+const getWslEnvEntryName = (entry: string): string => {
+ const slashIndex = entry.indexOf("/");
+ return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
+};
+
+const mergeWslEnv = (
+ existingWslEnv: string | undefined,
+ forwardedEnvNames: ReadonlyArray<string>,
+): string | undefined => {
+ const existing = existingWslEnv?.trim() ?? "";
+
+ // Names already declared, so we don't forward a duplicate. We parse the
+ // existing value only for this membership test — the string itself is
+ // preserved verbatim below rather than re-serialized.
+ const seenNames = new Set(
+ existing
+ .split(":")
+ .map((entry) => getWslEnvEntryName(entry.trim()))
+ .filter((name) => name.length > 0),
+ );
+
+ const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
+
+ // Preserve the user's WSLENV exactly as Windows handed it to us — empty
+ // "::" segments and duplicate entries are harmless no-ops to WSL and not
+ // ours to normalize — and only append the secrets we need to forward
+ // across the wsl.exe boundary.
+ const parts = [existing, ...additions].filter((part) => part.length > 0);
+ return parts.length > 0 ? parts.join(":") : undefined;
+};
+
const logBackendObservabilitySettingsReadFailure = (
settingsPath: string,
cause: PlatformError.PlatformError,
@@ -100,11 +166,168 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
};
});
-const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
- function* (input: {
- readonly bootstrapToken: string;
- readonly observabilitySettings: BackendObservabilitySettings;
- }): Effect.fn.Return<
+interface SharedBootstrapInput {
+ readonly bootstrapToken: string;
+ readonly observabilitySettings: BackendObservabilitySettings;
+}
+
+interface WslPreflightSuccess {
+ readonly _tag: "Ready";
+ readonly runningDistro: string;
+ readonly linuxEntryPath: string;
+ // Absolute path to the node binary the preflight validated after the shared
+ // remote resolver repaired PATH. The launch must use this exact path so it
+ // doesn't fall through to a different/old node than the one node-pty was
+ // built against.
+ readonly nodePath: string;
+ // PATH captured from the same login shell after the shared resolver loaded
+ // version managers. The launch forwards this value directly without a shell.
+ readonly resolvedPath: string;
+}
+
+interface WslPreflightFailure {
+ readonly _tag: "Failed";
+ readonly reason: string;
+ // Fatal: the WSL distro is misconfigured (no node, wrong version, missing
+ // build tools) and retrying won't help — surface it and (wsl-only) fall back
+ // to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
+ // boots), with a bounded window for self-healing before fallback.
+ readonly fatal: boolean;
+ readonly retryLimit?: number;
+}
+
+const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
+
+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<
+ WslPreflightSuccess | 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",
+ fatal: false,
+ } as const;
+ }
+
+ const distroProbe = yield* wslEnv.probeDistros.pipe(
+ Effect.map((distros) => ({ _tag: "Success", distros }) as const),
+ Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
+ );
+ if (distroProbe._tag === "Failure") {
+ return {
+ _tag: "Failed",
+ reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
+ fatal: false,
+ } as const;
+ }
+
+ const installedDistros = distroProbe.distros;
+ const runningDistro = input.distro
+ ? (installedDistros.find(
+ (installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
+ )?.name ?? null)
+ : (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
+ if (runningDistro === null) {
+ return {
+ _tag: "Failed",
+ reason: input.distro
+ ? `WSL distro is not installed: ${input.distro}`
+ : installedDistros.length === 0
+ ? "WSL has no installed distributions"
+ : "WSL has no default distribution",
+ fatal: true,
+ } 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}`,
+ fatal: true,
+ } as const;
+ }
+
+ const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
+ if (Option.isNone(linuxEntry)) {
+ return {
+ _tag: "Failed",
+ reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
+ fatal: false,
+ } as const;
+ }
+
+ const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
+ allowBuild: input.allowBuild,
+ nodeEngineRange: serverPackageJson.engines.node,
+ });
+ if (!nodePtyResult.ok) {
+ return {
+ _tag: "Failed",
+ reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
+ fatal: nodePtyResult.fatal,
+ ...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
+ } as const;
+ }
+
+ return {
+ _tag: "Ready",
+ runningDistro,
+ linuxEntryPath: linuxEntry.value,
+ nodePath: nodePtyResult.nodePath,
+ resolvedPath: nodePtyResult.resolvedPath,
+ } as const;
+});
+
+// True when the given IPv4 belongs to a Windows-side network
+// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
+// host's, which is the signature we use to detect that mode and
+// switch the renderer URL to loopback.
+const isLocalHostIpv4 = (ip: string): boolean => {
+ const interfaces = NodeOS.networkInterfaces();
+ for (const list of Object.values(interfaces)) {
+ if (!list) continue;
+ for (const entry of list) {
+ // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
+ // the Node build Electron ships (41 / Node 22, verified), but some Node
+ // builds report the numeric 4. Normalize to a string so a future runtime
+ // bump can't silently break mirrored-mode detection and leave the
+ // renderer pointed at the distro IP instead of loopback.
+ const family = String(entry.family);
+ if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
+ }
+ }
+ return false;
+};
+
+const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
+ ...Option.match(observabilitySettings.otlpTracesUrl, {
+ onNone: () => ({}),
+ onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
+ }),
+ ...Option.match(observabilitySettings.otlpMetricsUrl, {
+ onNone: () => ({}),
+ onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
+ }),
+});
+
+const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
+ function* (
+ input: SharedBootstrapInput,
+ ): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
@@ -113,70 +336,349 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const backendExposure = yield* serverExposure.backendConfig;
+ const bootstrap = {
+ mode: "desktop" as const,
+ noBrowser: true,
+ port: backendExposure.port,
+ t3Home: environment.baseDir,
+ host: backendExposure.bindHost,
+ desktopBootstrapToken: input.bootstrapToken,
+ tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
+ tailscaleServePort: backendExposure.tailscaleServePort,
+ ...buildObservabilityFragment(input.observabilitySettings),
+ };
+
return {
executablePath: process.execPath,
+ args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
entryPath: environment.backendEntryPath,
cwd: environment.backendCwd,
env: {
...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 }),
- }),
- },
+ // Primary 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 resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
+ input: SharedBootstrapInput & {
+ readonly port: number;
+ readonly distro: string | null;
+ },
+): Effect.fn.Return<
+ DesktopBackendManager.DesktopBackendStartConfig,
+ never,
+ | DesktopEnvironment.DesktopEnvironment
+ | DesktopWslEnvironment.DesktopWslEnvironment
+ | FileSystem.FileSystem
+> {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
+
+ // Bind to 0.0.0.0 inside WSL so the backend is reachable both via
+ // WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
+ // -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
+ // Windows. wslhost forwarding is unreliable on some Windows hosts:
+ // the desktop's readiness probe and the renderer's saved-env-style
+ // fetch both saw "Failed to fetch" when the backend only bound to
+ // 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
+ // WSL IP as the renderer-visible URL avoids that dependency.
+ // Security-wise this is acceptable for the local-only WSL backend:
+ // the network it exposes on is the WSL-vEthernet network, not the
+ // LAN; the primary owns LAN exposure when the user opts in.
+ const wslBindHost = "0.0.0.0";
+
+ const bootstrap = {
+ mode: "desktop" as const,
+ noBrowser: true,
+ port: input.port,
+ // Omit t3Home so the Linux backend uses its own home dir instead of
+ // the Windows-side baseDir (which would be a /mnt/c path and share
+ // the SQLite file with the primary).
+ host: wslBindHost,
+ desktopBootstrapToken: input.bootstrapToken,
+ // PortSchema rejects 0, so when tailscale serve is disabled we still
+ // need a valid number in this slot. The backend reads tailscaleServePort
+ // only when tailscaleServeEnabled is true, so the actual value here is
+ // inert.
+ tailscaleServeEnabled: false,
+ tailscaleServePort: 443,
+ ...buildObservabilityFragment(input.observabilitySettings),
+ };
+
+ // In packaged builds environment.appRoot is .../resources/app.asar — an
+ // archive FILE. The Windows primary reads its entry through
+ // ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
+ // `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
+ // the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
+ // to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
+ // already a real directory, so this is a no-op.
+ const wslAppRoot = environment.isPackaged
+ ? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
+ : environment.appRoot;
+ const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
+
+ const preflight = yield* runWslPreflight({
+ distro: input.distro,
+ windowsEntryPath: wslEntryPath,
+ windowsRepoRoot: wslAppRoot,
+ // Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
+ // attached to the Windows artifact — see build-desktop-artifact.ts), so the
+ // WSL backend never needs a compiler, node-gyp, or network on first launch.
+ // Compiling from source is a dev-only convenience: a checkout has no shipped
+ // prebuilt, and developers have the toolchain. In packaged builds we instead
+ // surface a clear diagnostic if the prebuilt can't load (unsupported
+ // arch/distro), rather than silently dropping into a fragile runtime build.
+ allowBuild: !environment.isPackaged,
+ });
+
+ // Every operation after preflight uses the same concrete distro. In
+ // default-tracking mode this closes the race where the system default
+ // changes between probing and spawning the backend.
+ const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
+ const distroForConfig = runningDistro ?? input.distro;
+
+ // Resolve the selected distro's IPv4 address. In mirrored mode the distro
+ // reports a host interface, so use loopback instead; a failed probe also
+ // falls back to loopback and preserves the previous behavior.
+ const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
+ const usesSharedNetworkStack = Option.match(distroIp, {
+ onNone: () => false,
+ onSome: (ip) => isLocalHostIpv4(ip),
+ });
+ const rendererHost = usesSharedNetworkStack
+ ? "127.0.0.1"
+ : Option.getOrElse(distroIp, () => "127.0.0.1");
+ const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
+
+ const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
+ 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);
+ }
+ }
+
+ // Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
+ // exports the Windows-side base dir for the primary; if it leaks into
+ // the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
+ // /mnt/c, which means both backends read/write the same database and
+ // their env-ids collide).
+ const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
+ for (const [key, value] of Object.entries(process.env)) {
+ if (key === "T3CODE_HOME") continue;
+ parentEnvWithoutT3Home[key] = value;
+ }
+ const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
+
+ const baseConfig = {
+ executablePath: "wsl.exe",
+ entryPath: wslEntryPath,
+ cwd: environment.backendCwd,
+ env: {
+ ...parentEnvWithoutT3Home,
+ ...backendChildEnvPatch(),
+ ...forwardedEnv,
+ ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
+ },
+ // env is already a complete process.env minus T3CODE_HOME; pass it
+ // verbatim instead of letting the spawner re-merge process.env on top.
+ extendEnv: false,
+ bootstrap,
+ bootstrapDelivery: "stdin" as const,
+ httpBaseUrl,
+ captureOutput: true,
+ ...(runningDistro !== null ? { runningDistro } : {}),
+ };
+
+ // 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") {
+ const retryLimit =
+ preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
+ return {
+ ...baseConfig,
+ args: [...distroArgs, "--", "node", "--version"],
+ preflightFailure: Option.some({
+ reason: preflight.reason,
+ fatal: preflight.fatal,
+ ...(retryLimit === undefined ? {} : { retryLimit }),
+ }),
+ } satisfies DesktopBackendManager.DesktopBackendStartConfig;
+ }
+
+ // The WSL server spawns commands its providers reference by name — `npm`/`npx`
+ // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
+ // live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
+ // the process PATH, so `npm install -g ...` fails with NotFound. Pass the
+ // user PATH entries captured by the login-shell preflight. Every dynamic
+ // value is a separate argv entry under `wsl.exe --exec`; no shell command is
+ // involved, so Windows cannot mangle nested quotes and stdin remains reserved
+ // for the bootstrap envelope.
+ const lastSlash = preflight.nodePath.lastIndexOf("/");
+ const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
+ const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
+
+ return {
+ ...baseConfig,
+ args: [
+ ...distroArgs,
+ "--exec",
+ "env",
+ `PATH=${launchPath}`,
+ preflight.nodePath,
+ preflight.linuxEntryPath,
+ "--bootstrap-fd",
+ "0",
+ ...devUrlArgs,
+ ],
+ preflightFailure: Option.none(),
+ } satisfies DesktopBackendManager.DesktopBackendStartConfig;
+});
+
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
const crypto = yield* Crypto.Crypto;
- const tokenRef = yield* Ref.make(Option.none<string>());
- const getOrCreateBootstrapToken = Effect.gen(function* () {
- const existing = yield* Ref.get(tokenRef);
- if (Option.isSome(existing)) {
- return existing.value;
- }
+ // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
+ // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
+ // resolve concurrently; with a plain Ref both could observe None, generate
+ // distinct tokens, and one would overwrite the other — leaving the two
+ // backends holding mismatched tokens and breaking the shared-token
+ // invariant the renderer relies on. modifyEffect serializes the whole
+ // get-or-create so the first caller wins and the rest reuse its token.
+ const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
+ const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
+ Option.match(current, {
+ onSome: (token) => Effect.succeed([token, current] as const),
+ onNone: () =>
+ crypto.randomBytes(24).pipe(
+ Effect.map((bytes) => {
+ const token = Encoding.encodeHex(bytes);
+ return [token, Option.some(token)] as const;
+ }),
+ ),
+ }),
+ );
+
+ // Both resolvers share the same bootstrap token: the renderer holds a
+ // single token and uses it against whichever backend it's currently
+ // talking to. Observability settings get re-read each resolve so a
+ // hot-swap of the server-settings file is picked up on the next
+ // restart cycle without having to bounce the desktop process.
+ const sharedInputs = Effect.gen(function* () {
+ const bootstrapToken = yield* getOrCreateBootstrapToken;
+ const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
+ );
+ return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
+ });
- const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
- yield* Ref.set(tokenRef, Option.some(token));
- return token;
+ const buildWslPrimaryConfig = Effect.gen(function* () {
+ // wsl-only mode pipes the WSL backend through the same port the
+ // Windows primary would normally take. That way the renderer
+ // still loads from the local-only endpoint advertised by
+ // DesktopServerExposure, and primary-aware code paths (cookie
+ // auth, the env switcher's "primary" id) keep working without
+ // a parallel "secondary" registration.
+ const backendExposure = yield* serverExposure.backendConfig;
+ const persistedSettings = yield* settings.get;
+ const shared = yield* sharedInputs;
+ return yield* resolveWslStartConfig({
+ ...shared,
+ port: backendExposure.port,
+ distro: persistedSettings.wslDistro,
+ }).pipe(
+ Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
+ Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ );
+ });
+
+ const buildWindowsPrimaryConfig = Effect.gen(function* () {
+ const shared = yield* sharedInputs;
+ return yield* resolvePrimaryStartConfig(shared).pipe(
+ Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
+ Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
+ );
+ });
+
+ // Single source of truth for what the primary actually runs as. Both
+ // the start-config dispatch and the renderer-facing label derive from
+ // this, so they can't disagree — e.g. the label reading "WSL" while the
+ // config silently fell back to Windows because WSL is unavailable.
+ // Dispatch happens at resolve time so toggling wsl-only between restarts
+ // is picked up on the next start cycle (the pool's primary instance is
+ // created once at layer init, but configResolve fires on each restart).
+ const describePrimary = Effect.gen(function* () {
+ const persistedSettings = yield* settings.get;
+ const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
+ // Only honor wsl-only when WSL is actually usable. If the user
+ // persisted wsl-only but WSL has since become unavailable (wsl.exe
+ // removed, no distro), fall back to the Windows primary instead of
+ // looping forever on preflight failures: the Connections backend
+ // control is hidden while WSL is unavailable, so a stuck WSL primary
+ // would otherwise leave no in-app way back to Windows.
+ const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
+ return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
});
return DesktopBackendConfiguration.of({
- resolve: Effect.gen(function* () {
- const bootstrapToken = yield* getOrCreateBootstrapToken;
- const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
- Effect.provideService(FileSystem.FileSystem, fileSystem),
- Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
- );
- return yield* resolveBackendStartConfig({
- bootstrapToken,
- observabilitySettings,
+ resolvePrimary: Effect.gen(function* () {
+ const { useWsl, wslRequested } = yield* describePrimary;
+ if (useWsl) {
+ return yield* buildWslPrimaryConfig;
+ }
+ if (wslRequested) {
+ yield* Effect.logWarning(
+ "WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
+ );
+ }
+ return yield* buildWindowsPrimaryConfig;
+ }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
+ resolvePrimaryLabel: Effect.gen(function* () {
+ const { useWsl, distro } = yield* describePrimary;
+ if (!useWsl) {
+ return environment.platform === "win32" ? "Windows" : "Local environment";
+ }
+ return distro ? `WSL (${distro})` : "WSL";
+ }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
+ resolveWsl: (input) =>
+ Effect.gen(function* () {
+ const shared = yield* sharedInputs;
+ return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
+ Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
+ Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ );
}).pipe(
- Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
- Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
- );
- }).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
+ Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
+ attributes: { port: input.port, distro: input.distro ?? null },
+ }),
+ ),
});
});
diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts
index 3c0a513c9..858c9b0d5 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts
@@ -3,15 +3,12 @@ import {
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
-import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
-import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -23,18 +20,15 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
-import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
-import * as DesktopState from "../app/DesktopState.ts";
-import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
-const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
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" },
@@ -48,8 +42,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 = {
@@ -59,9 +56,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
};
function makeProcess(options?: {
- readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
- readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
- readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
+ readonly stdout?: Stream.Stream<Uint8Array>;
+ readonly stderr?: Stream.Stream<Uint8Array>;
+ readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
@@ -105,114 +102,98 @@ function decodeBootstrap(raw: string) {
return decodeDesktopBackendBootstrap(raw);
}
-function makeManagerLayer(input: {
+interface MakeInstanceInput {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
- readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
- readonly desktopState?: DesktopState.DesktopState["Service"];
- readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
+ readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
+ readonly onReady?: Effect.Effect<void>;
+ readonly onShutdown?: Effect.Effect<void>;
+ readonly onPreflightFailed?: (
+ failure: DesktopBackendManager.PreflightFailure,
+ ) => Effect.Effect<boolean>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
-}) {
- return DesktopBackendManager.layer.pipe(
- Layer.provide(
- Layer.mergeAll(
- FileSystem.layerNoop({
- exists: () => Effect.succeed(true),
- }),
- Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
- resolve: Effect.succeed(input.config ?? baseConfig),
- }),
- input.spawnerLayer,
- input.httpClientLayer ?? healthyHttpClientLayer,
- input.desktopState
- ? Layer.succeed(DesktopState.DesktopState, input.desktopState)
- : DesktopState.layer,
- Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
- writeSessionBoundary: () => Effect.void,
- writeOutputChunk: () => Effect.void,
- ...input.backendOutputLog,
- } satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
- Layer.succeed(DesktopWindow.DesktopWindow, {
- createMain: Effect.die("unexpected createMain"),
- ensureMain: Effect.die("unexpected ensureMain"),
- revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
- activate: Effect.void,
- createMainIfBackendReady: Effect.void,
- handleBackendReady: Effect.void,
- dispatchMenuAction: () => Effect.void,
- syncAppearance: Effect.void,
- ...input.desktopWindow,
- } satisfies DesktopWindow.DesktopWindow["Service"]),
- ),
- ),
- );
+ readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
-describe("DesktopBackendManager", () => {
- it("preserves the complete restart cause and schedule context", () => {
- const cause = Cause.combine(
- Cause.fail(new Error("start failed")),
- Cause.die(new Error("restart defect")),
- );
- const error = new DesktopBackendManager.DesktopBackendRestartError({
- reason: "backend exited with code 1",
- delayMs: 500,
- cause,
- });
-
- assert.strictEqual(error.cause, cause);
- assert.equal(error.reason, "backend exited with code 1");
- assert.equal(error.delayMs, 500);
- assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
+// Helper that constructs a primary backend instance using the factory
+// directly. The factory's deps (FileSystem, ChildProcessSpawner,
+// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
+// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
+// to drive the instance's lifecycle.
+function makeTestInstance(input: MakeInstanceInput) {
+ const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
+ writeSessionBoundary: () => Effect.void,
+ writeOutputChunk: () => Effect.void,
+ ...input.backendOutputLog,
+ };
+ const servicesLayer = Layer.mergeAll(
+ FileSystem.layerNoop({
+ exists: () => Effect.succeed(true),
+ }),
+ input.spawnerLayer,
+ input.httpClientLayer ?? healthyHttpClientLayer,
+ Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
+ forInstance: () => Effect.succeed(stubLog),
+ } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
+ );
+
+ const instance = DesktopBackendManager.makeBackendInstance({
+ id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
+ label: Effect.succeed("Windows"),
+ configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
+ ...(input.onReady ? { onReady: () => input.onReady! } : {}),
+ ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
+ ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
});
+ return instance.pipe(Effect.provide(servicesLayer));
+}
+
+describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
- Effect.gen(function* () {
- let spawnedCommand: ChildProcess.Command | undefined;
- let bootstrapJson = "";
- let readyCount = 0;
- const ready = yield* Deferred.make<void>();
- const exited = yield* Queue.unbounded<void>();
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make((command) =>
- Effect.gen(function* () {
- spawnedCommand = command;
- if (command._tag === "StandardCommand") {
- const fd3 = command.options.additionalFds?.fd3;
- if (fd3?.type === "input" && fd3.stream) {
- bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
+ Effect.scoped(
+ Effect.gen(function* () {
+ let spawnedCommand: ChildProcess.Command | undefined;
+ let bootstrapJson = "";
+ let readyCount = 0;
+ const ready = yield* Deferred.make<void>();
+ const exited = yield* Queue.unbounded<void>();
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) =>
+ Effect.gen(function* () {
+ spawnedCommand = command;
+ if (command._tag === "StandardCommand") {
+ const fd3 = command.options.additionalFds?.fd3;
+ if (fd3?.type === "input" && fd3.stream) {
+ bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
+ }
}
- }
- return makeProcess({
- exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
- });
- }),
- ),
- );
-
- const managerLayer = makeManagerLayer({
- config: {
- ...baseConfig,
- bootstrap: configWithObservability,
- },
- spawnerLayer,
- desktopWindow: {
- handleBackendReady: Effect.sync(() => {
+ return makeProcess({
+ exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ });
+ }),
+ ),
+ );
+
+ const instance = yield* makeTestInstance({
+ config: {
+ ...baseConfig,
+ bootstrap: configWithObservability,
+ },
+ spawnerLayer,
+ onReady: Effect.sync(() => {
readyCount += 1;
- }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
- },
- backendOutputLog: {
- writeSessionBoundary: ({ phase }) =>
- phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
- },
- });
-
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- yield* manager.start;
+ }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
+ backendOutputLog: {
+ writeSessionBoundary: ({ phase }) =>
+ phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
+ },
+ });
+
+ yield* instance.start;
yield* Queue.take(exited);
assert.equal(readyCount, 1);
@@ -235,292 +216,52 @@ describe("DesktopBackendManager", () => {
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
- }).pipe(Effect.provide(managerLayer));
- }),
- );
-
- it.effect("preserves the readiness timeout cause and process context", () =>
- Effect.gen(function* () {
- const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
- const layer = Layer.merge(
- TestClock.layer(),
- httpClientLayer((request) =>
- Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
- ),
- );
-
- yield* Effect.gen(function* () {
- const readiness = yield* DesktopBackendManager.waitForHttpReady({
- executablePath: baseConfig.executablePath,
- entryPath: baseConfig.entryPath,
- cwd: baseConfig.cwd,
- httpBaseUrl: baseConfig.httpBaseUrl,
- timeout: Duration.millis(50),
- }).pipe(Effect.flip, Effect.forkChild);
-
- const request = yield* Deferred.await(requested);
- assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
-
- yield* TestClock.adjust(Duration.millis(50));
- const error = yield* Fiber.join(readiness);
-
- assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
- assert.equal(error.timeoutMs, 50);
- assert.isTrue(Cause.isTimeoutError(error.cause));
- assert.equal(
- error.message,
- "Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
- );
- }).pipe(Effect.provide(layer));
- }),
- );
-
- it.effect("reports bootstrap encoding failures with stable process context", () =>
- Effect.gen(function* () {
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
- );
- const error = yield* DesktopBackendManager.runBackendProcess({
- ...baseConfig,
- bootstrap: {
- ...baseConfig.bootstrap,
- port: 0,
- },
- }).pipe(
- Effect.flip,
- Effect.scoped,
- Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
- );
-
- if (error._tag !== "BackendProcessBootstrapEncodeError") {
- return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
- }
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.isDefined(error.cause);
- assert.equal(
- error.message,
- "Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
- );
- assert.isTrue(isBackendProcessError(error));
- }),
- );
-
- it.effect("preserves spawn failures without deriving their message from the cause", () =>
- Effect.gen(function* () {
- const spawnCause = PlatformError.systemError({
- _tag: "PermissionDenied",
- module: "ChildProcessSpawner",
- method: "spawn",
- pathOrDescriptor: baseConfig.executablePath,
- description: "low-level detail that must not become the public message",
- });
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
- );
- const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
- Effect.flip,
- Effect.scoped,
- Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
- );
-
- if (error._tag !== "BackendProcessSpawnError") {
- return assert.fail(`Expected backend spawn error, received ${error._tag}`);
- }
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.strictEqual(error.cause, spawnCause);
- assert.equal(
- error.message,
- "Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
- );
- assert.notInclude(error.message, spawnCause.message);
- assert.isTrue(isBackendProcessError(error));
- }),
- );
-
- it.effect("preserves exit-status failures without copying their detail into the message", () =>
- Effect.gen(function* () {
- const exitCause = PlatformError.systemError({
- _tag: "PermissionDenied",
- module: "ChildProcess",
- method: "exitCode",
- description: "exit-status-secret-sentinel",
- });
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.succeed(
- makeProcess({
- exitCode: Effect.fail(exitCause),
- }),
- ),
- ),
- );
- const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
- Effect.flip,
- Effect.scoped,
- Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
- );
-
- if (error._tag !== "BackendProcessExitStatusError") {
- return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
- }
- assert.equal(error.pid, 123);
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.strictEqual(error.cause, exitCause);
- assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
- assert.notInclude(error.message, "exit-status-secret-sentinel");
- assert.isTrue(isBackendProcessError(error));
- }),
- );
-
- it.effect("reports output stream failures with process and stream context", () =>
- Effect.gen(function* () {
- const outputCause = PlatformError.systemError({
- _tag: "BadResource",
- module: "ChildProcess",
- method: "stdout",
- description: "output-stream-secret-sentinel",
- });
- const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.succeed(
- makeProcess({
- stdout: Stream.fail(outputCause),
- exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
- }),
- ),
- ),
- );
-
- const exit = yield* DesktopBackendManager.runBackendProcess({
- ...baseConfig,
- onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
- }).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
- const error = yield* Deferred.await(reported);
-
- assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
- if (error._tag !== "BackendProcessOutputReadError") {
- return assert.fail(`Expected output read error, received ${error._tag}`);
- }
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.equal(error.pid, 123);
- assert.equal(error.streamName, "stdout");
- assert.strictEqual(error.cause, outputCause);
- assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
- assert.notInclude(error.message, "output-stream-secret-sentinel");
- }),
+ }),
+ ),
);
- it.effect("reports output handler failures separately from stream read failures", () =>
- Effect.gen(function* () {
- const chunk = new TextEncoder().encode("backend output");
- const outputCause = new Error("output-handler-secret-sentinel");
- const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.succeed(
- makeProcess({
- stdout: Stream.make(chunk),
- exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
- }),
+ it.effect("retries HTTP readiness before reporting the backend ready", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const requestUrls: Array<string> = [];
+ const statuses = [503, 200];
+ let readyCount = 0;
+ const firstRequest = yield* Deferred.make<void>();
+ const ready = yield* Deferred.make<void>();
+ const exited = yield* Queue.unbounded<void>();
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.succeed(
+ makeProcess({
+ exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ }),
+ ),
),
- ),
- );
-
- const exit = yield* DesktopBackendManager.runBackendProcess({
- ...baseConfig,
- onOutput: () => Effect.fail(outputCause),
- onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
- }).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
- const error = yield* Deferred.await(reported);
-
- assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
- if (error._tag !== "BackendProcessOutputHandlingError") {
- return assert.fail(`Expected output handling error, received ${error._tag}`);
- }
- assert.equal(error.executablePath, "/electron");
- assert.equal(error.entryPath, "/server/bin.mjs");
- assert.equal(error.cwd, "/server");
- assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
- assert.equal(error.pid, 123);
- assert.equal(error.streamName, "stdout");
- assert.equal(error.chunkByteLength, chunk.byteLength);
- assert.strictEqual(error.cause, outputCause);
- assert.equal(
- error.message,
- `Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
- );
- assert.notInclude(error.message, "output-handler-secret-sentinel");
- }),
- );
+ );
- it.effect("retries HTTP readiness before reporting the backend ready", () =>
- Effect.gen(function* () {
- const requestUrls: Array<string> = [];
- const statuses = [503, 200];
- let readyCount = 0;
- const firstRequest = yield* Deferred.make<void>();
- const ready = yield* Deferred.make<void>();
- const exited = yield* Queue.unbounded<void>();
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.succeed(
- makeProcess({
- exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ httpClientLayer: httpClientLayer((request) =>
+ Effect.gen(function* () {
+ const status = statuses.shift();
+ assert.isDefined(status);
+ requestUrls.push(request.url);
+ yield* Deferred.succeed(firstRequest, void 0);
+ return responseForRequest(request, status);
}),
),
- ),
- );
-
- const managerLayer = makeManagerLayer({
- spawnerLayer,
- httpClientLayer: httpClientLayer((request) =>
- Effect.gen(function* () {
- const status = statuses.shift();
- assert.isDefined(status);
- requestUrls.push(request.url);
- yield* Deferred.succeed(firstRequest, void 0);
- return responseForRequest(request, status);
- }),
- ),
- desktopWindow: {
- handleBackendReady: Effect.sync(() => {
+ onReady: Effect.sync(() => {
readyCount += 1;
- }).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
- },
- backendOutputLog: {
- writeSessionBoundary: ({ phase }) =>
- phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
- },
- });
-
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- yield* manager.start;
+ }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
+ backendOutputLog: {
+ writeSessionBoundary: ({ phase }) =>
+ phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
+ },
+ });
+
+ yield* instance.start;
yield* Deferred.await(firstRequest);
assert.equal(readyCount, 0);
@@ -534,106 +275,136 @@ describe("DesktopBackendManager", () => {
"http://127.0.0.1:3773/.well-known/t3/environment",
"http://127.0.0.1:3773/.well-known/t3/environment",
]);
- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
- }),
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
);
it.effect("starts the configured backend and closes the scoped process on stop", () =>
- Effect.gen(function* () {
- let startCount = 0;
- let closedCount = 0;
- const closed = yield* Deferred.make<void>();
- const startedPids = yield* Queue.unbounded<number>();
- const ready = yield* Deferred.make<void>();
- const backendReady = yield* Ref.make(false);
- const quitting = yield* Ref.make(false);
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.gen(function* () {
- const scope = yield* Scope.Scope;
- startCount += 1;
- yield* Queue.offer(startedPids, 123);
- const close = Effect.sync(() => {
- closedCount += 1;
- }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
-
- yield* Scope.addFinalizer(scope, close);
-
- return makeProcess({
- exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
- kill: () => close,
- });
- }),
- ),
- );
-
- const managerLayer = makeManagerLayer({
- spawnerLayer,
- desktopState: {
- backendReady,
- quitting,
- },
- desktopWindow: {
- handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
- },
- });
-
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- assert.isTrue(Option.isNone(yield* manager.currentConfig));
-
- yield* manager.start;
+ Effect.scoped(
+ Effect.gen(function* () {
+ let startCount = 0;
+ let closedCount = 0;
+ const closed = yield* Deferred.make<void>();
+ const startedPids = yield* Queue.unbounded<number>();
+ const ready = yield* Deferred.make<void>();
+ const backendReadyFlag = yield* Ref.make(false);
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.gen(function* () {
+ const scope = yield* Scope.Scope;
+ startCount += 1;
+ yield* Queue.offer(startedPids, 123);
+ const close = Effect.sync(() => {
+ closedCount += 1;
+ }).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
+
+ yield* Scope.addFinalizer(scope, close);
+
+ return makeProcess({
+ exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ kill: () => close,
+ });
+ }),
+ ),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ onReady: Ref.set(backendReadyFlag, true).pipe(
+ Effect.andThen(Deferred.succeed(ready, void 0)),
+ Effect.asVoid,
+ ),
+ onShutdown: Ref.set(backendReadyFlag, false),
+ });
+ assert.isTrue(Option.isNone(yield* instance.currentConfig));
+
+ yield* instance.start;
assert.equal(yield* Queue.take(startedPids), 123);
yield* Deferred.await(ready);
- assert.isTrue(yield* Ref.get(backendReady));
- assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
+ assert.isTrue(yield* Ref.get(backendReadyFlag));
+ assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
- const runningSnapshot = yield* manager.snapshot;
+ const runningSnapshot = yield* instance.snapshot;
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
- yield* manager.stop();
+ yield* instance.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
- const stoppedSnapshot = yield* manager.snapshot;
- assert.isFalse(yield* Ref.get(backendReady));
+ const stoppedSnapshot = yield* instance.snapshot;
+ assert.isFalse(yield* Ref.get(backendReadyFlag));
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
- }).pipe(Effect.provide(managerLayer));
- }),
+ }),
+ ),
);
- it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
- Effect.gen(function* () {
- const starts = yield* Queue.unbounded<number>();
- let startCount = 0;
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.sync(() => {
- startCount += 1;
- return makeProcess({
- exitCode: Queue.offer(starts, startCount).pipe(
- Effect.as(ChildProcessSpawner.ExitCode(1)),
- ),
- });
+ it.effect("does not notify shutdown before the first start has prior state", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let shutdownCount = 0;
+ const closed = yield* Deferred.make<void>();
+ const startedPids = yield* Queue.unbounded<number>();
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.gen(function* () {
+ yield* Queue.offer(startedPids, 123);
+ const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
+ return makeProcess({
+ exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ kill: () => close,
+ });
+ }),
+ ),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ httpClientLayer: httpClientLayer(() => Effect.never),
+ onShutdown: Effect.sync(() => {
+ shutdownCount += 1;
}),
- ),
- );
+ });
- const managerLayer = makeManagerLayer({
- spawnerLayer,
- httpClientLayer: httpClientLayer(() => Effect.never),
- });
+ yield* instance.start;
+ assert.equal(yield* Queue.take(startedPids), 123);
+ assert.equal(shutdownCount, 0);
+ }),
+ ),
+ );
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- yield* manager.start;
+ it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const starts = yield* Queue.unbounded<number>();
+ let startCount = 0;
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.sync(() => {
+ startCount += 1;
+ return makeProcess({
+ exitCode: Queue.offer(starts, startCount).pipe(
+ Effect.as(ChildProcessSpawner.ExitCode(1)),
+ ),
+ });
+ }),
+ ),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ httpClientLayer: httpClientLayer(() => Effect.never),
+ });
+
+ yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
@@ -646,107 +417,300 @@ describe("DesktopBackendManager", () => {
assert.equal(yield* Queue.size(starts), 0);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(yield* Queue.take(starts), 3);
- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
- }),
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
+ );
+
+ it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let shutdownCount = 0;
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ config: {
+ ...baseConfig,
+ preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
+ },
+ onShutdown: Effect.sync(() => {
+ shutdownCount += 1;
+ }),
+ });
+
+ yield* instance.start;
+ assert.equal(shutdownCount, 0);
+
+ yield* TestClock.adjust(Duration.millis(500));
+ assert.equal(shutdownCount, 0);
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
+ );
+
+ it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const failures: string[] = [];
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ config: {
+ ...baseConfig,
+ preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
+ },
+ onPreflightFailed: (failure) =>
+ Effect.sync(() => {
+ failures.push(failure.reason);
+ }).pipe(Effect.as(false)),
+ });
+
+ yield* instance.start;
+ assert.deepEqual(failures, []);
+
+ // Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
+ // the cap, at which point the failure is surfaced exactly once.
+ yield* TestClock.adjust(Duration.millis(500));
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* TestClock.adjust(Duration.seconds(2));
+ yield* TestClock.adjust(Duration.seconds(4));
+ assert.deepEqual(failures, ["Node.js not found"]);
+
+ // Past the cap the loop stops and nothing else is surfaced.
+ yield* TestClock.adjust(Duration.seconds(8));
+ yield* TestClock.adjust(Duration.seconds(30));
+ assert.deepEqual(failures, ["Node.js not found"]);
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
+ );
+
+ it.effect("can be started again after a fatal preflight cap once config recovers", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const failing = yield* Ref.make(true);
+ const starts = yield* Queue.unbounded<number>();
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Queue.offer(starts, 123).pipe(
+ Effect.as(
+ makeProcess({
+ exitCode: Effect.never,
+ }),
+ ),
+ ),
+ ),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ configResolve: Ref.get(failing).pipe(
+ Effect.map((isFailing) =>
+ isFailing
+ ? {
+ ...baseConfig,
+ preflightFailure: Option.some({
+ reason: "Node.js not found",
+ fatal: true,
+ }),
+ }
+ : baseConfig,
+ ),
+ ),
+ });
+
+ yield* instance.start;
+ yield* TestClock.adjust(Duration.millis(500));
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* TestClock.adjust(Duration.seconds(2));
+ yield* TestClock.adjust(Duration.seconds(4));
+ yield* TestClock.adjust(Duration.seconds(8));
+
+ const parked = yield* instance.snapshot;
+ assert.equal(parked.desiredRunning, false);
+ assert.equal(parked.ready, false);
+ assert.isTrue(Option.isNone(parked.activePid));
+ assert.equal(parked.restartScheduled, false);
+ assert.equal(yield* Queue.size(starts), 0);
+
+ yield* Ref.set(failing, false);
+ yield* instance.start;
+
+ assert.equal(yield* Queue.take(starts), 123);
+ const running = yield* instance.snapshot;
+ assert.equal(running.desiredRunning, true);
+ assert.deepEqual(running.activePid, Option.some(123));
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
+ );
+
+ it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const failures: string[] = [];
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ config: {
+ ...baseConfig,
+ preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
+ },
+ onPreflightFailed: (failure) =>
+ Effect.sync(() => {
+ failures.push(failure.reason);
+ }).pipe(Effect.as(false)),
+ });
+
+ yield* instance.start;
+ // Well beyond the fatal cap's worth of time: a transient failure must
+ // keep retrying (self-heal) and never surface.
+ yield* TestClock.adjust(Duration.minutes(2));
+ assert.deepEqual(failures, []);
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
+ );
+
+ it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const failures: string[] = [];
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
+ );
+
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ config: {
+ ...baseConfig,
+ preflightFailure: Option.some({
+ reason: "WSL toolchain probe timed out",
+ fatal: false,
+ retryLimit: 3,
+ }),
+ },
+ onPreflightFailed: (failure) =>
+ Effect.sync(() => {
+ failures.push(failure.reason);
+ }).pipe(Effect.as(false)),
+ });
+
+ yield* instance.start;
+ yield* TestClock.adjust(Duration.millis(500));
+ assert.deepEqual(failures, []);
+
+ yield* TestClock.adjust(Duration.seconds(1));
+ assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
);
it.effect("cancels a scheduled restart when start is requested manually", () =>
- Effect.gen(function* () {
- const starts = yield* Queue.unbounded<number>();
- const secondClosed = yield* Deferred.make<void>();
- let startCount = 0;
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.gen(function* () {
- startCount += 1;
- yield* Queue.offer(starts, startCount);
-
- if (startCount === 1) {
+ Effect.scoped(
+ Effect.gen(function* () {
+ const starts = yield* Queue.unbounded<number>();
+ const secondClosed = yield* Deferred.make<void>();
+ let startCount = 0;
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.gen(function* () {
+ startCount += 1;
+ yield* Queue.offer(starts, startCount);
+
+ if (startCount === 1) {
+ return makeProcess({
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
+ });
+ }
+
+ const scope = yield* Scope.Scope;
+ const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
+ yield* Scope.addFinalizer(scope, close);
return makeProcess({
- exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
+ exitCode: Deferred.await(secondClosed).pipe(
+ Effect.as(ChildProcessSpawner.ExitCode(0)),
+ ),
+ kill: () => close,
});
- }
-
- const scope = yield* Scope.Scope;
- const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
- yield* Scope.addFinalizer(scope, close);
- return makeProcess({
- exitCode: Deferred.await(secondClosed).pipe(
- Effect.as(ChildProcessSpawner.ExitCode(0)),
- ),
- kill: () => close,
- });
- }),
- ),
- );
+ }),
+ ),
+ );
- const managerLayer = makeManagerLayer({
- spawnerLayer,
- httpClientLayer: httpClientLayer(() => Effect.never),
- });
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ httpClientLayer: httpClientLayer(() => Effect.never),
+ });
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- yield* manager.start;
+ yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
- yield* manager.start;
+ yield* instance.start;
assert.equal(yield* Queue.take(starts), 2);
- yield* manager.stop();
+ yield* instance.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
- }),
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
);
it.effect("does not restart after stop cancels a scheduled restart", () =>
- Effect.gen(function* () {
- const starts = yield* Queue.unbounded<number>();
- let startCount = 0;
-
- const spawnerLayer = Layer.succeed(
- ChildProcessSpawner.ChildProcessSpawner,
- ChildProcessSpawner.make(() =>
- Effect.sync(() => {
- startCount += 1;
- return makeProcess({
- exitCode: Queue.offer(starts, startCount).pipe(
- Effect.as(ChildProcessSpawner.ExitCode(1)),
- ),
- });
- }),
- ),
- );
+ Effect.scoped(
+ Effect.gen(function* () {
+ const starts = yield* Queue.unbounded<number>();
+ let startCount = 0;
+
+ const spawnerLayer = Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.sync(() => {
+ startCount += 1;
+ return makeProcess({
+ exitCode: Queue.offer(starts, startCount).pipe(
+ Effect.as(ChildProcessSpawner.ExitCode(1)),
+ ),
+ });
+ }),
+ ),
+ );
- const managerLayer = makeManagerLayer({
- spawnerLayer,
- httpClientLayer: httpClientLayer(() => Effect.never),
- });
+ const instance = yield* makeTestInstance({
+ spawnerLayer,
+ httpClientLayer: httpClientLayer(() => Effect.never),
+ });
- yield* Effect.gen(function* () {
- const manager = yield* DesktopBackendManager.DesktopBackendManager;
- yield* manager.start;
+ yield* instance.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
- restartScheduled = (yield* manager.snapshot).restartScheduled;
+ restartScheduled = (yield* instance.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
- yield* manager.stop();
+ yield* instance.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
- assert.equal((yield* manager.snapshot).desiredRunning, false);
- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
- }),
+ assert.equal((yield* instance.snapshot).desiredRunning, false);
+ }).pipe(Effect.provide(TestClock.layer())),
+ ),
);
});
diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts
index d92f62d16..e3a4de661 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.ts
@@ -1,35 +1,63 @@
+// Per-instance backend factory. Replaces the legacy singleton
+// `DesktopBackendManager` Context.Service: each call to
+// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
+// its own state Ref, mutex, restart loop, and active child process. The
+// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
+// methods that operate on that single backend.
+//
+// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
+// backend it wants to run. Today that's the Windows primary; follow-up
+// commits add a second call for the WSL instance.
+//
+// Singleton couplings that the legacy service held inline are now
+// parameterized via the spec:
+// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
+// so each instance can resolve its own start config — the primary wires
+// `configuration.resolvePrimary`, the WSL orchestrator wires a
+// `configuration.resolveWsl({ port, distro })` closure.
+// - onReady / onShutdown drive UI side effects (window auto-open,
+// readiness latch) only for instances that want them — the primary's
+// spec passes the window's handleBackendReady/handleBackendNotReady,
+// other pool instances pass nothing.
+// - log writes go through a per-instance writer that the factory
+// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
+// so each instance lands in its own rotating file.
+
+import * as Brand from "effect/Brand";
import * as Cause from "effect/Cause";
-import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
-import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
+import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
-import * as HttpClient from "effect/unstable/http/HttpClient";
-import * as ChildProcess from "effect/unstable/process/ChildProcess";
-import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
+import { HttpClient } from "effect/unstable/http";
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
+import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
-import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
-import * as DesktopState from "../app/DesktopState.ts";
-import * as DesktopWindow from "../window/DesktopWindow.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
+// After this many consecutive fatal preflight failures, stop the silent
+// restart loop and surface the reason via onPreflightFailed. Transient
+// failures may instead provide their own larger retryLimit when they should
+// self-heal for a while but must not leave the app connecting forever.
+const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
@@ -42,145 +70,91 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
-export interface BackendProcessContext {
+export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
+
+export interface DesktopBackendStartConfig {
readonly executablePath: string;
+ readonly args: ReadonlyArray<string>;
readonly entryPath: string;
readonly cwd: string;
- readonly httpBaseUrl: URL;
-}
-
-export interface DesktopBackendStartConfig extends BackendProcessContext {
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<PreflightFailure>;
+ // Present for a WSL run after the configured/default distro has been
+ // resolved to the concrete distro passed to wsl.exe.
+ readonly runningDistro?: string;
+}
+
+// A preflight failure records whether it is fatal. Transient failures (WSL
+// cold-starting, wslpath while the VM boots) keep retrying so the backend can
+// self-heal; fatal ones (no node, wrong version, missing build tools) are
+// surfaced via onPreflightFailed and stop the restart loop after
+// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
+export interface PreflightFailure {
+ readonly reason: string;
+ readonly fatal: boolean;
+ readonly retryLimit?: number;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
+ readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
-const backendProcessContextSchema = {
- executablePath: Schema.String,
- entryPath: Schema.String,
- cwd: Schema.String,
- httpBaseUrl: Schema.URL,
-};
-
-export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
- "BackendReadinessTimeoutError",
+export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
+ "BackendTimeoutError",
{
- ...backendProcessContextSchema,
- readinessUrl: Schema.URL,
- timeoutMs: Schema.Number,
- cause: Schema.Defect(),
+ url: Schema.instanceOf(URL),
},
) {
- override get message(): string {
- return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
+ override get message() {
+ return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
-export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
+class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
- ...backendProcessContextSchema,
+ entryPath: Schema.String,
cause: Schema.Defect(),
},
) {
- override get message(): string {
+ override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
-export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
+class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
- ...backendProcessContextSchema,
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
- }
-}
-
-export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
- "BackendProcessOutputReadError",
- {
- ...backendProcessContextSchema,
- pid: Schema.Number,
- streamName: Schema.Literals(["stdout", "stderr"]),
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
- }
-}
-
-export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
- "BackendProcessOutputHandlingError",
- {
- ...backendProcessContextSchema,
- pid: Schema.Number,
- streamName: Schema.Literals(["stdout", "stderr"]),
- chunkByteLength: Schema.Number,
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
- }
-}
-
-export type BackendProcessOutputError =
- | BackendProcessOutputReadError
- | BackendProcessOutputHandlingError;
-
-export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
- "BackendProcessExitStatusError",
- {
- ...backendProcessContextSchema,
- pid: Schema.Number,
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return `Failed to read the exit status of desktop backend process ${this.pid}.`;
- }
-}
-
-export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
- "DesktopBackendRestartError",
- {
- reason: Schema.String,
- delayMs: Schema.Number,
+ executablePath: Schema.String,
cause: Schema.Defect(),
},
) {
- override get message(): string {
- return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
+ override get message() {
+ return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
}
}
-export const BackendProcessError = Schema.Union([
- BackendProcessBootstrapEncodeError,
- BackendProcessSpawnError,
- BackendProcessExitStatusError,
-]);
-export type BackendProcessError = typeof BackendProcessError.Type;
+type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
- readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
+ readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
- ) => Effect.Effect<void, Error>;
- readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
+ ) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -191,18 +165,60 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
-export class DesktopBackendManager extends Context.Service<
- DesktopBackendManager,
- {
- readonly start: Effect.Effect<void>;
- readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
- readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
- readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
- }
->()("@t3tools/desktop/backend/DesktopBackendManager") {}
+// Opaque identifier for one backend process inside the pool. Today only
+// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
+// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
+// these map 1:1 with environment ids on the frontend; keeping them
+// desktop-local for now avoids leaking the contracts dependency.
+export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
+export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
+
+export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
+);
+
+// One pooled backend instance. Same lifecycle surface as the legacy
+// `DesktopBackendManagerShape`; the id and label give the pool registry
+// + UI something to route on.
+export interface DesktopBackendInstance {
+ readonly id: BackendInstanceId;
+ readonly label: Effect.Effect<string>;
+ readonly start: Effect.Effect<void>;
+ readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
+ readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
+ readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
+ // Polls desiredRunning + the instance's own ready flag 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>;
+}
-const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
- DesktopObservability.makeComponentLogger("desktop-backend-manager");
+// Spec describing one backend instance to spawn. The configResolve
+// effect is awaited each time the instance is (re)started so live
+// settings changes are picked up on the next start cycle. onReady and
+// onShutdown let the primary instance trigger UI side effects (window
+// open, global readiness flag) without coupling the factory to those
+// concerns; other instances pass them as undefined.
+export interface BackendInstanceSpec {
+ readonly id: BackendInstanceId;
+ readonly label: Effect.Effect<string>;
+ // configResolve can now fail with PlatformError because the
+ // bootstrap-token closure inside DesktopBackendConfiguration uses
+ // crypto.randomBytes (Effect 4 beta.73 migration).
+ readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
+ // Receives the *resolved* httpBaseUrl of the run that just became
+ // ready. The window service uses this to decide what URL to load
+ // (the WSL backend reports its distro IP, the Windows backend reports
+ // 127.0.0.1). Splitting this off from configResolve avoids races
+ // between "fired onReady" and "currentConfig already advanced".
+ readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
+ readonly onShutdown?: () => Effect.Effect<void>;
+ // Fired once when a fatal or bounded preflight failure has exhausted its
+ // retries. Returns true when the callback changed configuration and the
+ // manager should resolve once more; false stops the failed instance.
+ readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
+}
interface ActiveBackendRun {
readonly id: number;
@@ -217,6 +233,9 @@ interface BackendManagerState {
readonly config: Option.Option<DesktopBackendStartConfig>;
readonly active: Option.Option<ActiveBackendRun>;
readonly restartAttempt: number;
+ // Consecutive bounded/fatal preflight failures, reset on a clean or
+ // unbounded-transient preflight. restartAttempt counts all restarts.
+ readonly preflightFailureAttempt: number;
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
readonly nextRunId: number;
}
@@ -227,6 +246,7 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
+ preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -259,198 +279,135 @@ const closeRun = (
).pipe(Effect.ignore);
};
-export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
- options: BackendProcessContext & { readonly timeout: Duration.Duration },
-): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
- const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
- const client = (yield* HttpClient.HttpClient).pipe(
- HttpClient.filterStatusOk,
- HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
- HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
- );
+const waitForHttpReady = (
+ baseUrl: URL,
+ timeout: Duration.Duration,
+): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
+ const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
+ return waitForHttpReadyShared({
+ baseUrl: baseUrl.href,
+ path: BACKEND_READINESS_PATH,
+ timeoutMs: Duration.toMillis(timeout),
+ intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
+ probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
+ makeError: () => new BackendTimeoutError({ url: readinessUrl }),
+ });
+};
- yield* client.get(readinessUrl).pipe(
- Effect.asVoid,
- Effect.timeout(options.timeout),
- Effect.mapError(
- (cause) =>
- new BackendReadinessTimeoutError({
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- readinessUrl,
- timeoutMs: Duration.toMillis(options.timeout),
- cause,
- }),
- ),
- );
-});
+function describeProcessExit(
+ result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
+): BackendProcessExit {
+ if (Result.isSuccess(result)) {
+ return {
+ code: Option.some(result.success),
+ reason: `code=${result.success}`,
+ result,
+ };
+ }
+
+ return {
+ code: Option.none(),
+ reason: result.failure.message,
+ result,
+ };
+}
function drainBackendOutput(
- context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
- onOutput: (
- streamName: BackendProcessOutputStream,
- chunk: Uint8Array,
- ) => Effect.Effect<void, Error>,
- onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
+ onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
- Stream.mapError(
- (cause) =>
- new BackendProcessOutputReadError({
- ...context,
- streamName,
- cause,
- }),
- ),
- Stream.runForEach((chunk) =>
- onOutput(streamName, chunk).pipe(
- Effect.mapError(
- (cause) =>
- new BackendProcessOutputHandlingError({
- ...context,
- streamName,
- chunkByteLength: chunk.byteLength,
- cause,
- }),
- ),
- ),
- ),
- Effect.catchTags({
- BackendProcessOutputReadError: onOutputFailure,
- BackendProcessOutputHandlingError: onOutputFailure,
- }),
+ Stream.runForEach((chunk) => onOutput(streamName, chunk)),
+ Effect.ignore,
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
-export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
+const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
- (cause) =>
- new BackendProcessBootstrapEncodeError({
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- cause,
- }),
+ (cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, 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).pipe(
- Effect.mapError(
- (cause) =>
- new BackendProcessSpawnError({
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- cause,
- }),
- ),
- );
+ const handle = yield* spawner
+ .spawn(command)
+ .pipe(
+ Effect.mapError(
+ (cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
+ ),
+ );
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
- const outputContext = {
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- pid: Number(handle.pid),
- };
- const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
- yield* drainBackendOutput(
- outputContext,
- "stdout",
- handle.stdout,
- onOutput,
- onOutputFailure,
- ).pipe(Effect.forkScoped);
- yield* drainBackendOutput(
- outputContext,
- "stderr",
- handle.stderr,
- onOutput,
- onOutputFailure,
- ).pipe(Effect.forkScoped);
+ yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
+ yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
}
- yield* waitForHttpReady({
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
- }).pipe(
+ yield* waitForHttpReady(
+ options.httpBaseUrl,
+ options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
+ ).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
- Effect.catchTags({
- BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
- }),
+ Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.forkScoped,
);
- const exitCode = yield* handle.exitCode.pipe(
- Effect.mapError(
- (cause) =>
- new BackendProcessExitStatusError({
- executablePath: options.executablePath,
- entryPath: options.entryPath,
- cwd: options.cwd,
- httpBaseUrl: options.httpBaseUrl,
- pid: Number(handle.pid),
- cause,
- }),
- ),
- );
- return {
- code: Option.some(exitCode),
- reason: `code=${exitCode}`,
- } satisfies BackendProcessExit;
+ return describeProcessExit(yield* Effect.result(handle.exitCode));
});
-export const make = Effect.gen(function* () {
+// Factory for one pooled backend instance. The returned instance owns
+// its own state Ref, mutex, restart loop, and active child process;
+// nothing is shared between instances created from separate
+// makeBackendInstance calls. The instance shuts down automatically when
+// the calling scope closes (typically the application scope).
+export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
+ spec: BackendInstanceSpec,
+): Effect.fn.Return<
+ DesktopBackendInstance,
+ never,
+ | FileSystem.FileSystem
+ | ChildProcessSpawner.ChildProcessSpawner
+ | HttpClient.HttpClient
+ | DesktopObservability.DesktopBackendOutputLogFactory
+ | Scope.Scope
+> {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
- const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
- const desktopState = yield* DesktopState.DesktopState;
- const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
+ const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
const mutex = yield* Semaphore.make(1);
+ const { logWarning: logInstanceWarning, logError: logInstanceError } =
+ DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
+
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
Ref.update(state, withActiveRun(runId, f));
@@ -490,11 +447,16 @@ export const make = Effect.gen(function* () {
return;
}
- yield* Ref.set(desktopState.backendReady, false);
- const config = yield* configuration.resolve.pipe(
+ if (current.ready) {
+ yield* spec.onShutdown?.() ?? Effect.void;
+ yield* Ref.update(state, (latest) =>
+ latest.ready ? { ...latest, ready: false } : latest,
+ );
+ }
+ const config = yield* spec.configResolve.pipe(
Effect.tapError((error) =>
- logBackendManagerError("failed to generate desktop backend configuration", {
- cause: error,
+ logInstanceError("failed to generate desktop backend configuration", {
+ cause: error.message,
}),
),
Effect.option,
@@ -506,14 +468,84 @@ export const make = Effect.gen(function* () {
.exists(config.value.entryPath)
.pipe(Effect.orElseSucceed(() => false));
+ const resetFatalPreflightCounter =
+ !current.desiredRunning && current.preflightFailureAttempt > 0;
yield* cancelRestart;
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
+ preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
}));
+ const preflightFailure = config.value.preflightFailure;
+ if (Option.isSome(preflightFailure)) {
+ const { reason, fatal, retryLimit } = preflightFailure.value;
+ if (!fatal && retryLimit === undefined) {
+ // Transient (WSL cold-starting, wslpath while the VM boots). Keep
+ // retrying so the backend self-heals once WSL is ready. Reset a
+ // prior bounded/fatal streak because this is a different failure.
+ yield* Ref.update(state, (latest) =>
+ latest.preflightFailureAttempt === 0
+ ? latest
+ : { ...latest, preflightFailureAttempt: 0 },
+ );
+ yield* scheduleRestart(reason);
+ return;
+ }
+ const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
+ const attempt = yield* Ref.modify(state, (latest) => {
+ const next = latest.preflightFailureAttempt + 1;
+ return [next, { ...latest, preflightFailureAttempt: next }] as const;
+ });
+ if (attempt > attemptLimit) {
+ // We already surfaced and asked for the Windows fallback, yet we're
+ // still resolving the WSL primary — the fallback didn't take (e.g.
+ // the settings write failed). Stop rather than loop forever.
+ yield* logInstanceError("backend preflight still failing after fallback; stopping", {
+ reason,
+ attempt,
+ });
+ yield* Ref.update(state, (latest) => ({
+ ...latest,
+ desiredRunning: false,
+ ready: false,
+ }));
+ return;
+ }
+ if (attempt === attemptLimit) {
+ // Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
+ // on the primary, shows a dialog and persists Windows mode), then
+ // schedule one more restart so the next resolve picks up the Windows
+ // primary and a window can open.
+ yield* logInstanceError(
+ "backend preflight failed repeatedly; surfacing and falling back",
+ { reason, attempt },
+ );
+ const shouldRestart = yield* (
+ spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
+ );
+ if (shouldRestart) {
+ yield* scheduleRestart(reason);
+ } else {
+ yield* Ref.update(state, (latest) => ({
+ ...latest,
+ desiredRunning: false,
+ ready: false,
+ }));
+ }
+ return;
+ }
+ yield* scheduleRestart(reason);
+ return;
+ }
+ // Clean preflight — reset the fatal counter so a later failure gets a
+ // fresh allowance.
+ yield* Ref.update(state, (latest) =>
+ latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
+ );
+
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
return;
@@ -534,7 +566,7 @@ export const make = Effect.gen(function* () {
},
]);
- const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
+ const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
@@ -586,7 +618,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid.value} ${reason}`,
});
}
- yield* Ref.set(desktopState.backendReady, false);
+ yield* spec.onShutdown?.() ?? Effect.void;
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -598,7 +630,7 @@ export const make = Effect.gen(function* () {
const program = runBackendProcess({
...config.value,
- onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
+ onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
@@ -608,7 +640,7 @@ export const make = Effect.gen(function* () {
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
- onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
+ onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
if (activeRun?.id !== runId) {
@@ -628,30 +660,19 @@ export const make = Effect.gen(function* () {
return;
}
- yield* Ref.set(desktopState.backendReady, true);
- yield* desktopWindow.handleBackendReady.pipe(
- Effect.catch((error) =>
- logBackendManagerError("failed to open main window after backend readiness", {
- cause: error,
- }),
- ),
- );
+ yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
}),
onReadinessFailure: (error) =>
- logBackendManagerWarning("backend readiness check failed during bootstrap", {
- error,
+ logInstanceWarning("backend readiness check failed during bootstrap", {
+ error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
- onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
- onFailure: (error) =>
- logBackendManagerError(error.message, { error }).pipe(
- Effect.andThen(finalizeRun(error.message)),
- ),
+ onFailure: (error) => finalizeRun(error.message),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -664,9 +685,9 @@ export const make = Effect.gen(function* () {
}));
}),
),
- ).pipe(Effect.withSpan("desktop.backendManager.start"));
+ ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
- const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
+ const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
reason: string,
) {
const scheduled = yield* Ref.modify(state, (latest) => {
@@ -686,8 +707,8 @@ export const make = Effect.gen(function* () {
yield* Option.match(scheduled, {
onNone: () => Effect.void,
- onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
- yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
+ onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
+ yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
reason,
delayMs: Duration.toMillis(delay),
});
@@ -706,17 +727,11 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
- Effect.catchCause((cause) => {
- if (Cause.hasInterruptsOnly(cause)) {
- return Effect.void;
- }
- const error = new DesktopBackendRestartError({
- reason,
- delayMs: Duration.toMillis(delay),
- cause,
- });
- return logBackendManagerError(error.message, { error });
- }),
+ Effect.catchCause((cause) =>
+ logInstanceError("desktop backend restart fiber failed", {
+ cause: Cause.pretty(cause),
+ }),
+ ),
),
parentScope,
);
@@ -732,7 +747,7 @@ export const make = Effect.gen(function* () {
});
});
- const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
+ const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
@@ -750,7 +765,15 @@ export const make = Effect.gen(function* () {
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
- yield* Ref.set(desktopState.backendReady, false);
+ // Ignore failures from spec.onShutdown so a downstream throw
+ // can't abort the rest of stop(). Ref.modify above already
+ // flipped state to "no active run / no restart fiber", and the
+ // physical cleanup (Fiber.interrupt + closeRun) runs after the
+ // mutex releases. If onShutdown were allowed to propagate, both
+ // would be skipped and the child process + restart fiber would
+ // be orphaned while state claimed nothing was running — the
+ // next start() would then spawn a second backend on top.
+ yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
return result;
}),
);
@@ -765,14 +788,32 @@ export const make = Effect.gen(function* () {
});
});
+ const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
+ Effect.gen(function* () {
+ const current = yield* Ref.get(state);
+ // Return false early if an external `stop()` flipped desiredRunning off
+ // — no point polling for a backend that is being torn down.
+ if (!current.desiredRunning) return { done: true, ready: false };
+ return current.ready ? { done: true, ready: true } : { done: false, ready: false };
+ }).pipe(
+ Effect.repeat({
+ until: (status) => status.done,
+ schedule: Schedule.spaced(Duration.millis(100)),
+ }),
+ Effect.map((status) => status.ready),
+ Effect.timeoutOption(timeout),
+ Effect.map(Option.getOrElse(() => false)),
+ );
+
yield* Effect.addFinalizer(() => stop());
- return DesktopBackendManager.of({
+ return {
+ id: spec.id,
+ label: spec.label,
start,
stop,
currentConfig,
snapshot,
- });
+ waitForReady,
+ } satisfies DesktopBackendInstance;
});
-
-export const layer = Layer.effect(DesktopBackendManager, make);
diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts
new file mode 100644
index 000000000..5e6a3f516
--- /dev/null
+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts
@@ -0,0 +1,137 @@
+import { assert, describe, it } from "@effect/vitest";
+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 Ref from "effect/Ref";
+import { HttpClient } from "effect/unstable/http";
+import { ChildProcessSpawner } from "effect/unstable/process";
+
+import * as DesktopObservability from "../app/DesktopObservability.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as ElectronDialog from "../electron/ElectronDialog.ts";
+import * as DesktopWindow from "../window/DesktopWindow.ts";
+import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
+import * as DesktopBackendPool from "./DesktopBackendPool.ts";
+import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
+
+function makeStubInstance(
+ id: DesktopBackendPool.BackendInstanceId,
+ label: string,
+): DesktopBackendPool.DesktopBackendInstance {
+ const snapshot: DesktopBackendSnapshot = {
+ desiredRunning: false,
+ ready: false,
+ activePid: Option.none(),
+ restartAttempt: 0,
+ restartScheduled: false,
+ };
+ return {
+ id,
+ label: Effect.succeed(label),
+ start: Effect.void,
+ stop: () => Effect.void,
+ currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
+ snapshot: Effect.succeed(snapshot),
+ waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
+ };
+}
+
+function makePoolLayer(
+ labelRef: Ref.Ref<string>,
+): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
+ return DesktopBackendPool.layer.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(
+ FileSystem.layerNoop({}),
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
+ ),
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make(() => Effect.die("unexpected HTTP request")),
+ ),
+ Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
+ forInstance: () =>
+ Effect.succeed({
+ writeSessionBoundary: () => Effect.void,
+ writeOutputChunk: () => Effect.void,
+ } satisfies DesktopObservability.DesktopBackendOutputLogShape),
+ } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
+ Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
+ resolvePrimary: Effect.die("unexpected primary config resolve"),
+ resolvePrimaryLabel: Ref.get(labelRef),
+ resolveWsl: () => Effect.die("unexpected WSL config resolve"),
+ } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
+ DesktopAppSettings.layerTest(),
+ ElectronDialog.layer,
+ Layer.succeed(DesktopWindow.DesktopWindow, {
+ createMain: Effect.die("unexpected window create"),
+ ensureMain: Effect.die("unexpected window ensure"),
+ revealOrCreateMain: Effect.die("unexpected window reveal"),
+ activate: Effect.die("unexpected window activate"),
+ createMainIfBackendReady: Effect.die("unexpected window create"),
+ showConnectingSplash: Effect.void,
+ handleBackendReady: () => Effect.void,
+ handleBackendNotReady: Effect.void,
+ dispatchMenuAction: () => Effect.die("unexpected menu action"),
+ syncAppearance: Effect.void,
+ } satisfies DesktopWindow.DesktopWindow["Service"]),
+ ),
+ ),
+ );
+}
+
+describe("DesktopBackendPool", () => {
+ it.effect("layerTest exposes registered instances by id", () =>
+ Effect.gen(function* () {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
+ const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
+ const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
+ const all = yield* pool.list;
+ const resolvedPrimary = yield* pool.primary;
+
+ assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
+ assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
+ assert.isTrue(Option.isNone(fetchedMissing));
+ assert.lengthOf(all, 2);
+ // First instance becomes primary in layerTest so single-instance
+ // stubs don't have to wire an explicit primary.
+ assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
+ }).pipe(
+ Effect.provide(
+ DesktopBackendPool.layerTest([
+ makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
+ makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
+ ]),
+ ),
+ ),
+ );
+
+ it.effect("layerTest dies when no instances are supplied", () =>
+ Effect.exit(
+ Effect.gen(function* () {
+ yield* DesktopBackendPool.DesktopBackendPool;
+ }).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
+ ).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
+ );
+
+ it.effect("resolves the primary label lazily after pool layer construction", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const labelRef = yield* Ref.make("Windows");
+ const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
+ Effect.provide(makePoolLayer(labelRef)),
+ );
+ const primary = yield* pool.primary;
+
+ yield* Ref.set(labelRef, "WSL (Ubuntu)");
+
+ assert.equal(yield* primary.label, "WSL (Ubuntu)");
+ }),
+ ),
+ );
+});
diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts
new file mode 100644
index 000000000..258f8731f
--- /dev/null
+++ b/apps/desktop/src/backend/DesktopBackendPool.ts
@@ -0,0 +1,470 @@
+// Pool registry for multiple backend processes. This file is the entry
+// point for the concurrent-Windows+WSL-backend feature; see the design
+// notes below before extending it.
+//
+// Current state:
+// - `DesktopBackendManager.ts` exposes a per-instance factory
+// (`makeBackendInstance(spec)`); the pool calls it once for the
+// Windows primary at startup, and `DesktopWslBackend.reconcile`
+// calls it through `pool.register` to bring up the WSL instance
+// when the user enables it.
+// - The primary spec wires `configResolve` to
+// `DesktopBackendConfiguration.resolvePrimary` and the
+// `onReady`/`onShutdown` callbacks to the window service. WSL
+// instances wire `configResolve: configuration.resolveWsl(...)`
+// and skip onReady/onShutdown — the window only follows the primary.
+// - The pool exposes `register(spec)` and `unregister(id)`. Each
+// registered instance gets its own child scope, so unregister can
+// stop it cleanly without tearing down the pool. The primary's id
+// refuses unregister.
+// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
+// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
+// load. IPC surface is `setWslBackendEnabled(boolean)` +
+// `setWslDistro(string | null)`; both persist and then call the
+// orchestrator's reconcile. No swap, no rollback, primary stays up.
+// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
+// pool instance currently registered with bootstrap info. The
+// primary keeps the "primary" id; WSL instances are "wsl:default"
+// or "wsl:<distro>".
+// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
+// it gives the Windows picker — what every existing caller gets,
+// and what non-WSL users see. WSL targets route to the wsl helpers.
+// - Web settings UX: a plain toggle for "WSL backend" plus a distro
+// picker that shows up when the toggle is on. Default-off, so
+// users who never opted in see the same surface as before.
+//
+// Renderer-side wiring (apps/web/src/environments/local/):
+// - reconcileLocalSecondaryEnvironments() runs at app boot and after
+// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
+// skips the primary (which the existing primary/ runtime owns),
+// and for every other entry POSTs the shared bootstrap token to
+// /api/auth/bootstrap/bearer on that backend's URL, fetches the
+// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
+// writes the bearer to the secret store, and opens a connection
+// through the same saved-env path remote envs use.
+// - The desktopLocal marker filters records out of saved-env
+// persistence, so toggling WSL off or switching distros doesn't
+// pollute the user's settings file. The sidebar, CommandPalette,
+// env switcher, and project-id routing all read the saved-env
+// registry, so the WSL backend shows up there without any
+// per-surface changes.
+//
+// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
+// wslDistro="Ubuntu"):
+// - Two backends listening on distinct loopback ports
+// (server.log: 13773 primary, 13774 wsl).
+// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
+// - Distinct environment ids reported by each backend's
+// /.well-known/t3/environment (Windows vs Linux platform).
+// - Renderer completes the bearer-token bootstrap against the WSL
+// backend (POST /api/auth/bootstrap/bearer 200), obtains a
+// ws-token (POST /api/auth/ws-token 200), and holds an
+// ESTABLISHED WebSocket connection to both ports (netstat).
+//
+// Migration history (commits):
+// 1. Reshape `DesktopBackendManager` into an instance factory and route
+// consumers through the pool. Pool held a single instance. (a8fc7845)
+// 2. Drop `DesktopState.backendReady`. The window owns its own
+// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
+// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
+// 4. Add register/unregister to the pool. (a0eaf560)
+// 5. Wire WSL through the pool: settings rename, BackendConfiguration
+// split, DesktopWslBackend orchestrator, new IPC, web compat.
+// (b1622191 + 31ce3add + 627c80cb)
+// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
+// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
+// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
+// 9. Register WSL backend as desktop-local saved env via
+// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
+// 10. CommandPalette enables file-manager picker for desktop-local
+// envs, routes pickFolder by env id. (38e8477a)
+
+import * as Context from "effect/Context";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as Scope from "effect/Scope";
+import * as SynchronizedRef from "effect/SynchronizedRef";
+
+import * as FileSystem from "effect/FileSystem";
+import { HttpClient } from "effect/unstable/http";
+import { ChildProcessSpawner } from "effect/unstable/process";
+
+import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
+import * as DesktopBackendManager from "./DesktopBackendManager.ts";
+import * as DesktopObservability from "../app/DesktopObservability.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as DesktopWindow from "../window/DesktopWindow.ts";
+import * as ElectronDialog from "../electron/ElectronDialog.ts";
+
+const { logWarning: logBackendPoolWarning } =
+ DesktopObservability.makeComponentLogger("desktop-backend-pool");
+
+export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
+export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
+export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
+export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
+export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
+
+// Caller tried to register an id that's already in the pool. The pool
+// refuses overwrites so two independent orchestrators racing on the
+// same id surface as a typed failure instead of one silently winning.
+export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
+ "DesktopBackendPoolInstanceAlreadyRegisteredError",
+ {
+ id: Schema.String,
+ },
+) {
+ override get message() {
+ return `Backend instance "${this.id}" is already registered in the pool.`;
+ }
+}
+
+// Primary instance is registered for the pool's lifetime. Unregister is
+// a no-op for it today (no real callers), but if someone wires it up
+// later it's a clear bug rather than something to "handle".
+export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
+ "DesktopBackendPoolCannotUnregisterPrimaryError",
+ {},
+) {
+ override get message() {
+ return "Refusing to unregister the primary backend from the pool.";
+ }
+}
+
+export class DesktopBackendPool extends Context.Service<
+ DesktopBackendPool,
+ {
+ // Look up a registered instance. None when no backend with that id is
+ // currently registered (e.g. WSL backend disabled).
+ readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
+ // Snapshot of all currently-registered instances. Order is unspecified;
+ // callers that need a canonical "primary first" view should sort by id.
+ readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
+ // Convenience accessor for the always-registered primary instance.
+ // Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
+ // exposed as a typed effect so consumers don't have to handle the
+ // Option for the case that's guaranteed to be present.
+ readonly primary: Effect.Effect<DesktopBackendInstance>;
+ // Build a fresh DesktopBackendInstance from `spec` and add it to the
+ // registry. The pool owns the instance's scope: unregister(id) or pool
+ // teardown closes it and runs the instance's auto-stop finalizer. The
+ // returned instance has not been started — callers decide when to
+ // start it (and can call start more than once if a retry-after-failure
+ // story makes sense for them).
+ readonly register: (
+ spec: BackendInstanceSpec,
+ ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
+ // Stop the named instance and remove it from the registry. Closing the
+ // instance's scope triggers its auto-stop finalizer; the registry is
+ // updated atomically with the scope close so subsequent get(id) calls
+ // observe the unregister before the underlying child process has fully
+ // exited.
+ readonly unregister: (
+ id: BackendInstanceId,
+ ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
+ }
+>()("@t3tools/desktop/backend/DesktopBackendPool") {}
+
+// Services required by makeBackendInstance — exported so caller
+// orchestrators that build their own specs can confirm the layer graph
+// satisfies them at compile time.
+export type BackendInstanceFactoryRequirements =
+ | FileSystem.FileSystem
+ | ChildProcessSpawner.ChildProcessSpawner
+ | HttpClient.HttpClient
+ | DesktopObservability.DesktopBackendOutputLogFactory;
+
+interface ActiveRegisteredInstance {
+ readonly _tag: "Active";
+ readonly instance: DesktopBackendInstance;
+ // None for the primary (which lives in the pool's own layer scope and
+ // is never unregistered); Some for instances added via register, whose
+ // scope unregister closes to stop them.
+ readonly scope: Option.Option<Scope.Closeable>;
+}
+
+interface ClosingRegisteredInstance {
+ readonly _tag: "Closing";
+ readonly done: Deferred.Deferred<void>;
+}
+
+type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
+
+type RegisterAction =
+ | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
+ | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
+
+type UnregisterAction =
+ | { readonly _tag: "Absent" }
+ | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
+ | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
+
+export const layer = Layer.effect(
+ DesktopBackendPool,
+ Effect.gen(function* () {
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ const electronDialog = yield* ElectronDialog.ElectronDialog;
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ // Anchor the pool's lifetime to its layer scope so registered
+ // instance scopes can be forked off it. Without this, instance
+ // scopes are orphaned: they only close via explicit unregister()
+ // calls, so on app shutdown the WSL backend child process gets
+ // hard-killed by the OS instead of receiving the graceful
+ // SIGTERM + grace period the instance's stop finalizer would
+ // otherwise run.
+ const layerScope = yield* Scope.Scope;
+ // Capture the services needed to build any future instance from the
+ // pool's layer scope. register() runs `makeBackendInstance` against
+ // a fresh child scope but reuses these services so the instance gets
+ // the same FileSystem, spawner, HTTP client and log factory the
+ // primary instance uses.
+ const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
+
+ // A WSL preflight failure on the primary only happens in wsl-only mode.
+ // Fatal configuration failures persist the Windows fallback. Bounded
+ // transport failures use an in-memory fallback for this launch so the app
+ // opens without overwriting the user's WSL preference.
+ const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
+ function* (failure: DesktopBackendManager.PreflightFailure) {
+ const { reason, fatal } = failure;
+ if (!fatal) {
+ yield* logBackendPoolWarning(
+ "primary WSL preflight retry window exhausted; using Windows for this launch",
+ { reason },
+ );
+ yield* electronDialog.showErrorBox(
+ "WSL backend is still unavailable",
+ `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
+ );
+ yield* appSettings.applyWslWindowsFallbackInMemory;
+ return true;
+ }
+
+ yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
+ reason,
+ });
+ yield* electronDialog.showErrorBox(
+ "WSL backend couldn't start",
+ `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
+ );
+ // Fully disable the WSL backend — both flags, matching the "Switch to
+ // Windows" recovery path — so the manager's next restart re-resolves the
+ // primary as Windows and reconcile won't register a secondary WSL backend
+ // against the same broken setup. Clearing wslBackendEnabled alone would
+ // leave a stale wslOnly:true that silently re-traps the user in wsl-only
+ // mode the next time they enable WSL. If the persisted write fails, keep
+ // this process recoverable by applying the fallback to in-memory settings.
+ yield* appSettings.applyWslWindowsFallback.pipe(
+ Effect.catch((error) =>
+ logBackendPoolWarning(
+ "failed to persist Windows fallback after WSL preflight failure",
+ {
+ error: error.message,
+ },
+ ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
+ ),
+ );
+ return true;
+ },
+ );
+
+ const primary = yield* DesktopBackendManager.makeBackendInstance({
+ id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
+ // Keep this lazy. The pool layer is initialized before startup loads
+ // persisted desktop settings, so resolving the primary label here would
+ // permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
+ // primaries as Windows.
+ label: configuration.resolvePrimaryLabel,
+ configResolve: configuration.resolvePrimary,
+ // Window creation errors propagating out of handleBackendReady must
+ // not block the readiness callback (that would prevent restartAttempt
+ // from being reset), so we absorb them here. The window service only
+ // logs on success, so log the failure here before swallowing it —
+ // otherwise a post-readiness window-open failure vanishes silently and
+ // is near-impossible to diagnose in production.
+ onReady: (httpBaseUrl) =>
+ desktopWindow.handleBackendReady(httpBaseUrl).pipe(
+ Effect.catch((error) =>
+ logBackendPoolWarning("failed to open main window after backend readiness", {
+ error: error.message,
+ }),
+ ),
+ ),
+ onShutdown: () => desktopWindow.handleBackendNotReady,
+ onPreflightFailed: handlePrimaryPreflightFailure,
+ });
+
+ const instancesRef = yield* SynchronizedRef.make<
+ ReadonlyMap<BackendInstanceId, RegisteredInstance>
+ >(
+ new Map([
+ [
+ DesktopBackendManager.PRIMARY_INSTANCE_ID,
+ { _tag: "Active", instance: primary, scope: Option.none() },
+ ],
+ ]),
+ );
+
+ const register: DesktopBackendPool["Service"]["register"] = (spec) =>
+ Effect.suspend(() =>
+ SynchronizedRef.modifyEffect(
+ instancesRef,
+ (
+ current,
+ ): Effect.Effect<
+ readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
+ DesktopBackendPoolInstanceAlreadyRegisteredError
+ > => {
+ const existing = current.get(spec.id);
+ if (existing?._tag === "Active") {
+ return Effect.fail(
+ new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
+ );
+ }
+ if (existing?._tag === "Closing") {
+ return Effect.succeed([
+ { _tag: "Wait", done: existing.done } as const,
+ current,
+ ] as const);
+ }
+ return Effect.gen(function* () {
+ // Provide the captured factory services first, then the child scope
+ // last so instance finalizers are owned by the unregisterable scope.
+ const instanceScope = yield* Scope.fork(layerScope, "sequential");
+ const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
+ Effect.provide(factoryContext),
+ Scope.provide(instanceScope),
+ );
+ const next = new Map(current);
+ next.set(spec.id, {
+ _tag: "Active",
+ instance,
+ scope: Option.some(instanceScope),
+ });
+ return [
+ { _tag: "Registered", instance } as const,
+ next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
+ ] as const;
+ });
+ },
+ ).pipe(
+ Effect.flatMap((result) =>
+ result._tag === "Registered"
+ ? Effect.succeed(result.instance)
+ : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
+ ),
+ ),
+ );
+
+ const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
+ Effect.gen(function* () {
+ if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
+ return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
+ }
+ const done = yield* Deferred.make<void>();
+ const action = yield* SynchronizedRef.modifyEffect(
+ instancesRef,
+ (
+ current,
+ ): Effect.Effect<
+ readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
+ > => {
+ const entry = current.get(id);
+ if (entry === undefined) {
+ return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
+ }
+ if (entry._tag === "Closing") {
+ return Effect.succeed([
+ { _tag: "Wait", done: entry.done } as const,
+ current,
+ ] as const);
+ }
+ const next = new Map(current);
+ next.set(id, { _tag: "Closing", done });
+ return Effect.succeed([
+ { _tag: "Close", entry } as const,
+ next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
+ ] as const);
+ },
+ );
+
+ if (action._tag === "Absent") return;
+ if (action._tag === "Wait") {
+ yield* Deferred.await(action.done);
+ return;
+ }
+
+ const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
+ const closing = current.get(id);
+ if (closing?._tag !== "Closing" || closing.done !== done) {
+ return Effect.succeed([undefined, current] as const);
+ }
+ const next = new Map(current);
+ next.delete(id);
+ return Effect.succeed([
+ undefined,
+ next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
+ ] as const);
+ }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
+ yield* Option.match(action.entry.scope, {
+ onNone: () => Effect.void,
+ onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
+ }).pipe(Effect.ensuring(finish));
+ });
+
+ return DesktopBackendPool.of({
+ get: (id) =>
+ SynchronizedRef.get(instancesRef).pipe(
+ Effect.map((instances) => {
+ const entry = instances.get(id);
+ return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
+ }),
+ ),
+ list: SynchronizedRef.get(instancesRef).pipe(
+ Effect.map((instances) =>
+ Array.from(instances.values()).flatMap((entry) =>
+ entry._tag === "Active" ? [entry.instance] : [],
+ ),
+ ),
+ ),
+ primary: Effect.succeed(primary),
+ register,
+ unregister,
+ });
+ }),
+);
+
+// Test layer for unit tests that want to assert against a known pool
+// composition without standing up the full manager. Each provided
+// instance is registered under its own id; the first one is also
+// surfaced as `primary` so callers can stub a single-instance pool.
+// `register` and `unregister` are stubbed to die so tests that
+// accidentally exercise pool registration fail loudly instead of
+// silently noop'ing.
+export const layerTest = (
+ instances: readonly DesktopBackendInstance[],
+): Layer.Layer<DesktopBackendPool> =>
+ Layer.effect(
+ DesktopBackendPool,
+ Effect.gen(function* () {
+ if (instances.length === 0) {
+ return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
+ }
+ const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
+ instances.map((instance) => [instance.id, instance] as const),
+ );
+ const primary = instances[0]!;
+ return DesktopBackendPool.of({
+ get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
+ list: Effect.succeed(Array.from(byId.values())),
+ primary: Effect.succeed(primary),
+ register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
+ unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
+ });
+ }),
+ );
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
index cd54c46c8..e7a58baef 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
@@ -5,11 +5,12 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
+import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
-import * as DesktopBackendManager from "./DesktopBackendManager.ts";
+import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
-const config: DesktopBackendManager.DesktopBackendStartConfig = {
+const config = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
@@ -54,20 +55,17 @@ describe("DesktopLocalEnvironmentAuth", () => {
),
),
);
- const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
- start: Effect.void,
- stop: () => Effect.void,
- currentConfig: Effect.succeed(Option.some(config)),
- snapshot: Effect.succeed({
- desiredRunning: true,
- ready: true,
- activePid: Option.none(),
- restartAttempt: 0,
- restartScheduled: false,
- }),
- });
+ const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
+ list: Effect.succeed([
+ {
+ id: PRIMARY_LOCAL_ENVIRONMENT_ID,
+ label: Effect.succeed("Windows"),
+ currentConfig: Effect.succeed(Option.some(config)),
+ },
+ ]),
+ } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
- Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
+ Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
index e619b330d..201492f0e 100644
--- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
+++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
@@ -1,4 +1,5 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
+import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -8,7 +9,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
-import * as DesktopBackendManager from "./DesktopBackendManager.ts";
+import * as DesktopBackendPool from "./DesktopBackendPool.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
@@ -42,7 +43,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
@@ -55,14 +56,20 @@ export const make = Effect.gen(function* () {
return cached.value;
}
- const configOption = yield* backendManager.currentConfig;
+ const instances = yield* pool.list;
+ const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
+ const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
+ const credential = config.bootstrap.desktopBootstrapToken;
+ if (!credential) {
+ return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
+ }
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
- credential: config.bootstrap.desktopBootstrapToken,
+ credential,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
diff --git a/apps/desktop/src/backend/DesktopServerExposure.test.ts b/apps/desktop/src/backend/DesktopServerExposure.test.ts
index 8b934fd8d..1a107c5c8 100644
--- a/apps/desktop/src/backend/DesktopServerExposure.test.ts
+++ b/apps/desktop/src/backend/DesktopServerExposure.test.ts
@@ -253,6 +253,11 @@ describe("DesktopServerExposure", () => {
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
+ setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
+ setWslDistro: () => Effect.die("unexpected WSL distro change"),
+ setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
+ applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
+ applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
return withHarness(
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 180e44e52..ec4284f5d 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -33,21 +33,22 @@ import {
import {
confirm,
getAppBranding,
+ getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
- getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
+import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
- yield* ipc.handleSync(getLocalEnvironmentBootstrap);
+ yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
@@ -70,6 +71,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTailscaleServeEnabled);
yield* ipc.handle(getAdvertisedEndpoints);
+ yield* ipc.handle(getWslState);
+ yield* ipc.handle(setWslBackendEnabled);
+ yield* ipc.handle(setWslDistro);
+ yield* ipc.handle(setWslOnly);
+
yield* ipc.handle(pickFolder);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index cc2a92ca8..d28c507fa 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -11,7 +11,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
-export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
+export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
@@ -32,6 +32,10 @@ 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_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
+export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
+export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts
new file mode 100644
index 000000000..a67b3246f
--- /dev/null
+++ b/apps/desktop/src/ipc/methods/window.test.ts
@@ -0,0 +1,128 @@
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+
+import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
+import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
+import { getLocalEnvironmentBootstraps } from "./window.ts";
+
+const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
+ executablePath: "wsl.exe",
+ args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
+ entryPath: "/app/bin.mjs",
+ cwd: "/app",
+ env: {},
+ extendEnv: false,
+ bootstrap: {
+ mode: "desktop",
+ noBrowser: true,
+ port: 3774,
+ host: "0.0.0.0",
+ desktopBootstrapToken: "bootstrap-token",
+ tailscaleServeEnabled: false,
+ tailscaleServePort: 443,
+ },
+ bootstrapDelivery: "stdin",
+ httpBaseUrl: new URL("http://127.0.0.1:3774"),
+ captureOutput: true,
+ preflightFailure: Option.none(),
+ runningDistro: "Ubuntu",
+};
+
+const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
+ id: DesktopBackendManager.BackendInstanceId("wsl:default"),
+ label: Effect.succeed("WSL (default distro)"),
+ start: Effect.void,
+ stop: () => Effect.void,
+ currentConfig: Effect.succeed(Option.some(readyWslConfig)),
+ snapshot: Effect.succeed({
+ desiredRunning: true,
+ ready: true,
+ activePid: Option.some(123),
+ restartAttempt: 0,
+ restartScheduled: false,
+ }),
+ waitForReady: () => Effect.succeed(true),
+};
+
+describe("getLocalEnvironmentBootstraps", () => {
+ it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
+ Effect.gen(function* () {
+ const result = yield* getLocalEnvironmentBootstraps.handler();
+
+ assert.deepEqual(result, [
+ {
+ id: "wsl:default",
+ label: "WSL (Ubuntu)",
+ runningDistro: "Ubuntu",
+ httpBaseUrl: "http://127.0.0.1:3774/",
+ wsBaseUrl: "ws://127.0.0.1:3774/",
+ bootstrapToken: "bootstrap-token",
+ },
+ ]);
+ }).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
+ );
+
+ it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
+ const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
+ ...readyWslConfig,
+ preflightFailure: Option.some({
+ reason: "WSL probe timed out",
+ fatal: false,
+ retryLimit: 12,
+ }),
+ };
+ const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
+ ...defaultWslInstance,
+ currentConfig: Effect.succeed(Option.some(retryingConfig)),
+ snapshot: Effect.succeed({
+ desiredRunning: true,
+ ready: false,
+ activePid: Option.none(),
+ restartAttempt: 2,
+ restartScheduled: true,
+ }),
+ };
+
+ return Effect.gen(function* () {
+ const result = yield* getLocalEnvironmentBootstraps.handler();
+ assert.deepEqual(result, [
+ {
+ id: "wsl:default",
+ label: "WSL (default distro)",
+ runningDistro: null,
+ httpBaseUrl: null,
+ wsBaseUrl: null,
+ },
+ ]);
+ }).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
+ });
+
+ it.effect("omits a bounded transient bootstrap after retries stop", () => {
+ const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
+ ...defaultWslInstance,
+ currentConfig: Effect.succeed(
+ Option.some({
+ ...readyWslConfig,
+ preflightFailure: Option.some({
+ reason: "WSL probe timed out",
+ fatal: false,
+ retryLimit: 12,
+ }),
+ }),
+ ),
+ snapshot: Effect.succeed({
+ desiredRunning: false,
+ ready: false,
+ activePid: Option.none(),
+ restartAttempt: 12,
+ restartScheduled: false,
+ }),
+ };
+
+ return Effect.gen(function* () {
+ const result = yield* getLocalEnvironmentBootstraps.handler();
+ assert.deepEqual(result, []);
+ }).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
+ });
+});
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index 3cb705d03..94357c7a1 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -4,14 +4,19 @@ import {
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickFolderOptionsSchema,
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
+ type DesktopEnvironmentBootstrap,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
-import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
+import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
+import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
+import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.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";
@@ -19,6 +24,11 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
+import {
+ extractDistroFromUncPath,
+ resolveWslPickFolderDefaultPath,
+ wslUncPathToLinuxPath,
+} from "../../wsl/wslPathParsing.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
@@ -45,26 +55,79 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
-export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
- result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
- handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
- const config = yield* backendManager.currentConfig;
- return Option.match(config, {
- onNone: () => null,
- onSome: ({ bootstrap, httpBaseUrl }) => ({
- label: "Local environment",
+export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
+ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
+ result: Schema.Array(DesktopEnvironmentBootstrapSchema),
+ handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const instances = yield* pool.list;
+ const bootstraps: DesktopEnvironmentBootstrap[] = [];
+ for (const instance of instances) {
+ const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
+ const config = yield* instance.currentConfig;
+ const snapshot = yield* instance.snapshot;
+ // A secondary backend (e.g. a parallel WSL backend) that hasn't produced
+ // a config yet (mid-registration, before its first start cycle) or that
+ // is retrying a *transient* preflight failure (WSL VM still booting, a
+ // not-yet-built linux server entry) is not listening on a port. We
+ // surface it as a *pending* bootstrap (null endpoints, no token) so the
+ // renderer can show a "Connecting…" indicator while it retries — null
+ // endpoints keep the renderer from dialing the dead port, avoiding the
+ // needless /api/auth/bootstrap/bearer error cycles a real endpoint would
+ // trigger.
+ if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
+ // Skip the primary (same-origin, no "connecting" affordance) and skip a
+ // secondary whose preflight failed *fatally* (no node, wrong version,
+ // missing build tools): it has stopped retrying, so an indefinite
+ // "Connecting…" would be misleading — its error is surfaced by the
+ // WSL-state UI instead.
+ const fatalPreflight =
+ Option.isSome(config) &&
+ Option.isSome(config.value.preflightFailure) &&
+ config.value.preflightFailure.value.fatal;
+ const stoppedPreflight =
+ Option.isSome(config) &&
+ Option.isSome(config.value.preflightFailure) &&
+ (!snapshot.desiredRunning || !snapshot.restartScheduled);
+ if (isPrimary || fatalPreflight || stoppedPreflight) continue;
+ bootstraps.push({
+ id: instance.id,
+ label: yield* instance.label,
+ runningDistro: null,
+ httpBaseUrl: null,
+ wsBaseUrl: null,
+ });
+ continue;
+ }
+ const { bootstrap, httpBaseUrl } = config.value;
+ const runningDistro = config.value.runningDistro ?? null;
+ bootstraps.push({
+ id: instance.id,
+ label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
+ runningDistro,
httpBaseUrl: httpBaseUrl.href,
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
...(bootstrap.desktopBootstrapToken
? { bootstrapToken: bootstrap.desktopBootstrapToken }
: {}),
- }),
- });
+ });
+ }
+ return bootstraps;
}),
});
+// Pull the distro selection out of a backend instance id like
+// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
+// for "track the user's WSL default distro" and maps to the
+// wslEnv-derived default at picker time.
+function extractWslDistroFromEnvironmentId(envId: string): string | null {
+ if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
+ return null;
+ }
+ const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
+ return suffix === "default" || suffix.length === 0 ? null : suffix;
+}
+
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
@@ -83,11 +146,62 @@ export const pickFolder = DesktopIpc.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;
+ // Three picker modes:
+ // - targetEnvironmentId omitted: default to the primary picker. Keeps
+ // the historical behavior unchanged for users who never enabled the
+ // WSL backend, and is what unfamiliar callers should get out of the
+ // box.
+ // - targetEnvironmentId starts with "wsl:": route to the WSL picker
+ // using the distro encoded in the id (or the user's selected
+ // wslDistro when the id is the "wsl:default" sentinel).
+ // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
+ const targetId = options?.targetEnvironmentId;
+ const wslDistroFromTarget =
+ targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
+ ? extractWslDistroFromEnvironmentId(targetId)
+ : null;
+ const useWsl =
+ targetId !== undefined &&
+ targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
+ targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
+ const settings = yield* appSettings.get;
+ // Fall back to the persisted wslDistro when the id is the
+ // "wsl:default" sentinel; the orchestrator uses the same fallback
+ // for the actual backend.
+ const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
+ const defaultPath = useWsl
+ ? Option.fromNullishOr(
+ resolveWslPickFolderDefaultPath(
+ options,
+ { distro: wslDistro },
+ yield* wslEnvironment.listDistros,
+ Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
+ ),
+ )
+ : environment.resolvePickFolderDefaultPath(options);
const selectedPath = yield* dialog.pickFolder({
owner: yield* electronWindow.focusedMainOrFirst,
- defaultPath: environment.resolvePickFolderDefaultPath(options),
+ defaultPath,
});
- return Option.getOrNull(selectedPath);
+ if (Option.isNone(selectedPath)) {
+ return null;
+ }
+ if (!useWsl) {
+ return selectedPath.value;
+ }
+
+ const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
+ if (linuxUncPath !== null) {
+ return linuxUncPath;
+ }
+
+ const converted = yield* wslEnvironment.windowsToWslPath(
+ extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
+ selectedPath.value,
+ );
+ return Option.getOrElse(converted, () => selectedPath.value);
}),
});
diff --git a/apps/desktop/src/ipc/methods/wsl.test.ts b/apps/desktop/src/ipc/methods/wsl.test.ts
new file mode 100644
index 000000000..3e07ae7f3
--- /dev/null
+++ b/apps/desktop/src/ipc/methods/wsl.test.ts
@@ -0,0 +1,274 @@
+import { DesktopWslStateSchema } from "@t3tools/contracts";
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
+import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
+import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
+import * as DesktopState from "../../app/DesktopState.ts";
+import * as ElectronApp from "../../electron/ElectronApp.ts";
+import * as ElectronTheme from "../../electron/ElectronTheme.ts";
+import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
+import * as DesktopWindow from "../../window/DesktopWindow.ts";
+import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
+import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
+import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
+
+const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
+
+const invokeSetWslBackendEnabled = (enabled: boolean) =>
+ setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
+const invokeSetWslDistro = (distro: string | null) =>
+ setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
+const invokeSetWslOnly = (enabled: boolean) =>
+ setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
+
+function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
+ return Layer.succeed(
+ DesktopWslBackend.DesktopWslBackend,
+ DesktopWslBackend.DesktopWslBackend.of({
+ reconcile: input.onReconcile ?? Effect.void,
+ lastPreflightError: Effect.succeed(Option.none()),
+ }),
+ );
+}
+
+function makeLifecycleLayer(relaunchReasons: Array<string>) {
+ return Layer.succeed(
+ DesktopLifecycle.DesktopLifecycle,
+ DesktopLifecycle.DesktopLifecycle.of({
+ relaunch: (reason) =>
+ Effect.sync(() => {
+ relaunchReasons.push(reason);
+ }),
+ register: Effect.void,
+ }),
+ );
+}
+
+const unusedLifecycleRuntimeLayer = Layer.mergeAll(
+ DesktopShutdown.layer,
+ DesktopState.layer,
+ Layer.succeed(
+ DesktopEnvironment.DesktopEnvironment,
+ DesktopEnvironment.DesktopEnvironment.of(
+ {} as DesktopEnvironment.DesktopEnvironment["Service"],
+ ),
+ ),
+ Layer.succeed(
+ DesktopWindow.DesktopWindow,
+ DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
+ ),
+ Layer.succeed(
+ ElectronApp.ElectronApp,
+ ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
+ ),
+ Layer.succeed(
+ ElectronTheme.ElectronTheme,
+ ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
+ ),
+);
+
+describe("WSL IPC", () => {
+ it.effect("stages dual-backend preferences before enabling without relaunching", () => {
+ const relaunchReasons: Array<string> = [];
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: false,
+ wslOnly: true,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer(),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ yield* invokeSetWslOnly(false);
+ yield* invokeSetWslDistro("Debian");
+ const state = yield* invokeSetWslBackendEnabled(true);
+
+ assert.deepEqual(state, {
+ enabled: true,
+ distro: "Debian",
+ available: true,
+ wslOnly: false,
+ distros: [],
+ preflightError: null,
+ });
+ assert.deepEqual(relaunchReasons, []);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
+ const relaunchReasons: Array<string> = [];
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer(),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ const stagedMode = yield* invokeSetWslOnly(true);
+ assert.equal(stagedMode.enabled, false);
+ assert.equal(stagedMode.wslOnly, true);
+ assert.deepEqual(relaunchReasons, []);
+
+ yield* invokeSetWslDistro("Debian");
+ assert.deepEqual(relaunchReasons, []);
+
+ const state = yield* invokeSetWslBackendEnabled(true);
+ assert.deepEqual(state, {
+ enabled: true,
+ distro: "Debian",
+ available: true,
+ wslOnly: true,
+ distros: [],
+ preflightError: null,
+ });
+ assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
+ const relaunchReasons: Array<string> = [];
+ let reconcileCount = 0;
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: false,
+ wslOnly: true,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer({
+ onReconcile: Effect.sync(() => {
+ reconcileCount += 1;
+ }),
+ }),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ const state = yield* invokeSetWslBackendEnabled(true);
+
+ assert.deepEqual(state, {
+ enabled: true,
+ distro: null,
+ available: true,
+ wslOnly: true,
+ distros: [],
+ preflightError: null,
+ });
+ assert.equal(reconcileCount, 0);
+ assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("reconciles in dual-backend mode without relaunching", () => {
+ const relaunchReasons: Array<string> = [];
+ let reconcileCount = 0;
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer({
+ onReconcile: Effect.sync(() => {
+ reconcileCount += 1;
+ }),
+ }),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ const state = yield* invokeSetWslBackendEnabled(true);
+
+ assert.equal(state.enabled, true);
+ assert.equal(state.wslOnly, false);
+ assert.equal(reconcileCount, 1);
+ assert.deepEqual(relaunchReasons, []);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
+ const relaunchReasons: Array<string> = [];
+ let reconcileCount = 0;
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: true,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer({
+ onReconcile: Effect.sync(() => {
+ reconcileCount += 1;
+ }),
+ }),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ const state = yield* invokeSetWslBackendEnabled(false);
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const settings = yield* appSettings.get;
+
+ assert.deepEqual(state, {
+ enabled: false,
+ distro: null,
+ available: true,
+ wslOnly: false,
+ distros: [],
+ preflightError: null,
+ });
+ assert.equal(settings.wslBackendEnabled, false);
+ assert.equal(settings.wslOnly, false);
+ assert.equal(reconcileCount, 0);
+ assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("clears dual-backend WSL without relaunching", () => {
+ const relaunchReasons: Array<string> = [];
+ let reconcileCount = 0;
+ const layer = Layer.mergeAll(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslOnly: false,
+ }),
+ DesktopWslEnvironment.layerTest({ isAvailable: true }),
+ makeWslBackendLayer({
+ onReconcile: Effect.sync(() => {
+ reconcileCount += 1;
+ }),
+ }),
+ makeLifecycleLayer(relaunchReasons),
+ unusedLifecycleRuntimeLayer,
+ );
+
+ return Effect.gen(function* () {
+ const state = yield* invokeSetWslBackendEnabled(false);
+
+ assert.equal(state.enabled, false);
+ assert.equal(state.wslOnly, false);
+ assert.equal(reconcileCount, 1);
+ assert.deepEqual(relaunchReasons, []);
+ }).pipe(Effect.provide(layer));
+ });
+});
diff --git a/apps/desktop/src/ipc/methods/wsl.ts b/apps/desktop/src/ipc/methods/wsl.ts
new file mode 100644
index 000000000..1d0dc262b
--- /dev/null
+++ b/apps/desktop/src/ipc/methods/wsl.ts
@@ -0,0 +1,122 @@
+import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
+import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
+import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
+import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
+import * as IpcChannels from "../channels.ts";
+import { makeIpcMethod } from "../DesktopIpc.ts";
+
+const readWslState: Effect.Effect<
+ DesktopWslState,
+ never,
+ | DesktopAppSettings.DesktopAppSettings
+ | DesktopWslEnvironment.DesktopWslEnvironment
+ | DesktopWslBackend.DesktopWslBackend
+> = Effect.gen(function* () {
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
+ 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 : [];
+ const preflightError = yield* wslBackend.lastPreflightError;
+ return {
+ enabled: settings.wslBackendEnabled,
+ distro: settings.wslDistro,
+ available,
+ wslOnly: settings.wslOnly,
+ distros,
+ // Only the dual-mode secondary records this; a wsl-only failure surfaces via
+ // a dialog + Windows fallback, so it stays null there.
+ preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
+ };
+});
+
+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 setWslBackendEnabled = makeIpcMethod({
+ channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
+ payload: Schema.Boolean,
+ result: DesktopWslStateSchema,
+ handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
+ const previousSettings = yield* appSettings.get;
+ const updateSettings = enabled
+ ? appSettings.setWslBackendEnabled(true)
+ : appSettings.applyWslWindowsFallback;
+ const change = yield* updateSettings;
+ const settings = yield* appSettings.get;
+ const changedWslOnlyPrimary = enabled
+ ? settings.wslOnly
+ : previousSettings.wslBackendEnabled && previousSettings.wslOnly;
+ if (changedWslOnlyPrimary && change.changed) {
+ const state = yield* readWslState;
+ yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
+ return state;
+ }
+ // Reconcile is idempotent and never fails; no need for a swap-style
+ // rollback when the WSL side has trouble coming up. With both
+ // backends running side by side, "WSL didn't start" is a transient
+ // state on one instance — the primary stays up either way.
+ yield* wslBackend.reconcile;
+ return yield* readWslState;
+ }),
+});
+
+export const setWslDistro = makeIpcMethod({
+ channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
+ payload: Schema.NullOr(Schema.String),
+ result: DesktopWslStateSchema,
+ handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
+ const change = yield* appSettings.setWslDistro(distro);
+ const settings = yield* appSettings.get;
+ // In active wsl-only mode the pool's primary IS the WSL backend, and its
+ // distro is captured when that backend starts, so relaunch to replace it.
+ // When WSL is disabled, this only stages a preference for the next enable.
+ if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
+ const state = yield* readWslState;
+ yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
+ return state;
+ }
+ yield* wslBackend.reconcile;
+ return yield* readWslState;
+ }),
+});
+
+export const setWslOnly = makeIpcMethod({
+ channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
+ payload: Schema.Boolean,
+ result: DesktopWslStateSchema,
+ handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
+ // wsl-only decides which backend the pool spins up as "primary", and that
+ // decision is captured once at layer init. A disabled WSL backend always
+ // leaves Windows primary active, so mode changes can be staged without a
+ // relaunch and applied by the subsequent enable call.
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
+ const change = yield* appSettings.setWslOnly(enabled);
+ const state = yield* readWslState;
+ if (state.enabled && change.changed) {
+ yield* lifecycle.relaunch(`wslOnly=${enabled}`);
+ }
+ return state;
+ }),
+});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index b88eb18e5..7a51700e0 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
-import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
+import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
@@ -50,6 +50,8 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
+import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
+import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
const desktopEnvironmentLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -143,12 +145,25 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopPreviewLayer),
);
-const desktopBackendLayer = DesktopBackendManager.layer.pipe(
+// Pool layer instantiates the backend factory once for the Windows
+// primary instance and exposes it via pool.primary. Consumers go through
+// the pool now; the legacy DesktopBackendManager service is gone. The
+// WSL second instance gets registered later in the migration. See
+// DesktopBackendPool.ts header for the full rollout plan.
+const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
+ Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(desktopWindowLayer),
);
+// WSL orchestrator hangs off the backend layer because it needs the
+// pool + configuration + serverExposure; it pulls NetService and the
+// foundation services through the same provideMerge chain.
+const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
+ Layer.provideMerge(desktopBackendLayer),
+);
+
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
@@ -160,6 +175,7 @@ const desktopApplicationLayer = Layer.mergeAll(
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
+ Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 6f126f413..4b5c0d2f6 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
- getLocalEnvironmentBootstrap: () => {
- const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
- if (typeof result !== "object" || result === null) {
- return null;
+ getLocalEnvironmentBootstraps: () => {
+ const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
+ if (!Array.isArray(result)) {
+ return [];
}
- return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
+ return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
@@ -91,6 +91,11 @@ 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),
+ setWslBackendEnabled: (enabled) =>
+ ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
+ setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
+ setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts
index c76ffa8bb..70b267982 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.test.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts
@@ -16,6 +16,10 @@ const DesktopSettingsPatch = Schema.Struct({
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
+ wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
+ wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
+ wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
+ wslOnly: Schema.optionalKey(Schema.Boolean),
});
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
@@ -92,6 +96,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings,
);
});
@@ -114,6 +121,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
const exposure = yield* settings.setServerExposureMode("local-only");
@@ -214,6 +224,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
@@ -253,6 +266,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -275,6 +291,9 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -296,8 +315,101 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
+ wslBackendEnabled: false,
+ wslOnly: false,
+ wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
+
+ it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
+ withSettings(
+ Effect.gen(function* () {
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ const enable = yield* settings.setWslBackendEnabled(true);
+ assert.isTrue(enable.changed);
+ assert.equal(enable.settings.wslBackendEnabled, true);
+
+ const distro = yield* settings.setWslDistro("Ubuntu-22.04");
+ assert.isTrue(distro.changed);
+ assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
+
+ const reloaded = yield* settings.load;
+ assert.equal(reloaded.wslBackendEnabled, true);
+ assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
+
+ const reject = yield* settings.setWslDistro("bad name!");
+ assert.equal(reject.settings.wslDistro, null);
+
+ const noop = yield* settings.setWslDistro(null);
+ assert.isFalse(noop.changed);
+ }),
+ ),
+ );
+
+ it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
+ withSettings(
+ Effect.gen(function* () {
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* settings.setWslBackendEnabled(true);
+ yield* settings.setWslOnly(true);
+
+ const persistedFallback = yield* settings.applyWslWindowsFallback;
+ assert.isTrue(persistedFallback.changed);
+ assert.equal(persistedFallback.settings.wslBackendEnabled, false);
+ assert.equal(persistedFallback.settings.wslOnly, false);
+
+ const persistedReload = yield* settings.load;
+ assert.equal(persistedReload.wslBackendEnabled, false);
+ assert.equal(persistedReload.wslOnly, false);
+
+ yield* settings.setWslBackendEnabled(true);
+ yield* settings.setWslOnly(true);
+
+ const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
+ assert.isTrue(volatileFallback.changed);
+ assert.equal(volatileFallback.settings.wslBackendEnabled, false);
+ assert.equal(volatileFallback.settings.wslOnly, false);
+
+ const current = yield* settings.get;
+ assert.equal(current.wslBackendEnabled, false);
+ assert.equal(current.wslOnly, false);
+
+ const diskReload = yield* settings.load;
+ assert.equal(diskReload.wslBackendEnabled, true);
+ assert.equal(diskReload.wslOnly, true);
+ }),
+ ),
+ );
+
+ it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
+ withSettings(
+ Effect.gen(function* () {
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* writeSettingsPatch({
+ wslMode: "wsl",
+ wslDistro: "Ubuntu-22.04",
+ });
+ const loaded = yield* settings.load;
+ assert.equal(loaded.wslBackendEnabled, true);
+ assert.equal(loaded.wslDistro, "Ubuntu-22.04");
+ }),
+ ),
+ );
+
+ it.effect("drops invalid persisted wsl distro values on load", () =>
+ withSettings(
+ Effect.gen(function* () {
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* writeSettingsPatch({
+ wslBackendEnabled: true,
+ wslDistro: "bad/name",
+ });
+ const loaded = yield* settings.load;
+ assert.equal(loaded.wslBackendEnabled, true);
+ assert.equal(loaded.wslDistro, null);
+ }),
+ ),
+ );
});
diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts
index 81aae92f0..6a26bf5a6 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.ts
@@ -17,6 +17,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;
@@ -24,6 +25,21 @@ export interface DesktopSettings {
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
+ // Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
+ // integration. We now run Windows and WSL backends side by side, so the
+ // setting is just whether the WSL backend should be running alongside the
+ // primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
+ // value are migrated to `wslBackendEnabled: true` on load.
+ readonly wslBackendEnabled: boolean;
+ readonly wslDistro: string | null;
+ // When true (and wslBackendEnabled is also true) the desktop runs only
+ // the WSL backend as the primary, and the Windows-side Node backend is
+ // not started. Designed for users who develop entirely inside WSL and
+ // don't want a second backend process running. Defaults to false so
+ // existing setups stay on the parallel-backends behavior. Changing
+ // this requires a desktop restart because the pool's primary spec is
+ // chosen once at layer init.
+ readonly wslOnly: boolean;
}
export interface DesktopSettingsChange {
@@ -39,6 +55,9 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
+ wslBackendEnabled: false,
+ wslDistro: null,
+ wslOnly: false,
};
const DesktopSettingsDocument = Schema.Struct({
@@ -47,6 +66,13 @@ const DesktopSettingsDocument = Schema.Struct({
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
+ // Newer form of the WSL toggle. `wslMode` is still accepted on load so
+ // existing on-disk settings keep working; on the next persist we write the
+ // new boolean and the legacy key drops out.
+ wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
+ wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
+ wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
+ wslOnly: Schema.optionalKey(Schema.Boolean),
});
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
@@ -98,6 +124,20 @@ export class DesktopAppSettings extends Context.Service<
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
+ readonly setWslBackendEnabled: (
+ enabled: boolean,
+ ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
+ readonly setWslDistro: (
+ distro: string | null,
+ ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
+ readonly setWslOnly: (
+ enabled: boolean,
+ ) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
+ readonly applyWslWindowsFallback: Effect.Effect<
+ DesktopSettingsChange,
+ DesktopSettingsWriteError
+ >;
+ readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
}
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
@@ -114,6 +154,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,
@@ -125,6 +169,13 @@ function normalizeDesktopSettingsDocument(
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
+ // Newer form wins when both are present; otherwise fall back to the legacy
+ // `wslMode === "wsl"` signal so users coming off the swap-mode build keep
+ // their WSL backend enabled.
+ const wslBackendEnabled =
+ parsed.wslBackendEnabled === true ||
+ (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
+
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
@@ -134,6 +185,9 @@ function normalizeDesktopSettingsDocument(
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
+ wslBackendEnabled,
+ wslDistro: normalizeWslDistro(parsed.wslDistro),
+ wslOnly: parsed.wslOnly === true,
};
}
@@ -158,6 +212,15 @@ function toDesktopSettingsDocument(
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
}
+ if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
+ document.wslBackendEnabled = settings.wslBackendEnabled;
+ }
+ if (settings.wslDistro !== defaults.wslDistro) {
+ document.wslDistro = settings.wslDistro;
+ }
+ if (settings.wslOnly !== defaults.wslOnly) {
+ document.wslOnly = settings.wslOnly;
+ }
return document;
}
@@ -204,6 +267,38 @@ function setUpdateChannel(
};
}
+function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
+ return settings.wslBackendEnabled === enabled
+ ? settings
+ : {
+ ...settings,
+ wslBackendEnabled: enabled,
+ };
+}
+
+function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
+ const normalized = normalizeWslDistro(distro);
+ return settings.wslDistro === normalized
+ ? settings
+ : {
+ ...settings,
+ wslDistro: normalized,
+ };
+}
+
+function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
+ return settings.wslOnly === enabled
+ ? settings
+ : {
+ ...settings,
+ wslOnly: enabled,
+ };
+}
+
+function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
+ return setWslOnly(setWslBackendEnabled(settings, false), false);
+}
+
function readSettings(
fileSystem: FileSystem.FileSystem,
settingsPath: string,
@@ -287,6 +382,12 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
+ const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
+ SynchronizedRef.modify(settingsRef, (settings) => {
+ const nextSettings = update(settings);
+ return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
+ });
+
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
@@ -342,6 +443,26 @@ export const make = Effect.gen(function* () {
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
+ setWslBackendEnabled: (enabled) =>
+ persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
+ Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
+ ),
+ setWslDistro: (distro) =>
+ persist((settings) => setWslDistro(settings, distro)).pipe(
+ Effect.withSpan("desktop.settings.setWslDistro", {
+ attributes: { distro: distro ?? null },
+ }),
+ ),
+ setWslOnly: (enabled) =>
+ persist((settings) => setWslOnly(settings, enabled)).pipe(
+ Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
+ ),
+ applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
+ Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
+ ),
+ applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
+ Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
+ ),
});
});
@@ -371,6 +492,12 @@ 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)),
+ setWslBackendEnabled: (enabled) =>
+ update((settings) => setWslBackendEnabled(settings, enabled)),
+ setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
+ setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
+ applyWslWindowsFallback: update(applyWslWindowsFallback),
+ applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
});
}),
);
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index 4c90afb2a..696bd7555 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -13,7 +13,7 @@ import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
-import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
@@ -107,7 +107,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"]);
- const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
+ const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
+ id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
+ label: Effect.succeed("Windows"),
start: Effect.void,
stop: () => options.stopBackend ?? Effect.void,
currentConfig: Effect.succeed(Option.none()),
@@ -118,7 +120,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
restartAttempt: 0,
restartScheduled: false,
}),
- });
+ waitForReady: () => Effect.succeed(true),
+ };
+ const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
@@ -152,6 +156,11 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
+ setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
+ setWslDistro: () => Effect.die("unexpected WSL distro change"),
+ setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
+ applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
+ applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
index aecbdcfc3..aabb0830b 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -18,7 +18,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
-import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
@@ -241,7 +241,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
export const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
- const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
const desktopState = yield* DesktopState.DesktopState;
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
const electronWindow = yield* ElectronWindow.ElectronWindow;
@@ -458,7 +458,19 @@ export const make = Effect.gen(function* () {
yield* Ref.set(updateInstallInFlightRef, true);
return yield* Effect.gen(function* () {
- yield* backendManager.stop({ timeout: Duration.seconds(5) });
+ // Stop every backend in the pool, not just the primary. With
+ // parallel WSL + Windows backends, leaving the WSL instance up
+ // means quitAndInstall's app.quit() exits before the pool's
+ // scope cascade has a chance to run its stop finalizer, so the
+ // WSL child gets hard-killed by the OS instead of receiving
+ // SIGTERM + grace. Stops run concurrently with the same 5s
+ // budget the primary had on its own.
+ const instances = yield* pool.list;
+ yield* Effect.forEach(
+ instances,
+ (instance) => instance.stop({ timeout: Duration.seconds(5) }),
+ { concurrency: "unbounded" },
+ );
yield* electronWindow.destroyAll;
yield* electronUpdater.quitAndInstall({
isSilent: true,
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index 04a1971ce..ba77292fd 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
@@ -73,7 +73,9 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
- handleBackendReady: Effect.void,
+ showConnectingSplash: Effect.void,
+ handleBackendReady: () => Effect.void,
+ handleBackendNotReady: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 7b9bdaf08..280f2109f 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -28,6 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
+import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -62,6 +63,7 @@ function makeFakeBrowserWindow() {
};
const window = {
+ close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => false),
@@ -83,6 +85,7 @@ function makeFakeBrowserWindow() {
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
+ send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -191,6 +194,100 @@ function makeTestLayer(input: {
);
}
+// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
+// given outcomes in order (null => simulated open failure), and whose
+// currentMainOrFirst mirrors the real fallback to the first live window (the
+// splash, before any main is registered). Reveal targets are recorded so tests
+// can assert what activation actually surfaced.
+const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
+ Effect.gen(function* () {
+ const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
+ const createCalls = yield* Ref.make(0);
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
+ const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
+ const fallbackWindow = createOutcomes.find(
+ (window): window is Electron.BrowserWindow => window !== null,
+ );
+
+ const currentMainOrFirst = Effect.gen(function* () {
+ const registered = yield* Ref.get(mainWindow);
+ if (Option.isSome(registered)) {
+ return registered;
+ }
+ const created = yield* Ref.get(createdWindows);
+ return Option.fromNullishOr(created[0] ?? null);
+ });
+
+ const electronWindowShape = {
+ create: () =>
+ Effect.gen(function* () {
+ const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
+ const outcome = createOutcomes[index] ?? null;
+ if (outcome === null) {
+ return yield* new ElectronWindow.ElectronWindowCreateError({
+ options: {
+ title: null,
+ width: null,
+ height: null,
+ minWidth: null,
+ minHeight: null,
+ show: null,
+ modal: null,
+ frame: null,
+ transparent: null,
+ backgroundColor: null,
+ webPreferences: {
+ preload: null,
+ partition: null,
+ sandbox: null,
+ contextIsolation: null,
+ nodeIntegration: null,
+ webviewTag: null,
+ },
+ },
+ cause: new Error("simulated window-open failure"),
+ });
+ }
+ yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
+ return outcome;
+ }),
+ main: Ref.get(mainWindow),
+ currentMainOrFirst,
+ focusedMainOrFirst: currentMainOrFirst,
+ setMain: (window) => Ref.set(mainWindow, Option.some(window)),
+ clearMain: () => Ref.set(mainWindow, Option.none()),
+ reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
+ sendAll: () => Effect.void,
+ destroyAll: Effect.void,
+ syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
+ } satisfies ElectronWindow.ElectronWindow["Service"];
+
+ const layer = DesktopWindow.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ desktopAssetsLayer,
+ desktopEnvironmentLayer,
+ desktopServerExposureLayer,
+ electronMenuLayer,
+ Layer.succeed(ElectronShell.ElectronShell, {
+ openExternal: () => Effect.succeed(true),
+ copyText: () => Effect.void,
+ } satisfies ElectronShell.ElectronShell["Service"]),
+ electronThemeLayer,
+ Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
+ Layer.mock(PreviewManager.PreviewManager)({
+ getBrowserSession: () => Effect.succeed({} as Electron.Session),
+ setMainWindow: () => Effect.void,
+ isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
+ getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
+ }),
+ ),
+ ),
+ );
+
+ return { layer, createCalls, mainWindow, revealedWindows } as const;
+ });
+
describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
@@ -231,7 +328,7 @@ describe("DesktopWindow", () => {
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(createCount), 0);
- yield* desktopWindow.handleBackendReady;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
@@ -254,7 +351,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
- yield* desktopWindow.handleBackendReady;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
@@ -323,7 +420,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
- yield* desktopWindow.handleBackendReady;
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
@@ -345,4 +442,108 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(layer));
}),
);
+
+ it.effect(
+ "retries opening the real main on activate when a failed post-readiness open left only the splash",
+ () =>
+ Effect.gen(function* () {
+ const splash = makeFakeBrowserWindow();
+ const main = makeFakeBrowserWindow();
+ // create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
+ // window-open error), #3 -> the real main on activate's retry.
+ const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+
+ // 1. WSL-only boot shows the connecting splash.
+ yield* desktopWindow.showConnectingSplash;
+ assert.equal(yield* Ref.get(scenario.createCalls), 1);
+
+ // 2. Backend reports ready, but opening the real main fails. The pool
+ // swallows that error in production, so handleBackendReady fails
+ // here without a registered main window -- only the splash is open.
+ const readyExit = yield* Effect.exit(
+ desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
+ );
+ assert.equal(readyExit._tag, "Failure");
+ assert.equal(yield* Ref.get(scenario.createCalls), 2);
+ assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
+
+ // 3. Activating must not mistake the splash for the main window: it
+ // retries the open and brings up the real main instead of leaving
+ // the user stranded on "Connecting to WSL".
+ yield* desktopWindow.activate;
+ assert.equal(yield* Ref.get(scenario.createCalls), 3);
+ const registeredMain = yield* Ref.get(scenario.mainWindow);
+ assert.isTrue(Option.isSome(registeredMain));
+ assert.equal(Option.getOrThrow(registeredMain), main.window);
+ }).pipe(Effect.provide(scenario.layer));
+ }),
+ );
+
+ it.effect(
+ "re-reveals the connecting splash on activate while the backend is still cold-booting",
+ () =>
+ Effect.gen(function* () {
+ const splash = makeFakeBrowserWindow();
+ // Only the splash is ever created; the backend never reports ready.
+ const scenario = yield* makeSplashScenario([splash.window]);
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+
+ yield* desktopWindow.showConnectingSplash;
+ assert.equal(yield* Ref.get(scenario.createCalls), 1);
+
+ // Taskbar/dock activation during cold boot must bring the splash back
+ // rather than no-op and leave it hidden until the backend finishes.
+ yield* desktopWindow.activate;
+ assert.equal(yield* Ref.get(scenario.createCalls), 1);
+ assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
+ }).pipe(Effect.provide(scenario.layer));
+ }),
+ );
+
+ it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
+ Effect.gen(function* () {
+ const splash = makeFakeBrowserWindow();
+ const main = makeFakeBrowserWindow();
+ const scenario = yield* makeSplashScenario([splash.window, main.window]);
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+
+ yield* desktopWindow.showConnectingSplash;
+ yield* desktopWindow.dispatchMenuAction("open-settings");
+
+ assert.equal(yield* Ref.get(scenario.createCalls), 1);
+ assert.equal(splash.send.mock.calls.length, 0);
+ assert.equal(main.send.mock.calls.length, 0);
+ }).pipe(Effect.provide(scenario.layer));
+ }),
+ );
+
+ it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
+ Effect.gen(function* () {
+ const splash = makeFakeBrowserWindow();
+ const main = makeFakeBrowserWindow();
+ const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
+
+ yield* Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+
+ yield* desktopWindow.showConnectingSplash;
+ const readyExit = yield* Effect.exit(
+ desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
+ );
+ assert.equal(readyExit._tag, "Failure");
+
+ yield* desktopWindow.dispatchMenuAction("open-settings");
+
+ assert.equal(yield* Ref.get(scenario.createCalls), 3);
+ assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
+ }).pipe(Effect.provide(scenario.layer));
+ }),
+ );
});
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 41bbbfd59..b1dfabe7a 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -10,7 +10,6 @@ import type * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
-import * as DesktopState from "../app/DesktopState.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
@@ -42,7 +41,6 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
- | DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -61,7 +59,22 @@ export class DesktopWindow extends Context.Service<
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly activate: Effect.Effect<void, DesktopWindowError>;
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
- readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
+ // Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
+ // mode), before the WSL backend that serves the renderer is ready. It is
+ // dismissed automatically once the real main window reveals.
+ readonly showConnectingSplash: Effect.Effect<void>;
+ // Marks the primary backend as ready so `createMainIfBackendReady` and the
+ // macOS "activate without windows" path may open the real main window. The
+ // renderer now always loads the local client URL (getDesktopUrl) and connects
+ // to the backend through the connection layer, so the reported httpBaseUrl is
+ // no longer used to point the window at the backend — it is kept only for the
+ // readiness log and to preserve the callback contract the backend pool drives.
+ readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
+ // Called when the backend transitions back to "not ready" (clean stop,
+ // restart, crash). Clears the latch that lets `activate` auto-create a
+ // window so a "macOS dock click" while the backend is down doesn't
+ // produce a stranded window pointing at nothing.
+ readonly handleBackendNotReady: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
@@ -86,6 +99,18 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
+// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
+// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
+// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
+function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
+ const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
+ const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
+ const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
+ const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
+ const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
+ return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
+}
+
export function isSameOriginRendererNavigation(input: {
readonly applicationUrl: string;
readonly navigationUrl: string;
@@ -177,11 +202,45 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
- const state = yield* DesktopState.DesktopState;
+ // Window-side latch for the primary backend's readiness. Set by
+ // handleBackendReady (driven by the pool's onReady callback), cleared
+ // by handleBackendNotReady (driven by onShutdown). Only consumed by
+ // createMainIfBackendReady, which gates the post-readiness window
+ // open in development and the macOS "activate without windows" path.
+ const backendReadyRef = yield* Ref.make(false);
+ // The transient "Connecting to WSL" splash window, tracked separately so it
+ // is never mistaken for the real main window.
+ const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
+ const dismissConnectingSplash = Effect.gen(function* () {
+ const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
+ if (Option.isSome(splash) && !splash.value.isDestroyed()) {
+ splash.value.close();
+ }
+ });
+
+ // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
+ // which during WSL-only boot is the connecting splash. The splash is never
+ // registered via setMain, so it must be treated as "no real main window" --
+ // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
+ // open (or retry) the real main. That is the failure the pool's swallowed
+ // post-readiness window-open error would otherwise strand the user in:
+ // splash up, backend ready, no main, and activation only re-reveals splash.
+ const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
+ Ref.get(splashWindowRef).pipe(
+ Effect.map((splash) =>
+ Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
+ ? Option.none<Electron.BrowserWindow>()
+ : window,
+ ),
+ );
+
+ const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
+ const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
+
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
@@ -402,7 +461,9 @@ export const make = Effect.gen(function* () {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
- void runPromise(electronWindow.reveal(window));
+ // Reveal the real window, then close the connecting splash (if any) so the
+ // two don't overlap and there's no blank gap between them.
+ void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
});
loadApplication();
@@ -426,7 +487,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.createMain"));
const ensureMain = Effect.gen(function* () {
- const existingWindow = yield* electronWindow.currentMainOrFirst;
+ const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
return existingWindow.value;
}
@@ -440,35 +501,101 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
const createMainIfBackendReady = Effect.gen(function* () {
- const backendReady = yield* Ref.get(state.backendReady);
+ const backendReady = yield* Ref.get(backendReadyRef);
if (!backendReady) return;
- const existingWindow = yield* electronWindow.currentMainOrFirst;
+ const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) return;
yield* createMain;
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
+ const showConnectingSplash = Effect.gen(function* () {
+ // Only when nothing is shown yet: no real window, no existing splash.
+ const existingSplash = yield* Ref.get(splashWindowRef);
+ if (Option.isSome(existingSplash)) return;
+ const existingWindow = yield* electronWindow.currentMainOrFirst;
+ if (Option.isSome(existingWindow)) return;
+
+ const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
+ const splash = yield* electronWindow.create({
+ width: 360,
+ height: 220,
+ resizable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ frame: false,
+ center: true,
+ show: false,
+ skipTaskbar: false,
+ backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
+ title: environment.displayName,
+ webPreferences: {
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ },
+ });
+ yield* Ref.set(splashWindowRef, Option.some(splash));
+ splash.once("closed", () => {
+ void runPromise(Ref.set(splashWindowRef, Option.none()));
+ });
+ splash.once("ready-to-show", () => {
+ if (!splash.isDestroyed()) {
+ splash.show();
+ }
+ });
+ void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
+ yield* logWindowInfo("connecting splash shown");
+ }).pipe(
+ // The splash is best-effort UX — never let it fail startup.
+ Effect.catch((error) =>
+ logWindowWarning("failed to show connecting splash", { message: error.message }),
+ ),
+ Effect.withSpan("desktop.window.showConnectingSplash"),
+ );
+
return DesktopWindow.of({
createMain,
ensureMain,
revealOrCreateMain,
activate: Effect.gen(function* () {
- const existingWindow = yield* electronWindow.currentMainOrFirst;
+ const existingWindow = yield* currentMainWindow;
if (Option.isSome(existingWindow)) {
yield* electronWindow.reveal(existingWindow.value);
- } else {
- yield* createMainIfBackendReady;
+ return;
+ }
+ // No real main window yet. While the backend is still cold-booting,
+ // re-reveal the connecting splash so taskbar/dock activation brings it
+ // back instead of doing nothing. Once the backend is ready we fall
+ // through to (re)create the real main -- including retrying a previously
+ // failed open the pool swallowed -- rather than latching onto the splash.
+ const backendReady = yield* Ref.get(backendReadyRef);
+ if (!backendReady) {
+ const splash = yield* Ref.get(splashWindowRef);
+ if (Option.isSome(splash)) {
+ yield* electronWindow.reveal(splash.value);
+ return;
+ }
}
+ yield* createMainIfBackendReady;
}).pipe(Effect.withSpan("desktop.window.activate")),
createMainIfBackendReady,
- handleBackendReady: Effect.gen(function* () {
- yield* Ref.set(state.backendReady, true);
- yield* logWindowInfo("backend ready", { source: "http" });
+ showConnectingSplash,
+ handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
+ yield* Ref.set(backendReadyRef, true);
+ yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
yield* createMainIfBackendReady;
- }).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
+ }),
+ handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
+ Effect.withSpan("desktop.window.handleBackendNotReady"),
+ ),
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
yield* Effect.annotateCurrentSpan({ action });
- const existingWindow = yield* electronWindow.focusedMainOrFirst;
- const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
+ const existingWindow = yield* focusedMainWindow;
+ if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
+ return;
+ }
+ const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
const send = () => {
if (targetWindow.isDestroyed()) return;
diff --git a/apps/desktop/src/wsl/DesktopWslBackend.test.ts b/apps/desktop/src/wsl/DesktopWslBackend.test.ts
new file mode 100644
index 000000000..2f58c6adc
--- /dev/null
+++ b/apps/desktop/src/wsl/DesktopWslBackend.test.ts
@@ -0,0 +1,199 @@
+import { assert, describe, it } from "@effect/vitest";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+
+import * as NetService from "@t3tools/shared/Net";
+
+import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
+import type {
+ DesktopBackendSnapshot,
+ DesktopBackendStartConfig,
+} from "../backend/DesktopBackendManager.ts";
+import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
+import * as DesktopWslBackend from "./DesktopWslBackend.ts";
+
+function makeStubInstance(input: {
+ readonly id: DesktopBackendPool.BackendInstanceId;
+ readonly label: string;
+ readonly snapshot: DesktopBackendSnapshot;
+ readonly start?: Effect.Effect<void>;
+}): DesktopBackendPool.DesktopBackendInstance {
+ return {
+ id: input.id,
+ label: Effect.succeed(input.label),
+ start: input.start ?? Effect.void,
+ stop: () => Effect.void,
+ currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
+ snapshot: Effect.succeed(input.snapshot),
+ waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
+ };
+}
+
+const idleSnapshot: DesktopBackendSnapshot = {
+ desiredRunning: false,
+ ready: false,
+ activePid: Option.none(),
+ restartAttempt: 5,
+ restartScheduled: false,
+};
+
+const primarySnapshot: DesktopBackendSnapshot = {
+ desiredRunning: true,
+ ready: true,
+ activePid: Option.some(123),
+ restartAttempt: 0,
+ restartScheduled: false,
+};
+
+const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
+ getState: Effect.die("unexpected getState"),
+ backendConfig: Effect.succeed({
+ port: 3773,
+ bindHost: "127.0.0.1",
+ httpBaseUrl: new URL("http://127.0.0.1:3773"),
+ tailscaleServeEnabled: false,
+ tailscaleServePort: 443,
+ }),
+ configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
+ setMode: () => Effect.die("unexpected setMode"),
+ setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
+ getAdvertisedEndpoints: Effect.succeed([]),
+} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
+
+const backendConfigurationLayer = Layer.succeed(
+ DesktopBackendConfiguration.DesktopBackendConfiguration,
+ {
+ resolvePrimary: Effect.die("unexpected resolvePrimary"),
+ resolvePrimaryLabel: Effect.succeed("Windows"),
+ resolveWsl: () => Effect.die("unexpected resolveWsl"),
+ } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
+);
+
+const netLayer = Layer.succeed(NetService.NetService, {
+ canListenOnHost: () => Effect.succeed(true),
+ isPortAvailableOnLoopback: () => Effect.succeed(true),
+ reserveLoopbackPort: () => Effect.succeed(41773),
+ findAvailablePort: (preferred) => Effect.succeed(preferred),
+} satisfies NetService.NetService["Service"]);
+
+describe("DesktopWslBackend", () => {
+ it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
+ let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
+ const primary = makeStubInstance({
+ id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
+ label: "Windows",
+ snapshot: primarySnapshot,
+ });
+ const wsl = makeStubInstance({
+ id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
+ label: "WSL (Ubuntu)",
+ snapshot: primarySnapshot,
+ });
+ const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
+ get: (id) =>
+ Effect.succeed(
+ id === DesktopBackendPool.PRIMARY_INSTANCE_ID
+ ? Option.some(primary)
+ : Option.none<DesktopBackendPool.DesktopBackendInstance>(),
+ ),
+ list: Effect.succeed([primary]),
+ primary: Effect.succeed(primary),
+ register: (spec) =>
+ Effect.sync(() => {
+ registeredSpec = spec;
+ return wsl;
+ }),
+ unregister: () => Effect.die("unexpected unregister"),
+ } satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
+
+ return Effect.gen(function* () {
+ const backend = yield* DesktopWslBackend.DesktopWslBackend;
+
+ yield* backend.reconcile;
+ const spec = registeredSpec;
+ assert.isDefined(spec);
+ if (spec === undefined) {
+ throw new Error("Expected WSL backend registration");
+ }
+ const recordFailure = spec.onPreflightFailed;
+ const clearFailure = spec.onReady;
+ assert.isDefined(recordFailure);
+ assert.isDefined(clearFailure);
+ if (recordFailure === undefined || clearFailure === undefined) {
+ throw new Error("Expected WSL backend callbacks");
+ }
+
+ assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
+ assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
+
+ yield* clearFailure(new URL("http://127.0.0.1:41773"));
+ assert.deepEqual(yield* backend.lastPreflightError, Option.none());
+ }).pipe(
+ Effect.provide(
+ DesktopWslBackend.layer.pipe(
+ Layer.provideMerge(poolLayer),
+ Layer.provideMerge(backendConfigurationLayer),
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(netLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslDistro: "Ubuntu",
+ wslOnly: false,
+ }),
+ ),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
+ ),
+ ),
+ );
+ });
+
+ it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
+ let startCount = 0;
+ const primary = makeStubInstance({
+ id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
+ label: "Windows",
+ snapshot: primarySnapshot,
+ });
+ const wsl = makeStubInstance({
+ id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
+ label: "WSL (Ubuntu)",
+ snapshot: idleSnapshot,
+ start: Effect.sync(() => {
+ startCount += 1;
+ }),
+ });
+
+ return Effect.gen(function* () {
+ const backend = yield* DesktopWslBackend.DesktopWslBackend;
+
+ yield* backend.reconcile;
+
+ assert.equal(startCount, 1);
+ }).pipe(
+ Effect.provide(
+ DesktopWslBackend.layer.pipe(
+ Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
+ Layer.provideMerge(backendConfigurationLayer),
+ Layer.provideMerge(serverExposureLayer),
+ Layer.provideMerge(netLayer),
+ Layer.provideMerge(
+ DesktopAppSettings.layerTest({
+ ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
+ wslBackendEnabled: true,
+ wslDistro: "Ubuntu",
+ wslOnly: false,
+ }),
+ ),
+ Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
+ ),
+ ),
+ );
+ });
+});
diff --git a/apps/desktop/src/wsl/DesktopWslBackend.ts b/apps/desktop/src/wsl/DesktopWslBackend.ts
new file mode 100644
index 000000000..605f4e7a4
--- /dev/null
+++ b/apps/desktop/src/wsl/DesktopWslBackend.ts
@@ -0,0 +1,268 @@
+// Orchestrator that keeps the WSL pool instance in sync with the user's
+// settings. `reconcile` is the single entry point — bootstrap calls it
+// once after the primary backend starts, and the wsl.ts IPC calls it
+// after persisting a `wslBackendEnabled` or `wslDistro` change. The
+// effect is idempotent and never fails: errors (WSL not available, port
+// allocation failed, register failed) get logged and reconcile returns
+// having left the pool in a consistent state (either the previous WSL
+// instance is still running, or none is).
+//
+// The instance id encodes the desired distro selection — `wsl:default`
+// when the user picked "track the WSL default" (settings.wslDistro is
+// null) and `wsl:<distro>` otherwise. Changing the distro setting
+// changes the id, so reconcile unregisters the old instance before
+// registering the new one. The label that the frontend env switcher
+// renders is derived from the same field.
+//
+// Port allocation: each WSL instance gets a freshly scanned port to
+// avoid colliding with the primary or with a previously-registered WSL
+// instance that's still tearing down. The scan only checks loopback
+// (127.0.0.1) since the WSL backend is loopback-only — the primary
+// owns LAN exposure when the user opts in.
+
+import * as Cause from "effect/Cause";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Ref from "effect/Ref";
+import * as Semaphore from "effect/Semaphore";
+
+import * as NetService from "@t3tools/shared/Net";
+
+import * as DesktopObservability from "../app/DesktopObservability.ts";
+import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
+import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
+import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
+
+// Exported so callers that parse pool ids (e.g. the pickFolder IPC
+// handler in ipc/methods/window.ts) reference the same prefix this
+// module produces. Keeping it inline in two places risks silent
+// divergence if one ever gets renamed.
+export const WSL_INSTANCE_ID_PREFIX = "wsl:";
+const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
+const MAX_TCP_PORT = 65_535;
+
+export class DesktopWslBackend extends Context.Service<
+ DesktopWslBackend,
+ {
+ // Bring the pool in line with the current persisted WSL settings.
+ // Idempotent. Never fails (errors are logged); callers can chain it
+ // after persisting settings without an error-handling dance.
+ readonly reconcile: Effect.Effect<void>;
+ // Reason the dual-mode WSL secondary last failed preflight (no node, wrong
+ // version, missing build tools), or None. Read by the getWslState IPC so
+ // Connections settings can show it inline. None in wsl-only mode (that path
+ // surfaces via a dialog + Windows fallback).
+ readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
+ }
+>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
+
+const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
+ DesktopObservability.makeComponentLogger("desktop-wsl-backend");
+
+const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
+ DesktopBackendPool.BackendInstanceId(
+ distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
+ );
+
+const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
+ id.startsWith(WSL_INSTANCE_ID_PREFIX);
+
+const buildLabel = (distro: string | null): string =>
+ distro === null ? "WSL (default distro)" : `WSL (${distro})`;
+
+// Loopback-only port scan starting one above the primary's port. The
+// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
+// auto-forwards), so we only need to verify the IPv4 loopback can bind.
+const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
+ startPort: number,
+): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
+ const net = yield* NetService.NetService;
+ for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
+ if (yield* net.canListenOnHost(port, "127.0.0.1")) {
+ return port;
+ }
+ }
+ return yield* new NetService.NetError({
+ message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
+ });
+});
+
+export const layer = Layer.effect(
+ DesktopWslBackend,
+ Effect.gen(function* () {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
+ const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
+ const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const net = yield* NetService.NetService;
+ // Serialize reconcile so the bootstrap fork and the IPC handlers
+ // (setWslBackendEnabled, setWslDistro) can't interleave. Without
+ // this, two reconciles could both observe "no WSL instance
+ // registered" between their pool reads and both call startNew
+ // with different distros, leaving the loser stranded.
+ const reconcileMutex = yield* Semaphore.make(1);
+
+ // Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
+ // inline in Connections settings. The primary's failure is handled by the
+ // pool (dialog + Windows fallback) instead; here the app stays usable on
+ // Windows, so we record the reason rather than interrupting. Cleared on any
+ // reconcile state change so it reflects the current attempt.
+ const preflightErrorRef = yield* Ref.make(Option.none<string>());
+
+ const findExistingWslInstance = pool.list.pipe(
+ Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
+ Effect.map(Option.fromNullishOr),
+ );
+
+ const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
+ pool.unregister(id).pipe(
+ Effect.catchTags({
+ DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
+ // Should never happen — wsl: ids are not the primary id — but
+ // log loudly if the logic ever drifts.
+ logWslBackendWarning("refusing to unregister primary as wsl instance", {
+ id,
+ error: cause.message,
+ }),
+ }),
+ );
+
+ const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
+ readonly distro: string | null;
+ }) {
+ const primaryConfig = yield* serverExposure.backendConfig;
+ const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
+ Effect.provideService(NetService.NetService, net),
+ Effect.map((value) => Option.some(value)),
+ Effect.catch((error) =>
+ logWslBackendWarning("could not allocate port for WSL backend", {
+ error: error.message,
+ }).pipe(Effect.as(Option.none<number>())),
+ ),
+ );
+
+ if (Option.isNone(port)) {
+ return;
+ }
+ const allocatedPort = port.value;
+
+ const targetId = resolveTargetInstanceId(input.distro);
+ yield* logWslBackendInfo("registering WSL backend with pool", {
+ id: targetId,
+ port: allocatedPort,
+ distro: input.distro ?? null,
+ });
+
+ const instance = yield* pool
+ .register({
+ id: targetId,
+ label: Effect.succeed(buildLabel(input.distro)),
+ configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
+ // Dual-mode secondary: record a fatal preflight failure so Connections
+ // settings can show why the WSL backend never appeared. No dialog or
+ // fallback — Windows is the primary and keeps working.
+ onPreflightFailed: (failure) =>
+ Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
+ onReady: () => Ref.set(preflightErrorRef, Option.none()),
+ })
+ .pipe(
+ Effect.map((registered) => Option.some(registered)),
+ Effect.catch((error) =>
+ logWslBackendWarning("WSL backend already registered, skipping start", {
+ id: targetId,
+ error: error.message,
+ }).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
+ ),
+ );
+
+ yield* Option.match(instance, {
+ onNone: () => Effect.void,
+ onSome: (registered) => registered.start,
+ });
+ });
+
+ const reconcileBody = Effect.gen(function* () {
+ const settings = yield* appSettings.get;
+ const available = yield* wslEnvironment.isAvailable;
+ const existing = yield* findExistingWslInstance;
+ const existingId = Option.map(existing, (instance) => instance.id);
+
+ // In wsl-only mode the pool's primary IS the WSL backend (see
+ // DesktopBackendConfiguration.resolvePrimary), so the
+ // orchestrator skips registering a parallel "wsl:<distro>"
+ // secondary. Without this skip we'd spin up two WSL processes
+ // on the same distro for users who explicitly asked for one.
+ const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
+ const targetId = shouldRun
+ ? Option.some(resolveTargetInstanceId(settings.wslDistro))
+ : Option.none<DesktopBackendPool.BackendInstanceId>();
+
+ // No-op if the desired state already matches what's registered.
+ if (Option.isNone(targetId) && Option.isNone(existingId)) {
+ return;
+ }
+ if (
+ Option.isSome(targetId) &&
+ Option.isSome(existing) &&
+ targetId.value === existing.value.id
+ ) {
+ const existingInstance = existing.value;
+ const snapshot = yield* existingInstance.snapshot;
+ const isIdle =
+ !snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
+ if (isIdle) {
+ yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
+ yield* Ref.set(preflightErrorRef, Option.none());
+ yield* existingInstance.start;
+ }
+ return;
+ }
+
+ // A real state change is happening (start, stop, or distro swap). Clear
+ // any stale secondary preflight error so it reflects this fresh attempt;
+ // onPreflightFailed re-sets it only if the new secondary exhausts retries.
+ yield* Ref.set(preflightErrorRef, Option.none());
+
+ if (Option.isSome(existingId)) {
+ yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
+ yield* stopExisting(existingId.value);
+ }
+
+ if (Option.isSome(targetId)) {
+ // Pre-warm the WSL VM before registering so the readiness probe
+ // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
+ // distro=null (uses the WSL default) and is bounded by its own
+ // timeout, so it's safe to await unconditionally here.
+ yield* wslEnvironment.preWarm(settings.wslDistro);
+ yield* startNew({ distro: settings.wslDistro });
+ }
+ });
+
+ // Top-level safety net. Every internal step today already catches
+ // its own failures (port allocation, register, preWarm), so the
+ // inferred error type is `never` and this catch is a no-op in
+ // steady state. It's here to enforce the file-header contract
+ // ("reconcile never fails; errors are logged") if a future change
+ // introduces an unhandled failure path — otherwise IPC callers
+ // like setWslBackendEnabled would surface it to the renderer as
+ // an opaque error.
+ const reconcile = reconcileMutex
+ .withPermits(1)(reconcileBody)
+ .pipe(
+ Effect.catchCause((cause) =>
+ logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
+ ),
+ Effect.withSpan("desktop.wslBackend.reconcile"),
+ );
+
+ return DesktopWslBackend.of({
+ reconcile,
+ lastPreflightError: Ref.get(preflightErrorRef),
+ });
+ }),
+);
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
new file mode 100644
index 000000000..cdb3fc782
--- /dev/null
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -0,0 +1,237 @@
+import { describe, it } from "@effect/vitest";
+import { expect } from "vite-plus/test";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import * as TestClock from "effect/testing/TestClock";
+import { ChildProcessSpawner } from "effect/unstable/process";
+
+import {
+ buildWslNodeEnvPreamble,
+ DesktopWslDistroListError,
+ formatMissingToolsReason,
+ formatNodePtyProbeFailureReason,
+ formatWslShellTransportFailureReason,
+ parseNodePath,
+ parseResolvedPath,
+ parseToolchainReport,
+ probeWslDistros,
+} from "./DesktopWslEnvironment.ts";
+
+const encoder = new TextEncoder();
+
+const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
+ ChildProcessSpawner.make(() =>
+ Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode:
+ result.exitCode === undefined
+ ? Effect.never
+ : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
+ isRunning: Effect.succeed(result.exitCode === undefined),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.make(encoder.encode(result.stdout ?? "")),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ ),
+ );
+
+describe("probeWslDistros", () => {
+ it.effect("preserves a successful empty distro list", () =>
+ Effect.gen(function* () {
+ const distros = yield* probeWslDistros;
+ expect(distros).toEqual([]);
+ }).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ makeDistroListSpawner({ stdout: "", exitCode: 0 }),
+ ),
+ ),
+ );
+
+ it.effect("fails when the distro-list command exits unsuccessfully", () =>
+ Effect.gen(function* () {
+ const error = yield* probeWslDistros.pipe(Effect.flip);
+ expect(error).toBeInstanceOf(DesktopWslDistroListError);
+ expect(error.message).toContain("exited with code 1");
+ }).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ makeDistroListSpawner({ exitCode: 1 }),
+ ),
+ ),
+ );
+
+ it.effect("fails when the distro-list command times out", () => {
+ const layer = Layer.merge(
+ TestClock.layer(),
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
+ );
+ return Effect.gen(function* () {
+ const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
+ yield* Effect.yieldNow;
+ yield* TestClock.adjust(Duration.seconds(8));
+ const error = yield* Fiber.join(fiber);
+ expect(error).toBeInstanceOf(DesktopWslDistroListError);
+ expect(error.message).toContain("timed out");
+ }).pipe(Effect.provide(layer));
+ });
+});
+
+describe("formatNodePtyProbeFailureReason", () => {
+ it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
+ const reason = formatNodePtyProbeFailureReason(4);
+
+ expect(reason).toContain("packaged Linux node-pty binary was not included");
+ expect(reason).toContain("--wsl-prebuild");
+ });
+
+ it("leaves other node-pty load failures to the compatibility diagnostic", () => {
+ expect(formatNodePtyProbeFailureReason(1)).toBeNull();
+ });
+});
+
+describe("formatWslShellTransportFailureReason", () => {
+ it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
+ expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
+ expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
+ expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
+ expect(formatWslShellTransportFailureReason(null)).toBeNull();
+ });
+});
+
+describe("buildWslNodeEnvPreamble", () => {
+ it("passes the required Node engine range into the shared resolver", () => {
+ const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
+
+ expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
+ expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
+ preamble.lastIndexOf("ensure_remote_node_path || true"),
+ );
+ });
+
+ it("keeps the shared resolver permissive when no Node engine range is provided", () => {
+ expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
+ });
+});
+
+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("parseNodePath", () => {
+ it("extracts the absolute node path from a nodePath: line", () => {
+ const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
+ expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
+ });
+
+ it("returns null when node was not found (empty value after prefix)", () => {
+ expect(parseNodePath("nodePath:")).toBeNull();
+ });
+
+ it("returns null when there is no nodePath line at all", () => {
+ expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
+ });
+
+ it("ignores surrounding noise and trims whitespace", () => {
+ const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
+ expect(parseNodePath(stdout)).toBe("/usr/bin/node");
+ });
+});
+
+describe("parseResolvedPath", () => {
+ it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
+ const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
+ expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
+ resolvedPath,
+ );
+ });
+
+ it("accepts CRLF output without retaining the carriage return", () => {
+ expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
+ "/usr/local/bin:/usr/bin",
+ );
+ });
+
+ it("returns null when the resolved PATH is absent or empty", () => {
+ expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
+ expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
+ });
+});
+
+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");
+ });
+});
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
new file mode 100644
index 000000000..b38675f0e
--- /dev/null
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -0,0 +1,849 @@
+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 Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
+
+import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
+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);
+const USER_HOME_TIMEOUT = Duration.seconds(5);
+const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
+const BUILD_TRANSPORT_RETRY_LIMIT = 2;
+
+export interface EnsureWslNodePtyOptions {
+ readonly allowBuild?: boolean;
+ readonly nodeEngineRange?: string | null;
+}
+
+export type EnsureWslNodePtyResult =
+ | { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
+ | {
+ readonly ok: false;
+ readonly reason: string;
+ readonly fatal: boolean;
+ readonly retryLimit?: number;
+ };
+
+export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
+ "DesktopWslDistroListError",
+ { reason: Schema.String },
+) {
+ override get message(): string {
+ return this.reason;
+ }
+}
+
+const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
+
+export class DesktopWslEnvironment extends Context.Service<
+ DesktopWslEnvironment,
+ {
+ readonly isAvailable: Effect.Effect<boolean>;
+ // Best-effort enumeration for renderer UX. Backend health checks must use
+ // probeDistros so a transient command failure is not mistaken for a
+ // successful empty installation.
+ readonly listDistros: Effect.Effect<readonly WslDistro[]>;
+ readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
+ readonly preWarm: (distro: string | null) => Effect.Effect<void>;
+ readonly windowsToWslPath: (
+ distro: string | null,
+ windowsPath: string,
+ ) => Effect.Effect<Option.Option<string>>;
+ // Resolves the user's Linux home dir inside the chosen distro (e.g.
+ // "/home/josh"). Used by the folder picker to expand `~` correctly.
+ readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
+ // Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
+ // (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
+ // httpBaseUrl so the renderer can reach it without relying on wslhost's
+ // localhost→WSL automatic forwarding, which is flaky in practice
+ // (the backend can be listening for 30+ seconds before wslhost starts
+ // forwarding 127.0.0.1:port to WSL-side localhost).
+ readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
+ readonly ensureNodePty: (
+ distro: string | null,
+ windowsRepoRoot: string,
+ options?: EnsureWslNodePtyOptions,
+ ) => Effect.Effect<EnsureWslNodePtyResult>;
+ }
+>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
+
+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;
+ readonly transportFailure: "timeout" | "spawn" | "process" | null;
+}
+
+const TIMEOUT_RESULT: ShellResult = {
+ exitCode: 124,
+ stdout: "",
+ stderr: "\n[timeout]",
+ transportFailure: "timeout",
+};
+
+export const formatWslShellTransportFailureReason = (
+ failure: ShellResult["transportFailure"],
+): string | null => {
+ switch (failure) {
+ case "timeout":
+ return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
+ case "spawn":
+ return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
+ case "process":
+ return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
+ case null:
+ return null;
+ }
+};
+
+// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
+// the same way. Passing the engine range lets the resolver fall through to
+// version managers like nvm when a system node exists but is too old.
+export const buildWslNodeEnvPreamble = (
+ nodeEngineRange?: string | null,
+): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
+ensure_remote_node_path || true
+`;
+
+// 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,
+ options: EnsureWslNodePtyOptions = {},
+): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
+ const spawner = ChildProcessSpawner.ChildProcessSpawner;
+ // -l picks up profile-managed PATH; the shared resolver covers supported
+ // version managers that non-interactive login shells can miss. -s so bash
+ // reads the script from stdin.
+ const command = ChildProcess.make(
+ "wsl.exe",
+ [...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
+ {
+ stdin: Stream.encodeText(
+ Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
+ ),
+ stdout: "pipe",
+ stderr: "pipe",
+ killSignal: "SIGTERM",
+ forceKillAfter: PROCESS_TERMINATE_GRACE,
+ },
+ );
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const spawnerService = yield* spawner;
+ const spawnResult = yield* spawnerService.spawn(command).pipe(
+ Effect.match({
+ onFailure: (error) => ({ _tag: "Failure", error }) as const,
+ onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
+ }),
+ );
+ if (spawnResult._tag === "Failure") {
+ return {
+ exitCode: 127,
+ stdout: "",
+ stderr: `\n${spawnResult.error.message}`,
+ transportFailure: "spawn",
+ } satisfies ShellResult;
+ }
+ const handle = spawnResult.handle;
+ // Drain stdout and stderr concurrently so neither pipe buffer can fill
+ // and stall the child (node-gyp rebuild emits large output on both).
+ const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
+ [Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
+ { concurrency: "unbounded" },
+ );
+ return {
+ exitCode: exitCode as unknown as number,
+ stdout: decodeUtf8(concatChunks(stdoutBytes)),
+ stderr: decodeUtf8(concatChunks(stderrBytes)),
+ transportFailure: null,
+ } 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}`,
+ transportFailure: "process",
+ }),
+ ),
+ );
+};
+
+const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
+
+const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
+
+export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
+ exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
+ ? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
+ : null;
+
+const NODE_PTY_PROBE_SCRIPT = (
+ linuxServerDir: string,
+) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
+printf 'resolvedPath:%s\\n' "$PATH"
+cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
+// The server bundle externalizes its deps to node_modules, and the WSL Node
+// can't read inside app.asar, so confirm those deps are unpacked on the real
+// filesystem before reporting the backend healthy. "effect" is the framework
+// every server module imports; resolving it validates the whole node_modules
+// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
+// report it accurately instead of letting the server crash on
+// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
+// launch with no fallback).
+try { require.resolve("effect"); } catch (_e) { process.exit(3); }
+const fs = require("node:fs");
+const path = require("node:path");
+const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
+// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
+// Node versions — require() succeeding IS the real compatibility test. Compare
+// only arch and node-pty version (a stale binary from a different node-pty),
+// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
+// whenever the user's WSL Node ABI differs from the build's, defeating the
+// whole point of shipping one prebuilt for all Node versions.
+const expected = {
+ arch: process.arch,
+ nodePtyVersion: require("node-pty/package.json").version,
+};
+const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
+const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
+const binary = path.join(prebuildDir, "pty.node");
+if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
+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 };
+};
+
+// Pulls the absolute node path the WSL distro resolved after the shared remote
+// resolver repaired PATH. Returns null when no node was found, which the caller
+// turns into an actionable "install Node" message instead of a confusing
+// node-pty error.
+export const parseNodePath = (stdout: string): string | null => {
+ const path = stdout
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.startsWith("nodePath:"))
+ .map((line) => line.slice("nodePath:".length).trim())
+ .find((value) => value.length > 0);
+ return path ?? null;
+};
+
+// Captures the login-shell PATH after the shared resolver has loaded version
+// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
+// paths containing spaces or apostrophes can be forwarded as one env argv.
+export const parseResolvedPath = (stdout: string): string | null => {
+ const prefix = "resolvedPath:";
+ const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
+ if (line === undefined) return null;
+ const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
+ return resolvedPath.length > 0 ? resolvedPath : null;
+};
+
+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}`,
+ fatal: false,
+ } 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,
+ options,
+ );
+ const nodePath = parseNodePath(probe.stdout);
+ const resolvedPath = parseResolvedPath(probe.stdout);
+
+ const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
+ if (transportFailureReason !== null) {
+ return { ok: false, reason: transportFailureReason, fatal: false } as const;
+ }
+
+ // No node at all, even after the shared resolver repaired PATH. Surface
+ // the specific, actionable toolchain message rather than a confusing
+ // node-pty error, and don't try to build.
+ if (nodePath === null) {
+ const toolchainCheck = yield* runWslShell(
+ distro,
+ TOOLCHAIN_CHECK_SCRIPT,
+ TOOLCHAIN_TIMEOUT,
+ options,
+ );
+ const toolchainTransportFailure = formatWslShellTransportFailureReason(
+ toolchainCheck.transportFailure,
+ );
+ if (toolchainTransportFailure !== null) {
+ return {
+ ok: false,
+ reason: toolchainTransportFailure,
+ fatal: false,
+ retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
+ } as const;
+ }
+ const report = parseToolchainReport(toolchainCheck.stdout);
+ const reason =
+ formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
+ "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
+ return { ok: false, reason, fatal: true } as const;
+ }
+
+ if (resolvedPath === null) {
+ return {
+ ok: false,
+ reason: "WSL login-shell PATH could not be resolved during backend preflight.",
+ fatal: true,
+ } as const;
+ }
+
+ // Server dependencies (e.g. "effect") couldn't be resolved on the WSL
+ // filesystem — a packaging regression, since the server bundle needs its
+ // node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
+ // Windows and dual mode surfaces the reason inline, instead of the server
+ // crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
+ if (probe.exitCode === 3) {
+ return {
+ ok: false,
+ reason:
+ "WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
+ fatal: true,
+ } as const;
+ }
+
+ if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
+
+ if (options.allowBuild !== true) {
+ const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
+ if (packagedProbeFailure !== null) {
+ return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
+ }
+ }
+
+ // node is present but node-pty's native module didn't load.
+ const toolchainCheck = yield* runWslShell(
+ distro,
+ TOOLCHAIN_CHECK_SCRIPT,
+ TOOLCHAIN_TIMEOUT,
+ options,
+ );
+ const toolchainTransportFailure = formatWslShellTransportFailureReason(
+ toolchainCheck.transportFailure,
+ );
+ if (toolchainTransportFailure !== null) {
+ return {
+ ok: false,
+ reason: toolchainTransportFailure,
+ fatal: false,
+ retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
+ } as const;
+ }
+ const report = parseToolchainReport(toolchainCheck.stdout);
+
+ if (options.allowBuild !== true) {
+ // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
+ // or network is needed — and we must not nag the user to install build
+ // tools they don't need. Still surface a missing/too-old Node (both the
+ // prebuilt and the server require a compatible Node); otherwise reaching
+ // here means the bundled binary itself couldn't load, which is almost
+ // always an unsupported CPU architecture or incompatible system libraries.
+ const nodeOnlyReason = formatMissingToolsReason(
+ {
+ missingTools: report.missingTools.filter((tool) => tool === "node"),
+ nodeVersion: report.nodeVersion,
+ },
+ options.nodeEngineRange?.trim() || null,
+ );
+ return {
+ ok: false,
+ reason:
+ nodeOnlyReason ??
+ "The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
+ fatal: true,
+ } as const;
+ }
+
+ // Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
+ // source. Run the toolchain check first so a missing compiler or out-of-range
+ // Node surfaces a specific, actionable message instead of an opaque node-gyp
+ // failure. Developers have the toolchain; end users never reach this path.
+ const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
+ if (missingReason !== null) {
+ return { ok: false, reason: missingReason, fatal: true } as const;
+ }
+
+ const build = yield* runWslShell(
+ distro,
+ NODE_PTY_BUILD_SCRIPT(linuxServerDir),
+ BUILD_TIMEOUT,
+ options,
+ );
+ const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
+ if (buildTransportFailure !== null) {
+ return {
+ ok: false,
+ reason: buildTransportFailure,
+ fatal: false,
+ retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
+ } as const;
+ }
+ if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } 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"}`,
+ fatal: true,
+ } as const;
+ });
+
+export const probeWslDistros: Effect.Effect<
+ readonly WslDistro[],
+ DesktopWslDistroListError,
+ 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 yield* new DesktopWslDistroListError({
+ reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
+ });
+ }
+ return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
+ }),
+).pipe(
+ Effect.mapError((error) =>
+ isDesktopWslDistroListError(error)
+ ? error
+ : new DesktopWslDistroListError({
+ reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
+ }),
+ ),
+ Effect.timeoutOption(LIST_TIMEOUT),
+ Effect.flatMap(
+ Option.match({
+ onNone: () =>
+ new DesktopWslDistroListError({
+ reason: "wsl.exe --list --verbose timed out",
+ }),
+ onSome: Effect.succeed,
+ }),
+ ),
+);
+
+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.orElseSucceed(() => Option.none<string>()),
+ );
+};
+
+const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
+
+const getDistroIpImpl = (
+ distro: string | null,
+): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ // `hostname -I` prints a space-separated list of all non-loopback
+ // IPs the distro has bound. The first entry on the WSL2 default
+ // network is always the eth0 vEthernet address Windows can reach
+ // directly (no wslhost forwarding required).
+ const command = ChildProcess.make(
+ "wsl.exe",
+ [...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
+ {
+ 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 raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
+ const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
+ return candidate ? Option.some(candidate) : Option.none<string>();
+ }),
+ ).pipe(
+ Effect.timeoutOption(USER_HOME_TIMEOUT),
+ Effect.map(Option.flatten),
+ Effect.orElseSucceed(() => Option.none<string>()),
+ );
+
+const getUserHomeImpl = (
+ distro: string | null,
+): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const command = ChildProcess.make(
+ "wsl.exe",
+ // printf so there's no trailing newline noise; getent so we get the
+ // real home from /etc/passwd even if $HOME is unset for some reason.
+ [
+ ...buildDistroArgs(distro),
+ "--",
+ "sh",
+ "-c",
+ 'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
+ ],
+ {
+ 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 home = decodeUtf8(concatChunks(stdoutBytes)).trim();
+ return home.startsWith("/") ? Option.some(home) : Option.none<string>();
+ }),
+ ).pipe(
+ Effect.timeoutOption(USER_HOME_TIMEOUT),
+ Effect.map(Option.flatten),
+ Effect.orElseSucceed(() => 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 distroListError?: DesktopWslDistroListError;
+ readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
+ readonly getUserHome?: (distro: string | null) => Option.Option<string>;
+ readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
+ readonly ensureNodePty?: (
+ distro: string | null,
+ windowsRepoRoot: string,
+ options?: EnsureWslNodePtyOptions,
+ ) => EnsureWslNodePtyResult;
+}
+
+export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
+ const probeDistros = stub.distroListError
+ ? Effect.fail(stub.distroListError)
+ : Effect.succeed(stub.distros ?? []);
+ return Layer.succeed(
+ DesktopWslEnvironment,
+ DesktopWslEnvironment.of({
+ isAvailable: Effect.succeed(stub.isAvailable ?? false),
+ listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
+ probeDistros,
+ preWarm: () => Effect.void,
+ windowsToWslPath: (distro, windowsPath) =>
+ Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
+ getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
+ getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
+ ensureNodePty: (distro, windowsRepoRoot, options) =>
+ Effect.succeed(
+ stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
+ ok: false,
+ reason: "ensureNodePty stub not configured",
+ fatal: true,
+ },
+ ),
+ }),
+ );
+};
+
+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));
+
+ // Probe wsl.exe once at layer init and cache the result, exposing
+ // `isAvailable` as a resolved value rather than a re-running effect.
+ // WSL availability is effectively static for the process lifetime — the
+ // Windows feature isn't added/removed mid-session, and backend mode
+ // changes already require an app restart — so the cached boolean stays
+ // accurate. Crucially this keeps `isAvailable` synchronously resolvable:
+ // it's read inside the sync IPC handler getLocalEnvironmentBootstraps
+ // (via the primary instance's lazy label -> resolvePrimaryLabel ->
+ // describePrimary). The underlying probe does a filesystem `exists`
+ // check, so leaving it as a live effect would make Effect.runSync throw
+ // there and break the renderer's synchronous bootstrap path.
+ const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(Path.Path, environment.path),
+ Effect.withSpan("desktop.wsl.isAvailable"),
+ );
+ const isAvailable = Effect.succeed(wslAvailable);
+
+ const windowsToWslPath = (distro: string | null, windowsPath: string) =>
+ provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
+ Effect.withSpan("desktop.wsl.windowsToWslPath"),
+ );
+
+ // Cache user-home results per distro key — folder picker can be opened
+ // many times in a session and the value is stable for the life of the
+ // distro. Negative results aren't cached so a transient wsl.exe failure
+ // doesn't permanently disable tilde expansion.
+ const userHomeCache = new Map<string, string>();
+ const getUserHome = (distro: string | null) =>
+ Effect.gen(function* () {
+ const key = distro ?? "__default__";
+ const cached = userHomeCache.get(key);
+ if (cached !== undefined) return Option.some(cached);
+ const resolved = yield* provideSpawner(getUserHomeImpl(distro));
+ if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
+ return resolved;
+ }).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
+
+ const getDistroIp = (distro: string | null) =>
+ provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
+
+ const probeDistros = provideSpawner(probeWslDistros).pipe(
+ Effect.withSpan("desktop.wsl.probeDistros"),
+ );
+
+ return DesktopWslEnvironment.of({
+ isAvailable,
+ listDistros: probeDistros.pipe(
+ Effect.orElseSucceed(() => []),
+ Effect.withSpan("desktop.wsl.listDistros"),
+ ),
+ probeDistros,
+ preWarm: (distro) =>
+ provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
+ windowsToWslPath,
+ getUserHome,
+ getDistroIp,
+ ensureNodePty: (distro, windowsRepoRoot, options) =>
+ provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
+ Effect.withSpan("desktop.wsl.ensureNodePty"),
+ ),
+ });
+ }),
+);
diff --git a/apps/desktop/src/wsl/wslPathParsing.test.ts b/apps/desktop/src/wsl/wslPathParsing.test.ts
new file mode 100644
index 000000000..41e358227
--- /dev/null
+++ b/apps/desktop/src/wsl/wslPathParsing.test.ts
@@ -0,0 +1,206 @@
+import { describe, it, expect } from "vite-plus/test";
+
+import {
+ DISTRO_NAME_PATTERN,
+ extractDistroFromUncPath,
+ isValidDistroName,
+ parseWslDistroList,
+ resolveWslHomeUncPath,
+ resolveWslPickFolderDefaultPath,
+ wslUncPathToLinuxPath,
+} 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("wslUncPathToLinuxPath", () => {
+ it("maps WSL UNC paths back to Linux absolute paths", () => {
+ expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toBe(
+ "/home/josh/repo",
+ );
+ });
+
+ it("maps a distro UNC root to Linux root", () => {
+ expect(wslUncPathToLinuxPath("\\\\wsl$\\Debian")).toBe("/");
+ expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/");
+ });
+
+ it("rejects invalid distro names and non-WSL paths", () => {
+ expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
+ expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).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({ distro: "Ubuntu" }, distros)).toBe(
+ "\\\\wsl.localhost\\Ubuntu\\home",
+ );
+ });
+
+ it("uses the actual default distro when config uses the WSL default", () => {
+ expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
+ "\\\\wsl.localhost\\Debian\\home",
+ );
+ });
+
+ it("omits the default path when no default distro is known", () => {
+ expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
+ });
+});
+
+describe("resolveWslPickFolderDefaultPath", () => {
+ const config = { 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("expands ~/path against the user's home dir when known", () => {
+ expect(
+ resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros, "/home/josh"),
+ ).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
+ });
+
+ it("resolves bare ~ to the user's home dir when known", () => {
+ expect(
+ resolveWslPickFolderDefaultPath({ initialPath: "~" }, config, distros, "/home/josh"),
+ ).toBe("\\\\wsl.localhost\\Debian\\home\\josh");
+ });
+
+ it("falls back to /home parent when the user's home dir isn't known", () => {
+ 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);
+ }
+ });
+});
diff --git a/apps/desktop/src/wsl/wslPathParsing.ts b/apps/desktop/src/wsl/wslPathParsing.ts
new file mode 100644
index 000000000..edbab81f6
--- /dev/null
+++ b/apps/desktop/src/wsl/wslPathParsing.ts
@@ -0,0 +1,129 @@
+export interface WslDistro {
+ readonly name: string;
+ readonly isDefault: boolean;
+ readonly version: 1 | 2;
+}
+
+export interface WslConfig {
+ readonly distro: string | 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 wslUncPathToLinuxPath(windowsPath: string): string | null {
+ const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath.trim());
+ if (!match) return null;
+
+ const distro = match[1]!;
+ if (!DISTRO_NAME_PATTERN.test(distro)) return null;
+
+ const rest = match[2] ?? "";
+ if (rest.length === 0) return "/";
+
+ return `/${rest.split("\\").filter(Boolean).join("/")}`;
+}
+
+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[],
+ // Absolute Linux path of the user's home dir inside the chosen distro
+ // (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
+ // we don't open the picker at a non-existent `/home/<rest>`. When null we
+ // fall back to the `/home` parent — wrong directory but at least it exists.
+ userHome: string | null = null,
+): 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("/", "\\")}`;
+
+ const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
+
+ if (trimmedPath === "~") {
+ return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
+ }
+ if (trimmedPath.startsWith("~/")) {
+ const remainder = trimmedPath.slice(2);
+ if (normalizedUserHome) {
+ return toUncPath(`${normalizedUserHome}/${remainder}`);
+ }
+ return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
+ }
+ if (trimmedPath.startsWith("/")) {
+ return toUncPath(trimmedPath);
+ }
+
+ return homePath;
+}
+
+export function isValidDistroName(value: string): boolean {
+ return DISTRO_NAME_PATTERN.test(value);
+}
diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts
index 53b1a7e79..5242dd738 100644
--- a/apps/server/src/auth/PairingGrantStore.test.ts
+++ b/apps/server/src/auth/PairingGrantStore.test.ts
@@ -137,11 +137,12 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
}).pipe(Effect.provide(makePairingGrantStoreLayer())),
);
- it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
+ it.effect("seeds the desktop bootstrap credential as a reusable grant", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
- const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
+ const second = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
+ const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
expect(first.method).toBe("desktop-bootstrap");
expect(first.scopes).toEqual([
@@ -155,7 +156,8 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
"relay:write",
]);
expect(first.subject).toBe("desktop-bootstrap");
- expect(second._tag).toBe("UnknownBootstrapCredentialError");
+ expect(second.method).toBe("desktop-bootstrap");
+ expect(third.method).toBe("desktop-bootstrap");
}).pipe(
Effect.provide(
makePairingGrantStoreLayer({
@@ -169,7 +171,13 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
- yield* TestClock.adjust(Duration.minutes(6));
+ // The desktop-bootstrap grant lives for 24h. Within that window
+ // it stays reusable.
+ yield* TestClock.adjust(Duration.hours(12));
+ const stillValid = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
+ expect(stillValid.method).toBe("desktop-bootstrap");
+
+ yield* TestClock.adjust(Duration.hours(13));
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts
index 7a8fb9477..588d5e377 100644
--- a/apps/server/src/auth/PairingGrantStore.ts
+++ b/apps/server/src/auth/PairingGrantStore.ts
@@ -234,6 +234,15 @@ type ConsumeResult =
};
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
+// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or
+// stdin) at backend launch, so it doesn't have to be short-lived the
+// way a user-facing pairing link does. Letting it live for the
+// lifetime of the backend process (24h is more than long enough for
+// practical desktop use, and well under "forever" in case the seed
+// gets logged anywhere by accident) means a page reload past the 5-min
+// window can still recover by re-bootstrapping rather than locking
+// the user out of the backend.
+const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -295,9 +304,14 @@ export const make = Effect.gen(function* () {
scopes: AuthAdministrativeScopes,
subject: "desktop-bootstrap",
expiresAt: DateTime.add(now, {
- milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
+ milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
}),
- remainingUses: 1,
+ // Unbounded uses so the renderer can re-exchange the seed for a
+ // fresh bearer session after a page reload (or after the prior
+ // bearer expires). The seed itself stays inside the desktop
+ // process and the rendered page, both of which the user already
+ // implicitly trusts.
+ remainingUses: "unbounded",
});
}
diff --git a/apps/server/src/bootstrap.ts b/apps/server/src/bootstrap.ts
index 0f2a5a436..04dcf277e 100644
--- a/apps/server/src/bootstrap.ts
+++ b/apps/server/src/bootstrap.ts
@@ -222,9 +222,12 @@ const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {
}
};
+// Stdin pipes inherited across the wsl.exe boundary report EACCES when we try
+// to re-open them via /proc/self/fd/0 — fall back to reading the fd directly
+// in that case, the same way we already do for ENXIO/EINVAL/EPERM.
const isBootstrapFdPathDuplicationError = Predicate.compose(
Predicate.hasProperty("code"),
- (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
+ (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM" || _.code === "EACCES",
);
function resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {
diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts
index 5ffb69cd5..f33a9bbce 100644
--- a/apps/server/src/provider/providerMaintenanceRunner.test.ts
+++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts
@@ -17,6 +17,8 @@ import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
+import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
+import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
@@ -35,6 +37,12 @@ const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
const encoder = new TextEncoder();
+// Pin a non-win32 platform so `resolveSpawnCommand` is a no-op and the raw
+// `{ command, args }` assertions below hold deterministically on any host
+// (including Windows). Windows-specific resolution is covered by the dedicated
+// win32 case at the end of this suite.
+const NonWindowsPlatform = Layer.succeed(HostProcessPlatform, "linux");
+
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
if (provider === CURSOR_DRIVER) {
return makeProviderMaintenanceCapabilities({
@@ -230,6 +238,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer((command, args) => {
calls.push({ command, args });
@@ -279,6 +288,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer((command, args) => {
calls.push({ command, args });
@@ -309,6 +319,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer((command, args) => {
calls.push({ command, args });
@@ -381,6 +392,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.124.0-alpha.3"),
mockSpawnerLayer((command, args) => {
calls.push({ command, args });
@@ -405,6 +417,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
),
@@ -430,6 +443,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("9.9.9"),
mockSpawnerLayer(() => ({ stdout: "updated" })),
),
@@ -468,6 +482,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer(() => {
startedLatch.resolve();
@@ -544,6 +559,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer((_command, args) => {
calls.push(args.join(" "));
@@ -587,6 +603,7 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer((_command, args) => {
calls.push(args.join(" "));
@@ -641,10 +658,73 @@ describe("providerMaintenanceRunner", () => {
}).pipe(
Effect.provide(
Layer.mergeAll(
+ NonWindowsPlatform,
latestVersionHttpClient("0.0.0"),
mockSpawnerLayer(() => ({ stdout: "updated" })),
),
),
),
);
+
+ it.effect("resolves npm to a .cmd shim and routes through the shell on win32", () => {
+ const captured: Array<{
+ readonly command: string;
+ readonly args: ReadonlyArray<string>;
+ readonly shell: boolean | string | undefined;
+ }> = [];
+ return Effect.gen(function* () {
+ const { registry } = yield* makeRegistry(baseProvider);
+ const runner = yield* makeTestRunner(registry);
+
+ const result = yield* runner.updateProvider(CODEX_DRIVER);
+
+ // On win32, resolveSpawnCommand resolves `npm` to the `.cmd` shim and
+ // routes the spawn through cmd.exe (shell: true), escaping every arg.
+ assert.strictEqual(captured.length, 1);
+ const call = captured[0];
+ assert.ok(call, "expected the spawner to be invoked once");
+ // The resolved command is the escaped `.cmd` path. Asserting the precise
+ // escaped string is brittle, so verify it carries the resolved shim and
+ // that shell mode was used.
+ assert.match(call.command, /npm\.cmd/i);
+ assert.strictEqual(call.shell, true);
+ // Args are escaped for cmd.exe shell mode (each quoted) but still carry
+ // the original install command (`install -g @openai/codex@latest`) in order.
+ assert.strictEqual(call.args.length, 3);
+ assert.match(call.args[0] ?? "", /install/);
+ assert.match(call.args[1] ?? "", /-g/);
+ assert.match(call.args[2] ?? "", /@openai\/codex@latest/);
+ assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ Layer.succeed(HostProcessPlatform, "win32"),
+ Layer.succeed(HostProcessEnvironment, {
+ PATH: "C:\\fake\\npm",
+ PATHEXT: ".COM;.EXE;.BAT;.CMD",
+ }),
+ Layer.succeed(SpawnExecutableResolution, (command) =>
+ command === "npm" ? "C:\\fake\\npm\\npm.cmd" : undefined,
+ ),
+ latestVersionHttpClient("0.0.0"),
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) => {
+ const childProcess = command as unknown as {
+ readonly command: string;
+ readonly args: ReadonlyArray<string>;
+ readonly options: { readonly shell?: boolean | string | undefined };
+ };
+ captured.push({
+ command: childProcess.command,
+ args: childProcess.args,
+ shell: childProcess.options.shell,
+ });
+ return Effect.succeed(mockHandle({ stdout: "updated" }));
+ }),
+ ),
+ ),
+ ),
+ );
+ });
});
diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts
index f04e97a13..3c114dd83 100644
--- a/apps/server/src/provider/providerMaintenanceRunner.ts
+++ b/apps/server/src/provider/providerMaintenanceRunner.ts
@@ -7,6 +7,7 @@ import {
type ServerProviderUpdatedPayload,
type ServerProviderUpdateState,
} from "@t3tools/contracts";
+import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
@@ -75,8 +76,14 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
}) {
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
function* () {
+ // Resolve the executable for the host platform before spawning. On
+ // Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),
+ // which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);
+ // resolveSpawnCommand finds the real `.cmd` and routes it through the
+ // shell. On Linux/macOS (incl. the WSL backend) this is a no-op.
+ const resolved = yield* resolveSpawnCommand(input.command, input.args);
const child = yield* input.spawner
- .spawn(ChildProcess.make(input.command, [...input.args]))
+ .spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))
.pipe(
Effect.mapError(
(cause) =>
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 6944dd640..26528c84d 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -3680,18 +3680,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
- it.effect("rejects reusing the same bootstrap credential after it has been exchanged", () =>
+ it.effect("allows reusing the desktop bootstrap credential", () =>
Effect.gen(function* () {
+ // The desktop-bootstrap grant is delivered over trusted IPC at
+ // backend launch and needs to stay claimable after a renderer
+ // refresh, so it's intentionally reusable (unlike user-facing
+ // one-time pairing credentials).
yield* buildAppUnderTest();
const first = yield* bootstrapBrowserSession();
const second = yield* bootstrapBrowserSession();
assert.equal(first.response.status, 200);
- assert.equal(second.response.status, 401);
- assert.equal((second.body as { readonly _tag?: string })._tag, "EnvironmentAuthInvalidError");
- assert.equal((second.body as { readonly code?: string }).code, "auth_invalid");
- assert.equal((second.body as { readonly reason?: string }).reason, "invalid_credential");
+ assert.equal(second.response.status, 200);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts
index ced16c15f..1a79f729b 100644
--- a/apps/web/src/authBootstrap.test.ts
+++ b/apps/web/src/authBootstrap.test.ts
@@ -74,13 +74,16 @@ function installTestBrowser(url: string) {
function installDesktopBootstrap() {
const testWindow = installTestBrowser("http://localhost/");
testWindow.desktopBridge = {
- getLocalEnvironmentBootstrap: () => ({
- label: "Local environment",
- httpBaseUrl: "http://localhost:3773",
- wsBaseUrl: "ws://localhost:3773",
- bootstrapToken: "desktop-bootstrap-token",
- }),
- } as DesktopBridge;
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Local environment",
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ },
+ ],
+ } as unknown as DesktopBridge;
}
function sequence<A>(...values: ReadonlyArray<A>) {
@@ -143,7 +146,18 @@ describe("resolveInitialServerAuthGateState", () => {
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
- installDesktopBootstrap();
+ const testWindow = installTestBrowser("http://localhost/");
+ testWindow.desktopBridge = {
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Windows",
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ },
+ ],
+ } as unknown as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
@@ -192,12 +206,15 @@ describe("resolveInitialServerAuthGateState", () => {
const testWindow = installTestBrowser("http://127.0.0.1:5733/");
testWindow.desktopBridge = {
- getLocalEnvironmentBootstrap: () => ({
- label: "Local environment",
- httpBaseUrl: "http://127.0.0.1:3773",
- wsBaseUrl: "ws://127.0.0.1:3773",
- }),
- } as DesktopBridge;
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Windows",
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ },
+ ],
+ } as unknown as DesktopBridge;
const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
await import("./environments/primary");
@@ -373,7 +390,18 @@ describe("resolveInitialServerAuthGateState", () => {
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
- installDesktopBootstrap();
+ const testWindow = installTestBrowser("http://localhost/");
+ testWindow.desktopBridge = {
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Windows",
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ },
+ ],
+ } as unknown as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index a11d6c4cb..8dccf9844 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -8,6 +8,7 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import {
DEFAULT_MODEL,
+ type DesktopWslState,
type EnvironmentId,
type FilesystemBrowseResult,
type ProjectId,
@@ -15,6 +16,7 @@ import {
type SourceControlDiscoveryResult,
type SourceControlProviderKind,
type SourceControlRepositoryInfo,
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import * as Option from "effect/Option";
@@ -44,9 +46,12 @@ import {
} from "react";
import { useAtomValue } from "@effect/atom-react";
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
+import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
+import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useClientSettings } from "../hooks/useSettings";
import { readLocalApi } from "../localApi";
+import { desktopLocalBackendId } from "../connection/desktopLocal";
import { filesystemEnvironment } from "../state/filesystem";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
@@ -79,6 +84,12 @@ import { getLatestThreadForProject } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
+import {
+ applyWslEnvironmentConfiguration,
+ parseWslUncPath,
+ resolveProjectPickerTarget,
+ resolveWslProjectSelection,
+} from "../wslPaths";
import {
ADDON_ICON_CLASS,
buildBrowseGroups,
@@ -458,6 +469,7 @@ function OpenCommandPaletteDialog(props: {
reportFailure: false,
});
const { environments } = useEnvironments();
+ const desktopLocalBootstraps = useDesktopLocalBootstraps();
const primaryEnvironment = usePrimaryEnvironment();
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
useHandleNewThread();
@@ -500,9 +512,43 @@ function OpenCommandPaletteDialog(props: {
return options;
}, [environments]);
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
+ const wslAddProjectEnvironmentOption = useMemo(
+ () =>
+ addProjectEnvironmentOptions.find((option) => {
+ const environment = environments.find(
+ (candidate) => candidate.environmentId === option.environmentId,
+ );
+ return environment
+ ? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true
+ : false;
+ }) ?? null,
+ [addProjectEnvironmentOptions, environments],
+ );
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
const browseEnvironment =
environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null;
+ // A desktop-local secondary backend (today: the WSL backend). The picker is
+ // available against these too — the desktop dispatches pickFolder into the
+ // backend's filesystem when routed by its instance id.
+ const browseEnvironmentIsDesktopLocal =
+ browseEnvironment !== null && isDesktopLocalConnectionTarget(browseEnvironment.entry.target);
+ // Map the browsed desktop-local env to its desktop pool instance id (e.g.
+ // "wsl:ubuntu"). The catalog environmentId is descriptor-derived and won't
+ // route on the desktop side; pickFolder only recognizes the pool id, which
+ // the bootstrap list exposes. Match on backend URL, exactly as Sidebar's
+ // LocalSecondaryStatus does (environment.displayUrl === bootstrap.httpBaseUrl).
+ const browseDesktopInstanceId = useMemo(() => {
+ if (!browseEnvironmentIsDesktopLocal || browseEnvironment === null) {
+ return null;
+ }
+ const displayUrl = browseEnvironment.displayUrl;
+ if (displayUrl === null) {
+ return null;
+ }
+ return (
+ desktopLocalBootstraps.find((bootstrap) => bootstrap.httpBaseUrl === displayUrl)?.id ?? null
+ );
+ }, [browseEnvironment, browseEnvironmentIsDesktopLocal, desktopLocalBootstraps]);
const sourceControlDiscovery = useEnvironmentQuery(
browseEnvironmentId === null
? null
@@ -984,6 +1030,21 @@ function OpenCommandPaletteDialog(props: {
},
});
+ if (wslAddProjectEnvironmentOption) {
+ actionItems.push({
+ kind: "action",
+ value: "action:add-project:wsl-folder",
+ searchTerms: ["add project", "open", "wsl", "linux", "folder", "directory"],
+ title: "Open WSL folder",
+ description: wslAddProjectEnvironmentOption.label,
+ icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
+ keepOpen: true,
+ run: async () => {
+ startAddProjectBrowse(wslAddProjectEnvironmentOption.environmentId);
+ },
+ });
+ }
+
actionItems.push({
kind: "action",
value: "action:settings",
@@ -1016,11 +1077,16 @@ function OpenCommandPaletteDialog(props: {
threadSearchItems: allThreadItems,
});
- const handleAddProject = useCallback(
- async (rawCwd: string) => {
- if (!browseEnvironmentId) return;
+ const handleAddProjectForEnvironment = useCallback(
+ async (input: {
+ readonly environmentId: EnvironmentId;
+ readonly rawCwd: string;
+ readonly platform: string;
+ readonly currentProjectCwd: string | null;
+ }) => {
+ const rawCwd = input.rawCwd;
- if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
+ if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1031,7 +1097,7 @@ function OpenCommandPaletteDialog(props: {
return;
}
- if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
+ if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) {
toastManager.add(
stackedThreadToast({
type: "error",
@@ -1042,11 +1108,11 @@ function OpenCommandPaletteDialog(props: {
return;
}
- const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse);
+ const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd);
if (cwd.length === 0) return;
const existing = findProjectByPath(
- projects.filter((project) => project.environmentId === browseEnvironmentId),
+ projects.filter((project) => project.environmentId === input.environmentId),
cwd,
);
if (existing) {
@@ -1084,7 +1150,7 @@ function OpenCommandPaletteDialog(props: {
const projectId = newProjectId();
const createResult = await createProject({
- environmentId: browseEnvironmentId,
+ environmentId: input.environmentId,
input: {
projectId,
title: inferProjectTitleFromPath(cwd),
@@ -1111,7 +1177,7 @@ function OpenCommandPaletteDialog(props: {
}
const navigationResult = await settlePromise(() =>
- handleNewThread(scopeProjectRef(browseEnvironmentId, projectId)),
+ handleNewThread(scopeProjectRef(input.environmentId, projectId)),
);
if (navigationResult._tag === "Failure") {
const error = squashAtomCommandFailure(navigationResult);
@@ -1127,9 +1193,6 @@ function OpenCommandPaletteDialog(props: {
setOpen(false);
},
[
- browseEnvironmentId,
- browseEnvironmentPlatform,
- currentProjectCwdForBrowse,
handleNewThread,
createProject,
navigate,
@@ -1140,6 +1203,24 @@ function OpenCommandPaletteDialog(props: {
],
);
+ const handleAddProject = useCallback(
+ async (rawCwd: string) => {
+ if (!browseEnvironmentId) return;
+ await handleAddProjectForEnvironment({
+ environmentId: browseEnvironmentId,
+ rawCwd,
+ platform: browseEnvironmentPlatform,
+ currentProjectCwd: currentProjectCwdForBrowse,
+ });
+ },
+ [
+ browseEnvironmentId,
+ browseEnvironmentPlatform,
+ currentProjectCwdForBrowse,
+ handleAddProjectForEnvironment,
+ ],
+ );
+
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
return getAddProjectInitialQueryForEnvironment(environmentId);
}
@@ -1372,8 +1453,13 @@ function OpenCommandPaletteDialog(props: {
const canOpenProjectFromFileManager =
isBrowsing &&
browseEnvironmentId !== null &&
- primaryEnvironmentId !== null &&
- browseEnvironmentId === primaryEnvironmentId &&
+ // For a desktop-local (WSL) env, only offer the picker once we have resolved
+ // its desktop pool instance id. Without it pickFolder can't be routed to the
+ // WSL filesystem and would open the primary (Windows) picker, then add the
+ // chosen Windows path against the WSL env -- a wrong-path footgun. Stay
+ // hidden until the bootstrap mapping is available rather than mis-routing.
+ (browseEnvironmentId === primaryEnvironmentId ||
+ (browseEnvironmentIsDesktopLocal && browseDesktopInstanceId !== null)) &&
typeof window !== "undefined" &&
window.desktopBridge !== undefined;
const fileManagerInitialPath = useMemo(() => {
@@ -1468,9 +1554,31 @@ function OpenCommandPaletteDialog(props: {
setIsPickingProjectFolder(true);
let pickedPath: string | null = null;
+ let desktopWslState: DesktopWslState | null = null;
try {
+ desktopWslState =
+ browseEnvironmentId === primaryEnvironmentId && browseEnvironmentPlatform === "Linux"
+ ? ((await window.desktopBridge?.getWslState().catch(() => null)) ?? null)
+ : null;
+ // Route the picker to the browsed env's backend filesystem. The desktop
+ // only resolves a "wsl:*" pool instance id, so for a desktop-local env we
+ // pass the bootstrap-mapped instance id (not the catalog environmentId).
+ // A WSL-only primary has no secondary bootstrap, so resolve its instance
+ // id from desktop settings. Windows and combo-mode primaries still omit
+ // the target to preserve the native primary picker. The desktop converts
+ // a WSL UNC selection back to a Linux path before returning.
+ const pickerTargetEnvironmentId = resolveProjectPickerTarget({
+ browseEnvironmentId,
+ primaryEnvironmentId,
+ desktopInstanceId: browseDesktopInstanceId,
+ wslConfiguration: desktopWslState,
+ });
+ const pickerOptions = {
+ ...(fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : {}),
+ ...(pickerTargetEnvironmentId ? { targetEnvironmentId: pickerTargetEnvironmentId } : {}),
+ };
pickedPath = await api.dialogs.pickFolder(
- fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined,
+ Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined,
);
} catch {
// Ignore picker failures and leave the palette open.
@@ -1481,12 +1589,69 @@ function OpenCommandPaletteDialog(props: {
if (!pickedPath) {
return;
}
+ if (parseWslUncPath(pickedPath)) {
+ desktopWslState ??= (await window.desktopBridge?.getWslState().catch(() => null)) ?? null;
+ let primaryRunningDistro: string | null = null;
+ try {
+ primaryRunningDistro =
+ window.desktopBridge
+ ?.getLocalEnvironmentBootstraps()
+ .find((bootstrap) => bootstrap.id === PRIMARY_LOCAL_ENVIRONMENT_ID)?.runningDistro ??
+ null;
+ } catch {
+ // Keep UNC routing strict when the live primary identity cannot be read.
+ }
+ const selection = resolveWslProjectSelection(
+ pickedPath,
+ applyWslEnvironmentConfiguration(
+ environments.flatMap((environment) => {
+ const backendId = desktopLocalBackendId(environment.entry.target);
+ if (!backendId) {
+ return [];
+ }
+
+ const bootstrap = desktopLocalBootstraps.find(
+ (candidate) => candidate.httpBaseUrl === environment.displayUrl,
+ );
+ const runningDistro = bootstrap?.runningDistro ?? null;
+ return [{ environmentId: environment.environmentId, backendId, runningDistro }];
+ }),
+ primaryEnvironmentId,
+ desktopWslState ?? null,
+ primaryRunningDistro,
+ ),
+ );
+ if (!selection) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not add WSL project",
+ description: "Start the matching WSL backend, then choose the folder again.",
+ }),
+ );
+ return;
+ }
+ await handleAddProjectForEnvironment({
+ environmentId: selection.environmentId,
+ rawCwd: selection.linuxPath,
+ platform: "Linux",
+ currentProjectCwd: null,
+ });
+ return;
+ }
await handleAddProject(pickedPath);
}, [
+ browseDesktopInstanceId,
+ browseEnvironmentId,
+ browseEnvironmentPlatform,
canOpenProjectFromFileManager,
+ desktopLocalBootstraps,
+ environments,
fileManagerInitialPath,
handleAddProject,
+ handleAddProjectForEnvironment,
isPickingProjectFolder,
+ primaryEnvironmentId,
]);
return (
diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx
new file mode 100644
index 000000000..b34f82a77
--- /dev/null
+++ b/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx
@@ -0,0 +1,226 @@
+import type { Dispatch, ReactElement, SetStateAction } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import {
+ type EnvironmentId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ type ServerProvider,
+} from "@t3tools/contracts";
+import { AsyncResult } from "effect/unstable/reactivity";
+
+import type {
+ LocalEnvironmentUpdateGroup,
+ ProviderUpdateCandidate,
+ ProviderUpdateRowStatus,
+} from "./ProviderUpdateLaunchNotification.logic";
+
+const testState = vi.hoisted(() => ({
+ groups: [] as LocalEnvironmentUpdateGroup[],
+ updateProvider: vi.fn(),
+}));
+
+const hooks = vi.hoisted(() => {
+ let cursor = 0;
+ let slots: unknown[] = [];
+
+ const nextIndex = () => cursor++;
+
+ return {
+ beginRender() {
+ cursor = 0;
+ },
+ reset() {
+ cursor = 0;
+ slots = [];
+ },
+ useCallback<T>(callback: T): T {
+ nextIndex();
+ return callback;
+ },
+ useMemo<T>(factory: () => T): T {
+ nextIndex();
+ return factory();
+ },
+ useMemoCache(size: number): unknown[] {
+ const index = nextIndex();
+ if (!slots[index]) {
+ slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
+ }
+ return slots[index] as unknown[];
+ },
+ useRef<T>(initialValue: T): { current: T } {
+ const index = nextIndex();
+ if (!slots[index]) {
+ slots[index] = { current: initialValue };
+ }
+ return slots[index] as { current: T };
+ },
+ useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
+ const index = nextIndex();
+ if (index >= slots.length) {
+ slots[index] =
+ typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
+ }
+ const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
+ const previous = slots[index] as T;
+ slots[index] =
+ typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
+ };
+ return [slots[index] as T, setValue];
+ },
+ };
+});
+
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>();
+ return {
+ ...actual,
+ useCallback: hooks.useCallback,
+ useMemo: hooks.useMemo,
+ useRef: hooks.useRef,
+ useState: hooks.useState,
+ };
+});
+
+vi.mock("react/compiler-runtime", () => ({
+ c: hooks.useMemoCache,
+}));
+
+vi.mock("~/state/server", () => ({
+ serverEnvironment: { updateProvider: Symbol("updateProvider") },
+}));
+
+vi.mock("~/state/use-atom-command", () => ({
+ useAtomCommand: () => testState.updateProvider,
+}));
+
+vi.mock("./ProviderUpdateLaunchNotification.environments", () => ({
+ useLocalEnvironmentUpdateGroups: () => ({
+ groups: testState.groups,
+ isAnySettling: false,
+ }),
+}));
+
+import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";
+
+const environmentId = "env-wsl" as EnvironmentId;
+const pendingExpiryMs = 6 * 60_000;
+
+function provider(updateStatus?: "succeeded"): ServerProvider {
+ const result: ServerProvider = {
+ instanceId: ProviderInstanceId.make("codex-wsl"),
+ driver: ProviderDriverKind.make("codex"),
+ enabled: true,
+ installed: true,
+ version: updateStatus ? "1.1.0" : "1.0.0",
+ status: "ready",
+ auth: { status: "authenticated" },
+ checkedAt: "2026-06-26T12:00:00.000Z",
+ models: [],
+ slashCommands: [],
+ skills: [],
+ versionAdvisory: {
+ status: updateStatus ? "current" : "behind_latest",
+ currentVersion: updateStatus ? "1.1.0" : "1.0.0",
+ latestVersion: "1.1.0",
+ updateCommand: "npm install -g @openai/codex@latest",
+ canUpdate: true,
+ checkedAt: "2026-06-26T12:00:00.000Z",
+ message: updateStatus ? "Up to date." : "Update available.",
+ },
+ };
+
+ return updateStatus
+ ? {
+ ...result,
+ updateState: {
+ status: updateStatus,
+ startedAt: "2026-06-26T12:00:00.000Z",
+ finishedAt: "2026-06-26T12:00:01.000Z",
+ message: "Provider updated.",
+ output: null,
+ },
+ }
+ : result;
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((complete) => {
+ resolve = complete;
+ });
+ return { promise, resolve };
+}
+
+type RowElement = ReactElement<{
+ readonly status: ProviderUpdateRowStatus;
+ readonly onUpdate: () => void;
+}>;
+
+function renderRow(): RowElement {
+ hooks.beginRender();
+ const output = ProviderUpdateEnvironmentRows({}) as ReactElement<{
+ readonly children: RowElement | RowElement[];
+ }>;
+ const children = output.props.children;
+ return Array.isArray(children) ? children[0]! : children;
+}
+
+async function flushPromises(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe("ProviderUpdateEnvironmentRows", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ hooks.reset();
+ testState.updateProvider.mockReset();
+ const candidate = provider() as ProviderUpdateCandidate;
+ testState.groups = [
+ {
+ environmentId,
+ label: "WSL",
+ isPrimary: false,
+ isSettling: false,
+ candidates: [candidate],
+ providers: [candidate],
+ },
+ ];
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("keeps a successor pending when an expired request resolves late, then shows its success", async () => {
+ const firstRequest =
+ deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();
+ const successorRequest =
+ deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();
+ testState.updateProvider
+ .mockReturnValueOnce(firstRequest.promise)
+ .mockReturnValueOnce(successorRequest.promise);
+
+ renderRow().props.onUpdate();
+ expect(renderRow().props.status.kind).toBe("loading");
+
+ await vi.advanceTimersByTimeAsync(pendingExpiryMs);
+ expect(renderRow().props.status.kind).toBe("failed");
+
+ renderRow().props.onUpdate();
+ expect(testState.updateProvider).toHaveBeenCalledTimes(2);
+ expect(renderRow().props.status.kind).toBe("loading");
+
+ firstRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));
+ await flushPromises();
+
+ expect(renderRow().props.status.kind).toBe("loading");
+
+ successorRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));
+ await flushPromises();
+
+ expect(renderRow().props.status.kind).toBe("success");
+ });
+});
diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx
new file mode 100644
index 000000000..28242b88f
--- /dev/null
+++ b/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx
@@ -0,0 +1,397 @@
+import { CheckIcon } from "lucide-react";
+import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
+import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+ type AtomCommandResult,
+} from "@t3tools/client-runtime/state/runtime";
+
+import { cn } from "~/lib/utils";
+import { serverEnvironment } from "~/state/server";
+import { useAtomCommand } from "~/state/use-atom-command";
+import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
+import {
+ collectProviderUpdateOutcomeSnapshots,
+ firstRejectedProviderUpdateMessage,
+ getProviderUpdateProgressToastView,
+ getProviderUpdateSidebarPillView,
+ isTerminalProviderUpdatePhase,
+ resolveEnvironmentUpdateRowStatus,
+ type LocalEnvironmentUpdateGroup,
+ type LocalProviderUpdateOutcome,
+ type ProviderUpdateRowStatus,
+ type ProviderUpdateRowStatusKind,
+ type ProviderUpdateToastView,
+} from "./ProviderUpdateLaunchNotification.logic";
+import { Button } from "./ui/button";
+import { Spinner } from "./ui/spinner";
+
+type ProviderUpdateCommandResult = AtomCommandResult<
+ { readonly providers: ReadonlyArray<ServerProvider> },
+ unknown
+>;
+
+/**
+ * Map one targeted instance's update command result into the settled-outcome
+ * shape the multi-backend reducers consume: a non-interrupted failure becomes a
+ * rejection carrying its message; a success carries the post-update snapshot of
+ * the targeted instance (null when the backend did not report it).
+ */
+function toProviderUpdateOutcome(input: {
+ readonly environmentId: EnvironmentId;
+ readonly isPrimary: boolean;
+ readonly target: {
+ readonly driver: ServerProvider["driver"];
+ readonly instanceId: ServerProvider["instanceId"];
+ };
+ readonly result: ProviderUpdateCommandResult;
+}): PromiseSettledResult<LocalProviderUpdateOutcome> {
+ if (input.result._tag === "Failure") {
+ if (isAtomCommandInterrupted(input.result)) {
+ // An interrupted dispatch (e.g. superseded) is neither a success nor a
+ // hard failure — surface it as a non-contributing, non-rejecting outcome.
+ return {
+ status: "fulfilled",
+ value: {
+ environmentId: input.environmentId,
+ isPrimary: input.isPrimary,
+ driver: input.target.driver,
+ instanceId: input.target.instanceId,
+ provider: null,
+ },
+ };
+ }
+ const error = squashAtomCommandFailure(input.result);
+ return {
+ status: "rejected",
+ reason: error instanceof Error ? error : new Error("Provider update failed."),
+ };
+ }
+
+ const provider =
+ input.result.value.providers.find(
+ (candidate) => candidate.instanceId === input.target.instanceId,
+ ) ?? null;
+ return {
+ status: "fulfilled",
+ value: {
+ environmentId: input.environmentId,
+ isPrimary: input.isPrimary,
+ driver: input.target.driver,
+ instanceId: input.target.instanceId,
+ provider,
+ },
+ };
+}
+
+// Transport-hang safety net. The dispatch's `finally` clears the spinner and the
+// in-flight guard on completion, so this only matters if a request never resolves
+// at all (e.g. the socket drops mid-flight without surfacing an error). Keep it
+// well beyond the server's own update timeout (5 min) so a legitimately slow
+// update (npm installs routinely run tens of seconds) is never cut off and left
+// showing a dead, unresponsive Update button.
+const PENDING_EXPIRY_MS = 6 * 60_000;
+
+function rowToneClass(kind: ProviderUpdateRowStatusKind): string {
+ switch (kind) {
+ case "failed":
+ return "text-destructive";
+ case "unchanged":
+ return "text-warning";
+ case "success":
+ return "text-success";
+ default:
+ return "text-muted-foreground";
+ }
+}
+
+function EnvironmentUpdateRow({
+ group,
+ status,
+ onUpdate,
+}: {
+ readonly group: LocalEnvironmentUpdateGroup;
+ readonly status: ProviderUpdateRowStatus;
+ readonly onUpdate: () => void;
+}) {
+ let trailing: ReactNode;
+ switch (status.kind) {
+ case "loading":
+ trailing = <Spinner className="size-4 text-muted-foreground" />;
+ break;
+ case "success":
+ trailing = <CheckIcon aria-hidden="true" className="size-4 text-success" />;
+ break;
+ case "failed":
+ case "unchanged":
+ trailing = (
+ <Button size="xs" variant="outline" onClick={onUpdate}>
+ Retry
+ </Button>
+ );
+ break;
+ default:
+ trailing = (
+ <Button size="xs" onClick={onUpdate}>
+ Update
+ </Button>
+ );
+ break;
+ }
+
+ return (
+ <div className="flex items-center justify-between gap-3 py-0.5">
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate font-medium text-foreground">{group.label}</span>
+ <span className={cn("truncate text-xs", rowToneClass(status.kind))}>{status.text}</span>
+ </div>
+ <div className="shrink-0">{trailing}</div>
+ </div>
+ );
+}
+
+/**
+ * The launch popover's body when WSL is present: one row per local environment
+ * (Windows + WSL), each with its own "update all" trigger that targets only
+ * that environment's backend.
+ */
+export function ProviderUpdateEnvironmentRows({
+ onInteract,
+}: {
+ /** Called the first time the user triggers an update, so the host can stop refreshing the prompt. */
+ readonly onInteract?: () => void;
+}) {
+ const { groups } = useLocalEnvironmentUpdateGroups();
+ const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
+ reportFailure: false,
+ });
+ const groupByEnvironment = useMemo(
+ () => new Map(groups.map((group) => [group.environmentId, group] as const)),
+ [groups],
+ );
+
+ // Only surface results that land after this popover opened.
+ const visibleAfterIsoRef = useRef<string>(new Date().toISOString());
+
+ // Synchronous re-entry guard. setPendingEnvironments is an async state update,
+ // and PENDING_EXPIRY_MS can clear the spinner while a request is still in
+ // flight, so a rapid double-click (or a click after the expiry fires mid-
+ // request) would otherwise dispatch a second full round of updates. A ref
+ // updates synchronously, so we can bail before doing any work.
+ const inFlightEnvironmentsRef = useRef<Set<EnvironmentId>>(new Set());
+
+ // Monotonic per-environment request version. Bumped on each dispatch and
+ // captured locally, so an attempt that was superseded -- e.g. one that already
+ // tripped the expiry safety net and was retried -- detects it is no longer
+ // current and skips every state write when it finally resolves, instead of
+ // clobbering the newer attempt's spinner/result/error or its in-flight guard.
+ const requestVersionRef = useRef<Map<EnvironmentId, number>>(new Map());
+
+ const [pendingEnvironments, setPendingEnvironments] = useState<ReadonlySet<EnvironmentId>>(
+ () => new Set(),
+ );
+ const [errorByEnvironment, setErrorByEnvironment] = useState<ReadonlyMap<EnvironmentId, string>>(
+ () => new Map(),
+ );
+ const [resultByEnvironment, setResultByEnvironment] = useState<
+ ReadonlyMap<EnvironmentId, ProviderUpdateToastView>
+ >(() => new Map());
+
+ const clearPending = useCallback((environmentId: EnvironmentId) => {
+ setPendingEnvironments((previous) => {
+ if (!previous.has(environmentId)) {
+ return previous;
+ }
+ const next = new Set(previous);
+ next.delete(environmentId);
+ return next;
+ });
+ }, []);
+
+ const handleUpdate = useCallback(
+ async (environmentId: EnvironmentId) => {
+ const group = groupByEnvironment.get(environmentId);
+ if (!group || group.candidates.length === 0) {
+ return;
+ }
+ if (inFlightEnvironmentsRef.current.has(environmentId)) {
+ return;
+ }
+ inFlightEnvironmentsRef.current.add(environmentId);
+ const requestVersion = (requestVersionRef.current.get(environmentId) ?? 0) + 1;
+ requestVersionRef.current.set(environmentId, requestVersion);
+ const isCurrentRequest = () =>
+ requestVersionRef.current.get(environmentId) === requestVersion;
+ onInteract?.();
+ const providerCount = group.candidates.length;
+ const targets = group.candidates.map((candidate) => ({
+ driver: candidate.driver,
+ instanceId: candidate.instanceId,
+ }));
+
+ setPendingEnvironments((previous) => new Set(previous).add(environmentId));
+ setErrorByEnvironment((previous) => {
+ if (!previous.has(environmentId)) {
+ return previous;
+ }
+ const next = new Map(previous);
+ next.delete(environmentId);
+ return next;
+ });
+ setResultByEnvironment((previous) => {
+ if (!previous.has(environmentId)) {
+ return previous;
+ }
+ const next = new Map(previous);
+ next.delete(environmentId);
+ return next;
+ });
+
+ const expiry = setTimeout(() => {
+ // A newer attempt may have superseded this one; if so, leave its state
+ // untouched.
+ if (!isCurrentRequest()) {
+ return;
+ }
+ // The request is presumed dead (see PENDING_EXPIRY_MS). Clear the
+ // spinner AND the in-flight guard together so the row never strands on a
+ // dead Update button, and surface feedback so the timeout is visible
+ // rather than silently reverting to idle.
+ inFlightEnvironmentsRef.current.delete(environmentId);
+ clearPending(environmentId);
+ setErrorByEnvironment((previous) =>
+ new Map(previous).set(environmentId, "Update timed out — try again."),
+ );
+ }, PENDING_EXPIRY_MS);
+ try {
+ // Dispatch each candidate's update to this environment's own backend and
+ // normalize every settled outcome into the multi-backend reducer shape.
+ const results = await Promise.all(
+ targets.map(async (target): Promise<PromiseSettledResult<LocalProviderUpdateOutcome>> => {
+ try {
+ const result = await updateProvider({
+ environmentId,
+ input: { provider: target.driver, instanceId: target.instanceId },
+ });
+ return toProviderUpdateOutcome({
+ environmentId,
+ isPrimary: group.isPrimary,
+ target,
+ result,
+ });
+ } catch (error) {
+ return {
+ status: "rejected",
+ reason: error instanceof Error ? error : new Error("Provider update failed."),
+ };
+ }
+ }),
+ );
+ if (!isCurrentRequest()) {
+ // A newer attempt superseded this one while it was in flight; leave
+ // the newer attempt's state intact.
+ return;
+ }
+ // The request resolved (not a transport hang), so clear any stale
+ // timeout error the expiry may have set -- otherwise a late success
+ // would be masked, since an error takes priority in the row status.
+ setErrorByEnvironment((previous) => {
+ if (!previous.has(environmentId)) {
+ return previous;
+ }
+ const next = new Map(previous);
+ next.delete(environmentId);
+ return next;
+ });
+ if (results.length === 0) {
+ setErrorByEnvironment((previous) =>
+ new Map(previous).set(
+ environmentId,
+ "This environment isn’t connected — try again once it reconnects.",
+ ),
+ );
+ return;
+ }
+ const rejectedMessage = firstRejectedProviderUpdateMessage(results);
+ if (rejectedMessage) {
+ setErrorByEnvironment((previous) =>
+ new Map(previous).set(environmentId, rejectedMessage),
+ );
+ return;
+ }
+ const view = getProviderUpdateProgressToastView({
+ providers: collectProviderUpdateOutcomeSnapshots(results),
+ providerCount,
+ });
+ // Only persist a terminal outcome. A non-terminal ("running"/"initial")
+ // view means this dispatch could not confirm completion — e.g. a snapshot
+ // came back without its targeted instance (collectProviderUpdateOutcome-
+ // Snapshots drops null providers), which happens when the command is
+ // interrupted as a second backend connects and supersedes the in-flight
+ // update. A stored view never re-polls, so persisting it would pin the
+ // row's spinner forever once the pending flag expires. Drop it and let
+ // the live per-environment provider state (pill) plus the pending expiry
+ // drive the row, so it self-heals to whatever the backend actually did.
+ if (isTerminalProviderUpdatePhase(view.phase)) {
+ setResultByEnvironment((previous) => new Map(previous).set(environmentId, view));
+ }
+ } catch (error) {
+ if (isCurrentRequest()) {
+ setErrorByEnvironment((previous) =>
+ new Map(previous).set(
+ environmentId,
+ error instanceof Error ? error.message : "Provider update failed.",
+ ),
+ );
+ }
+ } finally {
+ clearTimeout(expiry);
+ // Only the current attempt owns the shared spinner and in-flight guard;
+ // a superseded attempt resolving late must not clear a newer one's.
+ if (isCurrentRequest()) {
+ clearPending(environmentId);
+ inFlightEnvironmentsRef.current.delete(environmentId);
+ }
+ }
+ },
+ [clearPending, groupByEnvironment, onInteract, updateProvider],
+ );
+
+ const rows = groups
+ .map((group) => ({
+ group,
+ status: resolveEnvironmentUpdateRowStatus({
+ group,
+ error: errorByEnvironment.get(group.environmentId),
+ result: resultByEnvironment.get(group.environmentId),
+ // Derive the live pill from the candidates this row is actually
+ // tracking, not every provider in the environment. Otherwise an
+ // unrelated provider's recent success (or one candidate succeeding while
+ // another was interrupted) makes the pill report success and hides the
+ // Update action for candidates that are still outdated.
+ pill: getProviderUpdateSidebarPillView(group.candidates, {
+ visibleAfterIso: visibleAfterIsoRef.current,
+ }),
+ isPending: pendingEnvironments.has(group.environmentId),
+ }),
+ }))
+ .filter(({ group, status }) => group.candidates.length > 0 || status.kind !== "idle");
+
+ if (rows.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="mt-0.5 flex flex-col gap-1">
+ {rows.map(({ group, status }) => (
+ <EnvironmentUpdateRow
+ key={group.environmentId}
+ group={group}
+ status={status}
+ onUpdate={() => handleUpdate(group.environmentId)}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts
new file mode 100644
index 000000000..2fb9c16b6
--- /dev/null
+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts
@@ -0,0 +1,97 @@
+import type { ConnectionCatalogEntry } from "@t3tools/client-runtime/connection";
+import type { ServerConfig } from "@t3tools/contracts";
+import { useMemo } from "react";
+
+import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
+import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
+import {
+ buildLocalEnvironmentUpdateGroups,
+ deriveEnvironmentDisplayLabel,
+ type EnvironmentUpdateConnectionState,
+ type LocalEnvironmentProvidersInput,
+ type LocalEnvironmentUpdateGroup,
+} from "./ProviderUpdateLaunchNotification.logic";
+
+/**
+ * A local environment is either the same-origin primary backend or a
+ * desktop-local secondary (the parallel WSL backend), which connects over
+ * loopback with a bearer token and carries a `local:<backendInstanceId>`
+ * connection id. SSH, relay, and other remote targets are excluded.
+ */
+function isLocalConnectionTarget(target: ConnectionCatalogEntry["target"]): boolean {
+ return target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target);
+}
+
+function normalizeConnectionState(phase: string | undefined): EnvironmentUpdateConnectionState {
+ switch (phase) {
+ case "connected":
+ return "ready";
+ case "connecting":
+ case "reconnecting":
+ return "connecting";
+ case "error":
+ return "error";
+ case "offline":
+ return "disconnected";
+ default:
+ // "available" (or anything not yet observed) — the backend has not
+ // confirmed it is serving yet, so treat it as still settling so the
+ // popover waits for it.
+ return "connecting";
+ }
+}
+
+/**
+ * Reactively enumerate the enabled local environments (the primary plus any
+ * desktop-local secondary such as WSL) with each one's full provider list and a
+ * flag for whether any is still connecting. Drives the launch popover's gating
+ * and its per-environment update triggers.
+ */
+export function useLocalEnvironmentUpdateGroups(): {
+ readonly groups: LocalEnvironmentUpdateGroup[];
+ readonly isAnySettling: boolean;
+} {
+ const { environments } = useEnvironments();
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+
+ return useMemo(() => {
+ const inputs: LocalEnvironmentProvidersInput[] = [];
+
+ for (const environment of environments) {
+ if (!isLocalConnectionTarget(environment.entry.target)) {
+ continue;
+ }
+
+ const isPrimary = environment.environmentId === primaryEnvironmentId;
+ const serverConfig: ServerConfig | null = environment.serverConfig;
+
+ inputs.push({
+ environmentId: environment.environmentId,
+ // Secondaries carry a meaningful label straight from the platform source
+ // (e.g. "WSL (Ubuntu)"). The primary's catalog label can be the account
+ // name, so fall back to its platform OS so the row reads "Windows"/"Linux".
+ label: isPrimary
+ ? deriveEnvironmentDisplayLabel({
+ isWsl: false,
+ wslDistro: null,
+ platformOs: serverConfig?.environment.platform.os,
+ fallbackLabel: environment.label,
+ })
+ : environment.label,
+ isPrimary,
+ // The primary is the backend serving this renderer, so it is ready
+ // whenever its providers are available; secondaries report their live
+ // connection phase.
+ connectionState: isPrimary
+ ? "ready"
+ : normalizeConnectionState(environment.connection.phase),
+ providers: serverConfig?.providers ?? [],
+ });
+ }
+
+ // Primary first, then the rest in catalog order.
+ inputs.sort((left, right) => Number(right.isPrimary) - Number(left.isPrimary));
+
+ return buildLocalEnvironmentUpdateGroups(inputs);
+ }, [environments, primaryEnvironmentId]);
+}
diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts
index 8d1f88183..223960f83 100644
--- a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts
+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts
@@ -1,13 +1,24 @@
import { describe, expect, it } from "vite-plus/test";
-import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
+import {
+ type EnvironmentId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ type ServerProvider,
+} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import {
+ buildLocalEnvironmentUpdateGroups,
canOneClickUpdateProviderCandidate,
collectProviderUpdateCandidates,
+ collectProviderUpdateOutcomeSnapshots,
collectUpdatedProviderSnapshots,
+ deriveEnvironmentDisplayLabel,
+ environmentGroupsWithUpdates,
firstFailedProviderUpdateMessage,
+ firstRejectedProviderUpdateMessage,
+ firstUnsuccessfulSecondaryProviderOutcome,
getProviderUpdateInitialToastView,
getProviderUpdateProgressToastView,
getProviderUpdateRejectedToastView,
@@ -15,8 +26,17 @@ import {
getSingleProviderUpdateProgressToastView,
hasOneClickUpdateProviderCandidate,
isProviderUpdateCandidate,
+ isTerminalProviderUpdatePhase,
+ localEnvironmentUpdateNotificationKey,
+ parseWslDistroFromInstanceId,
providerUpdateNotificationKey,
+ resolveEnvironmentUpdateRowStatus,
+ type LocalEnvironmentProvidersInput,
+ type LocalEnvironmentUpdateGroup,
+ type LocalProviderUpdateOutcome,
type ProviderUpdateCandidate,
+ type ProviderUpdateSidebarPillView,
+ type ProviderUpdateToastView,
} from "./ProviderUpdateLaunchNotification.logic";
const checkedAt = "2026-04-23T10:00:00.000Z";
@@ -665,4 +685,431 @@ describe("provider update launch notification logic", () => {
]),
).toBeNull();
});
+
+ describe("multi-backend update outcomes", () => {
+ const terminalState = (
+ status: "succeeded" | "failed" | "unchanged",
+ message: string,
+ ): NonNullable<ServerProvider["updateState"]> => ({
+ status,
+ startedAt: checkedAt,
+ finishedAt: checkedAt,
+ message,
+ output: null,
+ });
+
+ const fulfilledOutcome = (
+ isPrimary: boolean,
+ snapshot: ServerProvider | null,
+ environment = "env",
+ ): PromiseSettledResult<LocalProviderUpdateOutcome> => ({
+ status: "fulfilled",
+ value: {
+ environmentId: environment as LocalProviderUpdateOutcome["environmentId"],
+ isPrimary,
+ driver: snapshot?.driver ?? driver("codex"),
+ instanceId: snapshot?.instanceId ?? instanceId("codex"),
+ provider: snapshot,
+ },
+ });
+
+ it("surfaces a secondary backend's failed update over the primary's success", () => {
+ const snapshots = collectProviderUpdateOutcomeSnapshots([
+ fulfilledOutcome(
+ true,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ }),
+ ),
+ fulfilledOutcome(
+ false,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("failed", "npm: NotFound"),
+ }),
+ ),
+ ]);
+
+ expect(snapshots).toHaveLength(1);
+ expect(snapshots[0]?.updateState?.status).toBe("failed");
+ expect(
+ getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),
+ ).toMatchObject({ phase: "failed" });
+ });
+
+ it("surfaces a secondary backend that stayed outdated over the primary's success", () => {
+ const snapshots = collectProviderUpdateOutcomeSnapshots([
+ fulfilledOutcome(
+ true,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ }),
+ ),
+ fulfilledOutcome(
+ false,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("unchanged", "still outdated"),
+ }),
+ ),
+ ]);
+
+ expect(snapshots[0]?.updateState?.status).toBe("unchanged");
+ expect(
+ getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),
+ ).toMatchObject({ phase: "unchanged" });
+ });
+
+ it("reports success only when every backend succeeded", () => {
+ const snapshots = collectProviderUpdateOutcomeSnapshots([
+ fulfilledOutcome(
+ true,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ }),
+ ),
+ fulfilledOutcome(
+ false,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ }),
+ ),
+ ]);
+
+ expect(
+ getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),
+ ).toMatchObject({ phase: "succeeded" });
+ });
+
+ it("ignores backends that did not return the targeted instance", () => {
+ const primary = provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ });
+ const snapshots = collectProviderUpdateOutcomeSnapshots([
+ fulfilledOutcome(true, primary),
+ fulfilledOutcome(false, null),
+ ]);
+
+ expect(snapshots).toEqual([primary]);
+ });
+
+ it("flags the first unsuccessful secondary outcome, skipping the primary and successes", () => {
+ const primaryFailed = provider({
+ driver: driver("codex"),
+ updateState: terminalState("failed", "primary boom"),
+ });
+
+ expect(
+ firstUnsuccessfulSecondaryProviderOutcome([
+ fulfilledOutcome(true, primaryFailed),
+ fulfilledOutcome(
+ false,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "ok"),
+ }),
+ ),
+ ]),
+ ).toBeNull();
+
+ expect(
+ firstUnsuccessfulSecondaryProviderOutcome([
+ fulfilledOutcome(true, primaryFailed),
+ fulfilledOutcome(
+ false,
+ provider({
+ driver: driver("codex"),
+ updateState: terminalState("failed", "wsl boom"),
+ }),
+ ),
+ ]),
+ ).toMatchObject({ status: "failed", provider: { updateState: { message: "wsl boom" } } });
+ });
+
+ it("treats a rejected dispatch as not contributing a snapshot", () => {
+ const primary = provider({
+ driver: driver("codex"),
+ updateState: terminalState("succeeded", "Provider updated."),
+ });
+ const results: PromiseSettledResult<LocalProviderUpdateOutcome>[] = [
+ fulfilledOutcome(true, primary),
+ { status: "rejected", reason: new Error("WebSocket closed") },
+ ];
+
+ expect(collectProviderUpdateOutcomeSnapshots(results)).toEqual([primary]);
+ expect(firstRejectedProviderUpdateMessage(results)).toBe("WebSocket closed");
+ });
+ });
+
+ describe("per-environment update grouping", () => {
+ const environment = (
+ input: {
+ readonly environmentId: string;
+ readonly providers: ReadonlyArray<ServerProvider>;
+ } & Partial<Omit<LocalEnvironmentProvidersInput, "environmentId" | "providers">>,
+ ): LocalEnvironmentProvidersInput => ({
+ environmentId: input.environmentId as EnvironmentId,
+ label: input.label ?? input.environmentId,
+ isPrimary: input.isPrimary ?? false,
+ connectionState: input.connectionState ?? "ready",
+ providers: input.providers,
+ });
+
+ it("groups each environment's outdated one-click candidates", () => {
+ const result = buildLocalEnvironmentUpdateGroups([
+ environment({
+ environmentId: "env-windows",
+ label: "Windows",
+ isPrimary: true,
+ providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
+ }),
+ environment({
+ environmentId: "env-wsl",
+ label: "WSL",
+ providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
+ }),
+ ]);
+
+ expect(result.isAnySettling).toBe(false);
+ expect(result.groups.map((group) => group.label)).toEqual(["Windows", "WSL"]);
+ expect(result.groups.every((group) => group.candidates.length === 1)).toBe(true);
+ });
+
+ it("flags settling while a secondary backend is still connecting", () => {
+ const result = buildLocalEnvironmentUpdateGroups([
+ environment({
+ environmentId: "env-windows",
+ isPrimary: true,
+ providers: [provider({ driver: driver("codex") })],
+ }),
+ environment({ environmentId: "env-wsl", connectionState: "connecting", providers: [] }),
+ ]);
+
+ expect(result.isAnySettling).toBe(true);
+ expect(
+ result.groups.find((group) => group.environmentId === ("env-wsl" as EnvironmentId))
+ ?.isSettling,
+ ).toBe(true);
+ });
+
+ it("keeps only environments that have a one-click update on offer", () => {
+ const { groups } = buildLocalEnvironmentUpdateGroups([
+ environment({
+ environmentId: "env-windows",
+ isPrimary: true,
+ providers: [provider({ driver: driver("codex") })],
+ }),
+ environment({
+ environmentId: "env-wsl",
+ providers: [
+ provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
+ ],
+ }),
+ ]);
+
+ expect(environmentGroupsWithUpdates(groups).map((group) => group.environmentId)).toEqual([
+ "env-windows",
+ ]);
+ });
+
+ it("keys the notification by environment, driver and latest version", () => {
+ const noUpdates = buildLocalEnvironmentUpdateGroups([
+ environment({
+ environmentId: "env-windows",
+ isPrimary: true,
+ providers: [
+ provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
+ ],
+ }),
+ ]);
+ expect(localEnvironmentUpdateNotificationKey(noUpdates.groups)).toBeNull();
+
+ const both = buildLocalEnvironmentUpdateGroups([
+ environment({
+ environmentId: "env-windows",
+ isPrimary: true,
+ providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
+ }),
+ environment({
+ environmentId: "env-wsl",
+ providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
+ }),
+ ]);
+ const key = localEnvironmentUpdateNotificationKey(both.groups);
+ expect(key).toContain("env-windows=codex:1.1.0");
+ expect(key).toContain("env-wsl=codex:1.1.0");
+ });
+
+ it("labels environments by platform so they are distinguishable", () => {
+ expect(
+ deriveEnvironmentDisplayLabel({
+ isWsl: false,
+ wslDistro: null,
+ platformOs: "windows",
+ fallbackLabel: "Jgratton24",
+ }),
+ ).toBe("Windows");
+ expect(
+ deriveEnvironmentDisplayLabel({
+ isWsl: true,
+ wslDistro: null,
+ platformOs: "linux",
+ fallbackLabel: "Jgratton24",
+ }),
+ ).toBe("WSL");
+ expect(
+ deriveEnvironmentDisplayLabel({
+ isWsl: true,
+ wslDistro: "ubuntu",
+ platformOs: "linux",
+ fallbackLabel: "Jgratton24",
+ }),
+ ).toBe("WSL · ubuntu");
+ expect(
+ deriveEnvironmentDisplayLabel({
+ isWsl: false,
+ wslDistro: null,
+ platformOs: undefined,
+ fallbackLabel: "My Device",
+ }),
+ ).toBe("My Device");
+ });
+
+ it("parses the WSL distro from the backend instance id", () => {
+ expect(parseWslDistroFromInstanceId("wsl:ubuntu")).toBe("ubuntu");
+ expect(parseWslDistroFromInstanceId("wsl:default")).toBeNull();
+ expect(parseWslDistroFromInstanceId("wsl:")).toBeNull();
+ expect(parseWslDistroFromInstanceId("ssh:host")).toBeNull();
+ expect(parseWslDistroFromInstanceId(undefined)).toBeNull();
+ });
+ });
+
+ describe("isTerminalProviderUpdatePhase", () => {
+ it("treats succeeded/failed/unchanged as terminal", () => {
+ expect(isTerminalProviderUpdatePhase("succeeded")).toBe(true);
+ expect(isTerminalProviderUpdatePhase("failed")).toBe(true);
+ expect(isTerminalProviderUpdatePhase("unchanged")).toBe(true);
+ });
+
+ it("treats running/initial as non-terminal so they are not persisted", () => {
+ // The per-environment update row uses this to decide what to store. A
+ // "running"/"initial" snapshot never re-polls, so persisting it would pin
+ // the row's spinner forever once pending clears (see the
+ // resolveEnvironmentUpdateRowStatus "keeps a non-terminal result on
+ // loading even after pending clears" case). Dropping these lets the live
+ // per-environment provider state drive the row so it self-heals.
+ expect(isTerminalProviderUpdatePhase("running")).toBe(false);
+ expect(isTerminalProviderUpdatePhase("initial")).toBe(false);
+ });
+ });
+
+ describe("resolveEnvironmentUpdateRowStatus", () => {
+ const group: LocalEnvironmentUpdateGroup = {
+ environmentId: "env-wsl" as EnvironmentId,
+ label: "WSL",
+ isPrimary: false,
+ isSettling: false,
+ candidates: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],
+ providers: [],
+ };
+ const runningResult: ProviderUpdateToastView = {
+ phase: "running",
+ type: "loading",
+ title: "Updating providers",
+ description: "Running provider update command.",
+ };
+ const succeededResult: ProviderUpdateToastView = {
+ phase: "succeeded",
+ type: "success",
+ title: "Provider updated",
+ description: "New sessions will use the updated provider.",
+ };
+ const successPill: ProviderUpdateSidebarPillView = {
+ key: "succeeded:codex",
+ tone: "success",
+ title: "Codex updated",
+ description: "New sessions will use the updated provider.",
+ };
+
+ it("prefers a transport error", () => {
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: "boom",
+ result: succeededResult,
+ pill: successPill,
+ isPending: true,
+ }),
+ ).toMatchObject({ kind: "failed", text: "boom" });
+ });
+
+ it("uses a terminal result snapshot", () => {
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: undefined,
+ result: succeededResult,
+ pill: null,
+ isPending: false,
+ }),
+ ).toMatchObject({ kind: "success" });
+ });
+
+ it("falls through a non-terminal result to live server state", () => {
+ // The dispatch snapshot is still "running", but server state already
+ // reports success — the row must not stay pinned on "Updating…".
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: undefined,
+ result: runningResult,
+ pill: successPill,
+ isPending: true,
+ }),
+ ).toMatchObject({ kind: "success" });
+ });
+
+ it("shows the pending spinner before any signal arrives", () => {
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: undefined,
+ result: runningResult,
+ pill: null,
+ isPending: true,
+ }),
+ ).toMatchObject({ kind: "loading" });
+ });
+
+ it("keeps a non-terminal result on loading even after pending clears", () => {
+ // The dispatch returned an incomplete ("running") snapshot and pending was
+ // cleared in finally — the row must not revert to the idle Update button.
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: undefined,
+ result: runningResult,
+ pill: null,
+ isPending: false,
+ }),
+ ).toMatchObject({ kind: "loading" });
+ });
+
+ it("lists the providers when idle", () => {
+ expect(
+ resolveEnvironmentUpdateRowStatus({
+ group,
+ error: undefined,
+ result: undefined,
+ pill: null,
+ isPending: false,
+ }),
+ ).toMatchObject({ kind: "idle", text: "Codex" });
+ });
+ });
});
diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts
index 3f77974e0..55999d2a3 100644
--- a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts
+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts
@@ -1,6 +1,8 @@
import {
defaultInstanceIdForDriver,
PROVIDER_DISPLAY_NAMES,
+ type EnvironmentId,
+ type ExecutionEnvironmentPlatformOs,
type ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
@@ -28,6 +30,17 @@ export interface ProviderUpdateToastView {
readonly dismissAfterVisibleMs?: number;
}
+/**
+ * Terminal update phases — outcomes that are safe to persist as a one-shot row
+ * result. A non-terminal ("initial"/"running") snapshot never re-polls itself,
+ * so storing one pins an update row's spinner indefinitely once its pending flag
+ * expires; such phases must be dropped in favor of the live per-environment
+ * provider state instead of being persisted.
+ */
+export function isTerminalProviderUpdatePhase(phase: ProviderUpdateToastPhase): boolean {
+ return phase === "succeeded" || phase === "failed" || phase === "unchanged";
+}
+
export type ProviderUpdateSidebarPillTone = "loading" | "warning" | "error" | "success";
export interface ProviderUpdateSidebarPillView {
@@ -540,3 +553,283 @@ function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvi
}
return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;
}
+
+// ===========================================================================
+// Multi-environment provider updates
+//
+// With a desktop-local secondary backend present (the WSL backend alongside the
+// Windows primary), a provider update is applied across every local backend.
+// Each environment owns its own provider instances, so candidates and progress
+// are computed per environment and the dispatch targets that environment's
+// connection. These helpers are pure; the dispatch itself runs through the
+// `serverEnvironment.updateProvider` atom command in the components.
+// ===========================================================================
+
+/**
+ * The settled result of dispatching a provider update to one local backend.
+ * `provider` is the post-update snapshot of the targeted instance returned by
+ * that backend (null when the backend did not report the targeted instance,
+ * e.g. it does not have it installed).
+ */
+export interface LocalProviderUpdateOutcome {
+ readonly environmentId: EnvironmentId;
+ readonly isPrimary: boolean;
+ readonly driver: ProviderDriverKind;
+ readonly instanceId: ProviderInstanceId;
+ readonly provider: ServerProvider | null;
+}
+
+// Worst-case ordering across backends: a failed copy outranks an unchanged one,
+// which outranks a still-running one, which outranks a succeeded one.
+const PROVIDER_UPDATE_STATUS_SEVERITY: Record<string, number> = {
+ succeeded: 1,
+ queued: 2,
+ running: 2,
+ unchanged: 3,
+ failed: 4,
+};
+
+function providerUpdateOutcomeSeverity(provider: ServerProvider): number {
+ return PROVIDER_UPDATE_STATUS_SEVERITY[provider.updateState?.status ?? ""] ?? 0;
+}
+
+export function firstRejectedProviderUpdateMessage(
+ results: ReadonlyArray<PromiseSettledResult<unknown>>,
+): string | null {
+ const rejected = results.find((result) => result.status === "rejected");
+ if (!rejected) {
+ return null;
+ }
+ return rejected.reason instanceof Error ? rejected.reason.message : "Provider update failed.";
+}
+
+/**
+ * Reduce per-backend update outcomes to one representative snapshot per driver,
+ * keeping the worst-case status across every local backend. Because the same
+ * driver has a distinct instance id per environment, a secondary backend (e.g.
+ * WSL) that *resolved* with a failed or unchanged provider would otherwise be
+ * filtered out (its instance id is not the primary's) or collapsed behind the
+ * primary's success — this surfaces it instead.
+ */
+export function collectProviderUpdateOutcomeSnapshots(
+ results: ReadonlyArray<PromiseSettledResult<LocalProviderUpdateOutcome>>,
+): ServerProvider[] {
+ const worstByDriver = new Map<ProviderDriverKind, ServerProvider>();
+ for (const result of results) {
+ if (result.status !== "fulfilled" || result.value.provider === null) {
+ continue;
+ }
+ const provider = result.value.provider;
+ const current = worstByDriver.get(provider.driver);
+ if (
+ !current ||
+ providerUpdateOutcomeSeverity(provider) > providerUpdateOutcomeSeverity(current)
+ ) {
+ worstByDriver.set(provider.driver, provider);
+ }
+ }
+ return [...worstByDriver.values()];
+}
+
+/**
+ * The first secondary (non-primary) backend whose update resolved without
+ * succeeding. The primary's own failed/unchanged state is already surfaced
+ * inline in settings, so only secondaries (which have no inline row) need an
+ * explicit callout.
+ */
+export function firstUnsuccessfulSecondaryProviderOutcome(
+ results: ReadonlyArray<PromiseSettledResult<LocalProviderUpdateOutcome>>,
+): { readonly provider: ServerProvider; readonly status: "failed" | "unchanged" } | null {
+ for (const result of results) {
+ if (result.status !== "fulfilled") {
+ continue;
+ }
+ const outcome = result.value;
+ if (outcome.isPrimary || outcome.provider === null) {
+ continue;
+ }
+ const status = outcome.provider.updateState?.status;
+ if (status === "failed" || status === "unchanged") {
+ return { provider: outcome.provider, status };
+ }
+ }
+ return null;
+}
+
+const WSL_INSTANCE_ID_PREFIX = "wsl:";
+
+/** The distro name from a WSL backend instance id ("wsl:ubuntu" -> "ubuntu"), or null for the default. */
+export function parseWslDistroFromInstanceId(instanceId: string | undefined): string | null {
+ if (!instanceId || !instanceId.startsWith(WSL_INSTANCE_ID_PREFIX)) {
+ return null;
+ }
+ const distro = instanceId.slice(WSL_INSTANCE_ID_PREFIX.length).trim();
+ return distro.length === 0 || distro === "default" ? null : distro;
+}
+
+/**
+ * A human label that distinguishes local environments by platform (so the
+ * popover shows "Windows" / "WSL" rather than the account name twice). WSL is
+ * identified by its backend instance id; everything else falls back to the
+ * reported OS, then the environment's own label.
+ */
+export function deriveEnvironmentDisplayLabel(input: {
+ readonly isWsl: boolean;
+ readonly wslDistro: string | null;
+ readonly platformOs: ExecutionEnvironmentPlatformOs | undefined;
+ readonly fallbackLabel: string;
+}): string {
+ if (input.isWsl) {
+ return input.wslDistro ? `WSL · ${input.wslDistro}` : "WSL";
+ }
+ switch (input.platformOs) {
+ case "windows":
+ return "Windows";
+ case "darwin":
+ return "macOS";
+ case "linux":
+ return "Linux";
+ default:
+ return input.fallbackLabel;
+ }
+}
+
+/** Connection state of a local environment, normalized across primary/secondary sources. */
+export type EnvironmentUpdateConnectionState = "connecting" | "ready" | "disconnected" | "error";
+
+export interface LocalEnvironmentProvidersInput {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly isPrimary: boolean;
+ readonly connectionState: EnvironmentUpdateConnectionState;
+ readonly providers: ReadonlyArray<ServerProvider>;
+}
+
+export interface LocalEnvironmentUpdateGroup {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly isPrimary: boolean;
+ /** True while this environment's backend is still connecting (e.g. WSL booting). */
+ readonly isSettling: boolean;
+ /** Outdated, one-click-updatable providers in this environment. */
+ readonly candidates: ProviderUpdateCandidate[];
+ /** Full provider list for this environment, used to derive live update progress. */
+ readonly providers: ReadonlyArray<ServerProvider>;
+}
+
+/**
+ * Build one update group per local environment, pairing each environment's
+ * outdated one-click candidates with its own provider list, and report whether
+ * any environment is still settling (so the caller can defer the popover).
+ */
+export function buildLocalEnvironmentUpdateGroups(
+ environments: ReadonlyArray<LocalEnvironmentProvidersInput>,
+): { groups: LocalEnvironmentUpdateGroup[]; isAnySettling: boolean } {
+ const groups = environments.map((environment) => ({
+ environmentId: environment.environmentId,
+ label: environment.label,
+ isPrimary: environment.isPrimary,
+ isSettling: environment.connectionState === "connecting",
+ candidates: collectProviderUpdateCandidates(environment.providers).filter((candidate) =>
+ canOneClickUpdateProviderCandidate(candidate, environment.providers),
+ ),
+ providers: environment.providers,
+ }));
+ const isAnySettling = environments.some(
+ (environment) => environment.connectionState === "connecting",
+ );
+ return { groups, isAnySettling };
+}
+
+/** Groups that actually have a one-click update available, in display order (primary first). */
+export function environmentGroupsWithUpdates(
+ groups: ReadonlyArray<LocalEnvironmentUpdateGroup>,
+): LocalEnvironmentUpdateGroup[] {
+ return groups.filter((group) => group.candidates.length > 0);
+}
+
+/**
+ * Stable key over the set of (environment, driver, latest version) updates on
+ * offer, so the popover is shown once per distinct set and re-shown when it
+ * changes.
+ */
+export function localEnvironmentUpdateNotificationKey(
+ groups: ReadonlyArray<LocalEnvironmentUpdateGroup>,
+): string | null {
+ const parts = environmentGroupsWithUpdates(groups)
+ .map((group) => {
+ const providerParts = group.candidates
+ .map((candidate) => `${candidate.driver}:${candidate.versionAdvisory.latestVersion}`)
+ .toSorted()
+ .join(",");
+ return `${group.environmentId}=${providerParts}`;
+ })
+ .toSorted();
+ return parts.length > 0 ? parts.join("|") : null;
+}
+
+export type ProviderUpdateRowStatusKind = "idle" | "loading" | "success" | "failed" | "unchanged";
+
+export interface ProviderUpdateRowStatus {
+ readonly kind: ProviderUpdateRowStatusKind;
+ readonly text: string;
+}
+
+function environmentProviderNames(group: LocalEnvironmentUpdateGroup): string {
+ return group.candidates
+ .map((candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver)
+ .join(", ");
+}
+
+/**
+ * Resolve one environment row's display from every available signal, in
+ * priority order: a transport rejection, then the dispatch's own *terminal*
+ * result payload (reliable even when a secondary backend's config does not
+ * re-sync), then live server state (reliable even when the dispatch RPC is lost
+ * to a reconnect), then the optimistic pending spinner, then the idle state.
+ *
+ * A non-terminal result snapshot ("running") is intentionally skipped rather
+ * than treated as authoritative, so live server state can still drive the row
+ * to its terminal status instead of pinning it on "Updating…".
+ */
+export function resolveEnvironmentUpdateRowStatus(input: {
+ readonly group: LocalEnvironmentUpdateGroup;
+ readonly error: string | undefined;
+ readonly result: ProviderUpdateToastView | undefined;
+ readonly pill: ProviderUpdateSidebarPillView | null;
+ readonly isPending: boolean;
+}): ProviderUpdateRowStatus {
+ if (input.error) {
+ return { kind: "failed", text: input.error };
+ }
+ if (input.result) {
+ switch (input.result.phase) {
+ case "succeeded":
+ return { kind: "success", text: "Updated" };
+ case "failed":
+ return { kind: "failed", text: input.result.description };
+ case "unchanged":
+ return { kind: "unchanged", text: input.result.description };
+ // "running" / "initial": non-terminal snapshot — fall through to live state.
+ }
+ }
+ if (input.pill) {
+ switch (input.pill.tone) {
+ case "success":
+ return { kind: "success", text: "Updated" };
+ case "error":
+ return { kind: "failed", text: input.pill.description };
+ case "warning":
+ return { kind: "unchanged", text: input.pill.description };
+ default:
+ return { kind: "loading", text: "Updating…" };
+ }
+ }
+ // A non-terminal result snapshot or the optimistic pending flag means an
+ // update is still in flight — keep showing the spinner rather than reverting
+ // to the Update button as if nothing happened.
+ if (input.result || input.isPending) {
+ return { kind: "loading", text: "Updating…" };
+ }
+ return { kind: "idle", text: environmentProviderNames(input.group) };
+}
diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx b/apps/web/src/components/ProviderUpdateLaunchNotification.tsx
index 56814dba1..2292a2c45 100644
--- a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx
+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.tsx
@@ -1,313 +1,197 @@
import { useNavigate } from "@tanstack/react-router";
-import { useAtomValue } from "@effect/atom-react";
import { DownloadIcon } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef } from "react";
-import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";
-import { usePrimaryEnvironment } from "../state/environments";
+import { useEnvironments } from "~/state/environments";
+import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
-import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
+import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";
+import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
import {
- canOneClickUpdateProviderCandidate,
collectProviderUpdateCandidates,
- collectUpdatedProviderSnapshots,
- firstFailedProviderUpdateMessage,
+ environmentGroupsWithUpdates,
getProviderUpdateInitialToastView,
- getProviderUpdateProgressToastView,
- getProviderUpdateRejectedToastView,
- getProviderUpdateRunningToastView,
- providerUpdateNotificationKey,
- type ProviderUpdateToastView,
+ localEnvironmentUpdateNotificationKey,
} from "./ProviderUpdateLaunchNotification.logic";
+import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";
import { stackedThreadToast, toastManager } from "./ui/toast";
-import { useAtomCommand } from "../state/use-atom-command";
-const seenProviderUpdateNotificationKeys = new Set<string>();
-type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
-
-type ActiveProviderUpdateToast =
- | { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
- | {
- readonly kind: "update";
- readonly key: string;
- readonly toastId: ProviderUpdateToastId;
- readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
- readonly providerCount: number;
- };
-
-function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
- const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
-
- if (!ProviderIcon) {
- return (
- <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
- <DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
- </span>
- );
- }
-
- return (
- <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
- <ProviderIcon aria-hidden="true" className="size-4" />
- <span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
- <DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
- </span>
- </span>
+/**
+ * True when a desktop-local secondary backend (the parallel WSL backend) is
+ * present alongside the primary. Local secondaries connect over loopback with a
+ * `local:<backendInstanceId>` bearer connection id; everything else (SSH, relay,
+ * remote) is ignored. Gating on this keeps non-WSL users on the unchanged
+ * single-prompt flow.
+ */
+function useHasLocalSecondaryEnvironment(): boolean {
+ const { environments } = useEnvironments();
+ return useMemo(
+ () =>
+ environments.some((environment) => isDesktopLocalConnectionTarget(environment.entry.target)),
+ [environments],
);
}
-function updateProviderUpdateToast(input: {
- readonly toastId: ProviderUpdateToastId;
- readonly view: ProviderUpdateToastView;
- readonly openSettings: () => void;
-}) {
- if (input.view.type === "loading" || input.view.type === "success") {
- toastManager.update(input.toastId, {
- type: input.view.type,
- title: input.view.title,
- description: input.view.description,
- timeout: 0,
- data: {
- hideCopyButton: true,
- ...(input.view.dismissAfterVisibleMs !== undefined
- ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
- : {}),
- },
- });
- return;
- }
+/**
+ * The provider update popover. With a WSL backend present it splits the update
+ * trigger per environment; without one (the common case) it falls back to the
+ * single-prompt flow so non-WSL users see no change.
+ */
+export function ProviderUpdateLaunchNotification() {
+ const hasLocalSecondary = useHasLocalSecondaryEnvironment();
- toastManager.update(
- input.toastId,
- stackedThreadToast({
- type: input.view.type,
- title: input.view.title,
- description: input.view.description,
- timeout: 0,
- actionProps: {
- children: "Settings",
- onClick: input.openSettings,
- },
- actionVariant: "outline",
- data: {
- hideCopyButton: true,
- },
- }),
+ return hasLocalSecondary ? (
+ <ProviderUpdateEnvironmentsNotification />
+ ) : (
+ <ProviderUpdatePrimaryNotification />
);
}
-function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
- return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
-}
+const seenProviderUpdateNotificationKeys = new Set<string>();
+type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
-export function ProviderUpdateLaunchNotification() {
+// While a local backend (e.g. WSL) is still connecting, defer the popover so it
+// reflects every environment. Cap the wait so a stuck or failed backend can't
+// suppress the primary's updates indefinitely.
+const SETTLING_GRACE_MS = 30_000;
+
+function ProviderUpdateEnvironmentsNotification() {
const navigate = useNavigate();
- const providers = useAtomValue(primaryServerProvidersAtom);
- const primaryEnvironment = usePrimaryEnvironment();
- const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
- reportFailure: false,
- });
- const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
+ const { groups, isAnySettling } = useLocalEnvironmentUpdateGroups();
const { dismissedNotificationKeys, dismissNotificationKey } =
useDismissedProviderUpdateNotificationKeys();
- const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
- const notificationKey = useMemo(
- () => providerUpdateNotificationKey(updateProviders),
- [updateProviders],
- );
- const oneClickProviders = useMemo(
- () =>
- updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
- [providers, updateProviders],
- );
-
- const openProviderSettings = useCallback(
- (toastId?: ProviderUpdateToastId) => {
- const activeToast = activeToastRef.current;
- if (toastId !== undefined) {
- toastManager.close(toastId);
- } else if (activeToast) {
- toastManager.close(activeToast.toastId);
- }
- if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
+ const activeToastRef = useRef<{
+ readonly toastId: ProviderUpdateToastId;
+ readonly key: string;
+ } | null>(null);
+ const notificationKeyRef = useRef<string | null>(null);
+ // Whether the user has triggered an update from the current toast. Until they
+ // do, the prompt is replaced when the available updates change; afterward it
+ // is kept so in-progress rows are not torn down.
+ const hasInteractedRef = useRef(false);
+
+ // Close our prompt if this flow unmounts (e.g. the WSL backend is disabled
+ // and we fall back to the single-prompt flow).
+ useEffect(() => {
+ return () => {
+ if (activeToastRef.current !== null) {
+ toastManager.close(activeToastRef.current.toastId);
activeToastRef.current = null;
}
- void navigate({ to: "/settings/providers" });
- },
- [navigate],
+ };
+ }, []);
+
+ const updateGroups = useMemo(() => environmentGroupsWithUpdates(groups), [groups]);
+ const notificationKey = useMemo(() => localEnvironmentUpdateNotificationKey(groups), [groups]);
+ useEffect(() => {
+ notificationKeyRef.current = notificationKey;
+ }, [notificationKey]);
+
+ // Title summarizes the distinct providers on offer across all environments;
+ // the per-environment detail lives in the popover body.
+ const candidateUnion = useMemo(
+ () => collectProviderUpdateCandidates(updateGroups.flatMap((group) => group.candidates)),
+ [updateGroups],
);
+ // Defer while any local backend is still connecting, up to the grace period.
+ const [settleGraceElapsed, setSettleGraceElapsed] = useState(false);
useEffect(() => {
- const activeToast = activeToastRef.current;
- if (activeToast?.kind !== "update") {
+ if (!isAnySettling) {
+ setSettleGraceElapsed(false);
return;
}
-
- const activeProviders = providers.filter((provider) =>
- activeToast.providerInstanceIds.has(provider.instanceId),
- );
- const view = getProviderUpdateProgressToastView({
- providers: activeProviders,
- providerCount: activeToast.providerCount,
- });
- updateProviderUpdateToast({
- toastId: activeToast.toastId,
- view,
- openSettings: () => openProviderSettings(activeToast.toastId),
- });
-
- if (isTerminalProviderUpdateToastView(view)) {
+ const timer = setTimeout(() => setSettleGraceElapsed(true), SETTLING_GRACE_MS);
+ return () => clearTimeout(timer);
+ }, [isAnySettling]);
+ const isGated = isAnySettling && !settleGraceElapsed;
+
+ const openProviderSettings = useCallback(() => {
+ const active = activeToastRef.current;
+ if (active !== null) {
+ toastManager.close(active.toastId);
activeToastRef.current = null;
}
- }, [providers, openProviderSettings]);
+ void navigate({ to: "/settings/providers" });
+ }, [navigate]);
useEffect(() => {
- const activeToast = activeToastRef.current;
- if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
- toastManager.close(activeToast.toastId);
+ // Whether a fresh prompt can actually be shown for the current update set.
+ const canShowPrompt =
+ notificationKey !== null &&
+ !isGated &&
+ !dismissedNotificationKeys.has(notificationKey) &&
+ !seenProviderUpdateNotificationKeys.has(notificationKey);
+
+ // Close a prompt the user hasn't acted on yet when the available updates
+ // change: when they clear entirely (key null) so the toast doesn't linger,
+ // and when a fresh set is ready to replace it. Keep it only while a backend
+ // is re-settling (updates still exist, just gated) — and once an update is
+ // in progress, so its rows survive.
+ const active = activeToastRef.current;
+ if (
+ active &&
+ active.key !== notificationKey &&
+ !hasInteractedRef.current &&
+ (notificationKey === null || !isGated)
+ ) {
+ toastManager.close(active.toastId);
activeToastRef.current = null;
}
- if (
- !notificationKey ||
- dismissedNotificationKeys.has(notificationKey) ||
- seenProviderUpdateNotificationKeys.has(notificationKey) ||
- activeToastRef.current
- ) {
+ if (!notificationKey || !canShowPrompt || activeToastRef.current !== null) {
return;
}
seenProviderUpdateNotificationKeys.add(notificationKey);
+ hasInteractedRef.current = false;
- const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
-
- let toastId!: ProviderUpdateToastId;
- let updateStarted = false;
- const openSettings = () => openProviderSettings(toastId);
const dismissPrompt = () => {
- dismissNotificationKey(notificationKey);
- };
-
- const runUpdates = () => {
- if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
- return;
+ // Dismiss whatever set is still on offer at close time, so the popover
+ // does not re-pop for updates the user just declined.
+ const liveKey = notificationKeyRef.current;
+ if (liveKey) {
+ dismissNotificationKey(liveKey);
}
- updateStarted = true;
-
- const providerCount = oneClickProviders.length;
- const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
- activeToastRef.current = {
- kind: "update",
- key: notificationKey,
- toastId,
- providerInstanceIds,
- providerCount,
- };
-
- updateProviderUpdateToast({
- toastId,
- view: getProviderUpdateRunningToastView(providerCount),
- openSettings,
- });
-
- void (async () => {
- const results = [];
- for (const provider of oneClickProviders) {
- results.push(
- await updateProvider({
- environmentId: primaryEnvironment.environmentId,
- input: {
- provider: provider.driver,
- instanceId: provider.instanceId,
- },
- }),
- );
- }
-
- const activeUpdateToast = activeToastRef.current;
- if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
- return;
- }
-
- const failedMessage = firstFailedProviderUpdateMessage(results);
- if (failedMessage) {
- updateProviderUpdateToast({
- toastId,
- view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
- openSettings,
- });
- activeToastRef.current = null;
- return;
- }
-
- const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
- results,
- providerInstanceIds,
- });
- const view = getProviderUpdateProgressToastView({
- providers: updatedProviderSnapshots,
- providerCount,
- });
- updateProviderUpdateToast({
- toastId,
- view,
- openSettings,
- });
-
- if (isTerminalProviderUpdateToastView(view)) {
- activeToastRef.current = null;
- }
- })();
+ activeToastRef.current = null;
};
- toastId = toastManager.add(
+ const toastId = toastManager.add(
stackedThreadToast({
- type: initialView.type,
- title: initialView.title,
- description: initialView.description,
+ type: "warning",
+ title: getProviderUpdateInitialToastView({
+ updateProviders: candidateUnion,
+ oneClickProviders: candidateUnion,
+ }).title,
+ description: (
+ <ProviderUpdateEnvironmentRows
+ onInteract={() => {
+ hasInteractedRef.current = true;
+ }}
+ />
+ ),
timeout: 0,
- actionProps:
- oneClickProviders.length > 0
- ? {
- children: "Update",
- onClick: runUpdates,
- }
- : {
- children: "Settings",
- onClick: openSettings,
- },
- actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
+ actionProps: {
+ children: "Settings",
+ onClick: openProviderSettings,
+ },
+ actionVariant: "outline",
data: {
- leadingIcon:
- updateProviders.length === 1 ? (
- <ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
- ) : undefined,
hideCopyButton: true,
+ leadingIcon: <DownloadIcon aria-hidden="true" className="size-4 text-success" />,
onClose: dismissPrompt,
- ...(oneClickProviders.length > 0
- ? {
- secondaryActionProps: {
- children: "Settings",
- onClick: openSettings,
- },
- secondaryActionVariant: "outline" as const,
- }
- : {}),
},
}),
);
- activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
+ activeToastRef.current = { toastId, key: notificationKey };
}, [
- updateProvider,
- dismissNotificationKey,
- dismissedNotificationKeys,
notificationKey,
- oneClickProviders,
+ isGated,
+ candidateUnion,
+ dismissedNotificationKeys,
+ dismissNotificationKey,
openProviderSettings,
- primaryEnvironment,
- updateProviders,
]);
return null;
diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx
new file mode 100644
index 000000000..a7f7a2c1e
--- /dev/null
+++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx
@@ -0,0 +1,331 @@
+import { useNavigate } from "@tanstack/react-router";
+import { useAtomValue } from "@effect/atom-react";
+import { DownloadIcon } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
+
+import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";
+import { usePrimaryEnvironment } from "../state/environments";
+import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
+import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
+import {
+ canOneClickUpdateProviderCandidate,
+ collectProviderUpdateCandidates,
+ collectUpdatedProviderSnapshots,
+ firstFailedProviderUpdateMessage,
+ getProviderUpdateInitialToastView,
+ getProviderUpdateProgressToastView,
+ getProviderUpdateRejectedToastView,
+ getProviderUpdateRunningToastView,
+ providerUpdateNotificationKey,
+ type ProviderUpdateToastView,
+} from "./ProviderUpdateLaunchNotification.logic";
+import { stackedThreadToast, toastManager } from "./ui/toast";
+import { useAtomCommand } from "../state/use-atom-command";
+
+const seenProviderUpdateNotificationKeys = new Set<string>();
+type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
+
+type ActiveProviderUpdateToast =
+ | { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
+ | {
+ readonly kind: "update";
+ readonly key: string;
+ readonly toastId: ProviderUpdateToastId;
+ readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
+ readonly providerCount: number;
+ };
+
+function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
+ const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
+
+ if (!ProviderIcon) {
+ return (
+ <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
+ <DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
+ </span>
+ );
+ }
+
+ return (
+ <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
+ <ProviderIcon aria-hidden="true" className="size-4" />
+ <span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
+ <DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
+ </span>
+ </span>
+ );
+}
+
+function updateProviderUpdateToast(input: {
+ readonly toastId: ProviderUpdateToastId;
+ readonly view: ProviderUpdateToastView;
+ readonly openSettings: () => void;
+}) {
+ if (input.view.type === "loading" || input.view.type === "success") {
+ toastManager.update(input.toastId, {
+ type: input.view.type,
+ title: input.view.title,
+ description: input.view.description,
+ timeout: 0,
+ data: {
+ hideCopyButton: true,
+ ...(input.view.dismissAfterVisibleMs !== undefined
+ ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
+ : {}),
+ },
+ });
+ return;
+ }
+
+ toastManager.update(
+ input.toastId,
+ stackedThreadToast({
+ type: input.view.type,
+ title: input.view.title,
+ description: input.view.description,
+ timeout: 0,
+ actionProps: {
+ children: "Settings",
+ onClick: input.openSettings,
+ },
+ actionVariant: "outline",
+ data: {
+ hideCopyButton: true,
+ },
+ }),
+ );
+}
+
+function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
+ return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
+}
+
+/**
+ * The single-prompt provider update notification used when there is only one
+ * local environment (no WSL backend). Non-WSL users see exactly this flow — the
+ * per-environment split is gated behind WSL presence.
+ */
+export function ProviderUpdatePrimaryNotification() {
+ const navigate = useNavigate();
+ const providers = useAtomValue(primaryServerProvidersAtom);
+ const primaryEnvironment = usePrimaryEnvironment();
+ const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
+ reportFailure: false,
+ });
+ const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
+ const { dismissedNotificationKeys, dismissNotificationKey } =
+ useDismissedProviderUpdateNotificationKeys();
+
+ // If this flow unmounts (e.g. a WSL backend appears and we switch to the
+ // per-environment popover), close any prompt it owns so it does not linger.
+ useEffect(() => {
+ return () => {
+ const activeToast = activeToastRef.current;
+ if (activeToast) {
+ toastManager.close(activeToast.toastId);
+ activeToastRef.current = null;
+ }
+ };
+ }, []);
+
+ const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
+ const notificationKey = useMemo(
+ () => providerUpdateNotificationKey(updateProviders),
+ [updateProviders],
+ );
+ const oneClickProviders = useMemo(
+ () =>
+ updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
+ [providers, updateProviders],
+ );
+
+ const openProviderSettings = useCallback(
+ (toastId?: ProviderUpdateToastId) => {
+ const activeToast = activeToastRef.current;
+ if (toastId !== undefined) {
+ toastManager.close(toastId);
+ } else if (activeToast) {
+ toastManager.close(activeToast.toastId);
+ }
+ if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
+ activeToastRef.current = null;
+ }
+ void navigate({ to: "/settings/providers" });
+ },
+ [navigate],
+ );
+
+ useEffect(() => {
+ const activeToast = activeToastRef.current;
+ if (activeToast?.kind !== "update") {
+ return;
+ }
+
+ const activeProviders = providers.filter((provider) =>
+ activeToast.providerInstanceIds.has(provider.instanceId),
+ );
+ const view = getProviderUpdateProgressToastView({
+ providers: activeProviders,
+ providerCount: activeToast.providerCount,
+ });
+ updateProviderUpdateToast({
+ toastId: activeToast.toastId,
+ view,
+ openSettings: () => openProviderSettings(activeToast.toastId),
+ });
+
+ if (isTerminalProviderUpdateToastView(view)) {
+ activeToastRef.current = null;
+ }
+ }, [providers, openProviderSettings]);
+
+ useEffect(() => {
+ const activeToast = activeToastRef.current;
+ if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
+ toastManager.close(activeToast.toastId);
+ activeToastRef.current = null;
+ }
+
+ if (
+ !notificationKey ||
+ dismissedNotificationKeys.has(notificationKey) ||
+ seenProviderUpdateNotificationKeys.has(notificationKey) ||
+ activeToastRef.current
+ ) {
+ return;
+ }
+
+ seenProviderUpdateNotificationKeys.add(notificationKey);
+
+ const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
+
+ let toastId!: ProviderUpdateToastId;
+ let updateStarted = false;
+ const openSettings = () => openProviderSettings(toastId);
+ const dismissPrompt = () => {
+ dismissNotificationKey(notificationKey);
+ };
+
+ const runUpdates = () => {
+ if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
+ return;
+ }
+ updateStarted = true;
+
+ const providerCount = oneClickProviders.length;
+ const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
+ activeToastRef.current = {
+ kind: "update",
+ key: notificationKey,
+ toastId,
+ providerInstanceIds,
+ providerCount,
+ };
+
+ updateProviderUpdateToast({
+ toastId,
+ view: getProviderUpdateRunningToastView(providerCount),
+ openSettings,
+ });
+
+ void (async () => {
+ const results = [];
+ for (const provider of oneClickProviders) {
+ results.push(
+ await updateProvider({
+ environmentId: primaryEnvironment.environmentId,
+ input: {
+ provider: provider.driver,
+ instanceId: provider.instanceId,
+ },
+ }),
+ );
+ }
+
+ const activeUpdateToast = activeToastRef.current;
+ if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
+ return;
+ }
+
+ const failedMessage = firstFailedProviderUpdateMessage(results);
+ if (failedMessage) {
+ updateProviderUpdateToast({
+ toastId,
+ view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
+ openSettings,
+ });
+ activeToastRef.current = null;
+ return;
+ }
+
+ const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
+ results,
+ providerInstanceIds,
+ });
+ const view = getProviderUpdateProgressToastView({
+ providers: updatedProviderSnapshots,
+ providerCount,
+ });
+ updateProviderUpdateToast({
+ toastId,
+ view,
+ openSettings,
+ });
+
+ if (isTerminalProviderUpdateToastView(view)) {
+ activeToastRef.current = null;
+ }
+ })();
+ };
+
+ toastId = toastManager.add(
+ stackedThreadToast({
+ type: initialView.type,
+ title: initialView.title,
+ description: initialView.description,
+ timeout: 0,
+ actionProps:
+ oneClickProviders.length > 0
+ ? {
+ children: "Update",
+ onClick: runUpdates,
+ }
+ : {
+ children: "Settings",
+ onClick: openSettings,
+ },
+ actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
+ data: {
+ leadingIcon:
+ updateProviders.length === 1 ? (
+ <ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
+ ) : undefined,
+ hideCopyButton: true,
+ onClose: dismissPrompt,
+ ...(oneClickProviders.length > 0
+ ? {
+ secondaryActionProps: {
+ children: "Settings",
+ onClick: openSettings,
+ },
+ secondaryActionVariant: "outline" as const,
+ }
+ : {}),
+ },
+ }),
+ );
+ activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
+ }, [
+ updateProvider,
+ dismissNotificationKey,
+ dismissedNotificationKeys,
+ notificationKey,
+ oneClickProviders,
+ openProviderSettings,
+ primaryEnvironment,
+ updateProviders,
+ ]);
+
+ return null;
+}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index ce925618c..21525b56b 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -3,8 +3,10 @@ import {
ArrowUpDownIcon,
ChevronRightIcon,
CloudIcon,
+ ContainerIcon,
FolderPlusIcon,
Globe2Icon,
+ LoaderIcon,
SearchIcon,
SettingsIcon,
SquarePenIcon,
@@ -69,6 +71,8 @@ import {
type SidebarThreadPreviewCount,
type SidebarThreadSortOrder,
} from "@t3tools/contracts/settings";
+import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
+import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { useOpenPrLink } from "../lib/openPullRequestLink";
@@ -398,7 +402,16 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
const isRemoteThread =
primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
const remoteEnvLabel = environment?.label ?? null;
- const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
+ // A desktop-local secondary backend (e.g. the WSL backend) shows up as a
+ // bearer environment whose connection id is prefixed "local:". It runs on the
+ // user's own machine, so the cloud icon is misleading — label it "Local" and
+ // suppress the cloud icon (the project header already shows a container icon
+ // for desktop-local projects, see sidebarProjectGrouping).
+ const isDesktopLocalThread =
+ environment !== null && isDesktopLocalConnectionTarget(environment.entry.target);
+ const threadEnvironmentLabel = isRemoteThread
+ ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote"))
+ : null;
// For grouped projects, the thread may belong to a different environment
// than the representative project. Look up the thread's own project cwd
// so git status (and thus PR detection) queries the correct path.
@@ -821,7 +834,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
) : null}
<span className={threadMetaClassName}>
<span className="inline-flex items-center gap-1">
- {isRemoteThread && (
+ {isRemoteThread && !isDesktopLocalThread && (
<Tooltip>
<TooltipTrigger
render={
@@ -2249,18 +2262,24 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
render={
<span
aria-label={
- project.environmentPresence === "remote-only"
- ? "Remote project"
- : "Available in multiple environments"
+ project.allRemoteMembersAreDesktopLocal
+ ? "Local sandbox project"
+ : "Remote project"
}
className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100"
/>
}
>
- <CloudIcon className="size-3" />
+ {project.allRemoteMembersAreDesktopLocal ? (
+ <ContainerIcon className="size-3" />
+ ) : (
+ <CloudIcon className="size-3" />
+ )}
</TooltipTrigger>
<TooltipPopup side="top">
- Remote environment: {project.remoteEnvironmentLabels.join(", ")}
+ {project.allRemoteMembersAreDesktopLocal
+ ? `Local sandbox: ${project.remoteEnvironmentLabels.join(", ")}`
+ : `Remote environment: ${project.remoteEnvironmentLabels.join(", ")}`}
</TooltipPopup>
</Tooltip>
)}
@@ -2452,6 +2471,81 @@ const SidebarProjectListRow = memo(function SidebarProjectListRow(props: Sidebar
);
});
+function LocalSecondaryStatus() {
+ const { environments } = useEnvironments();
+ // The desktop reports which local secondary backends (e.g. the WSL backend)
+ // exist; the hook polls because the bridge has no change event. A backend that
+ // is still cold-booting has no httpBaseUrl yet and isn't in the catalog, so we
+ // surface "Connecting" straight from the bootstrap list and clear it once the
+ // matching environment reports a connected phase.
+ const secondaries = useDesktopLocalBootstraps();
+
+ // Connected desktop-local environments keyed by their backend URL so we can
+ // match a bootstrap (which only knows the URL) to its connection phase.
+ const localEnvByUrl = useMemo(() => {
+ const map = new Map<string, { phase: string; error: string | null }>();
+ for (const environment of environments) {
+ if (
+ isDesktopLocalConnectionTarget(environment.entry.target) &&
+ environment.displayUrl !== null
+ ) {
+ map.set(environment.displayUrl, {
+ phase: environment.connection.phase,
+ error: environment.connection.error,
+ });
+ }
+ }
+ return map;
+ }, [environments]);
+
+ const connecting: string[] = [];
+ const failed: Array<{ label: string; error: string | null }> = [];
+ for (const bootstrap of secondaries) {
+ const env =
+ bootstrap.httpBaseUrl !== null ? localEnvByUrl.get(bootstrap.httpBaseUrl) : undefined;
+ if (env?.phase === "connected") {
+ continue;
+ }
+ if (env?.phase === "error") {
+ failed.push({ label: bootstrap.label, error: env.error });
+ continue;
+ }
+ connecting.push(bootstrap.label);
+ }
+
+ if (connecting.length === 0 && failed.length === 0) {
+ return null;
+ }
+
+ return (
+ <SidebarGroup className="px-2 pt-2 pb-0">
+ {connecting.length > 0 ? (
+ <Alert
+ variant="default"
+ className="rounded-2xl border-border/40 bg-accent/40 text-muted-foreground"
+ >
+ <LoaderIcon className="animate-spin" />
+ <AlertTitle className="text-xs font-medium text-foreground">
+ Connecting {connecting.join(", ")}
+ </AlertTitle>
+ </Alert>
+ ) : null}
+ {failed.length > 0 ? (
+ <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
+ <TriangleAlertIcon />
+ <AlertTitle>Couldn't connect {failed.map((entry) => entry.label).join(", ")}</AlertTitle>
+ <AlertDescription>
+ {failed
+ .map((entry) => entry.error)
+ .filter(Boolean)
+ .join("; ") || "The backend didn't respond."}
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ </SidebarGroup>
+ );
+}
+
type SortableProjectHandleProps = Pick<
ReturnType<typeof useSortable>,
"attributes" | "listeners" | "setActivatorNodeRef"
@@ -2889,6 +2983,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
</Alert>
</SidebarGroup>
) : null}
+ <LocalSecondaryStatus />
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between pl-2 pr-1.5">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
@@ -3058,6 +3153,15 @@ export default function Sidebar() {
),
[environments],
);
+ const desktopLocalEnvironmentIds = useMemo(
+ () =>
+ new Set(
+ environments
+ .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target))
+ .map((environment) => environment.environmentId),
+ ),
+ [environments],
+ );
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
@@ -3096,8 +3200,15 @@ export default function Sidebar() {
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
+ isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId),
});
- }, [environmentLabelById, orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
+ }, [
+ environmentLabelById,
+ desktopLocalEnvironmentIds,
+ orderedProjects,
+ projectGroupingSettings,
+ primaryEnvironmentId,
+ ]);
const sidebarProjectByKey = useMemo(
() => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)),
diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
new file mode 100644
index 000000000..c8f039e64
--- /dev/null
+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
@@ -0,0 +1,75 @@
+import type { DesktopWslState } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
+
+const baseWslState: DesktopWslState = {
+ enabled: false,
+ distro: null,
+ available: true,
+ wslOnly: true,
+ distros: [],
+ preflightError: null,
+};
+
+describe("applyWslEnableSelection", () => {
+ it("clears WSL-only and updates the distro before enabling both backends", async () => {
+ const calls: Array<string> = [];
+ let persistedWslOnly = true;
+ let persistedDistro: string | null = "Ubuntu";
+ const setWslDistro = vi.fn(async (distro: string | null) => {
+ calls.push(`setWslDistro:${distro ?? "default"}`);
+ persistedDistro = distro;
+ return { ...baseWslState, distro, wslOnly: persistedWslOnly };
+ });
+ const setWslBackendEnabled = vi.fn(async (enabled: boolean) => {
+ calls.push(`setWslBackendEnabled:${enabled}`);
+ return {
+ ...baseWslState,
+ enabled,
+ distro: persistedDistro,
+ wslOnly: persistedWslOnly,
+ };
+ });
+ const setWslOnly = vi.fn(async (enabled: boolean) => {
+ calls.push(`setWslOnly:${enabled}`);
+ persistedWslOnly = enabled;
+ return { ...baseWslState, distro: persistedDistro, wslOnly: enabled };
+ });
+
+ const state = await applyWslEnableSelection({
+ bridge: { setWslDistro, setWslBackendEnabled, setWslOnly },
+ mode: "both",
+ nextDistro: "Debian",
+ persistedDistro: "Ubuntu",
+ });
+
+ expect(calls).toEqual(["setWslOnly:false", "setWslDistro:Debian", "setWslBackendEnabled:true"]);
+ expect(state).toMatchObject({ enabled: true, distro: "Debian", wslOnly: false });
+ });
+
+ it("stages WSL-only before enabling without rewriting an unchanged distro", async () => {
+ const calls: Array<string> = [];
+ let persistedWslOnly = false;
+ const setWslDistro = vi.fn(async () => baseWslState);
+ const setWslOnly = vi.fn(async (enabled: boolean) => {
+ calls.push(`setWslOnly:${enabled}`);
+ persistedWslOnly = enabled;
+ return { ...baseWslState, wslOnly: enabled };
+ });
+ const setWslBackendEnabled = vi.fn(async (enabled: boolean) => {
+ calls.push(`setWslBackendEnabled:${enabled}`);
+ return { ...baseWslState, enabled, wslOnly: persistedWslOnly };
+ });
+
+ const state = await applyWslEnableSelection({
+ bridge: { setWslDistro, setWslBackendEnabled, setWslOnly },
+ mode: "wsl-only",
+ nextDistro: null,
+ persistedDistro: null,
+ });
+
+ expect(calls).toEqual(["setWslOnly:true", "setWslBackendEnabled:true"]);
+ expect(setWslDistro).not.toHaveBeenCalled();
+ expect(state).toMatchObject({ enabled: true, wslOnly: true });
+ });
+});
diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.ts
new file mode 100644
index 000000000..362a24dd3
--- /dev/null
+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts
@@ -0,0 +1,21 @@
+import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts";
+
+type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
+
+export async function applyWslEnableSelection(input: {
+ readonly bridge: WslEnableBridge;
+ readonly mode: "both" | "wsl-only";
+ readonly nextDistro: string | null;
+ readonly persistedDistro: string | null;
+}): Promise<DesktopWslState> {
+ const { bridge, mode, nextDistro, persistedDistro } = input;
+
+ // Stage every preference before enabling. The desktop only relaunches for
+ // mode/distro changes while WSL is active, so the final enable observes the
+ // complete selection and is the only call that may relaunch.
+ await bridge.setWslOnly(mode === "wsl-only");
+ if (persistedDistro !== nextDistro) {
+ await bridge.setWslDistro(nextDistro);
+ }
+ return await bridge.setWslBackendEnabled(true);
+}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 5012986ff..d0fb12f61 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -27,6 +27,7 @@ import {
type DesktopDiscoveredSshHost,
type DesktopSshEnvironmentTarget,
type DesktopServerExposureState,
+ type DesktopWslState,
type EnvironmentId,
} from "@t3tools/contracts";
import {
@@ -48,6 +49,7 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { cn } from "../../lib/utils";
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
+import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import { resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
import {
SettingsPageContainer,
@@ -82,6 +84,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { QRCodeSvg } from "../ui/qr-code";
import { Skeleton } from "../ui/skeleton";
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";
@@ -111,6 +114,7 @@ import {
type ServerClientSessionRecord,
type ServerPairingLinkRecord,
} from "~/environments/primary";
+import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { useUiStateStore } from "~/uiStateStore";
import { resolveServerConfigVersionMismatch } from "~/versionSkew";
import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
@@ -132,6 +136,7 @@ import {
refreshDesktopNetworkAccessState,
} from "~/state/desktopNetworkAccess";
import { desktopSshHostsStateAtom } from "~/state/desktopSshHosts";
+import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState";
import {
type EnvironmentPresentation,
useEnvironments,
@@ -145,6 +150,12 @@ const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
+// Sentinels for the consolidated WSL backend picker. The colon is
+// rejected by DISTRO_NAME_PATTERN (validated on the desktop side) so
+// neither can collide with a real distro name.
+const BACKEND_VALUE_DEFAULT_WSL = "backend:default-wsl";
+const BACKEND_VALUE_WSL_OFF = "backend:wsl-off";
+
const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short",
@@ -1461,6 +1472,12 @@ function SavedBackendListRow({
environment.relayManaged ? "T3 Connect" : null,
].filter((value): value is string => value !== null);
+ // The WSL backend is a desktop-managed local backend (it surfaces as a bearer
+ // environment whose connection id is prefixed "local:"), not a remote
+ // environment you connect to or remove here — its lifecycle is driven by the
+ // WSL on/off + distro picker on this page.
+ const isWslEnvironment = isDesktopLocalConnectionTarget(environment.entry.target);
+
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
@@ -1503,20 +1520,37 @@ function SavedBackendListRow({
) : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
- <Button
- size="xs"
- variant="outline"
- disabled={isConnecting || removingEnvironmentId === environmentId}
- onClick={() => void (isConnected ? onRemove(environmentId) : onConnect(environmentId))}
- >
- {isConnected
- ? removingEnvironmentId === environmentId
- ? "Disconnecting…"
- : "Disconnect"
- : isConnecting
- ? "Connecting…"
- : "Connect"}
- </Button>
+ {isWslEnvironment ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button size="xs" variant="outline" disabled>
+ Managed above
+ </Button>
+ }
+ />
+ <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
+ The WSL backend is managed by the WSL setting above — turn it on or off there.
+ </TooltipPopup>
+ </Tooltip>
+ ) : (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={isConnecting || removingEnvironmentId === environmentId}
+ onClick={() =>
+ void (isConnected ? onRemove(environmentId) : onConnect(environmentId))
+ }
+ >
+ {isConnected
+ ? removingEnvironmentId === environmentId
+ ? "Disconnecting…"
+ : "Disconnect"
+ : isConnecting
+ ? "Connecting…"
+ : "Connect"}
+ </Button>
+ )}
</div>
</div>
</div>
@@ -2066,6 +2100,30 @@ export function ConnectionsSettings() {
const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
const [isDesktopServerExposureDialogOpen, setIsDesktopServerExposureDialogOpen] = useState(false);
const [isUpdatingTailscaleServe, setIsUpdatingTailscaleServe] = useState(false);
+ const [isUpdatingWslBackend, setIsUpdatingWslBackend] = useState(false);
+ const [desktopWslMutationError, setDesktopWslMutationError] = useState<string | null>(null);
+ // Pending WSL setting change waiting on user confirmation. Set when
+ // the user tries a destructive change (disable, switch distro,
+ // toggle wsl-only) while the WSL backend has saved-env state on this
+ // machine. Confirming applies the change; cancelling drops it
+ // without touching the persisted setting. Null when nothing is
+ // pending.
+ type PendingWslChange =
+ // wasWslOnly is true when the user picked Off while wsl-only mode
+ // was active. In that case "disable" also clears wsl-only and
+ // relaunches onto the Windows backend, because leaving wsl-only on
+ // with wslBackendEnabled off is a meaningless state (wsl-only is
+ // only honoured when the WSL backend is enabled).
+ | { readonly kind: "disable"; readonly wasWslOnly: boolean }
+ | { readonly kind: "distro"; readonly nextDistro: string | null }
+ // Asked at enable time so the user picks the mode upfront instead
+ // of being dropped into "both backends" and having to discover the
+ // wsl-only switch separately. Resolved through enable-mode action
+ // buttons on the dialog rather than a single Confirm.
+ | { readonly kind: "enable"; readonly nextDistro: string | null }
+ | { readonly kind: "wsl-only"; readonly nextValue: boolean };
+ const [pendingWslChange, setPendingWslChange] = useState<PendingWslChange | null>(null);
+ const isWslConfirmDialogOpen = pendingWslChange !== null;
const [pendingTailscaleServeEndpoint, setPendingTailscaleServeEndpoint] =
useState<AdvertisedEndpoint | null>(null);
const [disableTailscaleServeDialogOpen, setDisableTailscaleServeDialogOpen] = useState(false);
@@ -2102,6 +2160,12 @@ export function ConnectionsSettings() {
? desktopSshHostsStateAtom
: null,
);
+ const desktopWsl = useEnvironmentQuery(
+ canManageLocalBackend && desktopBridge ? desktopWslStateAtom : null,
+ );
+ const desktopWslState = desktopWsl.data;
+ const desktopWslError = desktopWslMutationError ?? desktopWsl.error;
+ const isLoadingWslState = desktopWsl.isPending && desktopWsl.data === null;
const discoveredSshHosts = desktopSshHosts.data ?? EMPTY_DISCOVERED_SSH_HOSTS;
const unsavedDiscoveredSshHosts = useMemo(
() =>
@@ -2793,6 +2857,313 @@ export function ConnectionsSettings() {
);
})
: null;
+ // Apply a setting change immediately. The orchestrator reconciles the
+ // pool in the background and the primary backend is untouched, so we
+ // don't gate this behind a confirmation dialog. After the desktop
+ // side persists the change and nudges its orchestrator, we trigger
+ // the renderer's reconciler so the WSL backend's saved-env-shaped
+ // entry catches up (registers/unregisters) without a reload.
+ const applyWslSettingChange = useCallback(
+ async (apply: () => Promise<DesktopWslState>) => {
+ if (!desktopBridge) return;
+ setIsUpdatingWslBackend(true);
+ setDesktopWslMutationError(null);
+ try {
+ await apply();
+ refreshDesktopWslState();
+ // The connection platform source polls the desktop bootstrap list and
+ // reconciles the environment catalog automatically, so toggling the WSL
+ // backend on/off or switching distros is picked up here without an
+ // explicit renderer reconcile.
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to update WSL backend.";
+ setDesktopWslMutationError(message);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not change WSL backend",
+ description: message,
+ }),
+ );
+ refreshDesktopWslState();
+ } finally {
+ setIsUpdatingWslBackend(false);
+ }
+ },
+ [desktopBridge],
+ );
+
+ // Reload the keep-alive WSL state atom. Clearing the mutation error before
+ // refresh lets the atom-owned load error become the visible retry state.
+ const loadWslState = useCallback(() => {
+ setDesktopWslMutationError(null);
+ refreshDesktopWslState();
+ }, []);
+
+ // True when a desktop-local WSL backend is currently registered as an
+ // environment on this machine. We use this as a proxy for "the user has work
+ // that lives on the WSL side": if WSL has connected in a way that registered
+ // the env, disabling or switching distros could disrupt open threads/projects.
+ // If WSL never connected (fresh install, toggled on then immediately off,
+ // etc.) there's no local environment, so we skip the confirmation dialog.
+ const hasWslRegistrationToLose = useMemo(() => {
+ return environments.some((environment) =>
+ isDesktopLocalConnectionTarget(environment.entry.target),
+ );
+ }, [environments]);
+
+ // Single picker for "WSL backend off" vs "running on distro X". The
+ // dropdown maps "Off" to disable and any distro entry to enable +
+ // run on that distro. Splitting these into a separate switch and
+ // dropdown was confusing — they're the same decision.
+ const handleSelectWslMode = useCallback(
+ (value: string) => {
+ if (!desktopBridge || !desktopWslState) return;
+ const defaultDistroName =
+ desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null;
+ if (value === BACKEND_VALUE_WSL_OFF) {
+ // Match the recovery row's visibility (`enabled || wslOnly`): when WSL
+ // went unavailable while wsl-only was persisted, `enabled` can be false
+ // while `wslOnly` is true, and the "Switch to Windows" button must
+ // still clear that state instead of silently no-op'ing.
+ if (!desktopWslState.enabled && !desktopWslState.wslOnly) return;
+ const wasWslOnly = desktopWslState.wslOnly;
+ // Confirm when there's WSL state to lose, OR when wsl-only is
+ // on (turning the only running backend off needs to switch
+ // back to Windows and restart — always consequential).
+ if (hasWslRegistrationToLose || wasWslOnly) {
+ setPendingWslChange({ kind: "disable", wasWslOnly });
+ return;
+ }
+ void applyWslSettingChange(() => desktopBridge.setWslBackendEnabled(false));
+ return;
+ }
+ const nextDistro = value === BACKEND_VALUE_DEFAULT_WSL ? null : value;
+ const resolvedNext = nextDistro ?? defaultDistroName;
+ if (!desktopWslState.enabled) {
+ // Was off, user picked a distro: ask whether to run both
+ // backends or only WSL. We always ask here so the user picks
+ // the mode upfront instead of having to discover the wsl-only
+ // switch afterwards.
+ setPendingWslChange({ kind: "enable", nextDistro });
+ return;
+ }
+ // Already enabled — treat as a distro switch. Skip the change if
+ // the user re-picked the row that's already selected.
+ const resolvedCurrent = desktopWslState.distro ?? defaultDistroName;
+ if (resolvedCurrent === resolvedNext) return;
+ // Confirm when there's WSL registration to lose, OR in wsl-only mode:
+ // there the primary IS the WSL backend, so a distro change relaunches
+ // the app (the IPC handler does this) rather than swapping a secondary,
+ // and the user should see that coming.
+ if (hasWslRegistrationToLose || desktopWslState.wslOnly) {
+ setPendingWslChange({ kind: "distro", nextDistro });
+ return;
+ }
+ void applyWslSettingChange(() => desktopBridge.setWslDistro(nextDistro));
+ },
+ [applyWslSettingChange, desktopBridge, desktopWslState, hasWslRegistrationToLose],
+ );
+
+ // Dispatched from the enable modal's two action buttons.
+ const handleConfirmEnableWsl = useCallback(
+ (mode: "both" | "wsl-only") => {
+ if (!desktopBridge || !pendingWslChange || pendingWslChange.kind !== "enable") return;
+ const nextDistro = pendingWslChange.nextDistro;
+ setPendingWslChange(null);
+ const persistedDistro = desktopWslState?.distro ?? null;
+ void applyWslSettingChange(() =>
+ applyWslEnableSelection({
+ bridge: desktopBridge,
+ mode,
+ nextDistro,
+ persistedDistro,
+ }),
+ );
+ },
+ [applyWslSettingChange, desktopBridge, desktopWslState, pendingWslChange],
+ );
+
+ const handleToggleWslOnly = useCallback(
+ (enabled: boolean) => {
+ if (!desktopBridge || !desktopWslState || desktopWslState.wslOnly === enabled) return;
+ // wsl-only changes which backend the pool uses as "primary",
+ // which is decided once at app launch. The desktop side persists
+ // the setting immediately but doesn't tear down or restart
+ // anything itself; the renderer warns the user to expect a
+ // restart and (in a follow-up) can trigger it automatically.
+ // Always prompt — even enabling is consequential here.
+ setPendingWslChange({ kind: "wsl-only", nextValue: enabled });
+ },
+ [desktopBridge, desktopWslState],
+ );
+
+ const handleConfirmWslChange = useCallback(() => {
+ if (!desktopBridge || !pendingWslChange) return;
+ const change = pendingWslChange;
+ // The enable kind resolves through handleConfirmEnableWsl, not
+ // this single Confirm path.
+ if (change.kind === "enable") return;
+ setPendingWslChange(null);
+ if (change.kind === "disable") {
+ void applyWslSettingChange(async () => {
+ const next = await desktopBridge.setWslBackendEnabled(false);
+ if (change.wasWslOnly) {
+ // Clearing wsl-only relaunches onto the Windows backend.
+ return await desktopBridge.setWslOnly(false);
+ }
+ return next;
+ });
+ return;
+ }
+ if (change.kind === "distro") {
+ void applyWslSettingChange(() => desktopBridge.setWslDistro(change.nextDistro));
+ return;
+ }
+ void applyWslSettingChange(() => desktopBridge.setWslOnly(change.nextValue));
+ }, [applyWslSettingChange, desktopBridge, pendingWslChange]);
+
+ const renderWslRow = () => {
+ if (!desktopWslState) {
+ // A load failed: keep a recovery row (with retry) visible instead of
+ // silently hiding the section. The error persists across an in-flight
+ // retry so the row doesn't flicker away, and the button reflects the
+ // loading state. With no error we simply haven't loaded yet (or WSL
+ // management isn't available), so render nothing.
+ if (desktopWslError && canManageLocalBackend) {
+ return (
+ <SettingsRow
+ title="WSL backend"
+ description="Couldn't load the WSL backend state."
+ status={<span className="block text-destructive">{desktopWslError}</span>}
+ control={
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={loadWslState}
+ disabled={isLoadingWslState}
+ >
+ {isLoadingWslState ? "Retrying…" : "Retry"}
+ </Button>
+ }
+ />
+ );
+ }
+ return null;
+ }
+ // WSL went unavailable while the user still has the WSL backend persisted
+ // (it may have been uninstalled or its distro removed). The desktop side
+ // falls back to the Windows backend, but the normal distro picker needs a
+ // live distro list it no longer has. Without a control here the user would
+ // be stranded on a WSL preference they can't clear, so render a recovery
+ // row that switches back to Windows. When WSL is unavailable AND unused,
+ // there's nothing to recover — keep the section hidden as before.
+ if (!desktopWslState.available) {
+ if (!desktopWslState.enabled && !desktopWslState.wslOnly) return null;
+ return (
+ <SettingsRow
+ title="WSL backend"
+ description="WSL is no longer available, so the Windows backend is running instead. Switch off the WSL backend to clear this preference."
+ status={
+ desktopWslError ? (
+ <span className="block text-destructive">{desktopWslError}</span>
+ ) : null
+ }
+ control={
+ <Button
+ variant="outline"
+ disabled={isUpdatingWslBackend}
+ onClick={() => handleSelectWslMode(BACKEND_VALUE_WSL_OFF)}
+ >
+ Switch to Windows
+ </Button>
+ }
+ />
+ );
+ }
+ // Distro is null when the user wants the WSL default. Map it to the
+ // real default's name so the Select highlights a real option; fall
+ // back to the sentinel only when no distros are listed yet (the
+ // dropdown then renders a single placeholder that matches).
+ const defaultDistroName =
+ desktopWslState.distros.find((distro) => distro.isDefault)?.name ?? null;
+ const selectValue = !desktopWslState.enabled
+ ? BACKEND_VALUE_WSL_OFF
+ : (desktopWslState.distro ?? defaultDistroName ?? BACKEND_VALUE_DEFAULT_WSL);
+ const selectLabel =
+ selectValue === BACKEND_VALUE_WSL_OFF
+ ? "Off"
+ : selectValue === BACKEND_VALUE_DEFAULT_WSL
+ ? "Default distro"
+ : selectValue;
+ return (
+ <>
+ <SettingsRow
+ title="WSL backend"
+ description="Run a second backend inside a WSL distro alongside the Windows one. Pick a distro to start it; pick Off to stop it. Projects opened against the WSL backend live on the Linux side; Windows projects stay where they are."
+ status={
+ desktopWslError ? (
+ <span className="block text-destructive">{desktopWslError}</span>
+ ) : desktopWslState.preflightError ? (
+ <span className="block text-destructive">
+ WSL backend couldn't start: {desktopWslState.preflightError}
+ </span>
+ ) : null
+ }
+ control={
+ <Select
+ value={selectValue}
+ onValueChange={(value) => {
+ if (typeof value !== "string") return;
+ handleSelectWslMode(value);
+ }}
+ >
+ <SelectTrigger
+ className="w-full sm:w-56"
+ aria-label="WSL backend"
+ disabled={isUpdatingWslBackend}
+ >
+ <SelectValue>{selectLabel}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem hideIndicator value={BACKEND_VALUE_WSL_OFF}>
+ Off
+ </SelectItem>
+ {desktopWslState.distros.length === 0 ? (
+ <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
+ Default distro
+ </SelectItem>
+ ) : (
+ desktopWslState.distros.map((distro) => (
+ <SelectItem hideIndicator key={distro.name} value={distro.name}>
+ {distro.name}
+ {distro.isDefault ? " (default)" : ""}
+ </SelectItem>
+ ))
+ )}
+ </SelectPopup>
+ </Select>
+ }
+ />
+ {desktopWslState.enabled ? (
+ <SettingsRow
+ title="WSL only"
+ description="Stop the Windows backend and run only the WSL backend. Useful if you develop entirely inside WSL and don't want a second backend process. T3 Code restarts when you change this."
+ className="bg-muted/20 pl-7 sm:pl-8"
+ control={
+ <Switch
+ checked={desktopWslState.wslOnly}
+ disabled={isUpdatingWslBackend}
+ onCheckedChange={(checked) => handleToggleWslOnly(checked)}
+ aria-label="Run WSL only"
+ />
+ }
+ />
+ ) : null}
+ </>
+ );
+ };
+
const renderTailscaleRow = () => (
<SettingsRow
title="Tailscale HTTPS"
@@ -2928,6 +3299,7 @@ export function ConnectionsSettings() {
{renderNetworkAccessRow()}
{renderEndpointRows("endpoint-rail")}
{renderTailscaleRow()}
+ {renderWslRow()}
<CloudLinkRow canManageRelay={canManageRelay} />
</>
) : (
@@ -3011,6 +3383,114 @@ export function ConnectionsSettings() {
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
+ <AlertDialog
+ open={isWslConfirmDialogOpen}
+ onOpenChange={(open) => {
+ if (isUpdatingWslBackend) return;
+ if (!open) setPendingWslChange(null);
+ }}
+ >
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {pendingWslChange?.kind === "disable"
+ ? pendingWslChange.wasWslOnly
+ ? "Turn off WSL and switch back to Windows?"
+ : "Disable WSL backend?"
+ : pendingWslChange?.kind === "distro"
+ ? "Switch WSL distro?"
+ : pendingWslChange?.kind === "enable"
+ ? "Start the WSL backend"
+ : pendingWslChange?.nextValue
+ ? "Run only the WSL backend?"
+ : "Re-enable the Windows backend?"}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {pendingWslChange?.kind === "disable"
+ ? pendingWslChange.wasWslOnly
+ ? "T3 Code will restart on the Windows backend. Threads and projects opened against WSL stay safe inside the distro and become available again when you re-enable WSL."
+ : "The WSL backend will stop. Threads and projects opened against WSL stay safe inside the distro, but they'll be unavailable in T3 Code until you re-enable WSL."
+ : pendingWslChange?.kind === "distro"
+ ? "T3 Code will restart the WSL backend on the new distro. Sessions still running on the current distro will be interrupted."
+ : pendingWslChange?.kind === "enable"
+ ? "Run the WSL backend alongside the Windows one, or stop the Windows backend and use only WSL? You can change this later from Settings."
+ : pendingWslChange?.nextValue
+ ? "T3 Code will restart and start only the WSL backend. Your Windows-side projects won't be accessible until you turn this off again."
+ : "T3 Code will restart and bring the Windows backend back up alongside WSL."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ disabled={isUpdatingWslBackend}
+ render={<Button variant="outline" disabled={isUpdatingWslBackend} />}
+ >
+ Cancel
+ </AlertDialogClose>
+ {pendingWslChange?.kind === "enable" ? (
+ <>
+ <Button
+ variant="outline"
+ onClick={() => handleConfirmEnableWsl("wsl-only")}
+ disabled={isUpdatingWslBackend}
+ >
+ {isUpdatingWslBackend ? (
+ <>
+ <Spinner className="size-3.5" />
+ Applying…
+ </>
+ ) : (
+ "Use only WSL"
+ )}
+ </Button>
+ <Button
+ variant="default"
+ onClick={() => handleConfirmEnableWsl("both")}
+ disabled={isUpdatingWslBackend}
+ >
+ {isUpdatingWslBackend ? (
+ <>
+ <Spinner className="size-3.5" />
+ Applying…
+ </>
+ ) : (
+ "Run both backends"
+ )}
+ </Button>
+ </>
+ ) : (
+ <Button
+ variant={
+ pendingWslChange?.kind === "disable" ||
+ (pendingWslChange?.kind === "wsl-only" && pendingWslChange.nextValue)
+ ? "destructive"
+ : "default"
+ }
+ onClick={handleConfirmWslChange}
+ disabled={isUpdatingWslBackend}
+ >
+ {isUpdatingWslBackend ? (
+ <>
+ <Spinner className="size-3.5" />
+ Applying…
+ </>
+ ) : pendingWslChange?.kind === "disable" ? (
+ pendingWslChange.wasWslOnly ? (
+ "Switch to Windows"
+ ) : (
+ "Disable WSL"
+ )
+ ) : pendingWslChange?.kind === "distro" ? (
+ "Switch distro"
+ ) : pendingWslChange?.nextValue ? (
+ "Restart and enable"
+ ) : (
+ "Restart and disable"
+ )}
+ </Button>
+ )}
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
<AlertDialog
open={disableTailscaleServeDialogOpen}
onOpenChange={(open) => {
diff --git a/apps/web/src/connection/desktopLocal.test.ts b/apps/web/src/connection/desktopLocal.test.ts
new file mode 100644
index 000000000..adc101ed6
--- /dev/null
+++ b/apps/web/src/connection/desktopLocal.test.ts
@@ -0,0 +1,107 @@
+import {
+ BearerConnectionTarget,
+ PrimaryConnectionTarget,
+} from "@t3tools/client-runtime/connection";
+import { EnvironmentId, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ createDesktopSecondaryBootstrapsReader,
+ desktopLocalBackendId,
+ desktopLocalConnectionId,
+ isDesktopLocalConnectionTarget,
+} from "./desktopLocal";
+
+describe("desktop local connection identity", () => {
+ it("preserves the desktop backend instance id", () => {
+ const target = new BearerConnectionTarget({
+ connectionId: desktopLocalConnectionId("wsl:Ubuntu"),
+ environmentId: EnvironmentId.make("environment-wsl"),
+ label: "WSL (Ubuntu)",
+ });
+
+ expect(isDesktopLocalConnectionTarget(target)).toBe(true);
+ expect(desktopLocalBackendId(target)).toBe("wsl:Ubuntu");
+ });
+
+ it("does not classify the primary environment as desktop-local", () => {
+ const target = new PrimaryConnectionTarget({
+ environmentId: EnvironmentId.make("environment-primary"),
+ httpBaseUrl: "http://127.0.0.1:3773",
+ label: "This device",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ });
+
+ expect(isDesktopLocalConnectionTarget(target)).toBe(false);
+ expect(desktopLocalBackendId(target)).toBeNull();
+ });
+});
+
+describe("desktop local topology reads", () => {
+ it("distinguishes a successful empty topology from a read failure", () => {
+ let readBootstraps = () => [];
+ const reader = createDesktopSecondaryBootstrapsReader(() => ({
+ getLocalEnvironmentBootstraps: () => readBootstraps(),
+ }));
+
+ expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: [] });
+
+ const cause = new Error("IPC unavailable");
+ readBootstraps = () => {
+ throw cause;
+ };
+ expect(reader.readResult()).toEqual({ _tag: "Failure", cause });
+ });
+
+ it("filters the primary bootstrap from successful topology reads", () => {
+ const secondary = {
+ id: "wsl:Ubuntu",
+ label: "WSL: Ubuntu",
+ httpBaseUrl: "http://127.0.0.1:4000",
+ wsBaseUrl: "ws://127.0.0.1:4000",
+ };
+
+ const reader = createDesktopSecondaryBootstrapsReader(() => ({
+ getLocalEnvironmentBootstraps: () => [
+ {
+ ...secondary,
+ id: PRIMARY_LOCAL_ENVIRONMENT_ID,
+ label: "Windows",
+ },
+ secondary,
+ ],
+ }));
+
+ expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: [secondary] });
+ });
+
+ it("retains the last successful snapshot only until another read succeeds", () => {
+ const secondary = {
+ id: "wsl:Ubuntu",
+ label: "WSL: Ubuntu",
+ httpBaseUrl: "http://127.0.0.1:4000",
+ wsBaseUrl: "ws://127.0.0.1:4000",
+ };
+ let readBootstraps = () => [secondary];
+ const reader = createDesktopSecondaryBootstrapsReader(() => ({
+ getLocalEnvironmentBootstraps: () => readBootstraps(),
+ }));
+
+ const connectedSnapshot = reader.readSnapshot();
+ expect(connectedSnapshot).toEqual([secondary]);
+
+ readBootstraps = () => {
+ throw new Error("IPC unavailable");
+ };
+ expect(reader.readSnapshot()).toBe(connectedSnapshot);
+
+ readBootstraps = () => [];
+ const removedSnapshot = reader.readSnapshot();
+ expect(removedSnapshot).toEqual([]);
+
+ readBootstraps = () => {
+ throw new Error("IPC unavailable again");
+ };
+ expect(reader.readSnapshot()).toBe(removedSnapshot);
+ });
+});
diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.ts
new file mode 100644
index 000000000..c9d8b9387
--- /dev/null
+++ b/apps/web/src/connection/desktopLocal.ts
@@ -0,0 +1,104 @@
+import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
+import {
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
+ type DesktopBridge,
+ type DesktopEnvironmentBootstrap,
+} from "@t3tools/contracts";
+
+/**
+ * Desktop-local secondary backends (e.g. a parallel WSL backend) are registered
+ * by the connection platform source as bearer connections whose id carries this
+ * prefix. It is the renderer's single signal that an environment is a
+ * host-managed local backend rather than a user-saved remote, SSH, or relay
+ * environment.
+ *
+ * Keep this the one source of truth: the producer (`connection/platform.ts`)
+ * mints ids via {@link desktopLocalConnectionId} and every consumer classifies
+ * via {@link isDesktopLocalConnectionTarget}, so the convention can never drift
+ * between the two.
+ */
+export const DESKTOP_LOCAL_CONNECTION_ID_PREFIX = "local:";
+
+export function desktopLocalConnectionId(backendId: string): string {
+ return `${DESKTOP_LOCAL_CONNECTION_ID_PREFIX}${backendId}`;
+}
+
+export function isDesktopLocalConnectionTarget(
+ target: ConnectionTarget,
+): target is Extract<ConnectionTarget, { readonly _tag: "BearerConnectionTarget" }> {
+ return (
+ target._tag === "BearerConnectionTarget" &&
+ target.connectionId.startsWith(DESKTOP_LOCAL_CONNECTION_ID_PREFIX)
+ );
+}
+
+export function desktopLocalBackendId(target: ConnectionTarget): string | null {
+ return isDesktopLocalConnectionTarget(target)
+ ? target.connectionId.slice(DESKTOP_LOCAL_CONNECTION_ID_PREFIX.length)
+ : null;
+}
+
+export type DesktopSecondaryBootstrapsRead =
+ | {
+ readonly _tag: "Success";
+ readonly bootstraps: ReadonlyArray<DesktopEnvironmentBootstrap>;
+ }
+ | {
+ readonly _tag: "Failure";
+ readonly cause: unknown;
+ };
+
+export interface DesktopSecondaryBootstrapsReader {
+ readonly readResult: () => DesktopSecondaryBootstrapsRead;
+ readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;
+}
+
+/**
+ * Build a topology reader whose snapshot advances only after successful bridge
+ * reads. A successful empty read is authoritative; a thrown read preserves the
+ * previous snapshot so UI consumers cannot temporarily disagree with the
+ * platform's retained registrations.
+ */
+export function createDesktopSecondaryBootstrapsReader(
+ resolveBridge: () => Pick<DesktopBridge, "getLocalEnvironmentBootstraps"> | undefined,
+): DesktopSecondaryBootstrapsReader {
+ let snapshot: ReadonlyArray<DesktopEnvironmentBootstrap> = [];
+
+ const readResult = (): DesktopSecondaryBootstrapsRead => {
+ const bridge = resolveBridge();
+ if (bridge === undefined) {
+ snapshot = [];
+ return { _tag: "Success", bootstraps: snapshot };
+ }
+ try {
+ snapshot = bridge
+ .getLocalEnvironmentBootstraps()
+ .filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
+ return { _tag: "Success", bootstraps: snapshot };
+ } catch (cause) {
+ return { _tag: "Failure", cause };
+ }
+ };
+
+ return {
+ readResult,
+ readSnapshot: () => {
+ const result = readResult();
+ return result._tag === "Success" ? result.bootstraps : snapshot;
+ },
+ };
+}
+
+const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader(
+ () => window.desktopBridge,
+);
+
+/** Read the topology while preserving failures for platform cache policy. */
+export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {
+ return desktopSecondaryBootstrapsReader.readResult();
+}
+
+/** Read the latest successful topology snapshot for renderer consumers. */
+export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
+ return desktopSecondaryBootstrapsReader.readSnapshot();
+}
diff --git a/apps/web/src/connection/platform.test.ts b/apps/web/src/connection/platform.test.ts
index 2b428e266..b31634705 100644
--- a/apps/web/src/connection/platform.test.ts
+++ b/apps/web/src/connection/platform.test.ts
@@ -1,13 +1,23 @@
import {
AuthStandardClientScopes,
EnvironmentId,
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopBridge,
type DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
-import { provisionDesktopSshEnvironment } from "./platform.ts";
+import {
+ canRetainCachedPlatformRegistrationAfterRefreshFailure,
+ canReuseCachedPlatformRegistration,
+ primaryRegistrationToRetainAfterTopologyRead,
+ provisionDesktopSshEnvironment,
+ readPrimaryEnvironmentTargetResult,
+ secondaryRegistrationsToRetainAfterTopologyRead,
+ secondaryBearerExpiresAtEpochMs,
+ secondaryBearerRefreshAtEpochMs,
+} from "./platform.ts";
const TARGET: DesktopSshEnvironmentTarget = {
alias: "devbox",
@@ -86,3 +96,130 @@ describe("desktop SSH pairing", () => {
}),
);
});
+
+describe("desktop-local bearer cache", () => {
+ const registration = {} as never;
+
+ it("refreshes a secondary bearer before it expires", () => {
+ const issuedAtEpochMs = 10_000;
+ const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, 60);
+ const expiresAtEpochMs = secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, 60);
+ const cached = {
+ expiresAtEpochMs,
+ signature: "secondary-signature",
+ registration,
+ refreshAtEpochMs,
+ };
+
+ expect(refreshAtEpochMs).toBe(65_000);
+ expect(canReuseCachedPlatformRegistration(cached, cached.signature, 64_999)).toBe(true);
+ expect(canReuseCachedPlatformRegistration(cached, cached.signature, 65_000)).toBe(false);
+ expect(
+ canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 69_999),
+ ).toBe(true);
+ expect(
+ canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 70_000),
+ ).toBe(false);
+ });
+
+ it("does not cache credentials whose lifetime is shorter than the refresh skew", () => {
+ const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(10_000, 3);
+ const cached = {
+ expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(10_000, 3),
+ signature: "secondary-signature",
+ registration,
+ refreshAtEpochMs,
+ };
+
+ expect(refreshAtEpochMs).toBe(10_000);
+ expect(canReuseCachedPlatformRegistration(cached, cached.signature, 10_000)).toBe(false);
+ });
+
+ it("retains only unexpired secondaries after a topology read failure", () => {
+ const valid = {
+ expiresAtEpochMs: 20_000,
+ signature: "valid-secondary",
+ registration,
+ refreshAtEpochMs: 15_000,
+ };
+ const previous = new Map([
+ ["valid-secondary", valid],
+ [
+ "expired-secondary",
+ {
+ expiresAtEpochMs: 10_000,
+ signature: "expired-secondary",
+ registration,
+ refreshAtEpochMs: 5_000,
+ },
+ ],
+ ]);
+
+ expect(
+ secondaryRegistrationsToRetainAfterTopologyRead(
+ previous,
+ { _tag: "Failure", cause: new Error("IPC unavailable") },
+ 10_000,
+ ),
+ ).toEqual(new Map([["valid-secondary", valid]]));
+ });
+
+ it("treats a successful empty topology as authoritative removal", () => {
+ const previous = new Map([
+ [
+ "secondary",
+ {
+ expiresAtEpochMs: 20_000,
+ signature: "secondary",
+ registration,
+ refreshAtEpochMs: 15_000,
+ },
+ ],
+ ]);
+
+ expect(
+ secondaryRegistrationsToRetainAfterTopologyRead(
+ previous,
+ { _tag: "Success", bootstraps: [] },
+ 10_000,
+ ),
+ ).toEqual(new Map());
+ });
+});
+
+describe("primary topology cache", () => {
+ const registration = {} as never;
+ const cached = {
+ signature: "primary|http://127.0.0.1:3773/|ws://127.0.0.1:3773/",
+ registration,
+ };
+ const previous = new Map([[PRIMARY_LOCAL_ENVIRONMENT_ID, cached]]);
+
+ it("captures synchronous primary target read failures", () => {
+ const cause = new Error("invalid primary target");
+
+ expect(
+ readPrimaryEnvironmentTargetResult(() => {
+ throw cause;
+ }),
+ ).toEqual({ _tag: "Failure", cause });
+ });
+
+ it("retains the cached primary after a transient topology read failure", () => {
+ expect(
+ primaryRegistrationToRetainAfterTopologyRead(previous, {
+ _tag: "Failure",
+ cause: new Error("IPC unavailable"),
+ }),
+ ).toBe(cached);
+ });
+
+ it("treats a successful primary absence as authoritative removal", () => {
+ expect(
+ primaryRegistrationToRetainAfterTopologyRead(previous, {
+ _tag: "Success",
+ target: null,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index 1b7cba5cb..f74465048 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -8,37 +8,55 @@ import {
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
import {
+ BearerConnectionCredential,
+ BearerConnectionProfile,
+ BearerConnectionRegistration,
+ BearerConnectionTarget,
ConnectionBlockedError,
ConnectionTransientError,
Connectivity,
mapRemoteEnvironmentError,
+ type PlatformConnectionRegistration,
PrimaryConnectionRegistration,
PrimaryConnectionTarget,
Wakeups,
} from "@t3tools/client-runtime/connection";
+import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
import {
AuthStandardClientScopes,
type DesktopBridge,
+ type DesktopEnvironmentBootstrap,
type DesktopSshEnvironmentTarget,
+ PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
-import * as Schedule from "effect/Schedule";
+import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
+import { FetchHttpClient } from "effect/unstable/http";
import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
-import { readPrimaryEnvironmentTarget } from "../environments/primary/target";
+import {
+ readPrimaryEnvironmentTarget,
+ type PrimaryEnvironmentTarget,
+} from "../environments/primary/target";
import { clearComposerDraftsEnvironment } from "../composerDraftStore";
import { isHostedStaticApp } from "../hostedPairing";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
+import {
+ desktopLocalConnectionId,
+ readDesktopSecondaryBootstrapsResult,
+ type DesktopSecondaryBootstrapsRead,
+} from "./desktopLocal";
import { connectionStorageLayer } from "./storage";
let nextObservedRpcRequestId = 0;
@@ -267,14 +285,7 @@ const capabilitiesLayer = Layer.effectContext(
const loadPrimaryConnectionRegistration = Effect.fn(
"web.connectionPlatform.loadPrimaryConnectionRegistration",
-)(function* () {
- const resolved = readPrimaryEnvironmentTarget();
- if (resolved === null) {
- return yield* new ConnectionBlockedError({
- reason: "configuration",
- detail: "Unable to resolve the primary environment endpoint.",
- });
- }
+)(function* (resolved: PrimaryEnvironmentTarget) {
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolved.target.httpBaseUrl,
}).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
@@ -288,29 +299,280 @@ const loadPrimaryConnectionRegistration = Effect.fn(
});
});
-const primaryRegistrationRetrySchedule = Schedule.exponential("1 second").pipe(
- Schedule.either(Schedule.spaced("16 seconds")),
-);
-
-const platformConnectionSourceLayer = Layer.sync(PlatformConnectionSource, () => {
- if (isHostedStaticApp()) {
- return PlatformConnectionSource.of({
- registrations: Stream.empty,
+// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
+// own loopback origin, so — unlike the same-origin primary — it authenticates
+// with a bearer token minted from the bootstrap credential the desktop issues.
+const loadSecondaryConnectionRegistration = Effect.fn(
+ "web.connectionPlatform.loadSecondaryConnectionRegistration",
+)(function* (entry: DesktopEnvironmentBootstrap) {
+ if (
+ entry.httpBaseUrl === null ||
+ entry.wsBaseUrl === null ||
+ entry.bootstrapToken === undefined
+ ) {
+ return yield* new ConnectionTransientError({
+ reason: "endpoint-unavailable",
+ detail: `Desktop-local backend ${entry.id} is not ready yet.`,
});
}
- return PlatformConnectionSource.of({
- registrations: Stream.fromEffect(loadPrimaryConnectionRegistration()).pipe(
- Stream.tapError((error) =>
- Effect.logWarning("Could not discover the primary environment.", {
- error,
- }),
- ),
- Stream.retry(primaryRegistrationRetrySchedule),
- Stream.catchCause(() => Stream.empty),
- ),
- });
+ const httpBaseUrl = entry.httpBaseUrl;
+ const wsBaseUrl = entry.wsBaseUrl;
+ const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
+ Effect.mapError(mapRemoteEnvironmentError),
+ );
+ const issuedAtEpochMs = yield* Clock.currentTimeMillis;
+ const access = yield* bootstrapRemoteBearerSession({
+ httpBaseUrl,
+ credential: entry.bootstrapToken,
+ scopes: AuthStandardClientScopes,
+ clientMetadata: clientMetadata(),
+ }).pipe(Effect.mapError(mapRemoteEnvironmentError));
+ // Keep the desktop pool's stable backend id in the connection id. The
+ // descriptor environment id still scopes projects and RPC state, while the
+ // backend id lets desktop-only operations (notably the WSL folder picker)
+ // route back to the instance that owns the environment.
+ const connectionId = desktopLocalConnectionId(entry.id);
+ // Prefer the desktop's bootstrap label (it identifies the backend and distro,
+ // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
+ // a meaningful name without recovering it from the bootstrap list later.
+ const label = entry.label || descriptor.label;
+ return {
+ registration: new BearerConnectionRegistration({
+ target: new BearerConnectionTarget({
+ environmentId: descriptor.environmentId,
+ label,
+ connectionId,
+ }),
+ profile: new BearerConnectionProfile({
+ connectionId,
+ environmentId: descriptor.environmentId,
+ label,
+ httpBaseUrl,
+ wsBaseUrl,
+ }),
+ credential: new BearerConnectionCredential({ token: access.access_token }),
+ }),
+ expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
+ refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
+ };
});
+// Poll cadence for the desktop bootstrap topology. There is no change event on
+// the bridge, so the renderer polls; successful registrations are cached by a
+// signature of their endpoint + token until bearer credentials approach expiry.
+const PLATFORM_POLL_INTERVAL = "3 seconds";
+const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
+
+export function secondaryBearerExpiresAtEpochMs(
+ issuedAtEpochMs: number,
+ expiresInSeconds: number,
+): number {
+ return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
+}
+
+export function secondaryBearerRefreshAtEpochMs(
+ issuedAtEpochMs: number,
+ expiresInSeconds: number,
+): number {
+ return Math.max(
+ issuedAtEpochMs,
+ secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
+ SECONDARY_BEARER_REFRESH_SKEW_MS,
+ );
+}
+
+interface CachedPlatformRegistration {
+ readonly signature: string;
+ readonly registration: PlatformConnectionRegistration;
+ readonly expiresAtEpochMs?: number;
+ readonly refreshAtEpochMs?: number;
+}
+
+export type PrimaryEnvironmentTargetRead =
+ | {
+ readonly _tag: "Success";
+ readonly target: PrimaryEnvironmentTarget | null;
+ }
+ | {
+ readonly _tag: "Failure";
+ readonly cause: unknown;
+ };
+
+export function readPrimaryEnvironmentTargetResult(
+ readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
+): PrimaryEnvironmentTargetRead {
+ try {
+ return { _tag: "Success", target: readTarget() };
+ } catch (cause) {
+ return { _tag: "Failure", cause };
+ }
+}
+
+export function primaryRegistrationToRetainAfterTopologyRead(
+ previous: ReadonlyMap<string, CachedPlatformRegistration>,
+ topologyRead: PrimaryEnvironmentTargetRead,
+): CachedPlatformRegistration | undefined {
+ return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
+}
+
+export function canReuseCachedPlatformRegistration(
+ cached: CachedPlatformRegistration,
+ signature: string,
+ nowEpochMs: number,
+): boolean {
+ return (
+ cached.signature === signature &&
+ (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
+ );
+}
+
+export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
+ cached: CachedPlatformRegistration,
+ signature: string,
+ nowEpochMs: number,
+): boolean {
+ return (
+ cached.signature === signature &&
+ cached.expiresAtEpochMs !== undefined &&
+ nowEpochMs < cached.expiresAtEpochMs
+ );
+}
+
+export function secondaryRegistrationsToRetainAfterTopologyRead(
+ previous: ReadonlyMap<string, CachedPlatformRegistration>,
+ topologyRead: DesktopSecondaryBootstrapsRead,
+ nowEpochMs: number,
+): ReadonlyMap<string, CachedPlatformRegistration> {
+ if (topologyRead._tag === "Success") {
+ return new Map();
+ }
+ return new Map(
+ [...previous].filter(
+ ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
+ ),
+ );
+}
+
+const platformConnectionSourceLayer = Layer.effect(
+ PlatformConnectionSource,
+ Effect.gen(function* () {
+ if (isHostedStaticApp()) {
+ return PlatformConnectionSource.of({
+ registrations: Stream.empty,
+ });
+ }
+ const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
+
+ // Resolve the full set of platform-managed environments the host currently
+ // reports: the primary (same-origin cookie auth) plus any desktop-local
+ // backends running alongside it (bearer auth). Reused registrations come
+ // from the cache; a failed entry is skipped and retried on the next poll.
+ const buildPlatformRegistrations = Effect.gen(function* () {
+ const previous = yield* Ref.get(cacheRef);
+ const nowEpochMs = yield* Clock.currentTimeMillis;
+ const next = new Map<string, CachedPlatformRegistration>();
+ const registrations: Array<PlatformConnectionRegistration> = [];
+
+ const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
+ const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
+ previous,
+ primaryTopologyRead,
+ );
+ if (retainedPrimary !== undefined) {
+ next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
+ registrations.push(retainedPrimary.registration);
+ }
+
+ if (primaryTopologyRead._tag === "Failure") {
+ yield* Effect.logWarning("Could not read the primary environment topology.", {
+ cause: primaryTopologyRead.cause,
+ });
+ } else if (primaryTopologyRead.target !== null) {
+ const primaryTarget = primaryTopologyRead.target;
+ const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
+ const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
+ if (
+ cached !== undefined &&
+ canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
+ ) {
+ next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
+ registrations.push(cached.registration);
+ } else {
+ const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
+ Effect.tapError((error) =>
+ Effect.logWarning("Could not discover the primary environment.", { error }),
+ ),
+ Effect.option,
+ );
+ if (Option.isSome(built)) {
+ const cacheEntry = { signature, registration: built.value };
+ next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
+ registrations.push(built.value);
+ }
+ }
+ }
+
+ const topologyRead = readDesktopSecondaryBootstrapsResult();
+ for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
+ previous,
+ topologyRead,
+ nowEpochMs,
+ )) {
+ next.set(id, cached);
+ registrations.push(cached.registration);
+ }
+
+ if (topologyRead._tag === "Failure") {
+ yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
+ cause: topologyRead.cause,
+ });
+ } else {
+ for (const bootstrap of topologyRead.bootstraps) {
+ const signature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}|${bootstrap.bootstrapToken ?? ""}`;
+ const cached = previous.get(bootstrap.id);
+ if (
+ cached !== undefined &&
+ canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
+ ) {
+ next.set(bootstrap.id, cached);
+ registrations.push(cached.registration);
+ continue;
+ }
+ const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
+ Effect.tapError((error) =>
+ Effect.logWarning("Could not connect a desktop-local backend.", {
+ id: bootstrap.id,
+ error,
+ }),
+ ),
+ Effect.option,
+ );
+ if (Option.isSome(built)) {
+ const cacheEntry = { signature, ...built.value };
+ next.set(bootstrap.id, cacheEntry);
+ registrations.push(built.value.registration);
+ } else if (
+ cached !== undefined &&
+ canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, signature, nowEpochMs)
+ ) {
+ next.set(bootstrap.id, cached);
+ registrations.push(cached.registration);
+ }
+ }
+ }
+
+ yield* Ref.set(cacheRef, next);
+ return registrations as ReadonlyArray<PlatformConnectionRegistration>;
+ }).pipe(Effect.provide(FetchHttpClient.layer));
+
+ return PlatformConnectionSource.of({
+ registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
+ Stream.mapEffect(() => buildPlatformRegistrations),
+ ),
+ });
+ }),
+);
+
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
EnvironmentOwnedDataCleanup.of({
diff --git a/apps/web/src/connection/useDesktopLocalBootstraps.ts b/apps/web/src/connection/useDesktopLocalBootstraps.ts
new file mode 100644
index 000000000..71642aecb
--- /dev/null
+++ b/apps/web/src/connection/useDesktopLocalBootstraps.ts
@@ -0,0 +1,28 @@
+import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
+import { useEffect, useState } from "react";
+
+import { readDesktopSecondaryBootstraps } from "./desktopLocal";
+
+const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
+
+/**
+ * Reactively track the desktop's secondary local backends (e.g. a parallel WSL
+ * backend). The bridge exposes no change event, so we re-read on an interval;
+ * failed reads retain the latest successful snapshot, while a successful empty
+ * read clears it. Use this instead of polling the bridge ad hoc so every
+ * renderer consumer reads the same topology.
+ */
+export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
+ const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
+ readDesktopSecondaryBootstraps,
+ );
+
+ useEffect(() => {
+ const read = () => setBootstraps(readDesktopSecondaryBootstraps());
+ read();
+ const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
+ return () => clearInterval(interval);
+ }, []);
+
+ return bootstraps;
+}
diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.ts
index 96814b92b..1c5426d95 100644
--- a/apps/web/src/environments/primary/auth.ts
+++ b/apps/web/src/environments/primary/auth.ts
@@ -7,7 +7,7 @@ import type {
AuthSessionId,
AuthSessionState,
} from "@t3tools/contracts";
-import { EnvironmentHttpCommonError } from "@t3tools/contracts";
+import { EnvironmentHttpCommonError, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -176,9 +176,13 @@ export function takePairingTokenFromUrl(): string | null {
}
function getDesktopBootstrapCredential(): string | null {
- const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
- return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
- ? bootstrap.bootstrapToken
+ // Both backends share the same bootstrap token (DesktopBackendConfiguration
+ // mints one tokenRef and feeds it to both resolvers), so picking the
+ // primary entry is fine even when the WSL backend is also registered.
+ const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
+ const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
+ return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
+ ? primary.bootstrapToken
: null;
}
@@ -526,6 +530,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;
diff --git a/apps/web/src/environments/primary/bootstrap.test.ts b/apps/web/src/environments/primary/bootstrap.test.ts
index e8333c2e0..e200ecf2f 100644
--- a/apps/web/src/environments/primary/bootstrap.test.ts
+++ b/apps/web/src/environments/primary/bootstrap.test.ts
@@ -173,12 +173,15 @@ describe("environmentBootstrap", () => {
replaceState: vi.fn(),
},
desktopBridge: {
- getLocalEnvironmentBootstrap: () => ({
- label: "Local environment",
- httpBaseUrl: "http://127.0.0.1:3773",
- wsBaseUrl: "ws://127.0.0.1:3773",
- bootstrapToken: "desktop-bootstrap-token",
- }),
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Windows",
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ },
+ ],
},
});
await installDescriptorApi();
@@ -212,11 +215,14 @@ describe("environmentBootstrap", () => {
location: new URL("http://127.0.0.1:5733/"),
history: { replaceState: vi.fn() },
desktopBridge: {
- getLocalEnvironmentBootstrap: () => ({
- label: "Local environment",
- httpBaseUrl: "http://127.0.0.1:3773",
- bootstrapToken: "desktop-bootstrap-token",
- }),
+ getLocalEnvironmentBootstraps: () => [
+ {
+ id: "primary",
+ label: "Local environment",
+ httpBaseUrl: "http://127.0.0.1:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ },
+ ],
},
});
diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.ts
index 58342d530..f85c91c15 100644
--- a/apps/web/src/environments/primary/index.ts
+++ b/apps/web/src/environments/primary/index.ts
@@ -23,6 +23,7 @@ export {
peekPairingTokenFromUrl,
PrimaryEnvironmentPairingCredentialRejectedError,
PrimaryEnvironmentRequestError,
+ reauthenticatePrimaryEnvironment,
resolveInitialServerAuthGateState,
revokeOtherServerClientSessions,
revokeServerClientSession,
diff --git a/apps/web/src/environments/primary/target.ts b/apps/web/src/environments/primary/target.ts
index a14a99ec4..cc002419f 100644
--- a/apps/web/src/environments/primary/target.ts
+++ b/apps/web/src/environments/primary/target.ts
@@ -1,4 +1,4 @@
-import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
+import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
const PrimaryEnvironmentTargetSource = Schema.Literals([
@@ -76,7 +76,11 @@ export interface PrimaryEnvironmentTarget {
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
- return window.desktopBridge?.getLocalEnvironmentBootstrap() ?? null;
+ // The primary (Windows-native) backend keeps the "primary" id. The
+ // plural list may include a second WSL entry; the primary-target
+ // resolver only cares about the primary, so just find it.
+ const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
+ return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null;
}
function parseTargetUrl(input: {
diff --git a/apps/web/src/sidebarProjectGrouping.ts b/apps/web/src/sidebarProjectGrouping.ts
index c90cf51d9..599d43143 100644
--- a/apps/web/src/sidebarProjectGrouping.ts
+++ b/apps/web/src/sidebarProjectGrouping.ts
@@ -20,6 +20,12 @@ export interface SidebarProjectSnapshot extends Project {
displayName: string;
groupedProjectCount: number;
environmentPresence: EnvironmentPresence;
+ // True iff every non-primary member of this group lives in a
+ // desktopLocal env (today: the WSL backend). The sidebar uses this
+ // to differentiate "lives on this machine but in a sandbox" from
+ // "lives on a real remote" so the project header can pick a
+ // container icon instead of the generic cloud icon.
+ allRemoteMembersAreDesktopLocal: boolean;
memberProjects: readonly SidebarProjectGroupMember[];
memberProjectRefs: readonly ScopedProjectRef[];
remoteEnvironmentLabels: readonly string[];
@@ -44,6 +50,11 @@ export function buildSidebarProjectSnapshots(input: {
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
resolveEnvironmentLabel: (environmentId: EnvironmentId) => string | null;
+ // Returns true when an env id maps to a desktopLocal saved-env
+ // record (today: the WSL backend). Defaults to "false for every
+ // env" so callers that don't care about the distinction get the
+ // legacy behavior.
+ isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean;
}): SidebarProjectSnapshot[] {
const groupedMembers = new Map<string, SidebarProjectGroupMember[]>();
for (const project of input.projects) {
@@ -86,14 +97,17 @@ export function buildSidebarProjectSnapshots(input: {
input.primaryEnvironmentId !== null
? members.some((member) => member.environmentId !== input.primaryEnvironmentId)
: false;
- const remoteEnvironmentLabels = members
- .filter(
- (member) =>
- input.primaryEnvironmentId !== null &&
- member.environmentId !== input.primaryEnvironmentId,
- )
+ const remoteMembers = members.filter(
+ (member) =>
+ input.primaryEnvironmentId !== null && member.environmentId !== input.primaryEnvironmentId,
+ );
+ const remoteEnvironmentLabels = remoteMembers
.flatMap((member) => (member.environmentLabel ? [member.environmentLabel] : []))
.filter((label, index, labels) => labels.indexOf(label) === index);
+ const isDesktopLocal = input.isDesktopLocalEnvironment ?? (() => false);
+ const allRemoteMembersAreDesktopLocal =
+ remoteMembers.length > 0 &&
+ remoteMembers.every((member) => isDesktopLocal(member.environmentId));
result.push({
...representative,
@@ -108,6 +122,7 @@ export function buildSidebarProjectSnapshots(input: {
groupedProjectCount: members.length,
environmentPresence:
hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only",
+ allRemoteMembersAreDesktopLocal,
memberProjects: members,
memberProjectRefs: members.map((member) => scopeProjectRef(member.environmentId, member.id)),
remoteEnvironmentLabels,
diff --git a/apps/web/src/state/desktopWslState.test.ts b/apps/web/src/state/desktopWslState.test.ts
new file mode 100644
index 000000000..f3a532215
--- /dev/null
+++ b/apps/web/src/state/desktopWslState.test.ts
@@ -0,0 +1,97 @@
+import type { DesktopWslState } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
+import { AtomRegistry } from "effect/unstable/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { createDesktopWslStateAtom } from "./desktopWslState";
+
+const wslState: DesktopWslState = {
+ available: true,
+ distro: null,
+ distros: [
+ {
+ isDefault: true,
+ name: "Ubuntu",
+ version: 2,
+ },
+ ],
+ enabled: true,
+ preflightError: null,
+ wslOnly: false,
+};
+
+describe("desktopWslState", () => {
+ it("retains the loaded snapshot when the settings screen remounts", async () => {
+ const getWslState = vi.fn(async () => wslState);
+ const atom = createDesktopWslStateAtom(() => ({ getWslState }));
+ const registry = AtomRegistry.make();
+
+ const unmount = registry.mount(atom);
+ await vi.waitFor(() => {
+ expect(AsyncResult.value(registry.get(atom))).toEqual(
+ expect.objectContaining({ _tag: "Some", value: wslState }),
+ );
+ });
+ unmount();
+
+ const remount = registry.mount(atom);
+ expect(AsyncResult.value(registry.get(atom))).toEqual(
+ expect.objectContaining({ _tag: "Some", value: wslState }),
+ );
+ expect(getWslState).toHaveBeenCalledTimes(1);
+
+ remount();
+ registry.dispose();
+ });
+
+ it("retains the desktop bridge failure as the load error cause", async () => {
+ const cause = new Error("wsl unavailable");
+ const atom = createDesktopWslStateAtom(() => ({
+ getWslState: async () => Promise.reject(cause),
+ }));
+ const registry = AtomRegistry.make();
+ registry.mount(atom);
+
+ await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
+ const result = registry.get(atom);
+ if (!AsyncResult.isFailure(result)) throw new Error("Expected WSL state load to fail.");
+
+ expect(Cause.squash(result.cause)).toEqual(
+ expect.objectContaining({
+ _tag: "DesktopWslStateLoadError",
+ cause,
+ }),
+ );
+ registry.dispose();
+ });
+
+ it("replaces cached state with refreshed live desktop state", async () => {
+ const refreshedState: DesktopWslState = {
+ ...wslState,
+ preflightError: "WSL backend stopped unexpectedly.",
+ };
+ let currentState = wslState;
+ const getWslState = vi.fn(async () => currentState);
+ const atom = createDesktopWslStateAtom(() => ({ getWslState }));
+ const registry = AtomRegistry.make();
+ registry.mount(atom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.value(registry.get(atom))).toEqual(
+ expect.objectContaining({ _tag: "Some", value: wslState }),
+ );
+ });
+
+ currentState = refreshedState;
+ registry.refresh(atom);
+
+ await vi.waitFor(() => {
+ expect(AsyncResult.value(registry.get(atom))).toEqual(
+ expect.objectContaining({ _tag: "Some", value: refreshedState }),
+ );
+ });
+ expect(getWslState).toHaveBeenCalledTimes(2);
+ registry.dispose();
+ });
+});
diff --git a/apps/web/src/state/desktopWslState.ts b/apps/web/src/state/desktopWslState.ts
new file mode 100644
index 000000000..90964dc29
--- /dev/null
+++ b/apps/web/src/state/desktopWslState.ts
@@ -0,0 +1,60 @@
+import type { DesktopBridge, DesktopWslState } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import { Atom } from "effect/unstable/reactivity";
+
+import { appAtomRegistry } from "~/rpc/atomRegistry";
+
+const DESKTOP_WSL_STATE_STALE_TIME_MS = 30_000;
+
+type DesktopWslStateBridge = Pick<DesktopBridge, "getWslState">;
+
+class DesktopWslStateUnavailableError extends Schema.TaggedErrorClass<DesktopWslStateUnavailableError>()(
+ "DesktopWslStateUnavailableError",
+ {},
+) {
+ override get message(): string {
+ return "Desktop WSL state is unavailable.";
+ }
+}
+
+class DesktopWslStateLoadError extends Schema.TaggedErrorClass<DesktopWslStateLoadError>()(
+ "DesktopWslStateLoadError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Failed to load WSL state.";
+ }
+}
+
+function getDesktopWslStateBridge(): DesktopWslStateBridge | undefined {
+ return typeof window === "undefined" ? undefined : window.desktopBridge;
+}
+
+export function createDesktopWslStateAtom(getBridge: () => DesktopWslStateBridge | undefined) {
+ const loadDesktopWslState = Effect.fn("loadDesktopWslState")(function* () {
+ const bridge = getBridge();
+ if (!bridge) {
+ return yield* new DesktopWslStateUnavailableError();
+ }
+ return yield* Effect.tryPromise({
+ try: (): Promise<DesktopWslState> => bridge.getWslState(),
+ catch: (cause) => new DesktopWslStateLoadError({ cause }),
+ });
+ });
+
+ return Atom.make(loadDesktopWslState()).pipe(
+ Atom.swr({
+ staleTime: DESKTOP_WSL_STATE_STALE_TIME_MS,
+ revalidateOnMount: true,
+ }),
+ Atom.keepAlive,
+ Atom.withLabel("desktop:wsl-state:load"),
+ );
+}
+
+export const desktopWslStateAtom = createDesktopWslStateAtom(getDesktopWslStateBridge);
+
+export function refreshDesktopWslState(): void {
+ appAtomRegistry.refresh(desktopWslStateAtom);
+}
diff --git a/apps/web/src/wslPaths.test.ts b/apps/web/src/wslPaths.test.ts
new file mode 100644
index 000000000..2bec0fd26
--- /dev/null
+++ b/apps/web/src/wslPaths.test.ts
@@ -0,0 +1,297 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ applyWslEnvironmentConfiguration,
+ parseWslUncPath,
+ resolveProjectPickerTarget,
+ resolveWslProjectSelection,
+} from "./wslPaths";
+
+describe("parseWslUncPath", () => {
+ it("parses wsl.localhost UNC paths into distro and POSIX path", () => {
+ expect(parseWslUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toEqual({
+ distro: "Ubuntu-22.04",
+ linuxPath: "/home/josh/repo",
+ });
+ });
+
+ it("parses wsl$ UNC roots as distro root", () => {
+ expect(parseWslUncPath("\\\\wsl$\\Debian")).toEqual({
+ distro: "Debian",
+ linuxPath: "/",
+ });
+ });
+
+ it("rejects non-WSL paths and invalid distro names", () => {
+ expect(parseWslUncPath("C:\\Users\\Josh\\repo")).toBeNull();
+ expect(parseWslUncPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
+ });
+});
+
+describe("resolveWslProjectSelection", () => {
+ it("routes a UNC path to the matching WSL backend", () => {
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", [
+ { environmentId: "env-debian", backendId: "wsl:Debian", runningDistro: null },
+ { environmentId: "env-ubuntu", backendId: "wsl:Ubuntu", runningDistro: null },
+ ]),
+ ).toEqual({
+ distro: "Ubuntu",
+ environmentId: "env-ubuntu",
+ linuxPath: "/home/theo/repo",
+ });
+ });
+
+ it("does not route to the only WSL backend when its distro is unknown", () => {
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", [
+ { environmentId: "env-wsl", backendId: "wsl:default", runningDistro: null },
+ ]),
+ ).toBeNull();
+ });
+
+ it("does not route to a sole WSL backend for a different distro", () => {
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Debian\\home\\theo\\repo", [
+ { environmentId: "env-ubuntu", backendId: "wsl:Ubuntu", runningDistro: null },
+ ]),
+ ).toBeNull();
+ });
+
+ it("does not guess when multiple WSL backends fail to match", () => {
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Fedora\\home\\theo\\repo", [
+ { environmentId: "env-debian", backendId: "wsl:Debian", runningDistro: null },
+ { environmentId: "env-ubuntu", backendId: "wsl:Ubuntu", runningDistro: null },
+ ]),
+ ).toBeNull();
+ });
+
+ it("routes a default backend only to the distro used by its running process", () => {
+ const candidates = [
+ { environmentId: "env-wsl", backendId: "wsl:default", runningDistro: "Debian" },
+ ];
+
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Debian\\home\\theo\\repo", candidates),
+ ).toEqual({
+ distro: "Debian",
+ environmentId: "env-wsl",
+ linuxPath: "/home/theo/repo",
+ });
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", candidates),
+ ).toBeNull();
+ });
+});
+
+describe("applyWslEnvironmentConfiguration", () => {
+ const ubuntuConfiguration = {
+ enabled: true,
+ wslOnly: false,
+ distro: null,
+ distros: [
+ { name: "Debian", isDefault: false },
+ { name: "Ubuntu", isDefault: true },
+ ],
+ };
+
+ it("preserves a live default-distro backend instance id", () => {
+ expect(
+ applyWslEnvironmentConfiguration(
+ [
+ {
+ environmentId: "env-wsl",
+ backendId: "wsl:default",
+ runningDistro: "Debian",
+ },
+ ],
+ "env-primary",
+ ubuntuConfiguration,
+ ),
+ ).toEqual([{ environmentId: "env-wsl", backendId: "wsl:default", runningDistro: "Debian" }]);
+ });
+
+ it("does not replace a live default backend's running distro from current configuration", () => {
+ const candidates = applyWslEnvironmentConfiguration(
+ [{ environmentId: "env-wsl", backendId: "wsl:default", runningDistro: "Debian" }],
+ "env-primary",
+ ubuntuConfiguration,
+ );
+
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", candidates),
+ ).toBeNull();
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Debian\\home\\theo\\repo", candidates),
+ ).toEqual({
+ distro: "Debian",
+ environmentId: "env-wsl",
+ linuxPath: "/home/theo/repo",
+ });
+ });
+
+ it("represents an explicitly configured WSL-only primary by its distro", () => {
+ expect(
+ applyWslEnvironmentConfiguration([], "env-primary", {
+ ...ubuntuConfiguration,
+ wslOnly: true,
+ distro: "ubuntu",
+ }),
+ ).toEqual([{ environmentId: "env-primary", backendId: "wsl:Ubuntu", runningDistro: "Ubuntu" }]);
+ });
+
+ it("preserves default tracking for a WSL-only primary", () => {
+ expect(
+ applyWslEnvironmentConfiguration([], "env-primary", {
+ ...ubuntuConfiguration,
+ wslOnly: true,
+ }),
+ ).toEqual([{ environmentId: "env-primary", backendId: "wsl:default", runningDistro: null }]);
+ });
+
+ it("uses the live primary distro for a default-tracking WSL-only primary", () => {
+ const candidates = applyWslEnvironmentConfiguration(
+ [],
+ "env-primary",
+ {
+ ...ubuntuConfiguration,
+ wslOnly: true,
+ distros: [],
+ },
+ "Ubuntu",
+ );
+
+ expect(candidates).toEqual([
+ { environmentId: "env-primary", backendId: "wsl:default", runningDistro: "Ubuntu" },
+ ]);
+ expect(
+ resolveWslProjectSelection("\\\\wsl.localhost\\Ubuntu\\home\\theo\\repo", candidates),
+ ).toEqual({
+ distro: "Ubuntu",
+ environmentId: "env-primary",
+ linuxPath: "/home/theo/repo",
+ });
+ });
+
+ it("keeps a configured distro authoritative when discovery does not contain it", () => {
+ expect(
+ applyWslEnvironmentConfiguration([], "env-primary", {
+ ...ubuntuConfiguration,
+ wslOnly: true,
+ distro: "Fedora",
+ }),
+ ).toEqual([{ environmentId: "env-primary", backendId: "wsl:Fedora", runningDistro: "Fedora" }]);
+ });
+
+ it("does not synthesize a backend for an empty configured distro name", () => {
+ expect(
+ applyWslEnvironmentConfiguration([], "env-primary", {
+ ...ubuntuConfiguration,
+ wslOnly: true,
+ distro: " ",
+ }),
+ ).toEqual([]);
+ });
+});
+
+describe("resolveProjectPickerTarget", () => {
+ const ubuntuConfiguration = {
+ enabled: true,
+ wslOnly: true,
+ distro: "Ubuntu-22.04",
+ distros: [
+ { name: "Debian", isDefault: true },
+ { name: "Ubuntu-22.04", isDefault: false },
+ ],
+ };
+
+ it("routes a WSL-only primary picker to its configured distro", () => {
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: ubuntuConfiguration,
+ }),
+ ).toBe("wsl:Ubuntu-22.04");
+ });
+
+ it("routes a configured distro while discovery is temporarily empty", () => {
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: { ...ubuntuConfiguration, distro: "ubuntu-22.04", distros: [] },
+ }),
+ ).toBe("wsl:ubuntu-22.04");
+ });
+
+ it("uses installed casing when discovery finds the configured distro", () => {
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: { ...ubuntuConfiguration, distro: "ubuntu-22.04" },
+ }),
+ ).toBe("wsl:Ubuntu-22.04");
+ });
+
+ it("routes a default-tracking WSL-only primary picker through the live sentinel", () => {
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: { ...ubuntuConfiguration, distro: null },
+ }),
+ ).toBe("wsl:default");
+ });
+
+ it("routes a default-tracking picker when the distro catalog has no default", () => {
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: {
+ ...ubuntuConfiguration,
+ distro: null,
+ distros: [{ name: "Ubuntu-22.04", isDefault: false }],
+ },
+ }),
+ ).toBe("wsl:default");
+
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: { ...ubuntuConfiguration, distro: null, distros: [] },
+ }),
+ ).toBe("wsl:default");
+ });
+
+ it("preserves combo-mode routing for primary and WSL backends", () => {
+ const comboConfiguration = { ...ubuntuConfiguration, wslOnly: false };
+
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-primary",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: null,
+ wslConfiguration: comboConfiguration,
+ }),
+ ).toBeNull();
+ expect(
+ resolveProjectPickerTarget({
+ browseEnvironmentId: "env-wsl",
+ primaryEnvironmentId: "env-primary",
+ desktopInstanceId: "wsl:Ubuntu-22.04",
+ wslConfiguration: comboConfiguration,
+ }),
+ ).toBe("wsl:Ubuntu-22.04");
+ });
+});
diff --git a/apps/web/src/wslPaths.ts b/apps/web/src/wslPaths.ts
new file mode 100644
index 000000000..71cd2d274
--- /dev/null
+++ b/apps/web/src/wslPaths.ts
@@ -0,0 +1,159 @@
+export interface WslUncPath {
+ readonly distro: string;
+ readonly linuxPath: string;
+}
+
+export interface WslEnvironmentCandidate<TEnvironmentId extends string = string> {
+ readonly environmentId: TEnvironmentId;
+ readonly backendId: string;
+ readonly runningDistro: string | null;
+}
+
+export interface WslEnvironmentConfiguration {
+ readonly enabled: boolean;
+ readonly wslOnly: boolean;
+ readonly distro: string | null;
+ readonly distros: ReadonlyArray<{
+ readonly name: string;
+ readonly isDefault: boolean;
+ }>;
+}
+
+export interface WslProjectSelection<TEnvironmentId extends string = string> extends WslUncPath {
+ readonly environmentId: TEnvironmentId;
+}
+
+const WSL_UNC_PREFIXES = ["\\\\wsl.localhost\\", "\\\\wsl$\\"] as const;
+const WSL_DISTRO_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
+const WSL_DEFAULT_BACKEND_ID = "wsl:default";
+
+export function parseWslUncPath(input: string): WslUncPath | null {
+ const normalized = input.trim().replaceAll("/", "\\");
+ const prefix = WSL_UNC_PREFIXES.find((candidate) =>
+ normalized.toLowerCase().startsWith(candidate.toLowerCase()),
+ );
+ if (!prefix) {
+ return null;
+ }
+
+ const rest = normalized.slice(prefix.length);
+ const segments = rest.split("\\").filter((segment) => segment.length > 0);
+ const distro = segments.shift();
+ if (!distro || !WSL_DISTRO_NAME_PATTERN.test(distro)) {
+ return null;
+ }
+
+ return {
+ distro,
+ linuxPath: segments.length === 0 ? "/" : `/${segments.join("/")}`,
+ };
+}
+
+export function resolveWslProjectSelection<TEnvironmentId extends string>(
+ input: string,
+ candidates: ReadonlyArray<WslEnvironmentCandidate<TEnvironmentId>>,
+): WslProjectSelection<TEnvironmentId> | null {
+ const parsed = parseWslUncPath(input);
+ if (!parsed) {
+ return null;
+ }
+
+ const exact = candidates.find((candidate) => {
+ if (!candidate.backendId.startsWith("wsl:")) {
+ return false;
+ }
+
+ const backendDistro = candidate.backendId.slice("wsl:".length);
+ const runningDistro =
+ candidate.runningDistro ??
+ (backendDistro.length > 0 && backendDistro.toLowerCase() !== "default"
+ ? backendDistro
+ : null);
+ return runningDistro?.toLowerCase() === parsed.distro.toLowerCase();
+ });
+ return exact ? { ...parsed, environmentId: exact.environmentId } : null;
+}
+
+interface ConfiguredWslBackend {
+ readonly backendId: string;
+ readonly runningDistro: string | null;
+}
+
+function resolveConfiguredWslBackend(
+ configuration: WslEnvironmentConfiguration | null,
+): ConfiguredWslBackend | null {
+ if (!configuration) {
+ return null;
+ }
+
+ if (configuration.distro === null) {
+ return { backendId: WSL_DEFAULT_BACKEND_ID, runningDistro: null };
+ }
+
+ const configuredDistro = configuration.distro.trim();
+ if (configuredDistro.length === 0) {
+ return null;
+ }
+
+ const installedDistro = configuration.distros.find(
+ (distro) => distro.name.toLowerCase() === configuredDistro.toLowerCase(),
+ );
+ const resolvedDistro = installedDistro?.name ?? configuredDistro;
+ return { backendId: `wsl:${resolvedDistro}`, runningDistro: resolvedDistro };
+}
+
+export function resolveProjectPickerTarget<TEnvironmentId extends string>(input: {
+ readonly browseEnvironmentId: TEnvironmentId | null;
+ readonly primaryEnvironmentId: TEnvironmentId | null;
+ readonly desktopInstanceId: string | null;
+ readonly wslConfiguration: WslEnvironmentConfiguration | null;
+}): string | null {
+ if (input.desktopInstanceId !== null) {
+ return input.desktopInstanceId;
+ }
+
+ if (
+ input.browseEnvironmentId === null ||
+ input.browseEnvironmentId !== input.primaryEnvironmentId ||
+ !input.wslConfiguration?.enabled ||
+ !input.wslConfiguration.wslOnly
+ ) {
+ return null;
+ }
+
+ return resolveConfiguredWslBackend(input.wslConfiguration)?.backendId ?? null;
+}
+
+export function applyWslEnvironmentConfiguration<TEnvironmentId extends string>(
+ candidates: ReadonlyArray<WslEnvironmentCandidate<TEnvironmentId>>,
+ primaryEnvironmentId: TEnvironmentId | null,
+ configuration: WslEnvironmentConfiguration | null,
+ primaryRunningDistro: string | null = null,
+): ReadonlyArray<WslEnvironmentCandidate<TEnvironmentId>> {
+ if (!configuration) {
+ return candidates;
+ }
+
+ const configuredBackend = resolveConfiguredWslBackend(configuration);
+ if (!configuredBackend) {
+ return candidates;
+ }
+
+ if (
+ configuration.enabled &&
+ configuration.wslOnly &&
+ primaryEnvironmentId !== null &&
+ !candidates.some((candidate) => candidate.environmentId === primaryEnvironmentId)
+ ) {
+ return [
+ ...candidates,
+ {
+ environmentId: primaryEnvironmentId,
+ ...configuredBackend,
+ runningDistro: primaryRunningDistro ?? configuredBackend.runningDistro,
+ },
+ ];
+ }
+
+ return candidates;
+}
diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.ts
index 84f811531..8df3b2541 100644
--- a/packages/client-runtime/src/connection/catalog.ts
+++ b/packages/client-runtime/src/connection/catalog.ts
@@ -89,6 +89,21 @@ export const ConnectionRegistration = Schema.Union([
]);
export type ConnectionRegistration = typeof ConnectionRegistration.Type;
+/**
+ * Platform-managed registrations are reconciled from the host (the desktop
+ * bootstrap IPC) rather than persisted by the user. They cover the primary
+ * local environment plus any additional desktop-local backends running
+ * alongside it (e.g. a parallel WSL backend). The primary stays on same-origin
+ * cookie auth (`PrimaryConnectionRegistration`); secondary local backends live
+ * on a separate loopback origin and authenticate with a bearer token minted
+ * from their bootstrap credential (`BearerConnectionRegistration`).
+ */
+export const PlatformConnectionRegistration = Schema.Union([
+ PrimaryConnectionRegistration,
+ BearerConnectionRegistration,
+]);
+export type PlatformConnectionRegistration = typeof PlatformConnectionRegistration.Type;
+
export function connectionRegistrationTarget(
registration: ConnectionRegistration | PrimaryConnectionRegistration,
): ConnectionTarget {
diff --git a/packages/client-runtime/src/connection/layer.ts b/packages/client-runtime/src/connection/layer.ts
index a7485878e..798ec01e2 100644
--- a/packages/client-runtime/src/connection/layer.ts
+++ b/packages/client-runtime/src/connection/layer.ts
@@ -35,7 +35,7 @@ const connectionStartupLayer = Layer.effectDiscard(
const platformSource = yield* PlatformConnectionSource.PlatformConnectionSource;
yield* registry.start;
yield* platformSource.registrations.pipe(
- Stream.runForEach(registry.registerPlatform),
+ Stream.runForEach(registry.reconcilePlatform),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("clientRuntime.connection.application.start")),
diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts
index 3a95185d8..a3a36272f 100644
--- a/packages/client-runtime/src/connection/registry.ts
+++ b/packages/client-runtime/src/connection/registry.ts
@@ -16,10 +16,12 @@ import * as ClientCapabilities from "../platform/capabilities.ts";
import {
type ConnectionCatalogEntry,
type ConnectionRegistration,
+ type PlatformConnectionRegistration,
type PrimaryConnectionRegistration,
SshConnectionProfile,
connectionRegistrationCatalogEntry,
} from "./catalog.ts";
+import * as ConnectionCredentialStore from "./credentialStore.ts";
import * as ConnectionProfileStore from "./profileStore.ts";
import * as Connectivity from "./connectivity.ts";
import type {
@@ -69,6 +71,9 @@ export class EnvironmentRegistry extends Context.Service<
registration: ConnectionRegistration,
) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
readonly registerPlatform: (registration: PrimaryConnectionRegistration) => Effect.Effect<void>;
+ readonly reconcilePlatform: (
+ registrations: ReadonlyArray<PlatformConnectionRegistration>,
+ ) => Effect.Effect<void>;
readonly remove: (
environmentId: EnvironmentId,
) => Effect.Effect<
@@ -126,6 +131,7 @@ export const make = Effect.gen(function* () {
const cache = yield* Persistence.EnvironmentCacheStore;
const ownedDataCleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
+ const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
const connectivity = yield* Connectivity.Connectivity;
const driver = yield* ConnectionDriver.ConnectionDriver;
const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
@@ -402,47 +408,137 @@ export const make = Effect.gen(function* () {
);
});
- const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
- registration: PrimaryConnectionRegistration,
- ) {
- const entry = connectionRegistrationCatalogEntry(registration);
- const target = entry.target;
- yield* withLeaseLock(
- target.environmentId,
- Effect.gen(function* () {
- yield* Ref.update(platformEnvironmentIds, (current) => {
- const next = new Set(current);
- next.add(target.environmentId);
- return next;
- });
+ const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
+ function* (registration: PlatformConnectionRegistration) {
+ const entry = connectionRegistrationCatalogEntry(registration);
+ const target = entry.target;
+ yield* withLeaseLock(
+ target.environmentId,
+ Effect.gen(function* () {
+ yield* Ref.update(platformEnvironmentIds, (current) => {
+ const next = new Set(current);
+ next.add(target.environmentId);
+ return next;
+ });
- const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
- target.environmentId,
- );
- if (persistedTarget !== undefined) {
- yield* registrations.remove(persistedTarget).pipe(
- Effect.tap(() =>
- Ref.update(persistedTargetsByEnvironment, (current) => {
- const next = new Map(current);
- next.delete(target.environmentId);
- return next;
- }),
- ),
- Effect.catch((error) =>
- Effect.logWarning(
- "Could not remove a persisted registration shadowed by the primary environment.",
- {
+ // Secondary desktop-local backends (e.g. a parallel WSL backend) live
+ // on their own loopback origin, so they authenticate with a bearer
+ // token instead of the primary's same-origin cookie. Stash it where
+ // the resolver's bearer broker looks it up.
+ if (registration._tag === "BearerConnectionRegistration") {
+ yield* credentials.put(registration.target.connectionId, registration.credential).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Could not store the platform bearer credential.", {
environmentId: target.environmentId,
error,
- },
+ }),
),
- ),
+ );
+ }
+
+ const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
+ target.environmentId,
);
- }
+ if (persistedTarget !== undefined) {
+ yield* registrations.remove(persistedTarget).pipe(
+ Effect.tap(() =>
+ Ref.update(persistedTargetsByEnvironment, (current) => {
+ const next = new Map(current);
+ next.delete(target.environmentId);
+ return next;
+ }),
+ ),
+ Effect.catch((error) =>
+ Effect.logWarning(
+ "Could not remove a persisted registration shadowed by a platform environment.",
+ {
+ environmentId: target.environmentId,
+ error,
+ },
+ ),
+ ),
+ );
+ }
- yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
- }),
+ yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
+ }),
+ );
+ },
+ );
+
+ // Tear down a platform-managed environment that the host no longer reports
+ // (e.g. the user turned the parallel WSL backend off). Platform environments
+ // bypass the user-facing `remove` guard since they are reconciled from the
+ // bootstrap rather than removed by hand.
+ const removePlatformEnvironment = Effect.fn("EnvironmentRegistry.removePlatformEnvironment")(
+ function* (environmentId: EnvironmentId) {
+ yield* withLeaseLock(
+ environmentId,
+ Effect.gen(function* () {
+ const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
+ yield* Ref.update(platformEnvironmentIds, (current) => {
+ const next = new Set(current);
+ next.delete(environmentId);
+ return next;
+ });
+ yield* closeServiceScope(environmentId);
+ yield* SubscriptionRef.update(entries, (current) => {
+ const next = new Map(current);
+ next.delete(environmentId);
+ return next;
+ });
+ if (entry !== undefined && entry.target._tag === "BearerConnectionTarget") {
+ yield* credentials.remove(entry.target.connectionId).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Could not clear the platform bearer credential.", {
+ environmentId,
+ error,
+ }),
+ ),
+ );
+ }
+ yield* Effect.all(
+ [
+ cache.clear(environmentId).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Could not clear cached environment data after removal.", {
+ environmentId,
+ error,
+ }),
+ ),
+ ),
+ ownedDataCleanup.clear(environmentId),
+ ],
+ { concurrency: "unbounded", discard: true },
+ );
+ }),
+ );
+ },
+ );
+
+ const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
+ registration: PrimaryConnectionRegistration,
+ ) {
+ yield* installPlatformRegistration(registration);
+ });
+
+ // Reconcile the full set of platform-managed environments against what the
+ // host currently reports: add/refresh the desired ones and tear down any
+ // platform environment that disappeared (WSL toggled off, distro switched).
+ const reconcilePlatform = Effect.fn("EnvironmentRegistry.reconcilePlatform")(function* (
+ platformRegistrations: ReadonlyArray<PlatformConnectionRegistration>,
+ ) {
+ const desiredIds = new Set(
+ platformRegistrations.map((registration) => registration.target.environmentId),
+ );
+ const currentPlatformIds = yield* Ref.get(platformEnvironmentIds);
+ yield* Effect.forEach(
+ currentPlatformIds,
+ (environmentId) =>
+ desiredIds.has(environmentId) ? Effect.void : removePlatformEnvironment(environmentId),
+ { discard: true },
);
+ yield* Effect.forEach(platformRegistrations, installPlatformRegistration, { discard: true });
});
const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
@@ -567,6 +663,7 @@ export const make = Effect.gen(function* () {
start,
register,
registerPlatform,
+ reconcilePlatform,
remove,
removeRelayEnvironments,
retryNow,
diff --git a/packages/client-runtime/src/platform/source.ts b/packages/client-runtime/src/platform/source.ts
index 8b5bbeeea..517f4b9b5 100644
--- a/packages/client-runtime/src/platform/source.ts
+++ b/packages/client-runtime/src/platform/source.ts
@@ -1,11 +1,15 @@
import * as Context from "effect/Context";
import type * as Stream from "effect/Stream";
-import type { PrimaryConnectionRegistration } from "../connection/catalog.ts";
+import type { PlatformConnectionRegistration } from "../connection/catalog.ts";
export class PlatformConnectionSource extends Context.Service<
PlatformConnectionSource,
{
- readonly registrations: Stream.Stream<PrimaryConnectionRegistration>;
+ // Each emission is the full current set of platform-managed environments
+ // (the primary local environment plus any desktop-local backends running
+ // alongside it). The registry reconciles the set, so the source can drive
+ // both additions and removals by re-emitting.
+ readonly registrations: Stream.Stream<ReadonlyArray<PlatformConnectionRegistration>>;
}
>()("@t3tools/client-runtime/platform/source/PlatformConnectionSource") {}
diff --git a/packages/contracts/src/desktopBootstrap.ts b/packages/contracts/src/desktopBootstrap.ts
index c23dbbb39..e09f43a0e 100644
--- a/packages/contracts/src/desktopBootstrap.ts
+++ b/packages/contracts/src/desktopBootstrap.ts
@@ -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,
diff --git a/packages/contracts/src/ipc.test.ts b/packages/contracts/src/ipc.test.ts
new file mode 100644
index 000000000..20db75368
--- /dev/null
+++ b/packages/contracts/src/ipc.test.ts
@@ -0,0 +1,38 @@
+import * as Schema from "effect/Schema";
+import { describe, expect, it } from "vite-plus/test";
+
+import { DesktopEnvironmentBootstrapSchema } from "./ipc.ts";
+
+describe("DesktopEnvironmentBootstrapSchema", () => {
+ const decode = Schema.decodeUnknownSync(DesktopEnvironmentBootstrapSchema);
+
+ it("preserves the concrete running distro separately from the backend id", () => {
+ expect(
+ decode({
+ id: "wsl:default",
+ label: "WSL (Ubuntu)",
+ runningDistro: "Ubuntu",
+ httpBaseUrl: "http://127.0.0.1:3774/",
+ wsBaseUrl: "ws://127.0.0.1:3774/",
+ }),
+ ).toEqual({
+ id: "wsl:default",
+ label: "WSL (Ubuntu)",
+ runningDistro: "Ubuntu",
+ httpBaseUrl: "http://127.0.0.1:3774/",
+ wsBaseUrl: "ws://127.0.0.1:3774/",
+ });
+ });
+
+ it("allows non-running and non-WSL bootstraps to report no running distro", () => {
+ expect(
+ decode({
+ id: "primary",
+ label: "Windows",
+ runningDistro: null,
+ httpBaseUrl: null,
+ wsBaseUrl: null,
+ }).runningDistro,
+ ).toBeNull();
+ });
+});
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 6a8dce87c..bbb4d934c 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -259,15 +259,31 @@ export const DesktopUpdateCheckResultSchema = Schema.Struct({
state: DesktopUpdateStateSchema,
});
+// Stable id for the Windows-native primary backend. Desktop side wraps
+// this with a brand inside DesktopBackendManager; web side keeps it as
+// a plain string so the env-runtime can compare against it without
+// importing brand machinery from the desktop package.
+export const PRIMARY_LOCAL_ENVIRONMENT_ID = "primary";
+
export interface DesktopEnvironmentBootstrap {
+ // Stable backend instance id (e.g. "primary" or "wsl:ubuntu"). The
+ // web env runtime keys local environments off this so projects
+ // routed to a specific backend reopen against the same one.
+ id: string;
label: string;
+ // Concrete WSL distro used by the current backend run. This stays separate
+ // from id because a default-tracking instance keeps the stable
+ // "wsl:default" IPC target while each run launches a specific distro.
+ runningDistro?: string | null;
httpBaseUrl: string | null;
wsBaseUrl: string | null;
bootstrapToken?: string;
}
export const DesktopEnvironmentBootstrapSchema = Schema.Struct({
+ id: Schema.String,
label: Schema.String,
+ runningDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
httpBaseUrl: Schema.NullOr(Schema.String),
wsBaseUrl: Schema.NullOr(Schema.String),
bootstrapToken: Schema.optionalKey(Schema.String),
@@ -411,10 +427,59 @@ export const DesktopServerExposureStateSchema = Schema.Struct({
export interface PickFolderOptions {
initialPath?: string | null;
+ // When set, the desktop dialog opens against the named backend's
+ // filesystem instead of the primary's. Used by callers that already
+ // know which local environment they're targeting (e.g. opening a
+ // project that lives inside WSL). Omitting it keeps the historical
+ // behavior so non-WSL users never see a different picker.
+ targetEnvironmentId?: string;
}
export const PickFolderOptionsSchema = Schema.Struct({
initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)),
+ targetEnvironmentId: Schema.optionalKey(Schema.String),
+});
+
+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 {
+ // True when the user has opted the WSL backend in; the actual backend
+ // process is registered with the desktop pool independently of this
+ // flag and may take a moment to come up after the user enables it.
+ enabled: boolean;
+ // null means "track the current WSL default distro".
+ distro: string | null;
+ available: boolean;
+ // When true (and `enabled` is also true) the desktop runs only the
+ // WSL backend as the primary; the Windows-side Node backend is not
+ // started. Toggling this requires an app restart because the
+ // primary backend's spec is captured once at layer init.
+ wslOnly: boolean;
+ distros: readonly DesktopWslDistro[];
+ // Reason the dual-mode WSL backend last failed preflight (no node, wrong
+ // version, missing build tools), or null. Surfaced inline in Connections
+ // settings. Always null in wsl-only mode — that path shows a dialog and
+ // falls back to Windows instead.
+ preflightError: string | null;
+}
+
+export const DesktopWslStateSchema = Schema.Struct({
+ enabled: Schema.Boolean,
+ distro: Schema.NullOr(Schema.String),
+ available: Schema.Boolean,
+ wslOnly: Schema.Boolean,
+ distros: Schema.Array(DesktopWslDistroSchema),
+ preflightError: Schema.NullOr(Schema.String),
});
/**
@@ -881,7 +946,10 @@ export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
- getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
+ // One bootstrap per pool instance currently registered with bootstrap
+ // info (omits instances whose backend hasn't produced a config yet).
+ // The primary backend is identified by id === PRIMARY_LOCAL_ENVIRONMENT_ID.
+ getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];
getLocalEnvironmentBearerToken: () => Promise<string>;
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
@@ -913,6 +981,10 @@ export interface DesktopBridge {
readonly port?: number;
}) => Promise<DesktopServerExposureState>;
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;
+ getWslState: () => Promise<DesktopWslState>;
+ setWslBackendEnabled: (enabled: boolean) => Promise<DesktopWslState>;
+ setWslDistro: (distro: string | null) => Promise<DesktopWslState>;
+ setWslOnly: (enabled: boolean) => Promise<DesktopWslState>;
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
setTheme: (theme: DesktopTheme) => Promise<void>;
diff --git a/packages/shared/package.json b/packages/shared/package.json
index f0eab2c8b..e08844cbf 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -178,6 +178,10 @@
"./hostProcess": {
"types": "./src/hostProcess.ts",
"import": "./src/hostProcess.ts"
+ },
+ "./httpReadiness": {
+ "types": "./src/httpReadiness.ts",
+ "import": "./src/httpReadiness.ts"
}
},
"scripts": {
diff --git a/packages/shared/src/httpReadiness.ts b/packages/shared/src/httpReadiness.ts
new file mode 100644
index 000000000..c832f689b
--- /dev/null
+++ b/packages/shared/src/httpReadiness.ts
@@ -0,0 +1,168 @@
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as Ref from "effect/Ref";
+import * as Schedule from "effect/Schedule";
+import { HttpClient, HttpClientRequest } from "effect/unstable/http";
+
+export const DEFAULT_HTTP_READY_PROBE_TIMEOUT_MS = 1_000;
+
+/**
+ * Normalizes an arbitrary readiness probe failure into a plain, structured value
+ * suitable for diagnostic logging. Preserves the tagged-error `_tag` (and
+ * message/cause) shape for Effect tagged errors while recursing through nested
+ * `cause`/`reason` chains.
+ */
+export function describeReadinessCause(cause: unknown): unknown {
+ if (cause instanceof Error) {
+ const tag = (cause as { readonly _tag?: unknown })._tag;
+ const nested = (cause as { readonly cause?: unknown }).cause;
+ return {
+ ...(typeof tag === "string" ? { _tag: tag } : { name: cause.name }),
+ message: cause.message,
+ ...(nested === undefined ? {} : { cause: describeReadinessCause(nested) }),
+ };
+ }
+ if (typeof cause !== "object" || cause === null) {
+ return cause;
+ }
+
+ const record = cause as Readonly<Record<string, unknown>>;
+ return {
+ ...(typeof record._tag === "string" ? { _tag: record._tag } : {}),
+ ...(typeof record.message === "string" ? { message: record.message } : {}),
+ ...(record.reason === undefined ? {} : { reason: describeReadinessCause(record.reason) }),
+ ...(record.cause === undefined ? {} : { cause: describeReadinessCause(record.cause) }),
+ };
+}
+
+/**
+ * Generic HTTP readiness probe shared by the SSH tunnel and the desktop backend
+ * manager. Polls `baseUrl + path` until it returns a 2xx response or the overall
+ * `timeoutMs` elapses. Each individual probe is bounded by `probeTimeoutMs` so a
+ * single hung request cannot stall the retry loop, and the retry cadence is
+ * `intervalMs` bounded to roughly `timeoutMs / intervalMs` attempts.
+ *
+ * The error type is left to the caller via `makeError`, so each consumer keeps
+ * its own tagged error. `makeError` is called at every failure site; callers can
+ * inspect `cause` (which carries a `kind` discriminator for the probe-timeout and
+ * overall-timeout cases) to reproduce phase-specific messages, or ignore it.
+ */
+export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReady")(function* <
+ E,
+>(input: {
+ readonly baseUrl: string;
+ readonly path?: string;
+ readonly timeoutMs?: number;
+ readonly intervalMs?: number;
+ readonly probeTimeoutMs?: number;
+ readonly makeError: (info: {
+ readonly requestUrl: string;
+ readonly probeTimeoutMs: number;
+ readonly attempt: number;
+ readonly cause: unknown;
+ }) => E;
+}): Effect.fn.Return<void, E, HttpClient.HttpClient> {
+ const timeoutMs = input.timeoutMs ?? 30_000;
+ const intervalMs = input.intervalMs ?? 100;
+ const probeTimeoutMs = input.probeTimeoutMs ?? DEFAULT_HTTP_READY_PROBE_TIMEOUT_MS;
+ const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
+ Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
+ );
+ const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
+ const client = yield* HttpClient.HttpClient;
+ const lastProbeFailure = yield* Ref.make<unknown>(null);
+ let attempt = 0;
+
+ // Tracks errors this function itself produced via `makeError`, so the
+ // pass-through guards below never double-wrap an already-constructed error
+ // (mirrors the SSH original's `cause instanceof SshReadinessError` checks).
+ const makeError = input.makeError;
+ const madeErrors = new WeakSet<object>();
+ const fail = (cause: unknown): E => {
+ const error = makeError({ requestUrl, probeTimeoutMs, attempt, cause });
+ if (typeof error === "object" && error !== null) {
+ madeErrors.add(error);
+ }
+ return error;
+ };
+ const isMadeError = (value: unknown): value is E =>
+ typeof value === "object" && value !== null && madeErrors.has(value);
+
+ yield* Effect.logDebug("httpReadiness.start", {
+ baseUrl: input.baseUrl,
+ requestUrl,
+ timeoutMs,
+ intervalMs,
+ probeTimeoutMs,
+ });
+
+ const readinessClient = client.pipe(
+ HttpClient.filterStatusOk,
+ HttpClient.transform((effect) =>
+ Effect.gen(function* () {
+ attempt += 1;
+ const responseOption = yield* effect.pipe(
+ Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
+ Effect.mapError((cause) => fail(cause)),
+ );
+ return yield* Option.match(responseOption, {
+ onSome: Effect.succeed,
+ onNone: () =>
+ Effect.fail(
+ fail({
+ kind: "probe-timeout",
+ attempt,
+ probeTimeoutMs,
+ }),
+ ),
+ });
+ }).pipe(
+ Effect.mapError((cause) => (isMadeError(cause) ? cause : fail(cause))),
+ Effect.tapError((cause) =>
+ Ref.set(lastProbeFailure, {
+ attempt,
+ cause: describeReadinessCause(cause),
+ }),
+ ),
+ ),
+ ),
+ HttpClient.tap((response) => response.text.pipe(Effect.ignore)),
+ HttpClient.retry(retryPolicy),
+ );
+
+ const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
+ Effect.mapError((cause) => (isMadeError(cause) ? cause : fail(cause))),
+ Effect.timeoutOption(Duration.millis(timeoutMs)),
+ );
+
+ return yield* Option.match(result, {
+ onSome: () =>
+ Effect.logDebug("httpReadiness.succeeded", {
+ baseUrl: input.baseUrl,
+ requestUrl,
+ attempts: attempt,
+ }),
+ onNone: () =>
+ Effect.gen(function* () {
+ const lastFailure = yield* Ref.get(lastProbeFailure);
+ yield* Effect.logWarning("httpReadiness.timedOut", {
+ baseUrl: input.baseUrl,
+ requestUrl,
+ timeoutMs,
+ intervalMs,
+ probeTimeoutMs,
+ attempts: attempt,
+ lastFailure,
+ });
+ return yield* Effect.fail(
+ fail({
+ kind: "overall-timeout",
+ baseUrl: input.baseUrl,
+ timeoutMs,
+ lastFailure,
+ }),
+ );
+ }),
+ });
+});
diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts
index e8c2b9247..016d5e9a8 100644
--- a/packages/ssh/src/tunnel.ts
+++ b/packages/ssh/src/tunnel.ts
@@ -2,24 +2,24 @@ import type {
DesktopSshEnvironmentBootstrap,
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
+import {
+ describeReadinessCause,
+ waitForHttpReady as waitForHttpReadyShared,
+} from "@t3tools/shared/httpReadiness";
import * as NetService from "@t3tools/shared/Net";
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
-import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
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 Ref from "effect/Ref";
-import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
-import { HttpClient, HttpClientRequest } from "effect/unstable/http";
+import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -232,33 +232,9 @@ function applyScriptPlaceholders(
return result;
}
-export function describeReadinessCause(cause: unknown): unknown {
- if (cause instanceof SshReadinessError) {
- return {
- _tag: cause._tag,
- message: cause.message,
- ...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
- };
- }
- if (cause instanceof Error) {
- return {
- name: cause.name,
- message: cause.message,
- ...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
- };
- }
- if (typeof cause !== "object" || cause === null) {
- return cause;
- }
-
- const record = cause as Readonly<Record<string, unknown>>;
- return {
- ...(typeof record._tag === "string" ? { _tag: record._tag } : {}),
- ...(typeof record.message === "string" ? { message: record.message } : {}),
- ...(record.reason === undefined ? {} : { reason: describeReadinessCause(record.reason) }),
- ...(record.cause === undefined ? {} : { cause: describeReadinessCause(record.cause) }),
- };
-}
+// Re-exported from the shared HTTP readiness module so existing importers
+// (notably tunnel.test.ts) keep resolving it from here.
+export { describeReadinessCause };
export const REMOTE_PICK_PORT_SCRIPT = `const fs = require("node:fs");
const net = require("node:net");
@@ -666,7 +642,7 @@ export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string
);
}
-function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string {
+export function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string {
return stripTrailingNewlines(
applyScriptPlaceholders(REMOTE_NODE_ENV_SCRIPT, {
T3_NODE_ENGINE_RANGE: shellSingleQuote(input?.nodeEngineRange?.trim() || ""),
@@ -865,120 +841,46 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
return result.stdout.trim();
});
-export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
+export const waitForHttpReady = (input: {
readonly baseUrl: string;
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly probeTimeoutMs?: number;
readonly path?: string;
-}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
- const timeoutMs = input.timeoutMs ?? 30_000;
- const intervalMs = input.intervalMs ?? 100;
- const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
- const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
- Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
- );
- const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
- const client = yield* HttpClient.HttpClient;
- const lastProbeFailure = yield* Ref.make<unknown>(null);
- let attempt = 0;
-
- yield* Effect.logDebug("ssh.tunnel.httpReady.start", {
+}): Effect.Effect<void, SshReadinessError, HttpClient.HttpClient> =>
+ waitForHttpReadyShared({
baseUrl: input.baseUrl,
- requestUrl,
- timeoutMs,
- intervalMs,
- probeTimeoutMs,
- });
-
- const readinessClient = client.pipe(
- HttpClient.filterStatusOk,
- HttpClient.transform((effect) =>
- Effect.gen(function* () {
- attempt += 1;
- const responseOption = yield* effect.pipe(
- Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
- Effect.mapError(
- (cause) =>
- new SshReadinessError({
- message: `Backend readiness probe failed at ${requestUrl}.`,
- cause,
- }),
- ),
- );
- return yield* Option.match(responseOption, {
- onSome: Effect.succeed,
- onNone: () =>
- Effect.fail(
- new SshReadinessError({
- message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
- cause: {
- kind: "probe-timeout",
- attempt,
- probeTimeoutMs,
- },
- }),
- ),
- });
- }).pipe(
- Effect.mapError((cause) =>
- cause instanceof SshReadinessError
- ? cause
- : new SshReadinessError({
- message: `Backend readiness probe failed at ${requestUrl}.`,
- cause,
- }),
- ),
- Effect.tapError((cause) =>
- Ref.set(lastProbeFailure, {
- attempt,
- cause: describeReadinessCause(cause),
- }),
- ),
- ),
- ),
- HttpClient.tap((response) => response.text.pipe(Effect.ignore)),
- HttpClient.retry(retryPolicy),
- );
-
- const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
- Effect.mapError((cause) =>
- cause instanceof SshReadinessError
- ? cause
- : new SshReadinessError({
- message: `Backend readiness probe failed at ${requestUrl}.`,
+ ...(input.path === undefined ? {} : { path: input.path }),
+ ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
+ ...(input.intervalMs === undefined ? {} : { intervalMs: input.intervalMs }),
+ probeTimeoutMs: input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS,
+ makeError: ({ requestUrl, probeTimeoutMs, cause }) => {
+ if (typeof cause === "object" && cause !== null && "kind" in cause) {
+ const kind = (cause as { readonly kind?: unknown }).kind;
+ if (kind === "probe-timeout") {
+ return new SshReadinessError({
+ message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
cause,
- }),
- ),
- Effect.timeoutOption(Duration.millis(timeoutMs)),
- );
-
- return yield* Option.match(result, {
- onSome: () =>
- Effect.logDebug("ssh.tunnel.httpReady.succeeded", {
- baseUrl: input.baseUrl,
- requestUrl,
- attempts: attempt,
- }),
- onNone: () =>
- Effect.gen(function* () {
- const lastFailure = yield* Ref.get(lastProbeFailure);
- yield* Effect.logWarning("ssh.tunnel.httpReady.timedOut", {
- baseUrl: input.baseUrl,
- requestUrl,
- timeoutMs,
- intervalMs,
- probeTimeoutMs,
- attempts: attempt,
- lastFailure,
- });
- return yield* new SshReadinessError({
- message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
- cause: lastFailure,
- });
- }),
+ });
+ }
+ if (kind === "overall-timeout") {
+ const overall = cause as unknown as {
+ readonly baseUrl: string;
+ readonly timeoutMs: number;
+ readonly lastFailure: unknown;
+ };
+ return new SshReadinessError({
+ message: `Timed out waiting ${overall.timeoutMs}ms for backend readiness at ${overall.baseUrl}.`,
+ cause: overall.lastFailure,
+ });
+ }
+ }
+ return new SshReadinessError({
+ message: `Backend readiness probe failed at ${requestUrl}.`,
+ cause,
+ });
+ },
});
-});
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4645ecc34..8d7c462a7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -911,21 +911,25 @@ packages:
resolution: {integrity: sha512-SRYfQcsXlOq+CD/FqkQBTSHbaD++w73GnnO+NUV9adLYrca3kfetRwWT1iguY1cNS0l34dCR3rlzCPq78vg1Jg==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-gLbaFqcGppFJQd4DLNV4IXoeahejT/p2/M8bSSvRDbla9GOsBr1AxV5XLRyBn1e7xFGozZIAIQr3+1chp7NJgQ==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-m4+I0qBEk7cxRKS+pL+eoWXbXTFOAo83fQ0tQvap4z/mDMm06IWJtEPoYTaMBwsp32GJWLkHWKbZSBCHZnp2DQ==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-Xl/m7TaSC3T5IDBdHrZQ9fCQYyDmPELN34CL+MoyPIf7uSmuZnjE9fUOqDh2Rv26JxWssi1M6X+BBvVuKd6Cpg==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-IG+8isJNNJKbnnhO7m+PGhfVCg+XoQ/MDxGde5eigFI0WsEfitjuWSWwx82bT9ghxI1aa6qNvI+UPgPcZuo5Fg==}
@@ -977,24 +981,28 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@astrojs/[email protected]':
resolution: {integrity: sha512-O3e2CbN4yTsRguWYNnRd0p5YQ0H3fb7KpcR0W4R319q/gq5B1pJ7eqNbiO3b8g2AuiEcRTiUz5jeGT9j69cxOQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@astrojs/[email protected]':
resolution: {integrity: sha512-hbLBjXVp+96psMe7/7uqyrquGiULXANrq6REVxxPK/I5VzebZ7LHmSfykmByUbLyR1u+K6CTBKgvdQsK2L+2Xw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@astrojs/[email protected]':
resolution: {integrity: sha512-vIiEvOwrJfHZMaTmqUCrFTIwMYL0+PD3Rvy7kFDQgERyx3zhaw8CPa01MCCqa+/sj344BGrXKZ6ti37SgNLMhw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@astrojs/[email protected]':
resolution: {integrity: sha512-p9S2X8z/mUR2SMzAVJRFMCt8YaalKR+pjl2DgpdjzCQc6ww4bo8kiy54tgKqxZeNF5c+/2tCDTQIxVSm9V1FsA==}
@@ -1583,21 +1591,25 @@ packages:
resolution: {integrity: sha512-A/pWy8Jb/PhDYc2/JFuYh06gFJcsfBUBDl81YydGYBrL/Z4nItDfhNDNOibyeSN/lKKDRlycIHEIajjErk00sQ==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@bruits/[email protected]':
resolution: {integrity: sha512-L6YxmyOSickzo4pE5WmZfNTJnjX0MtgKOsuwQfNZECTx9Ir5vl2B37EIwnxe2AybuPPHl+FqVQtthNDUdH4Vgg==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@bruits/[email protected]':
resolution: {integrity: sha512-RgH6GPihg9Lzs2yHUsMjqiLxfLyOdmBty8sg9pBY9B4CBnvdOzvg8vklqN+C4qrEEdA9TwpbDpHr1AshLKyRpw==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@bruits/[email protected]':
resolution: {integrity: sha512-BeWhVORjNTIomePznUKiMbHZTqC0j7sMXZFsISmbX+po5d33KLkqBqKh6K332CHJ8KUmCWx16FfPjwsoysttQg==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@bruits/[email protected]':
resolution: {integrity: sha512-dFNcOHKWV2cztCPnYTn7kZ9D7kNOt8N239z5ysFkNHLxJrfK7zaKIXQbfXYN32C+JoVFqAcTIOeWH2+VnsCOHg==}
@@ -2575,21 +2587,25 @@ packages:
resolution: {integrity: sha512-m5+8vA+1veaUUWonwva1WsU6m1HRm8CpYUzr06KDB65mewlmPbqz7+Fh7hjEfiD8C4mHVHe6RysULvAH1yhsdw==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@ff-labs/[email protected]':
resolution: {integrity: sha512-EMeWm7CSTVkizy4ZEzUkLDP024tVcbCUthduuIhekFQRDsiaAze0YboIylWb9HBHJCZlCCoZrWAl4nnJbsX7AA==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@ff-labs/[email protected]':
resolution: {integrity: sha512-pglE0uLkhnlE6bStXqfgUjYTSj+2sVwXaPfoA0QksidAsQor6NRt8004mygzC9DPubgHq5B9QezPfEwigKaP9Q==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@ff-labs/[email protected]':
resolution: {integrity: sha512-VNKxgl8qs3aTfXViX7lqRK1aLu311h8dtBFqG4Scv+9Oi7WprybUp5L7IZ8sxKERaDAaiJMXHodXa1c90QdK8w==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@ff-labs/[email protected]':
resolution: {integrity: sha512-uFEt0aNL54vQxq1ivjxRuo+thnhS4wLqa4INl4VXnXJUmwB42XXxD+gsj7vzhBLLx4cFf0aWgy/+TVDR8yjZtQ==}
@@ -2676,89 +2692,105 @@ packages:
resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
@@ -3217,48 +3249,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-r8xlKJFcsRmn0H5jZrdORae6RX9jDBrZVvOoxF+bCQtampQJClv80aZEHsv+NsLsp2KCE5ql79O7DpPVzYWpXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-GRKv/HXHcwIVld/WU61rF0g0R16hl5EJ+ScKdpjevT57lnLnagj/U2YUbXf2mT+2Pg1uCzWC+mvGicPV3CDdLQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-rdv57enTiPtpSYRMKfAiEbQb0Puw5t9N7isVinDoo5qeLDScro2gznmZqSgSWbVZRzLisTeCTW8Qwgw0bOHv3A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-7v1nNrlD43VY6+sYQ6efYyb3lE6QY182304PD/768ZxTjOmFd/3dQa3u/nGBUAXYdGSWOQc5N3PnS0QzUXyEIA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-f4lJLUSPOgScjFl9LiflKCTocyNRwE25JmTMbN4XQdDjoZzEHjqf3wA3VESF1/csg7i8m7+EQLbrZyYDqe10UQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-MihqiPziJNoWy4MqNSV+jVA1g+07iQDjZiR0vaCaDoPgFEiJpCMsxamktzLV07cEeQsSJ04vQaU4CzCQwIvtDA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-Yqghym7KYAVjP9MmSrNZiDeerMuoejNjo0r3ox5H3GDKk8eAfl8VyJm9i+pWCLDCTnAbcTUMMN2ZKjUYXH1v3g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-s5SDvVVSbyQl1V5UU3Yl12M+XLUQ3rl5SglNqgAA2K4PXUtQhyNSS00wivONPEnNo5W01rCou8WkDNyvI/RGHg==}
@@ -3361,48 +3401,56 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-JiylyurlB0CLSedNtx1gzv3FvfWPF1h/2Y3BJszPLNt5XQFlBsH5ke0Jle3iJb3uqu5m2e7A/DwzpuCAHdiU+A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-J8VPG7I3/HmgaU4u8pNU2kFx2+0U+vPLS1dXFxXOaR/2TQ0f8AC7DRz0SRGRI1bfphnX2hVYTTtLuhL4nYKL+Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-N2+4lV2KLN+oXTIIIwmWDhwkrnvqf5oX7Hw0zPjk+RuIVgiBQSOlJWF7uQoFx2siEYX0ZQ5cfSbEAHm+J3t7Wg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-1e2L7cFCvx9QDzq6NPP+0tABKb5z6nWHyddWTNKprEsjO9xNrAtPowuCGpjNXxkTdsMiZ4jc8YQ5SstZd4XK6g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-Kwu/l/8GcYibCWA9m9N5pRXMIKVSsL/YbgpLzYkqDhWTiqdRfnNJ/+nqIKRKQiFbHWsdlHEhzMwruJK+qcEruA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-tap04CsHYOl0nSAQJfPNIuBxqEPB2HnhQqwaOXLg1jnp2XfRo8Fa814dA4QC4zpvTWXCjAAaCY1W5LOORkEQuQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-hzJa/WgvtJpbBD9rgfy0qe+MjbxOXNUT0bfR1S6EQQzfTtBFA9xg5q8KSwRrQ2QfSS+TaP4j+4mVPQrfNc6UNg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-xbsaNSNzVSnaJACCUYr1HQMyY/Q/Q1LkePmHG3UvZPvGCYGNxrsZp9OmtA6ick8xH47ltRRbRrPCM1YXYcyC+A==}
@@ -3889,108 +3937,126 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-50jD0uUwLvur7Zz9LHz17kaAdTPjn5wN93hEgjvmYFRZwiR7ZJYovTd5ipyWJDAnXKvZ+wgc+/Ika6dwSF5OcA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-BO9+oPL8K9poZJBfYPsXNtYjPE5uM3qeehT3aFcW4LITOl+iSqhp0abzjR2nWBUNjIZeKXjAEWBZ64WjNoHd6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-f3VpLB1vQ0Eo6ecr/6cekLnvYMFF4YBFoVGkfkvPLq1bAkbAwHYQPZKoAmG6OJyTcxxoC+AvezGx/S1obNC0Mw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AmurZ26Pqx/RI9N1gzEOCklkKXl927yjfXWUUS0O7Puh8ARM/Ob8qfrD3qnWksScdw6cSrW5PSHE9DyLu7+PtA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-JJpqs8bRGITDOdbkNKnlojzBabbOHrqjSvDr0IVsZObE1lBcPjxItUEY9eWIDbxaJ3cGrXPWGfGkIxFijg/URg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-rSJcdjPxzA/by/6/rYs+v+bXU7UjvnbUWz8MJb6kh6+knqB1dCrtHg0uu7C/4haqJvqdkYHQ5IGn+tCH9GLW/g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==}
@@ -4127,66 +4193,79 @@ packages:
resolution: {integrity: sha512-DxH0P3wxm+Yzs/p3zrk9dw1rURu8p0Nv5+MRK/L7OtnLNg5rLZraSBFZ8iUXOd9f2BlhJyEpIZUH/emjq4UJ4g==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-T6ZvMNe84kAz6TBWHC7hGAoEtzP1LWYw/AqayGWEF6uISt3Abk/st06LqRD9THd7Xz3NxzurUpzAuEAUbZf+nw==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-q/4hzvQkDs8b4jIBab1pnLiiM0ayTZsN2amBFPDzuyZxjEd4wDwx0UJFYM3cOZzSf5Kw8fnWSprJzIBMkcR44Q==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-vvYWX3akdEAY6km+9wAqFDnk6pQsbJKVnj7xawcvs/+fdlYBGp+U+Qq/lLfpIxYIZvZLHMAKD9HLdacSx/r3dw==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-DePa5cqOxDP/Zp0VOXpeWaGew5iIv5DXp9NYbzkX5PFQyWVX9184WCTh3hvr/7lhXo8ZVlbFLkz8+o/q1dU6gA==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-LV8aWMB8UChglMCEzs7RkN0GsH29RJaLLqwm9fCIjlqwxQTiWAqNcc7wjBkH31hV0PU/yVxGYvrYsgfea2qw6g==}
cpu: [loong64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-QoNSnwQtaeNu5grdBbsL0tt1uyl5EnS8DA8Mr3nluMXbhdQNyhN+G4tBax7VCdxLKj8YJ0/4OO9Ho84jMnJtKA==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-/zZp5MKapIIApE8trN8qLGNSiRN9TUoaUZ1cmVu4XnVdd5LQLOXTtyi+vtfUbNnT3iyjzpPqYeKXmvJ+gJGYWw==}
cpu: [ppc64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-RbrzcD3aJ1k3UbtMRRBNwojdVVyXjuVAFTfn/xPa6EEl6GE9Sm/akPgFTb9aAC9pMKGJ6CtWxaGrqWcabH+ySg==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-ZF+onDsBso8PJf1XaG9lB+O9RnBpKGnY6OrzC4CSHrtC1jb6jWLTKK4bRqdoCXHd22gyr2hiYmEAm8Wns/BOCw==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-Atk0aSIk5Zx2Wuh9dgRQgLP0Koc8hOeYpbWryMXyk8G8/HmPkwPPkMqIIDhrXHHYqfUzSJA/I7IWSBv8xSmRBA==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-0uMOcf3eZ5K+K4cYHkdxShFMPlPXCOdfDFEFn9dNYAEEd2cVvmOfH7zFgRVoDgmtQ1m9k5q7qfrHzyMAubKYUA==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-mvFtE4A/t/7hRJ7X8Ozmu8FsIkAUat2nzl12pgU337BRmq87AQUJztwHz2Zv5/tjo9/C95E66CK03SI/ToEDJw==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-z9b9+aTxvt8n2rNltMPvyaUfB8NJ+CVyOrGK/MdIKHx7B+lXmZpm/XbRsU7Rpf3fRqJ2uS6mBJiJveCtq8LHDg==}
@@ -4421,48 +4500,56 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qTJHELX8jetjhRQHCLilkVLmybpzNQAtaI/gaoVoidn/ufbNDbAo8KlK2J+yPoc8wQxvDxCmh/5lr8nC1+lTbg==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-Z6sukiQsngnWO+l39X4pPbiWT81IC+PLKF+PHxIlyZbGNb9MODfYlXEVlFvej5BOZInWX01kVyzeLvHsXhfczQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-DRNdQRpSGzRGfARVuVkxvM8Q12nh19l4BF/G7zGA1oe+9wcC6saFBHTISrpIcKzhiXtSrlSrluCfvMuledoCTQ==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-Z0IADbDo8bh6I7h2IQMx601AdXBLfFpEdUotft86evd/8ZPflZe9COPO8Q1vw+pfLWIUo9zN/JGZvwuAJqduqg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -4935,24 +5022,28 @@ packages:
engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-vUY7hYycZW0qEevpl7ImzZJFnOEKRYCaCOX4TBW0vk6MJZ+zj/xW7e0LOggzJcz2wbYAgLDqp5h+b8wV9dguDA==}
engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-tFxpToEaykBGxMQHp8M/qmr1yruRRED+c9gA1h9kmplqot04OxuqzRCWu/IiIvMJ0v3JFdOP3gqkyjXLLJhxIA==}
engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-2scSS7wEbLO2758fqr1/bAULg7nLCFa5V8LO2b5w3g1CrTYdMTDt2WX1ghPesIi+70pYGydRbXo6iaaN43zfMg==}
engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-3+5FJYhi9SqBszjngI2LBmvoiqEwxJWyQ5UsOUtNz6/d+yDrDw+tOgHLl4OKIh5aVNZeIGXzxvP6h24kcEqIyg==}
@@ -5035,24 +5126,28 @@ packages:
engines: {node: '>= 12'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@yuuang/[email protected]':
resolution: {integrity: sha512-lejvOSqypPziQH5rzfkDlJ6e92qhWbDutE9ttOO6z5I2k83zoh9iZhZWhaXSU5VqgQpcshRkrbtXb9gy1ft5dA==}
engines: {node: '>= 12'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@yuuang/[email protected]':
resolution: {integrity: sha512-s8VCFazaJKmgY2hgMTpWk4TtBY/zy5ovbaGgwyY0FvBD0YvyhcET4IrMsDJpHhFVTPCYfKZ1dN45clD/YiFp6g==}
engines: {node: '>= 12'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@yuuang/[email protected]':
resolution: {integrity: sha512-Ahr5chfKZKWUik20bEZRug+be57LZ2yYrtolyjSRoo7A4ZniBUHBZUNWm6TD6i0CJayqyxWeVk/XiaABD8bY0w==}
engines: {node: '>= 12'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@yuuang/[email protected]':
resolution: {integrity: sha512-yhpLcj0qel5VNlpzxPZfNmi7+rEX8444QHjUP6WWLxdRfqPllROu/Cp3OpkBpw3BLdxfcDhWkjWMD5QsJN0Pvg==}
@@ -7416,72 +7511,84 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-WKyLWztD71rTnou4xAD5kQT+982wvca7E6QoLpoawZ1gP9JM0GJj4Tp5jMUh9B3AitHbRZ2/H3W5xQmdEOUlLg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-jmUQVx4331m6LIX+0wUhBbmMX7TCfjF5FoOH6SD1CttzuYlGNVpA7QnrmLxrsub43ClTINfGSYyHe2HWeLl5CQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-mSL4rqPi4iXq5YVqzSsJgMVFENoa4nGTT/GjO2c0Yl9OuQfPsIfncvLrEW6RbbB24WtZ3xP/2CCmI3tNkNV4oA==}
@@ -14269,19 +14376,19 @@ snapshots:
babel-plugin-react-compiler: 1.0.0
dependencies:
'@testing-library/dom': 10.4.1
'@testing-library/user-event': 14.6.1(@testing-library/[email protected])
transitivePeerDependencies:
- bufferutil
- msw
- utf-8-validate
- vite
dependencies:
'@blazediff/core': 1.9.1
@@ -14290,7 +14397,7 @@ snapshots:
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.0
transitivePeerDependencies:
- bufferutil
@@ -19894,8 +20001,8 @@ snapshots:
dependencies:
'@oxc-project/types': 0.136.0
'@oxlint/plugins': 1.68.0
'@vitest/expect': 4.1.9
'@vitest/pretty-format': 4.1.9
@@ -19908,7 +20015,7 @@ snapshots:
oxlint-tsgolint: 0.23.0
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 0.2.1
'@voidzero-dev/vite-plus-darwin-x64': 0.2.1
@@ -19954,7 +20061,7 @@ snapshots:
optionalDependencies:
dependencies:
'@vitest/expect': 4.1.9
@@ -19978,7 +20085,7 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 24.12.4
transitivePeerDependencies:
- msw
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 446139ed6..ef20a23d8 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -5,6 +5,20 @@ packages:
- packages/*
- scripts
+# Install both Windows and Linux native binaries so the WSL (Linux) backend
+# can load platform-gated optional deps (e.g. @yuuang/ffi-rs-linux-x64-gnu)
+# out of the same node_modules the Windows desktop uses.
+supportedArchitectures:
+ os:
+ - current
+ - linux
+ cpu:
+ - current
+ - x64
+ libc:
+ - current
+ - glibc
+
catalog:
"@clerk/backend": 3.8.3-snapshot.v20260622234151
"@clerk/clerk-js": 6.21.0-snapshot.v20260622234151
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index 99aea602e..c7e33f6fc 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -210,10 +210,20 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
cpu: ["x64"],
},
});
+ // Windows artifacts also bundle the same-architecture WSL (Linux, glibc) backend, so the
+ // staged install must fetch its native optional deps (e.g. ffi-rs) too.
+ assert.deepStrictEqual(createStageWorkspaceConfig("win", "x64"), {
+ supportedArchitectures: {
+ os: ["win32", "linux"],
+ cpu: ["x64"],
+ libc: ["glibc"],
+ },
+ });
assert.deepStrictEqual(createStageWorkspaceConfig("win", "arm64"), {
supportedArchitectures: {
- os: ["win32"],
+ os: ["win32", "linux"],
cpu: ["arm64"],
+ libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "universal"), {
@@ -400,6 +410,25 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
);
+ it.effect("keeps executable resource editing enabled for unsigned Windows builds", () =>
+ Effect.gen(function* () {
+ const config = yield* createBuildConfig(
+ "win",
+ "nsis",
+ "1.2.3",
+ false,
+ false,
+ undefined,
+ undefined,
+ );
+
+ const win = config.win as Record<string, unknown>;
+ assert.equal(win.icon, "icon.ico");
+ assert.equal(win.signAndEditExecutable, true);
+ assert.notProperty(win, "azureSignOptions");
+ }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
+ );
+
it("promotes target fff binaries to direct staged dependencies", () => {
assert.deepStrictEqual(resolveFffNativeDependencies("mac", "arm64", "0.9.4"), {
"@ff-labs/fff-bin-darwin-arm64": "0.9.4",
@@ -411,6 +440,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.deepStrictEqual(resolveFffNativeDependencies("win", "x64", "0.9.4"), {
"@ff-labs/fff-bin-win32-x64": "0.9.4",
});
+ assert.deepStrictEqual(resolveFffNativeDependencies("linux", "x64", "0.9.4"), {
+ "@ff-labs/fff-bin-linux-x64-gnu": "0.9.4",
+ "@ff-labs/fff-bin-linux-x64-musl": "0.9.4",
+ });
assert.deepStrictEqual(resolveFffNativeDependencies("linux", "arm64", "0.9.4"), {
"@ff-labs/fff-bin-linux-arm64-gnu": "0.9.4",
"@ff-labs/fff-bin-linux-arm64-musl": "0.9.4",
@@ -496,6 +529,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
verbose: Option.none(),
mockUpdates: Option.none(),
mockUpdateServerPort: Option.none(),
+ wslPrebuild: Option.none(),
}).pipe(
Effect.provide(
Layer.mergeAll(
@@ -533,6 +567,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
verbose: Option.some(false),
mockUpdates: Option.some(false),
mockUpdateServerPort: Option.none(),
+ wslPrebuild: Option.none(),
}).pipe(
Effect.provide(
ConfigProvider.layer(
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index 5a6cbfb8b..58153efe8 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -47,6 +47,7 @@ const StageWorkspaceConfig = Schema.Struct({
supportedArchitectures: Schema.Struct({
os: Schema.Array(Schema.String),
cpu: Schema.Array(Schema.String),
+ libc: Schema.optional(Schema.Array(Schema.String)),
}),
});
@@ -55,6 +56,9 @@ const RepoRoot = Effect.service(Path.Path).pipe(
);
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
+const decodeNodePtyManifest = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(Schema.Struct({ version: Schema.String })),
+);
const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
@@ -107,6 +111,7 @@ interface BuildCliInput {
readonly verbose: Option.Option<boolean>;
readonly mockUpdates: Option.Option<boolean>;
readonly mockUpdateServerPort: Option.Option<number>;
+ readonly wslPrebuild: Option.Option<string>;
}
function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
@@ -360,6 +365,29 @@ export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClas
}
}
+export class WslNodePtyPrebuildMissingError extends Schema.TaggedErrorClass<WslNodePtyPrebuildMissingError>()(
+ "WslNodePtyPrebuildMissingError",
+ {
+ prebuildPath: Schema.String,
+ },
+) {
+ override get message(): string {
+ return `WSL node-pty prebuild not found at ${this.prebuildPath}.`;
+ }
+}
+
+export class WslNodePtyManifestReadError extends Schema.TaggedErrorClass<WslNodePtyManifestReadError>()(
+ "WslNodePtyManifestReadError",
+ {
+ manifestPath: Schema.String,
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ return `Could not read node-pty version from ${this.manifestPath}.`;
+ }
+}
+
export class LinuxIconResizeError extends Schema.TaggedErrorClass<LinuxIconResizeError>()(
"LinuxIconResizeError",
{
@@ -517,6 +545,7 @@ interface ResolvedBuildOptions {
readonly verbose: boolean;
readonly mockUpdates: boolean;
readonly mockUpdateServerPort: number | undefined;
+ readonly wslPrebuild: string | undefined;
}
interface StagePackageJson {
@@ -851,10 +880,26 @@ export function createStageWorkspaceConfig(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): typeof StageWorkspaceConfig.Type {
+ const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
+ const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
+ // Windows artifacts also bundle the same-architecture WSL Linux backend, which loads
+ // Linux-native optional deps at runtime (e.g. @yuuang/ffi-rs-linux-x64-gnu).
+ // Pull the Linux (glibc) variants in addition to the host platform's so
+ // they ship in the asar; without them the WSL backend crash-loops on require
+ // ("Cannot find module '@yuuang/ffi-rs-linux-x64-gnu'").
+ if (platform === "win") {
+ return {
+ supportedArchitectures: {
+ os: Array.from(new Set([hostOs, "linux"])),
+ cpu: hostCpu,
+ libc: ["glibc"],
+ },
+ };
+ }
return {
supportedArchitectures: {
- os: [platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux"],
- cpu: arch === "universal" ? ["arm64", "x64"] : [arch],
+ os: [hostOs],
+ cpu: hostCpu,
},
};
}
@@ -905,6 +950,11 @@ const BuildEnvConfig = Config.all({
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
mockUpdates: Config.boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)),
mockUpdateServerPort: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option),
+ // Path to a prebuilt Linux node-pty binary (pty.node) for the target arch,
+ // produced by the Linux CI job and handed to the Windows packaging job. Placed
+ // into the staged node-pty so the WSL backend ships a ready binary and never
+ // compiles on the user's machine.
+ wslPrebuild: Config.string("T3CODE_DESKTOP_WSL_PREBUILD").pipe(Config.option),
});
const MockUpdateServerPortSchema = Schema.NumberFromString.check(
@@ -988,6 +1038,9 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
),
));
+ const wslPrebuild =
+ Option.getOrUndefined(input.wslPrebuild) ?? Option.getOrUndefined(env.wslPrebuild);
+
return {
platform,
target,
@@ -1000,6 +1053,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
verbose,
mockUpdates,
mockUpdateServerPort,
+ wslPrebuild,
} satisfies ResolvedBuildOptions;
});
@@ -1300,10 +1354,23 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
appId: DESKTOP_APP_ID,
productName: resolveDesktopProductName(version),
artifactName: "T3-Code-${version}-${arch}.${ext}",
- asarUnpack: [...DESKTOP_ASAR_UNPACK],
directories: {
buildResources: "apps/desktop/resources",
},
+ // The Windows primary backend runs the server bundle through
+ // ELECTRON_RUN_AS_NODE (asar-aware), so it reads bin.mjs straight out of
+ // app.asar. The WSL backend instead launches plain `wsl.exe -- node`, which
+ // cannot read inside an asar archive, so everything it loads must be on the
+ // real filesystem. The server bundle externalizes its runtime dependencies
+ // (effect, @effect/*, node-pty, ...) to node_modules rather than inlining
+ // them, so unpacking just the bundle + node-pty isn't enough — the Linux Node
+ // fails with ERR_MODULE_NOT_FOUND (e.g. "Cannot find package 'effect'") before
+ // it even reaches node-pty. Unpack the server bundle AND the whole
+ // node_modules tree so every import resolves (this also covers the fff native
+ // binaries in DESKTOP_ASAR_UNPACK). The Windows primary keeps reading the same
+ // files through the asar (transparently redirected to the unpacked copy), so
+ // there's no duplication.
+ asarUnpack: [...DESKTOP_ASAR_UNPACK, "apps/server/dist/**", "**/node_modules/**"],
};
const updateChannel = resolveDesktopUpdateChannel(version);
const publishConfig = yield* resolveGitHubPublishConfig(updateChannel);
@@ -1357,11 +1424,13 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* (
const winConfig: Record<string, unknown> = {
target: [target],
icon: "icon.ico",
+ // Resource editing applies the product metadata and icon independently
+ // of code signing. Disabling it for local unsigned builds leaves the
+ // packaged executable with Electron's stock icon.
+ signAndEditExecutable: true,
};
if (signed) {
winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
- } else {
- winConfig.signAndEditExecutable = false;
}
buildConfig.win = winConfig;
}
@@ -1390,6 +1459,76 @@ const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(f
}
});
+// Stage the prebuilt Linux node-pty binary into the packaged app so the WSL
+// backend never compiles on the user's machine. node-pty publishes no Linux
+// prebuilt and the WSL Linux Node can't load the Windows/Electron binary, so the
+// Linux CI job builds pty.node and hands it here. We drop it into the staged
+// node-pty's prebuilds/linux-<arch>/ with a t3code marker the WSL preflight
+// checks (arch + node-pty version; the binary is N-API, hence ABI-stable across
+// Node versions). A missing prebuild is a warning, not an error, so local and
+// non-Windows builds still succeed — they just won't ship a working WSL backend.
+const stageWslNodePtyPrebuild = Effect.fn("stageWslNodePtyPrebuild")(function* (input: {
+ readonly stageAppDir: string;
+ readonly arch: typeof BuildArch.Type;
+ readonly prebuildPath: string | undefined;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ if (input.prebuildPath === undefined) {
+ yield* Effect.logWarning(
+ "[desktop-artifact] No WSL node-pty prebuild provided (--wsl-prebuild / T3CODE_DESKTOP_WSL_PREBUILD); the packaged WSL backend will not start until a Linux pty.node is bundled.",
+ );
+ return;
+ }
+
+ // WSL runs the same CPU arch as the Windows host; universal is mac-only.
+ const linuxArch = input.arch === "x64" ? "x64" : input.arch === "arm64" ? "arm64" : undefined;
+ if (linuxArch === undefined) {
+ yield* Effect.logWarning(
+ `[desktop-artifact] No WSL node-pty prebuild mapping for arch "${input.arch}"; skipping WSL backend bundling.`,
+ );
+ return;
+ }
+
+ const prebuildExists = yield* fs
+ .exists(input.prebuildPath)
+ .pipe(Effect.orElseSucceed(() => false));
+ if (!prebuildExists) {
+ return yield* new WslNodePtyPrebuildMissingError({
+ prebuildPath: input.prebuildPath,
+ });
+ }
+
+ // Resolve through the (pnpm) symlink so we write into the stage's own node-pty
+ // copy, never a shared content-addressable store.
+ const nodePtyLink = path.join(input.stageAppDir, "node_modules", "node-pty");
+ const nodePtyDir = yield* fs.realPath(nodePtyLink).pipe(Effect.orElseSucceed(() => nodePtyLink));
+
+ const manifestPath = path.join(nodePtyDir, "package.json");
+ const pkgRaw = yield* fs.readFileString(manifestPath);
+ const manifest = yield* decodeNodePtyManifest(pkgRaw).pipe(
+ Effect.mapError(
+ (cause) =>
+ new WslNodePtyManifestReadError({
+ manifestPath,
+ cause,
+ }),
+ ),
+ );
+ const nodePtyVersion = manifest.version;
+
+ const prebuildDir = path.join(nodePtyDir, "prebuilds", `linux-${linuxArch}`);
+ yield* fs.makeDirectory(prebuildDir, { recursive: true });
+ yield* fs.copyFile(input.prebuildPath, path.join(prebuildDir, "pty.node"));
+ const markerJson = yield* encodeJsonString({ arch: linuxArch, nodePtyVersion });
+ yield* fs.writeFileString(path.join(prebuildDir, "t3code-wsl-node-pty.json"), `${markerJson}\n`);
+
+ yield* Effect.log(
+ `[desktop-artifact] Staged WSL node-pty prebuild (linux-${linuxArch}, node-pty ${nodePtyVersion}).`,
+ );
+});
+
const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options: ResolvedBuildOptions,
) {
@@ -1558,6 +1697,17 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options.arch,
serverPackageJson.dependencies["@ff-labs/fff-node"],
),
+ // Windows artifacts also bundle the same-architecture WSL Linux backend, which loads the
+ // fff native binary through ffi-rs. The platform fff binary above is the
+ // host's (win32), so promote the matching Linux fff binaries too; without
+ // them file-finding in WSL fails to load its Linux native package.
+ ...(options.platform === "win"
+ ? resolveFffNativeDependencies(
+ "linux",
+ options.arch,
+ serverPackageJson.dependencies["@ff-labs/fff-node"],
+ )
+ : {}),
};
const stagePnpmConfig = createStagePnpmConfig(workspacePatchedDependencies, stageDependencies);
const stagePackageJson: StagePackageJson = {
@@ -1616,6 +1766,16 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
);
yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);
+ // WSL is Windows-only, so only the Windows artifact carries the Linux backend
+ // binary; other platforms ignore the prebuild input.
+ if (options.platform === "win") {
+ yield* stageWslNodePtyPrebuild({
+ stageAppDir,
+ arch: options.arch,
+ prebuildPath: options.wslPrebuild,
+ });
+ }
+
// electron-builder treats several set-but-empty variables (e.g. CSC_LINK="")
// as enabled, so copy the host env and scrub empty values instead of relying
// on `extendEnv` merging.
@@ -1769,6 +1929,12 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
Flag.withDescription("Mock update server port (env: T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT)."),
Flag.optional,
),
+ wslPrebuild: Flag.string("wsl-prebuild").pipe(
+ Flag.withDescription(
+ "Path to a prebuilt Linux node-pty (pty.node) for the target arch, staged for the WSL backend (env: T3CODE_DESKTOP_WSL_PREBUILD).",
+ ),
+ Flag.optional,
+ ),
}).pipe(
Command.withDescription("Build a desktop artifact for T3 Code."),
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),