Upstream #2964 migrated the workspace test imports from "vitest" to
"vite-plus/test" and dropped vitest as a resolvable module. Our WSL
test files predate that migration and still imported from "vitest",
which broke typecheck (TS2307) after merging main. Repoint them.
Resolve conflicts from the upstream bun->pnpm+Vite migration (#2899),
relay tunnels (#2837), and proof-key bootstrap auth:
- apps/web/src/environments/primary/auth.ts: upstream switched the
contracts import to `import type` and added ServerAuthSessionMethod;
keep that and re-add PRIMARY_LOCAL_ENVIRONMENT_ID as a value import
(still used at runtime to find the primary bootstrap entry).
- apps/web/src/environments/runtime/catalog.ts: keep both new optional
fields on SavedEnvironmentRecord (our desktopLocal marker and
upstream's relayManaged).
- apps/server/src/auth/PairingGrantStore.test.ts: keep upstream's new
proof-key thumbprint test and our reusable-bootstrap-grant test
(the desktop bootstrap credential is reusable: remainingUses
unbounded, 24h TTL).
- apps/web/src/components/settings/ConnectionsSettings.tsx: render both
the WSL row and upstream's CloudLinkRow in the connected section.
Two WSL-mode edge cases from review:
Medium (cursor) — WSL-only distro change ignored: in wsl-only mode the
pool's primary IS the WSL backend and its distro is captured when that
backend starts. setWslDistro only persisted + reconciled, but reconcile
deliberately skips the secondary in wsl-only mode, so nothing restarted
the primary — the old distro kept serving while labels/IPC showed the new
one. setWslDistro now relaunches (like the wsl-only toggle) when wslOnly &&
the distro actually changed; dual-backend mode still swaps the secondary
via reconcile. The renderer routes wsl-only distro changes through the
existing "Switch WSL distro?" confirm so the relaunch isn't a surprise.
High (macroscope) — recovery button non-functional: the "Switch to
Windows" recovery row in renderWslRow is shown when `enabled || wslOnly`,
but handleSelectWslMode's WSL-off path returned early on `!enabled` alone,
so when WSL went unavailable with wsl-only persisted (enabled false,
wslOnly true) the button did nothing. The guard is now `!enabled &&
!wslOnly`, matching the row's visibility; the disable flow then clears
wslOnly and relaunches onto Windows.
Companion to the backend fall-back-to-Windows fix. The Connections "WSL
backend" row was hidden whenever desktopWslState.available was false. If
the user still had the WSL backend persisted (enabled, possibly wsl-only)
but WSL went away (uninstalled, distro removed), the desktop falls back to
the Windows backend yet the UI offered no way to clear the WSL preference -
stranding the user until WSL worked again or settings were hand-edited.
renderWslRow now shows a recovery row in that state (WSL unavailable but
still persisted) with a "Switch to Windows" action that routes through the
existing disable flow (clears wslBackendEnabled and, if set, wslOnly, then
relaunches onto Windows). When WSL is unavailable and unused there's
nothing to recover, so the section stays hidden as before.
Resolves conflicts from upstream #2013 (mobile WIP), which moved several
web modules into @t3tools/client-runtime and deleted their old paths:
- ConnectionsSettings.tsx: drop the now-dead `~/rpc/wsRpcClient` type
import; WsRpcClient is now provided by @t3tools/client-runtime. Keep our
`~/environments/local` imports.
- runtime/service.ts: drop unused `projectReactQuery`/`providerReactQuery`
imports (source files removed upstream). Keep reconcileLocalSecondaryEnvironments.
- environments/local/index.ts (clean-merge breakage): `../remote/api` was
removed; repoint bootstrapRemoteBearerSession / fetchRemoteEnvironmentDescriptor
/ fetchRemoteSessionState to @t3tools/client-runtime. Those are now Effect.fn,
so wrap the three call sites in remoteHttpRuntime.runPromise(...), matching
the pattern upstream uses in runtime/service.ts.
Full typecheck green across all 14 packages; web tests 62/62.
Four review comments addressed in one pass:
- Park the local-secondary auto-retry loop in wsl-only mode too. WSL
is the primary there and the desktop never registers a wsl:<distro>
secondary, so the loop would otherwise poll forever for something
that can't appear. Initial probe and the post-toggle latch both
treat enabled+wslOnly as "no secondaries".
- Key the backend output log cache by the resolved file path, not the
raw instance id. Two ids that sanitize to the same filename (e.g.
`wsl:default` and `wsl_default`) would otherwise produce two
RotatingLogFileWriters racing on the same file.
- Fork registered instance scopes off the pool's layer scope instead
of leaving them as orphan `Scope.make` handles. On app shutdown the
pool's scope closes, which now also closes the WSL instance scope
and runs the BackendInstance stop finalizer (graceful SIGTERM +
grace period) rather than letting the OS hard-kill the child.
- Refresh the stale Sidebar comment that claimed we render a
container icon on desktop-local threads. The project-level header
already carries that icon (sidebarProjectGrouping); the thread row
only suppresses the cloud icon now.
The renderer's local-secondary reconciler was polling
getLocalEnvironmentBootstraps on a fixed backoff (2s, 4s, 8s, 16s,
30s, 45s, 60s, 60s) regardless of whether the user had any WSL
backend configured. On Windows hosts without WSL enabled that's eight
IPC round-trips plus a setTimeout chain doing zero useful work.
Probe desktopBridge.getWslState() once at module init. When the user
hasn't enabled the WSL backend, latch the auto-retry chain so it
parks. The settings page calls markSecondariesConfigured(state.enabled)
after every WSL toggle so flipping WSL on later wakes the loop back
up.
For users who *do* have WSL enabled, behavior is unchanged: the loop
still rides out the full 4-minute desktop-bootstrap TTL window
covering cold boot.
Two related state bugs in the WSL picker:
1. Turning the WSL backend off while wsl-only was on persisted
wslBackendEnabled=false but left wslOnly=true. The "Run WSL only"
row vanished, but the running app stayed on the WSL primary
(wsl-only is only honoured when WSL is enabled, so on next launch
the app would silently fall back to Windows). Off in wsl-only now
confirms and clears both flags, relaunching onto Windows.
2. Enabling the WSL backend dropped the user into "both backends" and
left them to discover the wsl-only switch separately. Enabling now
prompts with a modal that offers "Run both backends" or "Use only
WSL" so the mode is chosen upfront.
Both flows share the existing dialog. The enable kind uses two action
buttons instead of the single Confirm path.
Two separate controls for "is the WSL backend on?" and "which distro
does it run on?" was confusing. They're the same decision. Merge them
into a single dropdown: "Off" stops the backend, any distro entry
starts it on that distro. The confirmation paths (disable, switch
distro) keep their existing copy and gating against
hasWslRegistrationToLose.
Persisting the wsl-only setting and waiting for the next launch was
clunky: the user had to confirm a dialog and then close + reopen the
app for the toggle to take effect. The pool captures the primary
choice once at layer init, so the relaunch is unavoidable, but we can
do it for them. Same pattern the network-access toggle already uses.
Three things in one branch:
* fix(web): drop the per-thread container icon when every thread in
the project is already on WSL (a7a2e1bd, already pushed).
* feat(web): confirm before disable / distro-switch when WSL has
state (449e18f8, already pushed).
* This commit: add a third backend mode where the WSL backend runs
as the primary and the Windows backend isn't started.
The mode lands as a new `wslOnly` setting on DesktopAppSettings,
gated behind wslBackendEnabled. When both are true:
- DesktopBackendConfiguration.resolvePrimary now dispatches at
resolve time. The Windows path builds the same start config as
before; the WSL path reuses resolveWslStartConfig with the
primary port and the user's chosen distro, so the WSL backend
binds where the Windows backend would have, the renderer loads
from the same exposure endpoint, and cookie-auth keeps working.
- DesktopBackendPool reads settings once at layer init to pick the
primary's label ("Windows" vs "WSL (Ubuntu)"). The label is
captured per process; flipping the mode requires a restart.
- DesktopWslBackend.reconcile skips the parallel "wsl:<distro>"
registration when wsl-only is on, otherwise we'd run two WSL
processes on the same distro.
- New IPC channel SET_WSL_ONLY_CHANNEL plus a setWslOnly handler.
getWslState now includes the wslOnly flag, and the DesktopBridge
contract gains setWslOnly(enabled).
- Settings UI gets a third row ("Run WSL only") under the distro
picker, visible when WSL is enabled. The confirmation dialog
grows a third branch with restart-aware copy ("Save and restart
later") since the primary spec is captured at layer init.
Migration / defaults: wslOnly defaults to false. Existing setups
stay on parallel mode unless the user explicitly turns this on.
Tests: test bridges, settings mock, and IPC layerTest extended for
the new field. Existing settings + backend + WSL test suites pass.
When the user toggles WSL off or switches to a different distro, we
now stop and ask for confirmation if the WSL backend has ever
landed in the saved-environment registry on this machine. Skipping
the dialog when there's no registration to lose keeps the common
case (first-time enable, immediate undo, fresh install) frictionless;
prompting when WSL has actual state protects users from accidentally
disconnecting threads/projects they care about.
Enabling WSL never prompts: it's non-destructive (just starts a
second backend) and getting a confirmation dialog every time would
be noise.
Cancelling the dialog drops pendingWslChange without touching the
underlying setting, so the Switch / Select stay on their current
value.
The project header now carries the container icon for WSL-only
project groups (943e1ed9), so repeating the icon on every thread
inside the group is just noise: a WSL project's threads are
implicitly all WSL.
Skip the per-thread indicator when the thread's env is desktopLocal.
The CloudIcon path for true remote envs stays in place because the
project header doesn't differentiate "remote project A" from "remote
project B" - the cloud icon on the thread row carries the env label
tooltip for those.
pendingInstanceIds tracks "an attempt is in flight RIGHT NOW", which
empties out during the backoff delay between retries. That made the
sidebar status alert flash on and off once per setTimeout fire while
the WSL backend was cold-booting (the user reported "rendered in and
out a few times before the threads loaded").
Derive the connecting set from "secondary in bootstraps + not yet in
the saved-env registry + auto-retry budget still active" instead.
That stays true through all 8 attempts of the backoff schedule, so
the user sees one steady "Connecting WSL (Ubuntu)" line until the
backend lands.
The Retry button still works because the public reconcile entry
resets budgetExhausted, which makes the connecting predicate true
again until either the new attempt succeeds or the budget runs out
a second time.
A cold-start launch where the WSL backend is still booting (or where
the renderer's first registration attempt fails before retries cover
the gap) used to leave the sidebar silent: no projects, no
indication anything was happening. The user has no way to tell
whether the backend is starting up, broken, or simply not
configured.
Promote the reconciler's in-memory trace to a real zustand store
(useLocalSecondaryReconcileStore) tracking pendingInstanceIds,
per-instance registrationErrors, and budgetExhausted. The reconciler
writes:
- addPending/removePending around each register attempt
- setRegistrationError on Promise.race failure or timeout
- clearRegistrationError when an attempt actually returns a record
- budgetExhausted = true once auto-retry runs out of attempts
- budgetExhausted = false on user-driven reconcile (so Retry resets it)
The window.__t3LocalSecondaryDebug global keeps working - it now
just reads from the store.
Add a LocalSecondaryStatus component to the sidebar. It renders:
- A "Connecting <label>" alert with a spinner while pendingInstanceIds
is non-empty.
- A "Couldn't connect <label>" warning alert with the error message
and a Retry button when the retry budget runs out with errors
still recorded.
Retry calls reconcileLocalSecondaryEnvironments() (resetBudget: true)
so the loop gets a fresh shot.
Two issues from a fresh cold-start launch:
1. The first register attempt hit ERR_CONNECTION_REFUSED (WSL not
listening yet), surfaced as Failed to fetch, and then no retries
fired. Most likely a registration step hung past the descriptor
fetch (IPC bearer read, WS open, etc) so the per-instance pending
promise never resolved, which kept reconcileOnce awaiting forever
and left pendingReconcileRun wedged for every subsequent retry
tick. Wrap each attempt in a 25s hard ceiling via Promise.race so
a stuck step is force-rejected, the catch wrapper logs it, and the
scheduleAutoRetry chain keeps progressing.
2. Production renderers don't have CDP, so when the silent failure
above happened there was no way to inspect what state the reconciler
was actually in. Expose window.__t3LocalSecondaryDebug with two
methods:
- getState() returns the most recent bootstraps list, per-instance
registration errors, last reconcile timestamp, and attempt count.
- retryNow() re-fires the reconcile loop on demand.
Wrapped behind exposeDebugGlobal() so non-browser environments
(vitest under node) don't poison globalThis.
Also wrapped the IPC call to getLocalEnvironmentBootstraps in a
try/catch with logging, in case the bridge throws during a startup
race.
The thread-row icon was fixed in ad7e3d77, but the project-header
indicator still rendered a cloud for any group whose members were
all non-primary. That was visually wrong for WSL backends: the
project lives on the user's machine, just in a sandbox.
Pull the desktopLocal marker through into the sidebar's grouping
output as allRemoteMembersAreDesktopLocal, and let the project
header render ContainerIcon (plus a "Local sandbox" tooltip) when
every non-primary member is desktopLocal. Mixed groups and true
remote-only groups still get the cloud icon.
buildSidebarProjectSnapshots gains an optional
isDesktopLocalEnvironment resolver so callers without saved-env
context still get the legacy behavior.
The auto-retry loop short-circuited the moment readBootstraps()
returned no secondary entries. That looked right in isolation:
"nothing pending, stop polling." But the desktop pool only publishes
a backend's bootstrap once the backend's first start cycle has
produced a config (see desktop.ipc.window.getLocalEnvironmentBootstraps's
`Option.isNone(config) continue`), so a WSL backend mid-cold-boot is
indistinguishable from "no WSL configured" from the renderer's side.
The short-circuit fired before the WSL bootstrap got published, the
loop stopped, and the env never registered.
Drop the hasPendingSecondary gate. We still cap at the full backoff
schedule (8 attempts, ~225s) and reconcileOnce is a no-op when every
secondary is already registered, so the cost of running the budget
out is a handful of cheap IPC calls. The payoff is that a WSL cold
boot taking longer than the initial reconcile (which is the common
case, not the exception) now actually gets caught.
WSL threads were rendered with the same cloud icon as true remote
saved envs, which made an actively-connected WSL backend look like
cloud storage in the project tree.
Pull the desktopLocal marker out of the saved-env registry for each
thread and render ContainerIcon for those entries instead, so the
WSL backend shows as a local sandbox and cloud stays reserved for
remote envs. The thread row tooltip already surfaces the env's
saved label (e.g. "WSL (default distro)"), so the icon swap is the
only change visible to the user.
WSL cold boot routinely lands at the 30-60s mark, well past the two
quick reconcile passes the renderer was doing at app start. Once
those exhausted, the WSL secondary stayed missing from the saved-env
registry and the user lost access to threads stored against that
backend until they toggled the WSL setting off and on again.
Add an internal backoff loop in reconcileLocalSecondaryEnvironments:
when a pass finishes with any secondary still missing a record, it
schedules another pass at 2s, 4s, 8s, 16s, 30s, 45s, 60s, 60s. User-
driven calls (toggling the setting, or the boot path) reset the
budget; internal retries advance it. The whole budget fits inside
the desktop-bootstrap TTL with headroom.
Also reuse a persisted bearer when one exists. The session token we
stored from the first bootstrap stays valid for 30 days, so on page
reload we can skip the bootstrap exchange entirely if the backend
still recognizes the bearer. Falls back to a fresh bootstrap if the
bearer is missing or rejected, which keeps the existing "first
connect" path working unchanged.
Guard readBootstraps / reconcileOnce against test environments that
exercise the runtime-service entry point without a browser-shaped
global (window is undefined) or with a partially-mocked registry
store (byId undefined). This prevents unhandled rejections in the
saved-env and thread-subscription test suites without changing
observable test behavior.
Drop the now-redundant 5s retry timeout out of
startEnvironmentConnectionService - the reconciler owns its retry
loop end-to-end.
The saved-env registry subscriber kicks off a sync as soon as upsert
lands, and that path reads the bearer back via readSavedEnvironmentBearerToken.
Writing the bearer first means whichever path connects first finds
the credential.
The command-palette's add-project flow gated the "Open project from
File Manager" affordance on browseEnvironmentId === primary. That
held for the swap-mode world where the desktop only managed one
local backend. With the WSL backend now registered as a saved-env
with a desktopLocal marker, the file-manager picker should be
available there too — and the desktop side already knows how to
route a pickFolder call into the right WSL distro's filesystem when
the renderer passes targetEnvironmentId.
Open the gate to "primary OR desktopLocal" and forward
browseEnvironmentId as targetEnvironmentId on the pickFolder
call. Remote saved environments stay browse-only because the desktop
side has no way to spawn an OS file dialog over there.
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.
The WSL section in ConnectionsSettings was still shaped as a "switch
backend" decision: pick local-or-wsl from one dropdown, confirm in a
modal, watch a "restarting backend" spinner. That mental model is wrong
for parallel backends. Toggling the WSL backend on/off doesn't bounce
the Windows one, and switching distros only restarts the WSL instance.
Replace with two plain rows:
- "WSL backend" — a switch that enables/disables the second
backend. Off by default for users who never opted in, so the
normal flow looks the same as before.
- "WSL distro" — a select that lists the installed distros, shown
only when the toggle is on. Changing the selection writes the
new wslDistro setting and lets the orchestrator restart just the
WSL instance.
Both controls fire the relevant new IPCs (setWslBackendEnabled,
setWslDistro) without an AlertDialog confirmation. The reconcile is
non-destructive: the orchestrator unregisters and re-registers the
WSL pool instance, the primary stays up.
Drop the confirm-then-apply state machine
(pendingDesktopWslSelection, the dialog markup, the per-stage spinner
copy). The error toast and disabled-while-updating spinner stay so
the user gets feedback if the orchestrator's reconcile fails.
BACKEND_VALUE_LOCAL is gone — there's no longer a "switch to local"
option to express. BACKEND_VALUE_DEFAULT_WSL stays as the sentinel
for the "track the WSL default" choice in the distro picker.
getLocalEnvironmentBootstrap used to hand back a single bootstrap for
the primary backend. With the WSL backend running as a second pool
instance, the renderer needs to learn about both so step 7 can
register them as separate local environments.
Rename the IPC to getLocalEnvironmentBootstraps (plural) and walk
pool.list, emitting one entry per instance that already has a config.
Instances that are registered but haven't produced a config yet (WSL
backend mid-registration before its first start cycle) are skipped
and will appear on the next call.
The bootstrap entry gains an id field that mirrors the backend
instance id (e.g. "primary" or "wsl:ubuntu"). The renderer uses that
to find the primary entry today (auth.ts, target.ts); step 7 keys
local environments off the same id. PRIMARY_LOCAL_ENVIRONMENT_ID is
exported from contracts so web code can reference the primary by name
without importing brand machinery from the desktop package. The
desktop side wraps the same constant in BackendInstanceId so the two
stay locked together.
Test bridge mocks updated. The DesktopBridge casts in
authBootstrap.test.ts went through `as DesktopBridge` previously; the
array-returning plural is structurally different enough that TS
flagged it, so they go through `as unknown as DesktopBridge` now.