diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 50b1f5d2aa..b3347dab15 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -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) => { 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); diff --git a/apps/web/src/environments/local/index.ts b/apps/web/src/environments/local/index.ts new file mode 100644 index 0000000000..90131727ac --- /dev/null +++ b/apps/web/src/environments/local/index.ts @@ -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; +} + +const pendingByInstanceId = new Map(); +let pendingReconcileRun: Promise | 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 { + 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 { + 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 { + if (pendingReconcileRun) { + return pendingReconcileRun; + } + const next = reconcileOnce().finally(() => { + if (pendingReconcileRun === next) { + pendingReconcileRun = null; + } + }); + pendingReconcileRun = next; + return next; +} diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.ts index 7ece1ccb0c..f782afca8d 100644 --- a/apps/web/src/environments/runtime/catalog.ts +++ b/apps/web/src/environments/runtime/catalog.ts @@ -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; } +// 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, +): ReadonlyArray { + return valuesOfSavedEnvironmentRegistry(byId).filter((record) => !record.desktopLocal); +} + function persistSavedEnvironmentRegistryState( byId: Record, ): 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), + ), ); } diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 21a4561beb..9ae627641e 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -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 { + 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();