feat(web): register WSL backend as a desktop-local environment
Bring up the second local backend in the renderer so its env id
appears in the saved-environment registry alongside any remote saved
envs the user paired. The sidebar, env switcher, CommandPalette, and
project-routing UI all consume that registry, so they pick up the
WSL backend without per-surface plumbing.
How the data flows:
- On boot, runtime/service.ts calls
reconcileLocalSecondaryEnvironments() (and again after a 5s delay
to catch a slow WSL cold boot).
- The reconciler reads getLocalEnvironmentBootstraps() from the
desktop bridge. Primary stays owned by the primary/ runtime;
everything else with a desktopLocal instance id is routed here.
- For each new instance, the reconciler POSTs the shared bootstrap
token to /api/auth/bootstrap/bearer on the WSL backend's URL,
fetches the descriptor, builds a SavedEnvironmentRecord carrying
a desktopLocal marker, upserts it into the registry, writes the
bearer to the secret store, and triggers
ensureSavedEnvironmentConnection.
- Records carrying desktopLocal are filtered out of the saved-env
persistence path, so toggling WSL off or switching distros
doesn't leave stale entries on disk.
After-toggle wiring: ConnectionsSettings.applyWslSettingChange fires
reconcile after each setWslBackendEnabled/setWslDistro call, then
again after 1.5s for the same slow-boot reason.
Why bearer-token auth instead of cookies:
- The WSL backend runs on its own loopback port. Cookies are
per-origin, and the renderer's origin (the primary's URL in
packaged builds, the vite dev server URL in dev) doesn't match
that port, so a cookie set on the WSL origin wouldn't ride along.
- Bearer auth uses the Authorization header which the backend's
CORS layer already permits, and WS connections use the
?wsToken=... pattern that saved environments rely on. No CORS
surgery on the backend side.
- Auth state is per-env (a separate bearer per backend); the global
primary auth gate in primary/auth.ts stays untouched, so the
normal single-backend flow for non-WSL users is unaffected.
The reconciler is idempotent, dedupes concurrent calls per instance
id, and never throws — errors get logged and the caller can retry by
calling again. If the WSL backend restarts and its old bearer goes
stale, the user toggling settings re-bootstraps a fresh one.
Plumbing changes:
- ensureSavedEnvironmentConnection exported from runtime/service
so the reconciler can reuse the saved-env connection lifecycle
without duplicating it.
- New removeSavedEnvironmentByInstance variant: same teardown as
removeSavedEnvironment but skips the secret-store delete, since
desktopLocal entries may not own a persisted secret to remove.
This commit is contained in:
1 parent
60de6afede
commit
1c7e78733f
4 files changed
+272
-4
No files matched your search
@@ -84,6 +84,7 @@ import {
|
||||
type ServerClientSessionRecord,
|
||||
type ServerPairingLinkRecord,
|
||||
} from "~/environments/primary";
|
||||
import { reconcileLocalSecondaryEnvironments } from "~/environments/local";
|
||||
import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
import {
|
||||
type SavedEnvironmentRecord,
|
||||
@@ -2354,7 +2355,10 @@ 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.
|
||||
// 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;
|
||||
@@ -2362,6 +2366,14 @@ export function ConnectionsSettings() {
|
||||
setDesktopWslError(null);
|
||||
try {
|
||||
setDesktopWslState(await apply());
|
||||
// The desktop orchestrator may take a moment to register the new
|
||||
// WSL instance with bootstrap info — fire the renderer reconciler
|
||||
// now to remove stale entries (toggle-off, distro change), then
|
||||
// again after a short delay to pick up a freshly-registered one.
|
||||
void reconcileLocalSecondaryEnvironments();
|
||||
setTimeout(() => {
|
||||
void reconcileLocalSecondaryEnvironments();
|
||||
}, 1_500);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to update WSL backend.";
|
||||
setDesktopWslError(message);
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// Reconciles desktop-managed secondary local environments (today: the
|
||||
// WSL backend when the user enables it) with what's currently in the
|
||||
// saved-environment runtime registry.
|
||||
//
|
||||
// Why this lives alongside the saved-env machinery rather than inside
|
||||
// `apps/web/src/environments/primary/`:
|
||||
// - It needs the same per-env bearer-token transport as remote
|
||||
// saved envs. The primary path is cookie-based and same-origin;
|
||||
// a WSL backend at a different localhost port is cross-origin
|
||||
// for cookies but fine for `Authorization: Bearer ...`.
|
||||
// - Reusing `ensureSavedEnvironmentConnection` plus the existing
|
||||
// saved-env stores means the env switcher, sidebar lists, project
|
||||
// env-id routing, and connection lifecycle pick these up without
|
||||
// a parallel set of UI surfaces.
|
||||
// - The persistence layer for saved envs filters records carrying
|
||||
// `desktopLocal`, so toggling the WSL backend off or switching
|
||||
// distros doesn't leave stale entries in the user's settings file
|
||||
// when the desktop bootstrap stops reporting them.
|
||||
//
|
||||
// Reconciliation is driven by `getLocalEnvironmentBootstraps()` from
|
||||
// the desktop bridge. The primary entry (id === "primary") stays
|
||||
// owned by the primary/ runtime; everything else flows through here.
|
||||
// On each call, the reconciler:
|
||||
// 1. Drops registry entries whose desktopLocal.instanceId no longer
|
||||
// appears in the bootstraps list.
|
||||
// 2. Bootstraps + connects new entries that do appear.
|
||||
// It's safe to call multiple times — pending work is deduped by
|
||||
// `pendingByInstanceId` and entries already wired up are skipped.
|
||||
|
||||
import {
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { bootstrapRemoteBearerSession, fetchRemoteEnvironmentDescriptor } from "../remote/api";
|
||||
import {
|
||||
ensureSavedEnvironmentConnection,
|
||||
removeSavedEnvironmentByInstance,
|
||||
} from "../runtime/service";
|
||||
import {
|
||||
getSavedEnvironmentRecord,
|
||||
useSavedEnvironmentRegistryStore,
|
||||
writeSavedEnvironmentBearerToken,
|
||||
type SavedEnvironmentRecord,
|
||||
} from "../runtime/catalog";
|
||||
|
||||
interface PendingRegistration {
|
||||
readonly promise: Promise<SavedEnvironmentRecord | null>;
|
||||
}
|
||||
|
||||
const pendingByInstanceId = new Map<string, PendingRegistration>();
|
||||
let pendingReconcileRun: Promise<void> | null = null;
|
||||
|
||||
function readBootstraps(): readonly DesktopEnvironmentBootstrap[] {
|
||||
return window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
|
||||
}
|
||||
|
||||
function findRecordByInstanceId(instanceId: string): SavedEnvironmentRecord | null {
|
||||
const byId = useSavedEnvironmentRegistryStore.getState().byId;
|
||||
for (const record of Object.values(byId)) {
|
||||
if (record.desktopLocal?.instanceId === instanceId) {
|
||||
return record;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isRegisteredForBootstrap(
|
||||
bootstrap: DesktopEnvironmentBootstrap,
|
||||
record: SavedEnvironmentRecord,
|
||||
): boolean {
|
||||
// The httpBaseUrl is the load-bearing identity field: if the desktop
|
||||
// restarts the WSL backend on a new port (e.g. after a port collision)
|
||||
// we want to re-register so the renderer points at the new URL.
|
||||
return (
|
||||
record.desktopLocal?.instanceId === bootstrap.id &&
|
||||
record.httpBaseUrl === bootstrap.httpBaseUrl &&
|
||||
record.wsBaseUrl === bootstrap.wsBaseUrl
|
||||
);
|
||||
}
|
||||
|
||||
async function registerSecondaryLocalEnvironment(
|
||||
bootstrap: DesktopEnvironmentBootstrap,
|
||||
): Promise<SavedEnvironmentRecord | null> {
|
||||
if (!bootstrap.httpBaseUrl || !bootstrap.wsBaseUrl) {
|
||||
return null;
|
||||
}
|
||||
const credential = bootstrap.bootstrapToken;
|
||||
if (!credential) {
|
||||
// No way to authenticate without the shared bootstrap token. The
|
||||
// desktop side fills this in for every instance with a config, so
|
||||
// a missing token means we're racing the WSL backend's first
|
||||
// start; the next reconcile pass will pick it up.
|
||||
return null;
|
||||
}
|
||||
|
||||
const descriptor = await fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: bootstrap.httpBaseUrl,
|
||||
});
|
||||
const environmentId = descriptor.environmentId;
|
||||
|
||||
// Drop any stale record pointing at a different bootstrap (URL
|
||||
// change, instance-id rename) before writing the new one. We can't
|
||||
// just upsert because the old record may have used a different
|
||||
// environmentId.
|
||||
const stale = findRecordByInstanceId(bootstrap.id);
|
||||
if (stale && stale.environmentId !== environmentId) {
|
||||
await removeSavedEnvironmentByInstance(stale.environmentId);
|
||||
}
|
||||
|
||||
const bearerSession = await bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: bootstrap.httpBaseUrl,
|
||||
credential,
|
||||
});
|
||||
|
||||
const existing = getSavedEnvironmentRecord(environmentId);
|
||||
const record: SavedEnvironmentRecord = {
|
||||
environmentId,
|
||||
label: bootstrap.label,
|
||||
wsBaseUrl: bootstrap.wsBaseUrl,
|
||||
httpBaseUrl: bootstrap.httpBaseUrl,
|
||||
createdAt: existing?.createdAt ?? new Date().toISOString(),
|
||||
lastConnectedAt: new Date().toISOString(),
|
||||
desktopLocal: { instanceId: bootstrap.id },
|
||||
};
|
||||
|
||||
useSavedEnvironmentRegistryStore.getState().upsert(record);
|
||||
await writeSavedEnvironmentBearerToken(environmentId, bearerSession.sessionToken);
|
||||
await ensureSavedEnvironmentConnection(record, {
|
||||
bearerToken: bearerSession.sessionToken,
|
||||
role: bearerSession.role,
|
||||
});
|
||||
return record;
|
||||
}
|
||||
|
||||
async function reconcileOnce(): Promise<void> {
|
||||
const bootstraps = readBootstraps();
|
||||
const secondaries = bootstraps.filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
|
||||
const desiredInstanceIds = new Set(secondaries.map((entry) => entry.id));
|
||||
|
||||
// Drop registry entries whose backend instance is gone (user toggled
|
||||
// the WSL backend off, switched distros, or the orchestrator
|
||||
// unregistered for any other reason).
|
||||
const registry = useSavedEnvironmentRegistryStore.getState().byId;
|
||||
const stale: EnvironmentId[] = [];
|
||||
for (const record of Object.values(registry)) {
|
||||
const instanceId = record.desktopLocal?.instanceId;
|
||||
if (instanceId !== undefined && !desiredInstanceIds.has(instanceId)) {
|
||||
stale.push(record.environmentId);
|
||||
}
|
||||
}
|
||||
for (const environmentId of stale) {
|
||||
await removeSavedEnvironmentByInstance(environmentId);
|
||||
}
|
||||
|
||||
// Bring up entries we don't have yet. Concurrent reconcile calls
|
||||
// share a pending promise per instance id so we don't double-register.
|
||||
await Promise.all(
|
||||
secondaries.map(async (bootstrap) => {
|
||||
const existing = findRecordByInstanceId(bootstrap.id);
|
||||
if (existing && isRegisteredForBootstrap(bootstrap, existing)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = pendingByInstanceId.get(bootstrap.id);
|
||||
if (pending) {
|
||||
await pending.promise.catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const promise = registerSecondaryLocalEnvironment(bootstrap)
|
||||
.catch((error) => {
|
||||
console.error("[LOCAL_SECONDARY] register failed", bootstrap.id, error);
|
||||
return null;
|
||||
})
|
||||
.finally(() => {
|
||||
pendingByInstanceId.delete(bootstrap.id);
|
||||
});
|
||||
pendingByInstanceId.set(bootstrap.id, { promise });
|
||||
await promise;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Public entry point. Idempotent and never throws — internal failures
|
||||
// get logged and the caller can retry by calling again. Multiple
|
||||
// concurrent calls share a single underlying reconcile pass.
|
||||
export function reconcileLocalSecondaryEnvironments(): Promise<void> {
|
||||
if (pendingReconcileRun) {
|
||||
return pendingReconcileRun;
|
||||
}
|
||||
const next = reconcileOnce().finally(() => {
|
||||
if (pendingReconcileRun === next) {
|
||||
pendingReconcileRun = null;
|
||||
}
|
||||
});
|
||||
pendingReconcileRun = next;
|
||||
return next;
|
||||
}
|
||||
@@ -11,6 +11,20 @@ import { create } from "zustand";
|
||||
import { ensureLocalApi } from "../../localApi";
|
||||
import { getPrimaryKnownEnvironment } from "../primary";
|
||||
|
||||
// Marker for a SavedEnvironmentRecord that came from the desktop's
|
||||
// local backend pool (currently just the WSL backend when the user
|
||||
// enables it). It mirrors the desktopSsh pattern: the saved-env
|
||||
// runtime treats these like any other entry for connection lifecycle
|
||||
// and UI display, but the persistence layer skips them — they're
|
||||
// rederived on each renderer boot from the bootstrap IPC instead of
|
||||
// living on disk.
|
||||
export interface DesktopLocalEnvironmentMarker {
|
||||
// Backend instance id from the desktop pool (e.g. "wsl:default",
|
||||
// "wsl:ubuntu"). The reconciler keys off this to add/remove records
|
||||
// when the user toggles the WSL backend or switches distros.
|
||||
readonly instanceId: string;
|
||||
}
|
||||
|
||||
export interface SavedEnvironmentRecord {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
@@ -19,6 +33,7 @@ export interface SavedEnvironmentRecord {
|
||||
readonly createdAt: string;
|
||||
readonly lastConnectedAt: string | null;
|
||||
readonly desktopSsh?: PersistedSavedEnvironmentRecord["desktopSsh"];
|
||||
readonly desktopLocal?: DesktopLocalEnvironmentMarker;
|
||||
}
|
||||
|
||||
interface SavedEnvironmentRegistryState {
|
||||
@@ -56,13 +71,22 @@ function valuesOfSavedEnvironmentRegistry(
|
||||
return Object.values(byId) as ReadonlyArray<SavedEnvironmentRecord>;
|
||||
}
|
||||
|
||||
// Records with the desktopLocal marker are derived from the bootstrap
|
||||
// IPC at boot, so persisting them would shadow whatever the desktop
|
||||
// currently reports. Filter them out so they stay in-memory only.
|
||||
function persistableSavedEnvironmentRecords(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): ReadonlyArray<SavedEnvironmentRecord> {
|
||||
return valuesOfSavedEnvironmentRegistry(byId).filter((record) => !record.desktopLocal);
|
||||
}
|
||||
|
||||
function persistSavedEnvironmentRegistryState(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): void {
|
||||
try {
|
||||
void ensureLocalApi()
|
||||
.persistence.setSavedEnvironmentRegistry(
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
|
||||
persistableSavedEnvironmentRecords(byId).map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
),
|
||||
)
|
||||
@@ -240,7 +264,9 @@ export async function persistSavedEnvironmentRecord(record: SavedEnvironmentReco
|
||||
};
|
||||
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((entry) => toPersistedSavedEnvironmentRecord(entry)),
|
||||
persistableSavedEnvironmentRecords(byId).map((entry) =>
|
||||
toPersistedSavedEnvironmentRecord(entry),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
|
||||
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
|
||||
import { projectQueryKeys } from "~/lib/projectReactQuery";
|
||||
import { providerQueryKeys } from "~/lib/providerReactQuery";
|
||||
import { reconcileLocalSecondaryEnvironments } from "../local";
|
||||
import { getPrimaryKnownEnvironment } from "../primary";
|
||||
import {
|
||||
bootstrapRemoteBearerSession,
|
||||
@@ -1293,7 +1294,7 @@ function maybeCreatePrimaryEnvironmentConnection(): EnvironmentConnection | null
|
||||
return getPrimaryKnownEnvironment()?.environmentId ? createPrimaryEnvironmentConnection() : null;
|
||||
}
|
||||
|
||||
async function ensureSavedEnvironmentConnection(
|
||||
export async function ensureSavedEnvironmentConnection(
|
||||
record: SavedEnvironmentRecord,
|
||||
options?: {
|
||||
readonly client?: WsRpcClient;
|
||||
@@ -1639,6 +1640,21 @@ export async function removeSavedEnvironment(environmentId: EnvironmentId): Prom
|
||||
await removeSavedEnvironmentBearerToken(environmentId);
|
||||
}
|
||||
|
||||
// Variant for desktop-managed secondary local envs. Same teardown
|
||||
// shape as removeSavedEnvironment but skips the bearer-token-secret
|
||||
// delete: the local-secondary reconciler manages its own bearer
|
||||
// tokens and the secret store may not have a key for a transient,
|
||||
// non-persisted record.
|
||||
export async function removeSavedEnvironmentByInstance(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<void> {
|
||||
await disconnectSavedEnvironment(environmentId);
|
||||
disposeThreadDetailSubscriptionsForEnvironment(environmentId);
|
||||
useSavedEnvironmentRegistryStore.getState().remove(environmentId);
|
||||
useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
|
||||
useStore.getState().removeEnvironmentState(environmentId);
|
||||
}
|
||||
|
||||
export async function addSavedEnvironment(input: {
|
||||
readonly label: string;
|
||||
readonly pairingUrl?: string;
|
||||
@@ -1774,6 +1790,19 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
|
||||
maybeCreatePrimaryEnvironmentConnection();
|
||||
|
||||
// Bring up the desktop-managed secondary local environments (today
|
||||
// just the WSL backend, if enabled). The reconcile call is best-effort
|
||||
// and self-retrying: if the WSL backend is still mid-boot when this
|
||||
// fires, the next ConnectionsSettings interaction or a manual
|
||||
// re-toggle will pick it up via reconcileLocalSecondaryEnvironments.
|
||||
void reconcileLocalSecondaryEnvironments();
|
||||
// One delayed retry to catch the common case where the WSL backend
|
||||
// is mid-cold-boot at app start. Bounded to a single extra attempt
|
||||
// so we don't poll forever for users who never enable WSL.
|
||||
const localSecondaryRetryHandle = setTimeout(() => {
|
||||
void reconcileLocalSecondaryEnvironments();
|
||||
}, 5_000);
|
||||
|
||||
const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => {
|
||||
if (!hasSavedEnvironmentRegistryHydrated()) {
|
||||
return;
|
||||
@@ -1792,6 +1821,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
queryInvalidationThrottler,
|
||||
refCount: 1,
|
||||
stop: () => {
|
||||
clearTimeout(localSecondaryRetryHandle);
|
||||
unsubscribeSavedEnvironments();
|
||||
unsubscribeBrowserResumeReconnects();
|
||||
queryInvalidationThrottler.cancel();
|
||||
|
||||
Reference in new issue
Block a user