The WSL parallel-backend runs a Linux node against the same node_modules
the Windows desktop uses (via /mnt/c). Platform-gated optional native
deps -- e.g. @yuuang/ffi-rs-linux-x64-gnu (pulled in transitively) -- are
only fetched for the install host's platform, so a Windows pnpm install
omitted the Linux binaries and the WSL backend crash-looped on
"Cannot find module '@yuuang/ffi-rs-linux-x64-gnu'".
Add supportedArchitectures (current + linux, x64, glibc) so one install
fetches both platforms' native binaries: electron.exe stays for the
Windows desktop while the Linux variants become available to the WSL
backend. This makes every install pull both platforms' optional natives,
which is required for the WSL backend to start.
Catch up to upstream main (b2d17b71). One conflict, in Sidebar.tsx:
upstream relocated the T3Wordmark component, so the merge left a stale
copy of it next to our LocalSecondaryStatus (the WSL "Connecting" banner).
Kept our LocalSecondaryStatus and dropped the duplicate T3Wordmark in
favor of upstream's relocated definition.
Verified: web + desktop typecheck clean.
Per the app's service-definition convention (flagged by macroscope),
inline the standalone *Shape interfaces into their Context.Service type
arguments and drop the separate types:
- DesktopWslBackendShape -> DesktopWslBackend
- DesktopWslEnvironmentShape -> DesktopWslEnvironment
- DesktopBackendOutputLogFactoryShape -> DesktopBackendOutputLogFactory
- DesktopBackendPoolShape -> DesktopBackendPool
Internal and test references updated to X["Service"] (and
["Service"]["register"] / ["unregister"]). Pure type-level move; tags,
members, and runtime behavior are unchanged. Desktop typecheck clean;
affected tests pass.
The desktop backend manager and the SSH tunnel each had their own HTTP
readiness probe. Extract the richer SSH implementation into
@t3tools/shared/httpReadiness as a generic waitForHttpReady parameterized
by a makeError callback, so each caller keeps its own tagged error:
- ssh/tunnel: thin wrapper that still fails with SshReadinessError (tag,
messages, and cause shapes unchanged).
- DesktopBackendManager: delegates to the shared probe, still failing with
BackendTimeoutError; its external signature is unchanged. It picks up the
per-probe timeout + bounded-retry behavior the SSH probe already had.
Verified: shared + ssh + desktop typecheck clean; full ssh suite (25) and
desktop backend tests (14) pass; SshReadinessError is unchanged.
Lint:
- providerMaintenanceRunner: drop the shell:win32 spawn option to match
upstream main (which removed it), clearing the no-global-process-runtime
error. No WSL/desktop behavior change (server-side provider maintenance).
- DesktopBackendConfiguration.test: the runSync-safety test deliberately
uses ManagedRuntime + Effect.runSync to replicate the sync IPC handler's
exact path; add a justified oxlint-disable (converting to it.effect would
mask a regression to async-only resolution).
Normalize internal error classes from Data.TaggedError to
Schema.TaggedErrorClass, matching the app's normalized error style:
BackendTimeoutError, BackendProcessBootstrapEncodeError,
BackendProcessSpawnError, DesktopBackendPoolInstanceAlreadyRegisteredError,
DesktopBackendPoolCannotUnregisterPrimaryError, and
DesktopLogFileWriterConfigurationError. Tags, fields, and messages are
unchanged; this is type-level normalization only.
Verified: desktop + server typecheck clean, full lint green, and the
converted-error tests pass.
Two DesktopBackendManager error classes interpolated cause.message into
their caller-visible message, which violates the convention of deriving
messages from stable structural attributes (never from cause.message) and
leaked raw PlatformError text (command/path) into the message.
Restore the structural context these classes had dropped, and derive the
message from it while keeping the underlying error as cause:
- BackendProcessBootstrapEncodeError carries entryPath; message names it.
- BackendProcessSpawnError carries executablePath; message names it.
Addresses the two Macroscope conventions findings on DesktopBackendManager.
Follow-up to the pending-bootstrap change: a secondary backend whose
preflight failed fatally (no node, wrong version, missing build tools)
has stopped retrying, so reporting it as a pending bootstrap showed an
indefinite "Connecting..." that conflicted with the WSL-state UI already
surfacing the fatal error. Now only mid-registration or transiently
retrying (non-fatal) secondaries are emitted as pending; fatal ones are
dropped as before.
Addresses the Cursor "Stale Connecting after fatal preflight" finding.
getLocalEnvironmentBootstraps dropped secondary (WSL) instances whose
config carried a preflightFailure (or had no config yet), so the sidebar
"Connecting..." indicator -- which is driven by the bootstrap list --
never appeared while a dual-mode WSL backend was retrying transient
preflight.
Emit such secondaries as pending bootstraps with null endpoints (and no
token) instead of dropping them. The renderer surfaces them as
"Connecting..." (the Sidebar bootstrap-list banner) and, because the
endpoints are null, never dials the dead port -- so the
/api/auth/bootstrap/bearer error cycles the drop avoided stay avoided.
The primary instance is still skipped while not ready: it is same-origin
with no connecting affordance to surface.
Addresses the Cursor "WSL sidebar misses preflight boot" finding.
Resolve conflicts from upstream's Effect-service normalization batch while
preserving the WSL parallel-backend feature set.
Key resolutions:
- ipc/methods/window.ts: adopt the DesktopIpc.makeIpcMethod /
DesktopIpc.makeSyncIpcMethod namespace convention; keep our plural
getLocalEnvironmentBootstraps and the getLocalEnvironmentBearerToken
method.
- app/DesktopState.ts: adopt upstream's Context.Service class with
backendReady + quitting. The window keeps its own backendReadyRef, so
state.backendReady is unused but harmless.
- app/DesktopObservability.ts: keep our per-instance
DesktopBackendOutputLogFactory (per-instance backend logs are required
for parallel backends). Drop upstream's newly-extracted single-instance
DesktopBackendOutputLog.ts: zero consumers in this tree, fully
superseded by the factory (primary maps to forInstance(primary), same
server-child.log path).
- backend/DesktopBackendManager.test.ts: keep our factory-based harness.
Upstream's side provisioned the removed DesktopBackendManager.layer
service model (DesktopState / DesktopWindow / DesktopBackendConfiguration
deps), which no longer exists in this tree.
- Adapt DesktopObservability.ts + ipc/methods/wsl.test.ts to upstream's
removal of the standalone DesktopEnvironmentShape export: use
DesktopEnvironment.DesktopEnvironment["Service"] (the normalized form).
Verified: web + desktop typecheck clean; affected desktop tests pass
(DesktopObservability, DesktopBackendPool, DesktopBackendManager, wsl).
Addresses a Cursor Bugbot finding: loadWslState() cleared the error up front, so
clicking Retry made the error/retry row vanish (renderWslRow only shows it when
!desktopWslState and desktopWslError) until the IPC settled. Clear the error only
on success instead, so it persists across an in-flight retry, and add a loading
flag so the Retry button shows "Retrying..." and is disabled while in flight.
Follow-up to the WSL-state seeding fix, addressing two Cursor Bugbot findings:
- If getWslState() failed on mount, renderWslRow() returned null so the error
was hidden entirely. Now render an error row with a Retry control when the
load fails and the user can manage the local backend.
- Extract loadWslState(), which clears any prior error before fetching, so a
stale failure message cannot linger after a later successful load.
The merge resolution that dropped the old desktop access-management useEffect
(now owned by the desktopNetworkAccess hook upstream) also removed the
getWslState() initializer it was bundled with. As a result desktopWslState
stayed null and renderWslRow() returned null, hiding the WSL settings picker
entirely. Re-add a focused effect that seeds desktopWslState from the bridge
when local-backend management is available.
Addresses Macroscope review finding on ConnectionsSettings.tsx.
Brings in upstream's desktop-auth to Clerk-bridge migration (#3092) plus 9 other
commits. Resolution preserves the WSL parallel-backends work while adopting the
new primary-auth flow.
Contracts / IPC: keep our plural getLocalEnvironmentBootstraps; add upstream's
new getLocalEnvironmentBearerToken (primary bearer token) across the bridge,
preload, and the IPC channel / method / handlers.
Desktop:
- DesktopLocalEnvironmentAuth (upstream's new primary-auth service) now reads the
primary instance from our DesktopBackendPool instead of the removed legacy
DesktopBackendManager.
- main.ts composes both our WSL backend layer and the new local-environment-auth
and Clerk layers.
- DesktopWindow adopts upstream's local-client window loading (getDesktopUrl /
t3:// scheme) rather than loading the backend URL, dropping the now-obsolete
backend-URL plumbing. The "Connecting to WSL" splash is kept, re-pointed onto
the existing backend-ready latch (upstream's DesktopState.backendReady addition
did not land in this merge; the backend pool drives readiness through
handleBackendReady / handleBackendNotReady).
Web: keep our Layer.effect platform source (primary plus WSL secondaries); the
primary now authenticates via upstream's primaryEnvironmentHttpLayer and the
secondaries via FetchHttpClient.
Verified: typecheck (web, desktop), web tests (connection / provider /
authBootstrap / desktopAuth), desktop tests (DesktopWindow splash,
DesktopLocalEnvironmentAuth), and lint all pass.
Follow-up cleanups from the upstream connection-rewrite merge.
#1 Centralize the desktop-local classification. The renderer was inlining
`target._tag === "BearerConnectionTarget" && connectionId.startsWith("local:")`
in ~7 places to detect a WSL / desktop-local environment. Add
connection/desktopLocal.ts as the single source of truth
(DESKTOP_LOCAL_CONNECTION_ID_PREFIX, desktopLocalConnectionId for the producer,
isDesktopLocalConnectionTarget for consumers) and route platform.ts plus every
consumer (Sidebar, ConnectionsSettings, ProviderUpdate*) through it.
#2 Carry the WSL label at registration time. platform.ts now labels a secondary
from the desktop bootstrap (e.g. "WSL (Ubuntu)") instead of the generic
descriptor label, so the provider feature no longer recovers the distro by
matching the environment's loopback URL against the bootstrap list. Drops the
brittle localBackendInstanceId URL-matcher.
#3 Share the desktop-bootstrap reader. Extract readDesktopSecondaryBootstraps
into desktopLocal.ts (used by both the platform source and the renderer) and add
a useDesktopLocalBootstraps() hook, replacing the Sidebar's bespoke setInterval
poller. The platform source's Effect poller and the React hook remain separate
timers (different runtimes), but they now read through one function.
Verified: web typecheck, connection + provider-logic tests, and lint pass.
Re-integrates the WSL parallel-backends renderer onto upstream's rewritten
connection/RPC architecture (#2978), which deleted the saved-env / environmentApi
/ serverState / wsConnectionState subsystem this branch was built on.
Core (packages/client-runtime/connection):
- Add dynamic platform-managed bearer environments: a PlatformConnectionRegistration
union (Primary|Bearer) and registry.reconcilePlatform(set), which adds/removes
platform-managed environments as the host topology changes and stashes the bearer
credential. This models the dual-mode WSL secondary (separate loopback origin,
bearer auth, dynamic port so it is rederived rather than persisted). The primary
and the WSL-only primary keep the same-origin cookie path.
Web platform source (apps/web/src/connection/platform.ts):
- Emit the platform set from the plural getLocalEnvironmentBootstraps() IPC: the
primary (cookie) plus each WSL backend (bearer via bootstrap-token exchange),
polling and reconciling on toggle. Replaces the deleted 541-line reconciler.
Renderer re-home:
- Drop the old subsystem (environmentApi, rpc/serverState, rpc/wsConnectionState,
environments/runtime/*, environments/local/*) and their tests.
- Re-home the Sidebar cold-boot indicator, the ConnectionsSettings WSL picker, and
the multi-environment provider-update feature onto the new hooks (useEnvironments,
serverEnvironment.updateProvider, the primaryServer* atoms). Desktop-local
environments are identified by a BearerConnectionTarget with a "local:"
connection id.
- Drop the inert swap-suppression surface superseded by parallel backends.
Verified: typecheck (web, desktop, client-runtime), connection / provider /
localApi / authBootstrap tests, and lint all pass.
Same class as the ffi-rs fix. The WSL (Linux x64) backend loads fff's
native binary (through ffi-rs / fff-node), but resolveFffNativeDependencies
only promotes the host platform's fff binary (win32) to a direct staged
dep, so @ff-labs/fff-bin-linux-x64-gnu never shipped in the artifact. The
backend connects fine because fff loads lazily, but file-finding in WSL
would fail to load the missing binary.
For Windows builds, also promote the Linux x64 fff binaries (gnu + musl)
alongside the host's, reusing resolveFffNativeDependencies("linux", "x64").
Windows artifacts also ship the WSL (Linux x64) backend, which loads
Linux-native optional dependencies at runtime -- e.g. ffi-rs's
@yuuang/ffi-rs-linux-x64-gnu. The staged production install set pnpm's
supportedArchitectures to the host platform only (win32/x64), so just the
Windows bindings were fetched. The WSL backend then crash-looped on
require ("Cannot find module '@yuuang/ffi-rs-linux-x64-gnu'") and never
bound its port, surfacing in the app as "Couldn't connect WSL".
For Windows builds, extend supportedArchitectures to also include
linux/x64/glibc so the staged install pulls the Linux optional deps
alongside the Windows ones. Confirmed pnpm then fetches
@yuuang/ffi-rs-linux-x64-gnu into the staged tree.
Resolve scripts/build-desktop-artifact.ts: keep both our WSL node-pty
prebuild staging (decodeNodePtyManifest) and upstream's fff native binary
staging (encodeStageWorkspaceConfig / DESKTOP_ASAR_UNPACK), and collapse
the duplicated asarUnpack key the merge left behind into a single entry
that unpacks the fff native binaries, the server bundle, and the full
node_modules tree.
The previous change made activate ignore the connecting splash so a
failed post-readiness open would retry instead of latching onto it. That
regressed the cold-boot case: before the backend is ready,
createMainIfBackendReady is a no-op, so taskbar/dock activation while the
splash was hidden or minimized left the user with nothing until the
backend finished.
Branch activate on backend readiness: reveal the real main if present;
while still cold-booting (not ready) re-reveal the splash; once ready,
fall through to createMainIfBackendReady so the failed-open retry is
preserved.
Share the fake-ElectronWindow setup between the splash regression tests
via makeSplashScenario, and add a test that activation during cold boot
re-reveals the splash without creating a window.
The connecting splash is a real BrowserWindow, so currentMainOrFirst /
focusedMainOrFirst (which fall back to "any first window") return it
while the app is still booting. Only createMainIfBackendReady excluded
it; ensureMain, revealOrCreateMain, activate, and dispatchMenuAction
still treated it as the main window.
The backend pool deliberately swallows window-open errors raised after
backend readiness (so they cannot block restartAttempt reset). In
WSL-only mode a failed main open therefore left the splash up with no
real main while the backend was ready, and activation only re-revealed
the splash and never retried the open, stranding the user on
"Connecting to WSL".
Centralize splash exclusion in a withoutSplash helper and route every
main-window lookup (currentMainWindow / focusedMainWindow) through it, so
activate retries the open instead of latching onto the splash.
dispatchMenuAction now falls back to ensureMain rather than createMain to
avoid opening a duplicate main when one already exists.
Add a regression test: a swallowed post-readiness open failure leaves
only the splash, and activate must bring up the real main.
In WSL-only mode the renderer is served by the WSL backend (distro IP),
so the main window cannot load until WSL has cold-booted. That left the
app with no window at all for several seconds after launch, which reads
as a hang.
Show a lightweight frameless "Connecting to WSL" splash window as soon
as bootstrap starts (gated on wslOnly + wslBackendEnabled), and dismiss
it the moment the real main window reveals. Dual mode opens fast off the
Windows primary, so no splash is shown there.
- DesktopWindow: add showConnectingSplash, tracked in its own
splashWindowRef so currentMainOrFirst and createMainIfBackendReady
never mistake the splash for the real main window; dismiss on reveal.
- DesktopApp bootstrap: trigger the splash before primary start when the
persisted settings select WSL-only mode.
- Drop the now-unused DesktopState import left over from the
backendReadyRef refactor.
- Add shared compact subheader styling for preview, file, and diff panels
- Open diff files in the thread file viewer when available
- Fix macOS cursor auto-hide and Option-modified shortcut matching
- Replace attachment and favicon routes with signed asset URLs
- Harden workspace and attachment asset resolution
- Update browser preview components and shared contracts
- Tie preview and debugger listeners to Effect scopes
- Factor shared automation helpers for snapshot and input handling
- Improve cleanup for browser preview sessions and port scanning
- derive preview partitions through `BrowserSession`
- serialize session state and async preview control flow
- update tests for screenshot, automation, and partition behavior
- Move preview session and IPC wiring into the new preview module
- Tighten IPC validation with schema-based handlers
- Update preview asset paths and tests for the browser preview port
- Move MCP session registry and preview broker out of `Layers/` and `Services/`
- Update imports, tests, and server wiring to use the new module layout
- Add IPC and runtime plumbing for preview annotation theming
- Generate and ship annotation CSS for the desktop overlay
- Add pointer and artifact handling for browser preview interactions
- Add structured annotation payload validation and tests
- Update preview preload to capture selected elements, regions, and strokes
- Wire new preview annotation UI into the web app
Co-authored-by: codex <[email protected]>
Adds an in-page element picker to the preview browser. Clicking the
crosshair button in the chrome row activates a blue-highlight picker
inside the guest webview; clicking an element captures its component
name (via react-grab), source location, html/css preview, and selector,
then attaches it to the chat composer as a chip that serializes into an
`<element_context>` block in the outgoing message.
Architecture:
- Per-`<webview>` preload bundle (`preview-pick-preload.cjs`) renders
the overlay, hosts the picker event loop, and bubbles the picked
payload back to main via the per-WebContents `wc.ipc` channel (not
`sendToHost`, which only fires on the host renderer's <webview>
element and never reaches main).
- Main coordinates via `PreviewViewManager.pickElement(tabId)`, which
cancels any in-flight session, force-focuses the guest (so the first
click on a remote page actually reaches the preload), then awaits the
payload. User-initiated cancels (Escape, beforeunload) echo `null`
back to main; main-initiated cancels and supersession tear down
silently to avoid the new-pick-resolves-with-stale-null race.
- Renderer fetches partition + webPreferences + preload URL in a single
`getPreviewConfig()` IPC call, snapshots the previously-focused host
element before triggering a pick, and restores focus when the pick
resolves so the user's textarea cursor isn't lost.
Security posture for the guest webview:
- `webpreferences="contextIsolation=false,sandbox=true,nodeIntegration=false"`
centralized in `preview-webview-preferences.ts`. contextIsolation off
is required so react-grab's `getElementContext` can reach the page's
React DevTools hook on `globalThis`. sandbox stays on so the page
cannot reach Node APIs even with shared globals (without it, the
preload's `require` would land on the page's `globalThis` and any
third-party site could send arbitrary IPC to main).
- Defense in depth: a `will-attach-webview` handler in main, gated on
the preview partition, force-pins `sandbox: true`, all
`nodeIntegration*: false`, and the absolute preload PATH (not URL —
that field rejects file:// URLs with "preload script must have
absolute path" and silently disables the picker).
Composer + transcript integration:
- New `elementContexts` slice in `composerDraftStore` (mirrors the
terminal-context slice: dedup by selector+tag+component+url, persist
via partializer, restore on send-failure retry).
- `ComposerPendingElementContexts` chip row above the editor.
- `deriveDisplayedUserMessageState` now strips both `<element_context>`
AND `<terminal_context>` blocks (element first, since it's appended
last) and exposes element entries to `MessagesTimeline`, which renders
them as compact chips beneath the message body.
- Pick button is disabled with explanatory tooltip when the page failed
to load (the React `<PreviewUnreachable>` overlay covers the webview,
so picks would silently dangle otherwise).
Tests added:
- `preview-webview-preferences.test.ts` locks down the security flags
(contextIsolation=false, sandbox=true, nodeIntegration=false, no
whitespace, only true/false literal values).
- `preview-pick-label-position.test.ts` covers the floating-label
clamp/flip math (no off-screen overflow, flip-below when no room
above, etc.).
- `picked-element-payload.test.ts` validator coverage.
- `elementContext.test.ts` for the serialization round-trip,
normalization, dedup, and label formatting.
- `composerDraftStore.test.ts` element-contexts slice (add, dedup,
remove, set, clear, persistence round-trip).
- `ChatView.logic.test.ts` sendable-content-with-element-only.
Build: new `tsdown` entry inlines react-grab + bippy into the picker
preload bundle (~59KB / 19KB gzipped).
Adds a desktop-only browser preview that lives in the right panel slot
alongside plan/diff. Lets the user point an Electron <webview> at any
URL — typed into a chrome-style URL bar, clicked from the empty-state
list of detected localhost dev servers, or auto-opened by a project
script with `previewUrl` set. Single-tab per thread.
Server (Effect/Layers):
- PreviewManager: per-(thread, tab) session metadata via SynchronizedRef
+ PubSub<PreviewEvent>; survives WS reconnect via `list`/replay.
- PreviewPortScanner: lsof on macOS/Linux, TCP probe fallback on
Windows; reference-counted polling so we only scan when subscribed.
- WS RPC + streams (`preview.open|navigate|refresh|close|list|reportStatus`,
`subscribePreviewEvents`, `subscribeDiscoveredLocalServers`).
Desktop:
- PreviewViewManager owns Chromium WebContents per tab, mediates
navigation/zoom/devtools/clear-storage. registerWebview gates by
webContents.getType() === "webview" and host-window match.
- IPC channels for create/close/register/navigate/back/forward/refresh/
zoom/hardReload/openDevTools/clearCookies/clearCache/getBrowserPartition.
- Forwards app-level shortcuts (mod+shift+J, mod+K, mod+,, mod+W) from
the webview back to the main window.
- Persisted browser session partition (cookies, cache).
Web:
- PreviewPanel/PreviewView/PreviewWebview render the surface; chrome row
with back/forward/refresh + URL input + Open-in-browser + 3-dot menu
(Hard reload, DevTools, Zoom −/+/reset, Clear cookies/cache).
- usePreviewSession subscribes to server events; usePreviewBridge
mirrors desktop state into the store and forwards Loading→Success/
LoadFailed back to the server.
- previewStateStore: per-thread snapshot + desktopOverlay + recently-
seen URLs (Zustand).
- rightPanelStore arbitrates plan vs. preview vs. diff; ChatView's
toggles strip the `?diff=1` URL hint when switching to preview and
vice versa so the panels are mutually exclusive.
- Top-nav Globe toggle in ChatHeader (desktop builds only) and a
`mod+shift+J` keybinding routed via a typed previewActionBus.
- PreviewEmptyState lists detected localhost servers (scanner +
configured project URLs + recently-seen) with live "listening" pulse.
- PreviewUnreachable: theme-aware port of Chromium's "site can't be
reached" page.
- Resizable inline panel (RightPanelResizeHandle + useResizableWidth);
width persists to localStorage on drag-end.
- Terminal link "Open in preview" context-menu integration for loopback
URLs.
Contracts:
- preview.ts schemas (PreviewSessionSnapshot, PreviewNavStatus,
PreviewEvent, RPC inputs/results, DiscoveredLocalServer).
- ProjectScript schema gains optional `previewUrl` + `autoOpenPreview`.
- New keybinding commands: preview.toggle/refresh/focusUrl/zoomIn/Out/
resetZoom; new `when:` contexts `previewFocus` / `previewOpen`.
Shared:
- @t3tools/shared/preview: normalizePreviewUrl, isPreviewableUrl,
isLoopbackHost, newPreviewTabId, LSOF_LOCAL_HOST_TOKENS.
Tests:
- contracts: schema decode tests for all preview events/snapshots/inputs.
- shared: URL normalization coverage.
- server: PreviewManager (open/navigate/reportStatus/refresh/close,
multi-subscriber isolation, idempotency); PortScanner (lsof parsing
including IPv6, TCP probe, reference-counted polling).
- web: previewStateStore (per-tab event application, dedupe,
reconnect recovery); rightPanelStore arbitration.
The previous review fix gated closing a stale, un-acted prompt on
canShowPrompt, which is false once notificationKey becomes null (all updates
cleared) — so the toast could linger empty after the updates disappeared.
Close it when the update set clears (key null) or a fresh set can replace it,
and keep it only while a backend is re-settling (updates still exist, just
gated) or an update is already in progress.
- A non-terminal ("running") dispatch result now keeps the environment row on
the loading spinner instead of falling through to the idle Update button once
pending clears in finally. A terminal server-state pill still overrides it,
so the original "stale result blocks live status" case stays fixed.
- The stale-prompt replacement now only closes the active toast when a fresh
prompt can actually be shown, so the popover no longer disappears when the
update set changes while backends are re-settling (gated).
- Resolve each environment row from live server state when the dispatch's
own result snapshot is still non-terminal ("running"), instead of pinning
the row on "Updating...". A stale snapshot no longer blocks the terminal
status that server state later reports. Row-status resolution moved to the
logic module and unit-tested.
- Replace a prompt the user hasn't acted on yet when the available updates
change (a new version or environment), matching the single-prompt flow,
which previously could leave the per-environment toast stale. Once an
update is in progress the toast is kept so its in-progress rows survive.
The launch popover now renders one row per local environment (e.g. Windows
and WSL), each with its own "update all" trigger that targets only that
environment's backend, instead of a single button that fanned out to every
environment at once.
- Defer the popover until every local backend leaves "connecting" (30s
safety cap) so it reflects every environment, rather than appearing from
the primary alone while WSL is still booting; rows pick up WSL reactively
if it connects later.
- Label rows by platform ("Windows" / "WSL" / "macOS" / "Linux"), detecting
WSL by its backend instance id and otherwise the reported OS, falling back
to the environment's own label.
- Resolve each row's result from both the dispatch payload and live server
state, so it lands correctly whether a secondary backend's config fails to
re-sync or the dispatch RPC is lost to a reconnect; a 20s backstop reverts
the spinner if the request never reaches the backend.
- Gate the entire split behind WSL presence: without a WSL backend the
popover keeps the original single-prompt flow, so non-WSL users see no
change.
collectUpdatedProviderSnapshots (and its instance-id dedupe helper) is
superseded by collectProviderUpdateOutcomeSnapshots: each fan-out dispatch
now narrows its payload to the exact targeted (driver, instanceId) before
the collector runs, so the instance filtering it performed is no longer
needed. Remove the dead export and its tests.
The provider-update fan-out dispatches to the primary and every connected
desktopLocal backend, but completion handling only inspected promise
rejections and the primary's instance ids. A secondary backend (e.g. WSL)
whose updateProvider resolved with a failed or unchanged provider in its
payload was silently dropped, so the launch toast and settings flow could
report success while the WSL copy stayed outdated.
- updateProviderAcrossLocalEnvironments now resolves each dispatch to a
normalized outcome carrying the matched provider snapshot (with its
terminal updateState) plus isPrimary / environment metadata.
- The launch toast aggregates outcomes across backends to the worst-case
status per driver, and gates the primary-only serverState effect behind
an awaitingSettlement flag so it cannot finalize success before every
dispatched update settles.
- The settings flow surfaces a secondary backend's failed/unchanged result
via a toast; the primary's own result is already shown inline.
Provider update executables are package-manager launcher shims (`npm` ->
`npm.cmd`, `pnpm` -> `pnpm.cmd`, etc.). On Windows a bare-name spawn does
not resolve PATHEXT, so `ChildProcess.spawn("npm", ...)` fails with ENOENT,
surfaced to users as "Failed to run update command npm: NotFound". This
broke one-click updates for every npm/pnpm/bun/vp-managed provider on the
Windows backend.
Spawn the maintenance command with `shell: true` on win32 so the shell
resolves the shim, matching how every other provider command is already
spawned (ClaudeProvider, CodexSessionRuntime, CursorProvider, GrokProvider,
opencodeRuntime, AcpSessionRuntime). The update args are a fixed allowlist
of package names, so there is no shell-injection surface.
The provider update popover and settings dispatched updateProvider only to the
primary environment (ensureLocalApi). In dual-backend mode that left the WSL (or
any other local secondary) provider un-updated.
Add a small helper that fans the update out to the primary plus every connected
local secondary backend that has the provider configured, looking up each
environment's own instance id (the same driver has a distinct instance id per
environment). Wire it into both dispatch sites and reuse the existing result
aggregation / toasts unchanged. Remote (SSH / relay) environments are skipped.
The WSL server spawns provider update commands (e.g. `npm install -g
@openai/codex@latest`) by name, but `wsl.exe -- node` leaves the resolved Node's
bin dir off the process PATH, so npm/npx (and the installed CLIs like codex)
weren't found and the update failed with "npm: NotFound". Provider maintenance
already runs per-backend server, so this broke updates for every provider in the
WSL backend, and in WSL-only mode there's no Windows fallback to mask it.
Launch the WSL server through a shell that front-loads the resolved Node's bin
dir (plus the standard system dirs) onto PATH, then `exec` the same absolute
Node. exec preserves fd 0, so the bootstrap-over-stdin delivery is unchanged.
npm/npx and globally-installed provider CLIs now resolve to the distro's Node
toolchain.
Verified on a packaged build in WSL-only mode: the backend still starts cleanly
through the shell wrapper, and the server's PATH resolves and runs npm.
The WSL preflight only validated node-pty, so when the server's externalized
node_modules wasn't readable by WSL's Node (the ERR_MODULE_NOT_FOUND bug),
preflight passed and wsl-only mode failed to launch with no Windows fallback.
Add a server-dependency canary to the probe: resolve "effect" (the framework
every server module imports) from the server directory, which validates the
whole node_modules tree is present on the WSL filesystem. On failure (exit 3,
kept distinct from a node-pty problem) report a fatal preflight failure, 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 launches.
The WSL backend launches the server with the distro's own Linux Node, which
can't read inside app.asar. asarUnpack only covered the server bundle and
node-pty, but bin.mjs externalizes its runtime dependencies (effect, @effect/*,
...) to node_modules rather than inlining them. So the Linux Node crashed with
ERR_MODULE_NOT_FOUND ("Cannot find package 'effect'") before it even reached
node-pty, which left WSL-only mode unable to launch (the node-pty preflight had
already passed, so there was no Windows fallback).
Unpack the whole node_modules tree so every server import resolves on the real
filesystem. The Windows primary keeps reading the same files through the asar
via ELECTRON_RUN_AS_NODE, so there's no duplication.
- Connections settings: disable Connect/Disconnect and Remove on the WSL
backend's row. It's a desktop-managed local backend, not a remote environment
you connect to or remove here, and reconcile would just re-create a removed
one. Added a tooltip pointing at the WSL on/off setting that actually manages
its lifecycle.
- Command palette: drop the dedicated "Open WSL folder" command. The generic
"Add project" flow already offers the WSL-vs-Windows environment picker, so a
WSL-only shortcut with no Windows counterpart was redundant and asymmetric.
The build matrix gated every entry on build_wsl_node_pty succeeding, but only
the Windows artifact consumes the Linux node-pty prebuild, so a failed prebuild
would skip the macOS and Linux builds too. Gate the build job on preflight and
relay only (via !cancelled() instead of !failure()); build_wsl_node_pty stays in
needs for ordering and the Windows-only download step fails just that platform
when the prebuild is missing.
In packaged builds the server bundle and node-pty were sealed inside app.asar,
which the WSL backend's Linux Node cannot read, so the WSL backend never started
in release builds. It dead-ended on a misleading "node-pty not prepared / run
prepare:wsl" error. node-pty also publishes no Linux prebuilt, and the Windows
artifact is built on a Windows CI runner that cannot compile one.
- asarUnpack the server bundle and node-pty, and point the WSL backend at the
app.asar.unpacked sibling. The Windows primary still reads app.asar via
ELECTRON_RUN_AS_NODE, so it is unaffected and there is no payload duplication.
- Build the Linux pty.node in a dedicated Linux CI job and hand it to the
Windows packaging job as an artifact. build-desktop-artifact stages it into
node-pty/prebuilds/linux-<arch>/ with a marker, so the packaged app ships a
ready binary and needs no compiler, node-gyp, or network on first launch.
- node-pty is N-API, so one Linux binary works across all WSL Node versions;
drop the modules ABI comparison from the preflight probe accordingly.
- Runtime compile is now dev-only (allowBuild: !isPackaged). In packaged builds
a prebuilt that cannot load surfaces a clear arch/distro diagnostic instead of
nagging for build tools or silently compiling.
A fatal WSL preflight failure (no node, wrong version, missing build tools)
used to reschedule the backend forever with no cap and no UI, so in wsl-only
mode the app sat invisible (no onReady, no window) retrying a setup that can't
fix itself.
Classify preflight failures as fatal vs transient. Transient ones (WSL cold-
starting, wslpath while the VM boots) keep retrying so the backend self-heals.
Fatal ones stop after MAX_PREFLIGHT_FAILURE_ATTEMPTS and fire onPreflightFailed.
On the primary the pool wires that to show an error dialog and persist Windows
mode, so the manager's next restart re-resolves the primary as Windows and a
window opens instead of hanging.
The WSL preflight ran probes via 'bash -l -s' and the backend launched bare
'node' via 'wsl.exe -- node'. Both miss version-manager-installed node: nvm/
fnm/asdf/volta hook in below the interactive guard at the bottom of .bashrc,
which a non-interactive login shell returns before reaching, and a bare
'wsl.exe -- node' uses the non-login PATH. So wsl-only mode failed preflight
(or launched the wrong node) for the common nvm setup.
Source the managers explicitly via a preamble prepended to every WSL probe,
resolve the absolute node path the preflight validated, and launch with that
exact path so preflight and launch agree on one node.
Align the four list/path/IP/home probe fallbacks with the convention
upstream adopted in #2968: replace Effect.catch(() => Effect.succeed(x))
with the more direct Effect.orElseSucceed(() => x). Behavior is
identical (recover from the error channel with a default); silences the
new catchToOrElseSucceed lint.
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.
mergeWslEnv split the user's WSLENV on every colon and re-serialized it,
collapsing empty :: segments, trimming, and de-duplicating entries. That
diverged the forwarded value from what the user configured on Windows.
Keep the existing WSLENV byte-for-byte and only append the secret names
we forward that aren't already declared. Empty segments are WSL no-ops,
so nothing stopped forwarding, but verbatim preservation matches intent
(and the test name) and removes the surprise.
isLocalHostIpv4 matched interface family against the string IPv4 only.
Some Node builds report family as the numeric 4 (Electron 41 / Node 22
reports the string, but the representation has varied across versions),
which would make mirrored-mode detection silently miss and leave the
renderer pointed at the distro IP instead of loopback. Normalize via
String() and accept either form.
The merge combined our handleBackendReady(httpBaseUrl) signature change
with an upstream-added test that still yielded it as a bare Effect.
Pass the resolved URL like the other call site so the merged test
typechecks against the function form.
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.
Bugbot (medium): the lazy primary label (resolved via instance.label ->
resolvePrimaryLabel -> describePrimary -> wslEnvironment.isAvailable) is
read inside getLocalEnvironmentBootstraps, a makeSyncIpcMethod handler
evaluated with Effect.runSync. isAvailable's real layer probes the
filesystem (fileSystem.exists on wsl.exe), so leaving it as a live async
effect would make runSync throw and break the renderer's synchronous
bootstrap path.
Probe wsl.exe once at DesktopWslEnvironment layer init and expose
isAvailable as the cached value (Effect.succeed). WSL availability is
process-static — the Windows feature isn't added/removed mid-session and
backend mode changes already require a restart — so the cached boolean
stays accurate while keeping the whole label chain synchronously
resolvable (settings.get is already a SynchronizedRef read). Added a
regression test that builds the real WSL layer and resolves the primary
label with a top-level runSync, exactly as the handler does.
Bugbot (medium): the pool computed primaryLabel once at init purely from
persisted settings (wslOnly && wslBackendEnabled -> "WSL"), but
resolvePrimary now falls back to the Windows config when WSL is
unavailable. So the pool's instance.label could read "WSL" while the
backend actually ran Windows-native, and getLocalEnvironmentBootstraps
surfaced that stale label to the sidebar/env switcher.
Centralize the decision: DesktopBackendConfiguration gains a
resolvePrimaryLabel derived from the same describePrimary helper that
resolvePrimary now uses (wsl-only + WSL actually available, else Windows),
so the label and the start-config can't disagree. The pool consumes
configuration.resolvePrimaryLabel and no longer reads settings directly.
Added label regression tests (available -> WSL distro, unavailable ->
Windows).
Bugbot (low): getOrCreateBootstrapToken did a non-atomic read-then-write on
a plain Ref — Ref.get, check, crypto.randomBytes (a yield point), Ref.set.
Now that resolvePrimary and resolveWsl share this closure, two concurrent
resolutions before the token is cached could both observe None, generate
distinct tokens, and have one overwrite the other, leaving the backends
with mismatched tokens that break the shared-token invariant the renderer
relies on.
Switch tokenRef to a SynchronizedRef and generate via modifyEffect, which
serializes the whole get-or-create so the first caller wins and the rest
reuse its token. Added a concurrent-resolution regression test.
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.
Bugbot (low): the pool's onReady absorbed handleBackendReady failures with
Effect.catch(() => Effect.void), and the comment claimed the window service
logs them. It doesn't — createWindow/createMain/createMainIfBackendReady
only log on success, so a post-readiness window-open failure vanished
silently and was near-impossible to diagnose in production.
Log the error via a new desktop-backend-pool component logger before
swallowing it (we still must not let it block the readiness callback, which
would prevent restartAttempt from being reset). Corrected the comment.
Parity with the #2353 fix for the "WSL off hides recovery control" report.
resolvePrimary took the wsl-only primary path whenever wslOnly +
wslBackendEnabled were persisted, without checking whether WSL is actually
usable. If WSL became unavailable (wsl.exe removed, no distro), the primary
looped on preflight failures while the Connections backend control is
hidden, leaving no in-app way back to Windows.
resolvePrimary now checks wslEnvironment.isAvailable and resolves the
Windows primary (logging a warning) when wsl-only was requested but WSL
isn't usable. Added a regression test asserting the Windows primary path
under isAvailable: false.
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.
- DesktopObservability: cache the IO sink, not the per-call shape. The
shape closes over `instanceId: id` for log annotations, so a cache
hit on a file-path collision (two ids that sanitize to the same
filename, e.g. `wsl:default` and `wsl_default`) would attribute the
second caller's writes to the first caller's id. Split into
`makeBackendOutputSinkForInstance` (cacheable RotatingLogFileWriter)
+ `makeBackendOutputLogShape` (per-call wrapper that annotates with
the actual caller's id). The cache still dedupes file handles to
avoid currentSize races.
- DesktopWslBackend: add a top-level `Effect.catchCause` safety net on
reconcile to enforce the file-header contract ("idempotent, never
fails, errors are logged"). Every internal step today catches its
own failures so the inferred error type is `never` and this is a
no-op in steady state — but if a future change ever introduces an
unhandled failure path, IPC callers like setWslBackendEnabled would
otherwise surface it to the renderer as an opaque error.
`WSL_INSTANCE_ID_PREFIX = "wsl:"` was defined twice — once in
DesktopWslBackend (which produces the ids) and once in
ipc/methods/window.ts (which parses them in pickFolder). A rename of
one would silently break the other: pickFolder would stop recognizing
WSL targets and fall through to the Windows picker without error.
Export the constant from DesktopWslBackend (the producer) and import
it in window.ts. Same value, one declaration.
Inside stop(), Ref.modify atomically flips state to "no active run, no
restart fiber" before spec.onShutdown is invoked, but the physical
teardown (Fiber.interrupt + closeRun) runs *after* the mutex releases.
If onShutdown raised, the whole mutex effect failed and both cleanup
steps were skipped — leaving the child process and restart fiber
running while state claimed nothing was active. The next start() would
then spawn a second backend on top.
Wrap the onShutdown call in Effect.ignore so its failure can't abort
the surrounding teardown. Matches the pattern closeRun already uses
for the same reason.
Two review-feedback fixes:
- getLocalEnvironmentBootstraps was exposing the bootstrap info (URL,
token) for backends whose configResolve produced a preflightFailure.
Those backends never actually listen — the manager calls
scheduleRestart instead of spawning — so the renderer would pick up
a phantom URL, POST to /api/auth/bootstrap/bearer, fail, and register
a broken saved-env. Skip them in the IPC handler.
- wslBackend.reconcile read pool state and settings non-atomically.
The bootstrap fork + an in-flight setWslDistro IPC could both
observe "no WSL instance registered", both proceed to startNew with
different distros, and leave a stranded instance behind. Wrap the
reconcile body in a single-permit semaphore so concurrent callers
queue.
WSL2's `networkingMode=mirrored` makes the distro share the Windows
network stack, so `hostname -I` returns the host's own IP (e.g.
192.168.0.64). Our renderer URL resolution was passing that IP through
verbatim, and Windows can't route a packet to its own NIC address and
have it loop back to a WSL listener — the request just times out.
Loopback DOES forward correctly in mirrored mode, so detect the
collision (distro IP matches one of our own interfaces) and fall back
to 127.0.0.1.
NAT mode is unchanged: the distro IP there is a private vEthernet
address that won't match any Windows interface, so we keep advertising
it as before (which is the path that avoids the flaky wslhost proxy).
Same pattern as the update-install path (ba31706c) but on the normal
quit path. The scoped program finalizer was only stopping the primary
backend before marking shutdown complete, so any registered WSL
instance was left for the layer-scope cascade to clean up. The
electronApp.quit() in listenForQuit can race ahead of that cascade,
hard-killing the WSL child instead of letting it receive SIGTERM +
grace. Iterate pool.list and stop every instance concurrently.
quitAndInstall fires app.quit() + a hard relaunch, which may not wait
for Effect's scope finalizer cascade to drain. With parallel backends
that meant the WSL instance got hard-killed by the OS instead of
receiving the SIGTERM + grace period the BackendInstance stop
finalizer provides. Iterate pool.list and stop every instance
concurrently with the same 5s budget the primary had on its own.
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.
In wsl-only mode, serverExposure.backendConfig.httpBaseUrl
(127.0.0.1:3773) doesn't match the URL the WSL backend actually
listens on (the distro IP, e.g. 172.27.152.141:3773). wslhost
localhost forwarding is flaky on some Windows hosts, so loadURL at
127.0.0.1 leaves the renderer black-screened with did-fail-load.
Plumb the primary instance's resolved httpBaseUrl through onReady to
the window service, store it, and let createMain read it. Falls back
to serverExposure when nothing's been reported yet so existing
behavior (dev mode, activate path before ready) is unchanged.
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 desktop-bootstrap credential used the same single-use + 5-minute
TTL semantics as a user-facing pairing link. That fit the original
mental model (one renderer, one bootstrap exchange) but breaks
parallel backends where a slow WSL cold boot lands outside the
renderer's first reconcile pass, and breaks page reloads where the
renderer no longer has the bearer it traded the bootstrap for and
needs to re-exchange.
Switch the seed for `desktopBootstrapToken` to `remainingUses:
"unbounded"` with a 24h TTL. The seed is delivered over trusted IPC
(fd3 / stdin) at backend launch and lives in the renderer/desktop
processes the user already trusts, so single-use buys us nothing
operationally and costs us recoverable error paths.
Tests:
- BootstrapCredentialService.test.ts now asserts repeat consumption
succeeds and that expiry kicks in past 24h, not 5 minutes.
- server.test.ts: the "rejects reusing" test is rewritten as
"allows reusing" against the same credential.
The WSL backend was bound to 127.0.0.1 inside the distro and the
renderer reached it through wslhost (Windows' built-in localhost
forwarder). That forwarding is flaky on at least my Win11 install:
the readiness probe and saved-env descriptor fetch both saw "Failed
to fetch" against a backend that was otherwise healthy.
Bind to 0.0.0.0 inside WSL and advertise the distro's eth0 IP as the
renderer-visible httpBaseUrl. DesktopWslEnvironment.getDistroIp uses
`hostname -I` inside the distro (cached per distro) and falls back
to 127.0.0.1 + wslhost when the probe fails, so a busted setup
degrades to the prior behavior instead of regressing.
The network this exposes on is the WSL-vEthernet network, not the
LAN; primary owns LAN exposure when the user opts in, so this
doesn't widen the attack surface for non-WSL users.
After step 7a landed, the renderer registers each non-primary
bootstrap as a desktop-local SavedEnvironmentRecord via the
reconcileLocalSecondaryEnvironments path. The desktopLocal marker
keeps these entries out of saved-env persistence so they don't end
up in the user's settings file, and the saved-env runtime takes care
of the connection lifecycle, sidebar listing, env-switcher, and
project-id routing for free.
Browser validation done with a real dev:desktop run with
wslBackendEnabled=true and wslDistro="Ubuntu":
- Distinct ports (13773 primary, 13774 wsl) listening side by
side, both serving distinct env descriptors (windows vs linux
platform).
- Per-instance log files in dev/logs/ (server-child.log +
server-child-wsl_Ubuntu.log).
- Renderer completes the bearer-token bootstrap against the WSL
backend (200), obtains a ws-token (200), holds an ESTABLISHED
WebSocket connection to each port (netstat).
Header docblock now lists this state explicitly + the per-commit
migration history.
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.
Rewrite the "current state" section so it matches what's actually in
the tree (plural bootstraps IPC, pickFolder routing, toggle-style
settings UX). Note the renderer-side gap: the web env runtime still
treats the primary as the only local environment, and lifting that
requires a per-environment auth bootstrap pass that we deliberately
left for a follow-up. The desktop side is ready when the renderer
takes it up.
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.
PickFolderOptions gains an optional targetEnvironmentId so callers
that know which local backend they're targeting (a project opened in
WSL, for example) can ask for that backend's filesystem picker.
The default behavior is unchanged: when targetEnvironmentId is
undefined, the dialog opens against the Windows-native primary, which
is what every existing caller gets. This is deliberate — most users
never enable the WSL backend and shouldn't see a different picker
showing up. Only callers that explicitly opt in route to WSL.
When targetEnvironmentId starts with "wsl:", the handler uses the
WSL helpers in wslPathParsing.ts. The id encodes the distro
selection (e.g. "wsl:ubuntu") and falls back to the persisted
wslDistro setting when the id is the "wsl:default" sentinel, matching
how DesktopWslBackend.reconcile resolves the same input. The legacy
"if wslBackendEnabled then always use WSL picker" branch is gone —
that was the swap-mode mental model.
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.
The pool's design-notes block was still describing the step-4 cut-off
("WSL instance not yet registered, IPC still uses swap mode"). Step 5
shipped, so update the "current state" section and convert the
forward-looking migration list into a history block + a short "what's
left" callout for steps 6+. No code changes here, just the header
docblock.
This is the cut-over to parallel backends. The old "swap the primary
into WSL and bounce it" flow goes away; the WSL backend is now a
second instance registered with the pool, running alongside the
Windows primary. Toggling the WSL backend on/off doesn't touch the
primary at all.
New service DesktopWslBackend (apps/desktop/src/wsl/DesktopWslBackend.ts)
owns the orchestration. Its one entry point, reconcile, reads the
persisted wslBackendEnabled + wslDistro settings, looks at what's
currently registered with the pool, and brings the two in line:
- If WSL should be running and isn't, allocate a loopback port
starting one above the primary's, register a fresh instance via
pool.register({ id, label, configResolve: resolveWsl(...) }),
and kick off instance.start.
- If WSL is running with a stale distro selection, unregister the
old instance (which closes its scope and stops the child process)
before registering the new one.
- If WSL should not be running, unregister whatever wsl: instance
is registered.
reconcile never fails. Port-allocation failures, "WSL not available",
and pool-already-registered errors are logged and the call returns
having left the pool in a consistent state. The primary backend is
never affected.
Instance ids encode the user's distro selection: wsl:default when
wslDistro is null (track the WSL default) and wsl:<distro> otherwise.
These ids are what the env-id work in step 6/7 will key off, so they
stay stable across underlying-default-distro changes — picking
"track default" doesn't reshuffle env ids if the user later sets a
different WSL distro as the default.
Bootstrap call site (DesktopApp.ts) forks reconcile after the primary
start request. The WSL backend can take a moment to come up first
time (wsl.exe cold spawn, node-pty build); the fork keeps that off
the primary's critical path.
IPC surface change:
- Drop setWslBackend({mode, distro}) — the swap call with rollback
semantics — and the SWAP_READINESS_TIMEOUT / waitForReady /
in-process primary stop+start dance in apps/desktop/src/ipc/methods/wsl.ts.
- Add setWslBackendEnabled(boolean) + setWslDistro(string | null).
Each persists the setting via DesktopAppSettings and then calls
wslBackend.reconcile to bring the pool in line. No rollback path:
with both backends running, "WSL didn't come up" is transient
state on one instance, not a degraded app.
- Drop DesktopWslMode / DesktopWslModeSchema from contracts. The
DesktopWslState wire shape changes mode: "local" | "wsl" to a
plain enabled: boolean.
- New IPC channels SET_WSL_BACKEND_ENABLED_CHANNEL +
SET_WSL_DISTRO_CHANNEL.
DesktopBackendConfiguration's resolveWsl bootstrap now hardcodes
tailscaleServePort: 443 when tailscaleServeEnabled is false, because
PortSchema rejects 0. The backend only reads the port when serve is
on, so the value is inert.
Web UI (ConnectionsSettings.tsx) is wired against the new IPC. The
swap ceremony (reauth, welcome-race, suppressReconnect, 6-minute
flow timeout) goes away — toggling is fast and non-destructive now.
The dialog is still the same select-with-confirm shape; step 8 will
rework it into a proper "WSL backend: enabled + distro picker"
control. SettingsPanels.browser.tsx and localApi.test.ts pick up
the new mock shape.
DesktopBackendConfiguration.resolve was a single effect that picked
between local and WSL config based on the persisted wslMode. Now that
the two backends run in parallel, each pool instance needs its own
resolver. Split into:
- resolvePrimary: Effect<DesktopBackendStartConfig>
Always Windows-native. Reads port/host/exposure from
DesktopServerExposure.backendConfig like before.
- resolveWsl({ port, distro }): Effect<DesktopBackendStartConfig>
Builds a WSL-via-wsl.exe config for the given distro on the
given port. Doesn't touch DesktopServerExposure since the WSL
backend is loopback-only by design; the primary owns LAN
exposure when the user enables network-accessible mode.
Shared bits (bootstrap token via tokenRef, persisted observability
endpoints, env patching, mergeWslEnv) stay private to this module.
Both resolvers reuse the same bootstrapToken so the renderer can
authenticate against either backend with one token.
The WSL config now hardcodes 127.0.0.1 + tailscaleServeEnabled=false
in the bootstrap envelope. The old code copied the primary's host
(could be 0.0.0.0) and tailscale flags into the WSL bootstrap, which
made sense when WSL was a replacement but is wrong when both run
side by side: a tailscale-serve forwarder bound on Windows can't also
bind from inside WSL on the same port. Loopback-only WSL plus the
primary handling LAN exposure is the cleaner v1 contract.
DesktopBackendPool's primary spec now wires configuration.resolvePrimary;
the WSL spec call site lands in the orchestrator commit. Tests updated
to drive the two resolvers explicitly and to assert the shared-token
guarantee.
The "local" vs "wsl" swap mode is going away. Windows and WSL backends
will run in parallel as two pool instances, so the setting that drives
WSL only needs to answer "should there be a WSL backend at all". Rename
the persisted field to wslBackendEnabled and replace setWslMode with
two narrower setters (setWslBackendEnabled, setWslDistro) so the
upcoming orchestrator IPC can toggle each independently.
Existing on-disk settings that still carry the legacy wslMode key get
migrated on load: wslMode=="wsl" becomes wslBackendEnabled=true. The
schema still accepts wslMode for one release so users coming off the
swap-mode build keep their selection. The new wslBackendEnabled wins
when both keys are present, and the next persist drops wslMode.
Consumers that read settings.wslMode get pointed at wslBackendEnabled:
DesktopBackendConfiguration (the resolver still produces a single WSL
config in this commit; the split lands next), the pickFolder IPC, and
the wsl.ts IPC's readWslState/setWslBackend handlers. The wire shape
for the renderer stays the same in this commit so the web app keeps
compiling; the renderer-facing IPC gets reworked alongside the
orchestrator.
Lays the groundwork for the WSL second-instance orchestrator. Pool now
exposes:
- register(spec): builds a DesktopBackendInstance via the factory under
a fresh child Scope owned by the pool, adds it to the registry, and
returns the instance unstarted so the caller decides when to start.
- unregister(id): atomically removes the entry from the registry and
closes the child scope, which runs the instance's auto-stop finalizer.
Each registered instance lives under its own Scope so a single unregister
stops just that instance without disturbing the rest of the pool. The
primary instance keeps its place in the pool's own layer scope and is
guarded by a DesktopBackendPoolCannotUnregisterPrimaryError; that case
is treated as a wiring bug rather than something callers handle.
The instances Ref upgrades to a SynchronizedRef so register and
unregister can run as serialized modify-effects without racing each
other on the underlying Map. Duplicate registration on the same id
fails with a typed DesktopBackendPoolInstanceAlreadyRegisteredError.
No caller registers a second instance yet — that arrives in the next
commit when the WSL orchestrator goes in.
Backend child output and session boundaries used to land in one shared
server-child.log via the DesktopBackendOutputLog singleton. With a
second backend instance on the way, intermixing two processes' stdout
streams into one file makes triage harder than it needs to be.
Replace the singleton with DesktopBackendOutputLogFactory.forInstance(id)
that vends a rotating writer per backend id. The primary keeps the
historical server-child.log path so existing ops tooling, packaged-build
log inspection, and habit don't break; non-primary instances land in
server-child-<sanitized-id>.log. A SynchronizedRef-backed cache keyed by
id ensures repeated forInstance lookups on the same id reuse the writer
(important under restart loops that re-resolve the factory).
Each emitted record now carries an instanceId annotation so cross-file
greps can still associate records belonging to the same backend even if
log paths drift later. The redundant "instance=<id>" prefix on session
boundary details is dropped — that info now lives in the structured
annotation and in the file path.
DesktopBackendManager pulls its writer from the factory at instance
construction time so each instance carries a fixed writer for its
lifetime. DesktopBackendManager.test.ts stubs the factory directly;
DesktopObservability.test.ts asserts the new instanceId annotation.
DesktopState.backendReady was the last global coupling tying backend
lifecycle to app-wide state. With the pool owning per-instance
readiness (instance.snapshot.ready), the only remaining consumer of the
global latch is the window's auto-create-on-ready path. Move ownership
of the latch into DesktopWindow's own internals so DesktopState only
carries truly app-wide state (the quitting flag).
DesktopWindow gains handleBackendNotReady, called by the primary
instance's onShutdown callback so the latch clears on clean stop,
restart, or crash. Without it the macOS dock-click activation path could
produce a window pointing at a backend that is no longer up. The pool
spec wires both callbacks against the window service instead of the
state Ref.
Test stubs for DesktopWindowShape pick up the new handleBackendNotReady
field; DesktopWindow.test.ts drops its DesktopState dependency.
Replace the singleton DesktopBackendManager Context.Service with a
factory function makeBackendInstance(spec) that returns one
DesktopBackendInstance per call. Each instance owns its own state Ref,
mutex, restart fiber, and active child process so no state is shared
across pool members.
The pool layer calls the factory once for the Windows primary at
startup, wiring the spec's configResolve to DesktopBackendConfiguration
and the onReady/onShutdown callbacks to the legacy global side effects
(DesktopState.backendReady, DesktopWindow.handleBackendReady). Those
last couplings move per-instance in steps 2 and 3.
All five consumers (DesktopApp bootstrap + shutdown, wsl.ts swap IPC,
window.ts bootstrap IPC, DesktopUpdates installer) now read the primary
instance via pool.primary instead of the deleted manager service. Log
session boundaries are prefixed with the instance id so per-backend
output stays distinguishable until step 3 splits the output log.
DesktopBackendManager.test.ts rewritten to use the factory directly
under Effect.scoped. DesktopUpdates.test.ts swaps its backend stub from
a Layer.succeed(DesktopBackendManager, ...) to
DesktopBackendPool.layerTest([stub]).
Phase-1 foundation for running Windows and WSL backends side by side.
Introduces:
* BackendInstanceId brand + PRIMARY_INSTANCE_ID constant
* DesktopBackendInstance interface mirroring the legacy backend manager
surface so consumers can migrate one call site at a time
* DesktopBackendPool service with get/list/primary operations
* Phase-1 layer that wraps the existing singleton DesktopBackendManager
and exposes it under PRIMARY_INSTANCE_ID, no behavior change
* layerTest helper for unit tests
The pool is wired into the desktop application layer alongside the
existing manager; current consumers (window/wsl IPC, lifecycle hooks,
telemetry) still depend on DesktopBackendManager directly. The header
docblock on DesktopBackendPool.ts captures the full migration sequence
for follow-up commits: reshape the manager into an instance factory,
move per-instance state off DesktopState/DesktopBackendOutputLog, wire
WSL as a second pooled instance, widen the bootstrap IPC, and retire
the swap-mode dialog.
onWelcome subscribes with `immediate: true`, so the listener fires
synchronously with whatever welcome payload is already in the atom. The
previous code compared against `previousPrimaryEnvId` (descriptor-derived);
if the descriptor hadn't loaded yet, that was null and any non-null current
welcome would resolve the promise instantly, completing the "syncing" stage
before the new backend's welcome actually arrived. Capture the current
welcome's env-id from the atom as the baseline instead so the immediate
fire never matches the "new welcome arrived" predicate.
- remove the unused `enabled` field from WslConfig and the unreferenced
DEFAULT_WSL_CONFIG export; the toggle moved to DesktopAppSettings.wslMode
during the migration and the field was carried along by every caller as
noise that didn't influence behavior
- wrap the entire backend-swap flow (success + catch) in suppressReconnect
so the catch-block reauth doesn't fire reconnect/offline toasts on top of
the error toast the user is reading. The previous structure only
suppressed during the happy path; recovery work landed outside the window
The renderer's 180s ceiling was shorter than the IPC's worst-case duration:
setWslBackend can take up to ~2min for the initial readiness wait plus
another ~2min for the rollback readiness wait before throwing
WslBackendSwapError, so the client was firing "Backend swap took too long"
while the main process was still actively rolling back. Bump the ceiling
to 6 minutes (4min IPC worst case + ~60s reauth retry budget + 45s welcome
race) so a real hang still surfaces but a legitimate rollback completes.
The dropdown maps state.distro: null to the actual default distro's name
so the Select highlights a real option, but the no-op check still compared
target.distro (e.g. "Ubuntu") against state.distro (null). Re-picking the
visually-active row opened the confirmation dialog and triggered a full
backend restart for what was clearly a no-op. Resolve both sides through
the same null->default mapping before comparing.
- swap "__local__" / "__default__" select values for "backend:local" /
"backend:default-wsl" — the colon is rejected by DISTRO_NAME_PATTERN so
the sentinels can never collide with an actual WSL distro name
- remove VITE_DEV_SERVER_URL from WSL_FORWARDED_ENV_NAMES; the value is
delivered exclusively via the --dev-url CLI flag because WSLENV translation
of URL-shaped values is unreliable, and keeping it in both paths
contradicted the comment at the CLI-flag site
- map null distro to the actual default distro name in the backend select
so the dropdown highlights a real option instead of an orphan "__default__"
with no matching item when distros are listed
- add getUserHome to DesktopWslEnvironment (cached per distro) and pass the
resolved /home/<user> into the picker helper so ~/path expands correctly
instead of producing /home/<rest>
- surface a clearer error when the rollback backend also fails to start, so
the user knows the app is degraded rather than seeing the misleading
"Rolled back to the previous mode" message
- move clearTimeout(flowTimeoutHandle) into the finally block so it fires
on success, error, and timeout — previously the error path left a live
180s timer that would reject an unreferenced promise (unhandled rejection)
- remove the second removeEnvironmentState call after welcome; the first
call right after the IPC swap already wipes the old environment state
and nothing recreates state under the old env id during reauth/welcome
- drain stdout/stderr concurrently in runWslShell so node-gyp output
on both pipes can't deadlock the child
- short-circuit waitForReady when desiredRunning flips off, so an
external stop() during swap doesn't waste the full timeout
- guard runSwap continuations after the 180s flow timeout so an
orphaned IPC resolution can't overwrite rolled-back UI state
- drop unused refreshPrimaryEnvironmentDescriptor — descriptor URL is
stable across the swap and consumers re-fetch lazily
Lets the desktop app launch the local backend inside a WSL distro
instead of natively on Windows. Adds:
- Backend plumbing (apps/desktop/src/wsl): pure path parsing
utilities, a DesktopWslEnvironment Effect service wrapping
wsl.exe operations (listDistros, preWarm, windowsToWslPath,
ensureNodePty, isAvailable), and an explicit preflight that
checks for missing node / build tools before spawning so the
failure message names the actual problem.
- Spawn path: DesktopBackendConfiguration branches on the new
wslMode setting and assembles "wsl.exe -d <distro> -- node
<linux-entry> --bootstrap-fd 0" with the bootstrap envelope on
stdin (wsl.exe drops additional file descriptors). Sensitive env
vars forward via WSLENV; --dev-url is passed as a CLI flag so the
WSL dev backend lands in dev/ instead of userdata/ deterministi-
cally. The Windows-side T3CODE_HOME is scrubbed and extendEnv is
disabled for WSL so the WSL backend cannot accidentally share a
baseDir with the local backend via /mnt/c/...
- Settings: wslMode + wslDistro on DesktopAppSettings, with
validation that drops distro names containing control or shell
meta characters. Contracts get DesktopWslMode / DesktopWslDistro
/ DesktopWslState schemas.
- IPC: getWslState and setWslBackend on the desktop bridge. The
setter pre-warms the WSL VM, persists settings, then drives an
in-process backend stop + start with a 2-minute readiness wait
and a rollback path that reverts to the previous mode if the new
backend never reports ready. pickFolder defaults to the WSL home
UNC path when wslMode is "wsl".
- Web UI: backend-runtime selector in Connection Settings with a
three-stage swap modal (restarting / re-establishing session /
syncing) that suppresses the WS reconnect toast for the duration
of the swap, waits for the new backend's welcome event before
closing, and clears the previous env's store state so the side-
bar does not render stale threads. New suppressReconnect helper
on the connection-status atom plus exports for the descriptor
refresh and reauth used by the swap flow.
Stdin pipes inherited across the wsl.exe boundary fail to re-open
via /proc/self/fd/0, so add EACCES to the codes that drop back to
reading the fd directly. Without this the WSL desktop backend
fails to load its bootstrap envelope with "Failed to duplicate
bootstrap fd" and ends up in a scheduled-restart loop.
- Restrict release workflow defaults to read-only access
- Grant `id-token` only to the publish job
- Document safe handling for `pull_request_target` in PR size checks
OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes.
Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle.
Rejected: Disable provider refresh | would hide model and auth state changes.
Confidence: high
Scope-risk: narrow
Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts
Tested: bun fmt
Tested: bun lint
Tested: bun typecheck
Tested: bun run build:desktop
-`.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
-`.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
## Imports and module namespaces
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
## Service definition
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
-`infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
-`Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
## Change discipline
- Preserve useful comments, invariants, and specification documentation while moving code.
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1.`ServerAuth` service boundary.
2. route classification and route guards.
3.`ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
-`app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
-`app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
-`bun fmt`
-`bun lint`
-`bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
-`Services/VcsDriver.ts`
-`Services/VcsRepositoryResolver.ts`
-`Services/VcsProcess.ts`
-`Layers/GitVcsDriver.ts`
-`errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
-`VcsDriver`: local repository mechanics.
-`RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
-`WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
-`ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
-`RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
exportinterfaceVcsDriverCapabilities{
readonlykind:"git"|"jj"|"sapling"|"unknown";
readonlysupportsWorktrees: boolean;
readonlysupportsBookmarks: boolean;
readonlysupportsAtomicSnapshot: boolean;
readonlysupportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
-`detectRepository(cwd)`
-`status(cwd, options)`
-`listRefs(cwd, query/pagination)`
-`checkoutRef(cwd, ref)`
-`createRef(cwd, ref, from?)`
-`createWorkspace(cwd, ref, path?)`
-`removeWorkspace(path)`
-`prepareChangeContext(cwd, filePaths?)`
-`createChange(cwd, message, options)`
-`push(cwd, target?)`
-`rangeContext(cwd, base, head)`
-`listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
-`VcsProcessSpawnError`
-`VcsProcessExitError`
-`VcsProcessTimeoutError`
-`VcsOutputDecodeError`
-`VcsRepositoryDetectionError`
-`VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
-`apps/server/src/git/Layers/GitCore.ts`
-`apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
-`Services/SourceControlProvider.ts`
-`Services/SourceControlProviderRegistry.ts`
-`Services/SourceControlProcess.ts`
-`Layers/GitHubSourceControlProvider.ts`
-`errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
-`SourceControlProvider`: hosted repository and change-request mechanics.
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
-`apps/server/src/git/Layers/GitHubCli.ts`
-`apps/server/src/git/Layers/GitHubCli.test.ts`
-`apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
-`VcsDriver` for local repository mechanics.
-`SourceControlProviderRegistry` for hosted provider selection.
-`TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
-`GitLabSourceControlProvider` using `glab`.
-`AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
-`GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
-`rpc/orchestrationActions.ts`
-`rpc/terminalActions.ts`
-`rpc/gitActions.ts`
-`rpc/projectActions.ts`
-`platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
-`@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
-`desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
# Use `bun add <name>@<url>` instead of `bun add <url>`. Without an
# explicit name, bun's resolver hits a DependencyLoop bug when the
# consumer already has the same package name resolved from npm
# (oven-sh/bun#5789, oven-sh/bun#17946). The aliased form bypasses
# the buggy reconciliation path and works on fresh and existing
# projects alike.
BODY=$(printf '%s\n\nInstall the packages built from this commit:\n\n**alchemy**\n```sh\nbun add alchemy@https://pkg.ing/alchemy/%s\n```\n\n**@alchemy.run/better-auth**\n```sh\nbun add @alchemy.run/better-auth@https://pkg.ing/@alchemy.run/better-auth/%s\n```\n\n**@alchemy.run/pr-package**\n```sh\nbun add @alchemy.run/pr-package@https://pkg.ing/@alchemy.run/pr-package/%s\n```\n' "$MARKER" "$SHORT_SHA" "$SHORT_SHA" "$SHORT_SHA")
Alchemy Effect is an Infrastructure-as-Effects (IaE) framework that extends Infrastructure-as-Code (IaC) by combining business logic and infrastructure config into a single, type-safe program expressed as Effects.
It includes a core IaC engine built with Effect. Effect provides the foundation for type-safe, composable, and testable infrastructure programs. It brings errors into the type-system and provides declarative/composable retry logic that ensure proper and reliable handling of failures.
# Concepts
- **Cloud Provider** - a cloud provider that offers a set of Services, e.g. AWS, Azure, GCP, Cloudflare, Stripe, Planetscale, Neon, etc.
- **Service** - a collection of Resources, Functions, and Bindings offered by a Cloud Provider.
- **Resource** - a named entity that is configuted with "Input Properties" and produces "Output Attributes". May or may not have Binding Contract.
- **Input Properties** - the properties passed as input to configure a Resource. Otherwise known as the "desired state" of the Resource.
- **Output Attributes** - the attributes produced by a Resource. Otherwise known as the "current state" of the Resource.
- **Stable Properties** - properties that are not affected by an Update, e.g. the ID or ARN of a Resource.
- **Function** (aka. **Runtime**) - a special kind of Resource that includes a runtime implementation expressed as a Function producing an `Effect<A, Err, Req>`. The `Req` type captures runtime dependencies, from which Infrastructure Dependencies are inferred.
- **Resource Provider** (see [Provider](./packages/alchemy/src/Provider.ts))
A Resource Provider implements the following Lifecycle Operations:
- **Diff** - compares new props with old props and determines if the Resource needs to be updated or replaced. For updates, it can also specify a list of Stable Properties that will not be changed by the update.
- **Read** - reads the current state of a Resource and returns the current Output Attributes. May return `Unowned(attrs)` to signal an existing-but-foreign resource that the engine should refuse to take over unless `--adopt` is set.
- **Pre-Create** - an optional operation that creates a stub of a Resource before reconcile runs. Used to resolve circular dependencies — e.g. Function A and B depend on each other, so we create a stub of Function A first and then `reconcile` later wires up the real dependency.
- **Reconcile** - converges a Resource's actual cloud state to the desired state described by the new Input Properties. Called for both first-time provisioning and subsequent updates. The provider receives `output` (current Attributes) and `olds` (previous Props) which may both be `undefined` on a greenfield create, both defined on an update, or `output !== undefined && olds === undefined` on an adoption. See the **Reconciler doctrine** section below for the required shape.
- **Delete** - deletes an existing Resource. It must be designed as idempotent because it is always possible for state persistence to fail after the delete operation is called. If the resource doesn't exist during deletion, it should not be considered an error.
- **Capability** - a runtime requirement of a Function (e.g. require `SQS.SendMessage` on a `SQS.Queue`). Each Capability is split into two parts: a `Binding.Service` (runtime SDK wrapper) and a `Binding.Policy` (deploy-time IAM/binding attachment).
- **Binding.Service** - an Effect Service that wraps an SDK client and exposes a `.bind(resource)` method returning a typed callable for runtime use. Provided as a Layer on the **Function** Effect so it gets bundled into the Lambda/Worker. See [Binding](./packages/alchemy/src/Binding.ts).
- **Binding.Policy** - an Effect Service that runs only at deploy time to attach IAM policies (AWS) or bindings (Cloudflare) to a Function's role/config. At runtime, `Binding.Policy` uses `Effect.serviceOption` so it gracefully becomes a no-op when the layer is not provided. Policy layers are provided on the **Stack** via `AWS.providers()()`, not on the Function.
- **Binding** - data attached to a Resource via `resource.bind(data)`. A Binding is a `{ context: PolicyContext, data: BindingData }` tuple that is collected on the Stack during plan/deploy. Bindings enable circular references between Resources — the `Binding.Policy` calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records the binding data on the Stack. The Resource Provider then receives the resolved binding data in its `reconcile` lifecycle operation via the `bindings` parameter.
- **Binding Contract** - the shape of data a Resource accepts from Bindings. For example, a Lambda Function accepts `{ env?: Record<string, any>, policyStatements?: PolicyStatement[] }` because it needs environment variables and IAM policies. A Cloudflare Worker accepts `{ bindings: Worker.Binding[] }` for its native binding system. The Binding Contract is declared as the fourth type parameter on the `Resource` interface. See [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) and [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts).
- **Dependency** - Resources depend on other Resources through two mechanisms:
- Output Properties of one Resource passed as Input Properties to another Resource (non-circular, directed acyclic graph)
- Bindings that attach data (IAM policies, env vars, Cloudflare bindings) from one Resource to another, enabling circular references between Resources.
- **Output** - a reference to (or derived from) a Resource's "Output Attributes". E.g. Bucket.bucketArn
- **Stack** - a collection of Resources, Functions, and Bindings that are deployed together.
- **Stack Name** - the name of a Stack, e.g. `my-stack`
- **Stage** - the stage of a Stack, e.g. `dev`, `prod`, `dev-sam`
- **Stack Instance** - a deployed instance of a Stack+Stage
- **Resource Type** - the type of a Resource, e.g. `Bucket`, `Instance`
- **Physical Name** - a unique name for a Resource, e.g. `my-bucket-1234567890`. It is usually best to generate them using the built-in createPhysicalName utility function which generates
- **Logical ID** - the logical ID identifying a resource within a Stack, e.g. `my-bucket`. It is stable across creates, updates, deletes and replaces.
- **Instance ID** - a unique identifier for an instance of a Resource. It is stable across creates, updates and deletes. It changes when a resource is replaced. It is truncated and used as the suffix of the Physical Name.
- **Event Source** - a special kind of Binding between a Function and a Resource that produces events that invoke the Function, e.g. `SQS.QueueEventSource`. Event Sources are implemented as Binding.Service + Binding.Policy pairs, where the attach logic creates/updates the event source mapping via the cloud provider API.
- **Replacement** - the process of replacing a Resource with a new one. A new one is created, downstream dependencies are updated with the new reference, and then the old one is deleted. Or, the old one is deleted first and then the new one is created.
- **Dependency Violation** - an error that some APIs call when an operation cannot be performed because a dependency is not met. E.g. you cannot delete an EIP until the NAT Gateway it is attached to is deleted. Lifecycle operations typically retry Dependency Violations.
- **Eventual Consistency** - create/update/delete operations can be eventually consistent leading to a variety of failure modes. For example, a Resource may be created but not yet available for use, or a Resource may be deleted but still appear in the console. Errors caused by eventual consistency should be retried, and lifecycle operations/tests should be carefully designed to wait for consistency before proceeding.
- **Retryable Error** - an error that can be retried. E.g. a Dependency Violation, Eventual Consistency Error, Transient Failure, etc.
- **Non-Retryable Error** - an error that cannot be retried. E.g. a Validation Error, Authorization Error, etc.
- **Retry Policy** - a policy for retrying errors. E.g. a fixed delay, exponential backoff, max retries, while some condition is true, or until some condition is true/false, etc.
# File System Conventions
Each Service's Resources follow the same pattern. Resource contract and provider are co-located in the same file. Capabilities (Binding.Service + Binding.Policy) are in separate files named after the capability.
```sh
# source files
packages/alchemy/src/{Cloud}/{Service}/index.ts # re-exports all resources and capabilities
**Source of truth:** The source code is the single source of truth for all API documentation. JSDoc comments in `packages/alchemy/src/**/*.ts` are extracted and used to generate the public API reference markdown.
:::warning
**Never edit the generated markdown files** under `website/src/content/docs/providers/{Cloud}/`. They are overwritten on every regeneration.
To "update the docs", edit the JSDoc on the source `.ts` file (resource-level JSDoc on the exported `const`, plus field-level JSDoc on each prop/attribute) and re-run the generator. There is no separate doc file to update.
:::
**How to generate docs:**
```sh
bun generate:api-reference # -> website/src/content/docs/providers/{Cloud}/{Resource}.md
```
This is the only doc generator that produces user-facing output. ([scripts/generate-api-reference.ts](./scripts/generate-api-reference.ts)) does the following:
1. Discovers resource files in `packages/alchemy/src/{Cloud}/{Service}/`
2. Parses TypeScript with `ts-morph`
3. Extracts the resource-level summary plus `@section` / `@example` blocks from JSDoc
4. Writes one markdown file per resource at `website/src/content/docs/providers/{Cloud}/{Resource}.md`
After editing JSDoc on a resource, run `bun generate:api-reference` to refresh the website docs.
**Writing good documentation:** When adding or updating a resource, ensure all Props and Attrs have JSDoc comments:
```typescript
exportinterfaceBucketProps{
/**
* Name of the bucket. If omitted, a unique name will be generated.
* Must be lowercase and between 3-63 characters.
*/
bucketName?: string;
/**
* Whether to delete all objects when the bucket is destroyed.
* @default false
*/
forceDestroy?: boolean;
}
```
The `@default` tag is used to document default values and will appear in the generated documentation.
### Examples and Sections (IMPORTANT)
**Examples are critical for documentation.** Every resource should have examples demonstrating common use cases. Use `@section` and `@example` JSDoc tags on the main Resource export to organize examples into a navigable table of contents.
**Format:**
-`@section <Section Title>` - Creates a heading in the Examples section and adds an entry to the Quick Reference table of contents
-`@example <Example Title>` - Creates a subheading for a specific code example (must follow a `@section`)
- Code blocks inside examples use standard markdown fenced code blocks (` `)
1. A "Quick Reference" section with links to each `@section`
2. An "Examples" section with organized code examples under each section heading
**Best practices for examples:**
- Start with the simplest use case and progress to more complex ones
- Include examples for all major capabilities (GetObject, PutObject, etc.)
- Show real-world patterns like error handling, combining with other resources
- Use descriptive titles that explain what the example demonstrates
# Workflow
Development of Alchemy-Effect Resources is heavily pattern based. Each Service has many Resources that each have 0 oor more Capabilities and Event Sources. When working on a new Service, the following steps should be followed.
1. Research the AWS Service and identify its Resources, Identifier Types, Structs, Capabilities, and Event Sources. Refer to the corresponding Terraform Provider, Pulumi Provider, and CloudFormation docs for that service (use the provided tools specifically for searching these docs for services and resources).
- Output Attributes (for each attribute: Name, Type, Description)
3. Document each of the Capabilities and Bindings
Include the following information:
- Capability Name, e.g. `GetObject`, `PutObject` (it maps 1:1 with an AWS API)
- Constraints (e.g. `Key`)
- IAM Policies (how the capability maps to an IAM Policy, e.g. Effect: Allow, Action: s3:GetObject, Resource: `arn:aws:s3:::${bucketName}/${Key}`)
- Environment Variables (what environment variables should be added to a Lambda Function so that it can access the capability, e.g. `BUCKET_NAME`, `BUCKET_ARN`, `QUEUE_URL`, `QUEUE_ARN`, etc.)
4. Research and design each of the Lifecycle Operations
- **Diff** - identify which properties are always stable across any update, which properties change conditionally depending on new and old values, which properties trigger a replacement. This is usually just a distinct list, but can sometimes require if-this-then-that logic. Document it explicitly and exhaustively. Cross-reference with AWS CloudFormation, Terraform Provider and Pulumi Provider docs.
:::warning
You should almost never use `no-op` in the Diff. No-op should be explicitly designed as a way to say "i know this property changed, but i don't want it to trigger an update". This is an edge-case and not the norm. Usually you want diff to return `undefined` or `void` to let the engine apply the default update logic. Diff is usually just use as an optimization or to identify replacement instead of update.
:::
- **Read** - determine which API calls are required to read the Output Attributes of a Resource from the Cloud Provider state (otherwise known as refresh or synchronize resource state). This is usually a single Get{Resource} API call, but can be a complex set of calls depending on the Service. Read can also be called without the current Output Attributes because of past state persistence failures. These cases are handled by computing the deterministic Physical Name and looking it up or by searching for Resources using tags (if the Cloud Provider supports it). Read may return `Unowned(attrs)` when the resource exists but lacks our ownership tags, signalling the engine to gate adoption behind `--adopt` or `adopt(true)`.
- **Pre-Create** - determine if the Resource needs a pre-create operation. This is usually only the case for the special Function/Runtime Resources like AWS Lambda Functions. If it is required, then document which API call(s) should be called and what the empty (unit) input properties are. E.g. a Lambda Function takes a simple script that exports a no-op handler function.
- **Reconcile** - determine the API calls needed to converge the cloud's actual state to the desired state described by the new Input Properties. Reconcile must be a single flow that works whether the resource is missing (greenfield create), pre-existing under our ownership (update), or freshly adopted (`output` defined but `olds` absent). See the **Reconciler doctrine** section below.
- **Delete** - determine which APIs should be called and in what order to delete an existing Resource. Delete should be idempotent so that if the resource has already been deleted, it is not considered an error. It is common for deletions to fail because of Dependency Violations or Eventual Consistency Errors. These are not always called Dependency Violations in the API docs, so attention should be paid to investigating each API's possible error codes and how they should be handled by the Delete operation. Should we retry for a period of time, indefinitely, or fail immediately?
# Reconciler doctrine
The provider's `reconcile` function replaces the legacy `create` + `update` pair. It runs every time the engine wants to make the cloud match the desired state — whether that's the first time the resource is being provisioned, a routine update, or a takeover after `read` returned an existing cloud resource.
It receives `output: Attributes | undefined` and `olds: Props | undefined`:
| defined | defined | Routine update — engine-owned resource |
| defined | `undefined` | Adoption — engine adopted via `read` |
A reconciler MUST work correctly for all three combinations. It MUST NOT branch the body on `output === undefined` and run different code paths for "create" vs "update". That pattern is just rename-and-branch and re-introduces every assumption the old `create`/`update` split made. Instead, write one flow:
```
1. Observe — derive the physical identifier; read live cloud state via getX/describeX
2. Ensure — if the resource is missing, call createX. Catch AlreadyExists/ConflictException
as a race and continue. Wait for active state if applicable.
3. Sync — for each mutable aspect (settings, sub-resources, tags, policy):
- read OBSERVED cloud state (not olds)
- compute desired state from news + bindings
- diff observed against desired
- apply only the delta API call (skip the API entirely on no-op)
4. Return — re-read final state if needed; return the fresh Attributes shape
```
Key invariants:
- **Observation > assumption.** Cloud state is authoritative. `olds` is at most a hint to skip a no-op API call; it is never the source of truth for what's actually deployed.
- **Each sync step is independently idempotent.** Crash mid-reconcile, re-run, you converge.
- **`output` is treated as a cache** for stable identifiers (physical name, ARN, immutable id). It is NOT a guarantee that the resource still exists. If it doesn't, observation falls through to "missing" and ensure recreates.
- **`AlreadyExists`/`NotFoundException`/`ResourceInUseException`-style errors are caught**, not propagated — they're races or eventual-consistency, not failures.
- **Tags use observed cloud tags as the diff baseline**, not `olds.tags` or `output.tags`. Adoption may bring you a resource with foreign tags that need to be reconciled.
:::warning
**Do not write `if (output === undefined) { /* create body */ } else { /* update body */ }`.** That is rename-and-branch, not reconciliation. The reconciler's body is one observe-ensure-sync flow that produces correct cloud state regardless of starting point.
:::
The canonical reference reconcilers cover the common shapes:
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts) — uses `ensureBucketExists` + `syncBucketTags` + `syncBucketPolicy` helpers; each helper is itself a tiny reconciler.
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts) — observe via `getQueueUrl`, ensure via `createQueue` (tolerates `QueueNameExists` race), sync attributes by diffing `getQueueAttributes` against desired, sync tags.
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts) — many mutable aspects (mode, shards, retention, encryption, metrics), each its own observed-vs-desired sync block.
- [EC2 Vpc](./packages/alchemy/src/AWS/EC2/Vpc.ts) — auto-assigned id, observe via `describeVpcs([output.vpcId])` with NotFound fallback to create, sync DNS attrs by reading `describeVpcAttribute`, sync tags from observed `vpc.Tags`.
- [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts) — non-AWS API; the underlying `putWorker` is a true upsert, so reconcile observes existing settings and delegates.
Existence-only resources (Lambda Permission, EC2 Route, EC2 RouteTableAssociation, IAM AccessKey, etc.) have nothing mutable beyond their identity. Their reconciler is just observe → if missing, create. There is no sync step.
5. Research and design the test cases for each resource. Test cases can be single or multi-step. Single-step test cases are just testing a single create success or failure mode. Multi-step cases are testing a sequence of operations, starting with create and then updating or replacing the resource multiple times. Test cases should be designed to be exhaustive and cover all possible success and failure modes, starting from simple happy paths to long, complicated aggregate (including other resources) smoke tests.
6. Implement the Resource contract and Provider in `packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts`.
The Resource contract (Props, Attributes, Binding Contract) and the Resource Provider (lifecycle operations) are co-located in the same file.
Read through the established examples to understand the pattern:
For Resources that accept Bindings (like Lambda Function), include a fourth type parameter for the Binding Contract:
```ts
exportinterfaceFunctionextendsResource<
"AWS.Lambda.Function",
FunctionProps,
{
functionArn: string;
functionName: string;
functionUrl: string|undefined;
roleName: string;
roleArn: string;
},
{
env?: Record<string,any>;
policyStatements?: PolicyStatement[];
}
>{}
```
:::tip
Some Input Property types are wrapped in an `Input<T>`, but not all are. Only properties that may need to be references to another resource's Output Attribute. E.g. common use-cases are `Input<VpcId>`, `Input<QueueUrl>`, `Tags: Record<string, Input<string>>`.
:::
:::warning
For fields like `name: string`, `bucketName: string`, `bucketPrefix: string`, you should not use `Input<string>` because these properties need to be statically knowable in the `diff` function.
:::
7. Implement the Capabilities as `Binding.Service` + `Binding.Policy` pairs in `packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts`.
Each capability has two parts:
- **`Binding.Service`** — runtime SDK wrapper, provided on the Function Effect (bundled into Lambda/Worker)
- **`Binding.Policy`** — deploy-time IAM policy attachment, provided on the Stack via `AWS.providers()()` (never bundled)
Read through the established capabilities to understand the pattern:
The `Binding.Policy` implementation calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records binding data on the Stack. The `Binding.Service` implementation resolves the Policy via `yield* Policy(resource)`, then returns a typed callable that wraps the SDK client. At runtime, the Policy is not provided and becomes a no-op.
### Runtime-only methods: color with `Alchemy.RuntimeContext`
The runtime callable returned by a `Binding.Service` (the inner Effect inside `.bind(resource)`'s return) **must** declare `Alchemy.RuntimeContext` as a requirement. This is how Alchemy models "this code can only run inside a deployed Function/Worker" at the type level — analogous to a colored function.
- **Outer Effect** (the `bind(resource)` setup) runs at the Function's init phase. It does NOT require `RuntimeContext`.
- **Inner Effect** (the actual SDK invocation) only makes sense inside a running Function. It MUST require `RuntimeContext`.
- Resolve cloud-environment services (`WorkerEnvironment`, AWS SDK clients, etc.) once during Layer construction and close over them. Do NOT leak `WorkerEnvironment` / `Lambda.FunctionEnvironment` onto the runtime callable — that couples downstream service code to a specific cloud and breaks Layer encapsulation. The Function/Worker runtime satisfies `RuntimeContext` automatically.
- The implementation can return `Effect.Effect<A, E>` without explicitly providing `RuntimeContext` (it's contravariant in `R`); just declare it on the interface.
Why this matters: consumers can build cloud-agnostic services on top of bindings using `Layer.effect(Tag, ...)` without polluting their service interface with `WorkerEnvironment`. See [Layers concept](./website/src/content/docs/concepts/layers.mdx).
After implementing, register the Policy in `AWS.providers()()`:
- Add the `*PolicyLive` layer to `bindings()` in [Providers.ts](./packages/alchemy/src/AWS/Providers.ts)
- Re-export from the service's `index.ts`
:::tip
If you need to know what AWS region or account ID the resource is being created/updated in, you can use this inside any of the lifecycle operations.
```ts
constregion=yield*Region;
constaccount=yield*Account;
```
:::
:::warning
You should favor getting the region/account INSIDE the lifecycle operations instead of inside the Layer effect like this because then it's scoped to the resource isntead of the resource provider:
Do not use `Effect.orDie` in the lifecycle operations since this will crash the whole IaC engine.
:::
:::warning
**Never use `async`/`await`, raw `Promise`, `node:fs/promises`, `node:fs`, `node:os`, or `pathe` directly in resource code.** Always use the Effect platform services so that effects remain composable, traceable, retryable, and testable:
Sync, CPU-only Node APIs (e.g. `crypto.createHash().update().digest()`, `process.cwd()`, `Buffer`, `TextEncoder`) must still be wrapped in `Effect.sync(() => ...)` (or `Effect.try` if they can throw) so the call participates in the Effect runtime — tracing, interruption, and error channels. Don't call them as bare expressions inside `Effect.gen`.
This applies to **lifecycle operations, helpers, AND tests**. Tests must use `FileSystem.FileSystem`/`Path.Path` for any file/path access (see [Database.test.ts](./packages/alchemy/test/Cloudflare/D1/Database.test.ts) for the pattern).
:::
:::tip
If a Resource supports tags, you should always include the internal Alchemy tags to brand the resource with the app, stage and logical ID so that we can "know" that we created it and are responsible for it.
Do not roll your own tag diffing logic, always use `diffTags` from [Tags.ts](./packages/alchemy/src/Tags.ts), and diff against **observed cloud tags** (not `olds.tags` or `output.tags`). Adoption can hand you a resource whose tags don't match what we last persisted.
// Option 3. use `upsert` only if the API doesn't expect you to remove tags (only PUT/UPDATe)
const{upsert}=diffTags(oldTags,newTags);
```
:::
9. Implement the test cases in `packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts`.
Read through the established test cases before continuing so that you understand the pattern and structure of the test cases.
- [S3 Bucket Test Cases](./test/AWS/S3/Bucket.test.ts)
- [SQS Queue Test Cases](./test/AWS/SQS/Queue.test.ts)
- [Lambda Function Test Cases](./test/AWS/Lambda/Function.test.ts)
- [Kinesis Stream Test Cases](./test/AWS/Kinesis/Stream.test.ts)
- [DynamoDB Table Test Cases](./test/AWS/DynamoDB/Table.test.ts)
- [VPC Test Cases](./test/AWS/EC2/Vpc.test.ts)
- [Subnet Test Cases](./test/AWS/EC2/Subnet.test.ts)
:::warning
Never use `Date.now()` when constructing the physical name of a resource. You should either:
1. Do not proide a name and rely on the resource provider to generate a unique name for you from the app, stage and logical ID.
2. Construct a deterministic one unique to each test case. But it should be the same on each subsequent run of the test case.
:::
3. Consider implementing an aggregate Smoke test that brings together multiple resources that are often used together.
See the [VPC Smoke Test](./test/AWS/EC2/Vpc.smoke.test.ts) for an example.
11. Add the resource-level JSDoc (`@section` + `@example` blocks) and field-level JSDoc on each prop/attribute on the source `.ts` file. Then run `bun generate:api-reference` to refresh `website/src/content/docs/providers/{Cloud}/{Resource}.md`. Do NOT manually edit the generated markdown.
# Test Fixtures for Effect-Native Workers / Functions
To test runtime behavior of an Effect-native Worker, Workflow, Lambda, etc., write a **fixture** that defines the Worker/Function with the bindings under test and exposes one HTTP route per behavior, then write a **test** that deploys the fixture once via `beforeAll` and drives it over HTTP.
## File system layout
Put fixtures in a `fixtures/` directory next to the test file. Each test suite owns its own fixtures — never reach across suites:
Compose a `Stack` that deploys the fixture, share one deploy across the file with `beforeAll`/`afterAll`, drive it via `HttpClient`, and retry the first request through edge propagation:
-`beforeAll(deploy(Stack))` returns a handle (`stack` above) that every `test` body can `yield*` to get the stack outputs.
-`afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack))` is the standard cleanup — set `NO_DESTROY=1` locally to keep the deployment around between runs while iterating.
- Always retry the first request (`Schedule.exponential("500 millis")`) — fresh workers.dev URLs and Lambda function URLs take a few seconds to start serving 200s.
- For POST: use `client.post(url)` for empty bodies, or `HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)))` for typed bodies.
- **Never use `while (Date.now() < deadline)` loops to poll** for an async side effect (a workflow status, a cron fire, a queue drain, eventual-consistency read, etc.). Use `Effect.repeat` with a `Schedule` and an `until` predicate so the polling participates in the Effect runtime — tracing, interruption, and error propagation work correctly, and the intent is declarative. Cap iterations with `times: N` (or a bounded schedule) so the test fails fast instead of running until the vitest timeout:
```ts
// good — declarative, bounded, interruption-safe
const value = yield* fetchValue.pipe(
Effect.repeat({
schedule: Schedule.spaced("5 seconds"),
until: (v) => v.ready,
times: 36,
}),
);
// bad — opaque loop, ignores interruption, leaks into vitest timeout
let value: Value | undefined;
const deadline = Date.now() + 180_000;
while (Date.now() < deadline) {
value = yield* fetchValue;
if (value.ready) break;
yield* Effect.sleep("5 seconds");
}
```
See [CronEventSource.test.ts](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) for a real-world example (polling a DO via the worker's `/times` route until the cron handler fires).
## Reference implementations
- Cloudflare AiGateway — [worker fixture](./packages/alchemy/test/Cloudflare/AiGateway/worker.ts) + [test](./packages/alchemy/test/Cloudflare/AiGateway/AiGateway.test.ts) (the deploy+fetch case lives at the bottom of the file)
- Cloudflare Cron Trigger — [worker + DO fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/cron-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) (cron handler writes to a DO; test polls a fetch route with `Effect.repeat` until the scheduled handler fires)
- AWS Lambda (DynamoDB bindings) — [Lambda fixture](./packages/alchemy/test/AWS/DynamoDB/handler.ts) + [test](./packages/alchemy/test/AWS/DynamoDB/Bindings.test.ts) (one `describe("<BindingName>")` per binding, all driving the same deployed Lambda)
# Spec-Driven Service Bring-Up
Use @processes/AWS.md as the source of truth for bringing a single AWS service from zero to full coverage.
That process covers:
- deriving resources, bindings, event sources, and helpers from distilled
- the audit-driven implementation loop
- deterministic checks for registration and binding test coverage
- Lambda fixture testing conventions
- learned conventions like no auto-marshalling and one `describe("<BindingName>")` block per binding
Keep `AGENTS.md` high-level and update @processes/AWS.md when the process evolves.
When a canonical resource needs mutable event-source configuration and there is any chance of circularity, prefer a resource binding contract over a plain input prop. DynamoDB Streams is the reference case: `Table` owns the actual stream state, while `streams(table)` injects that state via bindings and the runtime-specific layer handles the subscription mechanics. See @processes/AWS.md for the DynamoDB Streams case study.
# Build and Type Checking
Always run type checking before committing changes:
```bash
bun tsc -b
```
This runs the TypeScript compiler in build mode, which checks all projects in the workspace. This is critical because CI will fail if there are type errors.
Tutorials under `website/src/content/docs/tutorial/` are **step-by-step and granular**: every code snippet introduces exactly **one** new thing, followed by a short prose explanation of just that thing. Each step gets its own `##` heading.
**Anti-pattern** — one snippet that adds multiple distinct changes, followed by a numbered list or bullet list explaining each:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
+import { HttpServerRequest } from "...";
Effect.gen(function* () {
+ const counters = yield* Counter;
return {
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
}),
};
})
```
Two things just happened:
1. `yield* Counter` registers the DO ...
2. `counters.getByName(name)` returns a typed stub ...
````
**Correct** — split into one heading per step, each with one snippet and one explanation:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
Effect.gen(function* () {
+ const counters = yield* Counter;
...
})
```
`yield* Counter` registers the DO with the Worker (binding + class-migration metadata) and hands you the namespace.
## Call the DO from `fetch`
```diff lang="typescript"
+import { HttpServerRequest } from "...";
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
})
```
`counters.getByName(name)` returns a typed stub — `increment()` and `get()` round-trip through Cloudflare's RPC machinery.
````
Rules of thumb:
- If you find yourself writing "Two/three things just happened", "A few things are happening here", or a numbered/bulleted list explaining separate parts of a single snippet — **split the snippet**.
- One concept ⇒ one heading ⇒ one diff snippet ⇒ one explanation paragraph (no bullets).
- Bullet/numbered lists are fine when they describe a recap, prerequisites, or genuinely list-shaped content (e.g. "the Worker now handles two routes: PUT and GET" at the end). They are **not** fine as a substitute for splitting a compound snippet.
- A single API call that internally does several things (e.g. `Cloudflare.upgrade()`) doesn't need splitting — describe its behavior in prose.
- Use `diff lang="typescript"` blocks so each step shows what's added on top of the previous step.
# Pull Request Conventions
When you automatically open a PR, it MUST follow this structure:
- **Title**: Use conventional commit format (e.g. `fix(website): mobile theme metas`, `feat(aws/s3): add bucket lifecycle rules`).
- **Description heading levels**: NEVER use `#` or `##` in the PR description. The smallest heading allowed is `###`. The PR description must NOT begin with its own title heading — GitHub already renders the PR title above it.
- **Content**: Aim for the minimal content needed to convey the idea.
- Use simple sentences. If there are multiple discrete changes, use bullet points.
- **Prefer code snippets over prose.** A short ` ```ts ` or ` ```diff ` block showing the new/changed shape is worth more than a paragraph explaining it. Reach for code first; only add prose to fill in the "why" the snippet can't show on its own.
- Be direct and succinct. Cut adjectives, justifications, and anything that reads like marketing copy. If a sentence is restating what the diff already shows, delete it.
- **Never include a "Test plan", "Testing", or checklist of TODOs.** PR descriptions document the change, not the verification process. If something needs manual verification, follow the draft-PR rule below.
- Skip examples for trivial fixes, internal refactors, or doc-only changes.
Example PR description (good — code snippet does the talking):
````
Track which state-store backend each project uses by emitting a `state_store.init` span tagged with `alchemy.state_store.kind`.
```ts
// every Layer.effect(State, …) site now wraps construction:
Dashboard groups projects by kind from these spans (Axiom can't APL-query metric datasets).
````
- **Outstanding work / testing / review needed**: If there are outstanding steps, manual testing required, or review items, DO NOT leave a comment on the PR and DO NOT include them in the PR description. Instead:
1. Mark the PR as **draft**.
2. Tell the user (in the chat that initiated the PR creation) what is outstanding.
:::warning
**Markdown content must reach GitHub verbatim** — un-escaped backticks, fenced code blocks, etc. The reliable shape is to write the description to a file and pass `--body-file <path>` to `gh pr create` / `gh pr edit`:
```sh
# write the body to a temp file (use Write tool, not echo/cat heredoc)
gh pr edit 179 --body-file /tmp/pr-body.md
```
Do **not** inline the body via `--body "$(cat <<'EOF' ... EOF)"`. Even with a single-quoted heredoc some shells / `gh` versions still mangle backticks and backslashes; the resulting PR body ends up with literal `\`` sequences instead of inline code spans. `--body-file` sidesteps shell quoting entirely.
If you need to update an already-created PR's body, prefer `gh pr edit --body-file ...`. If that silently no-ops (older `gh` versions), fall back to `gh api -X PATCH repos/<owner>/<repo>/pulls/<n> -F body=@/tmp/pr-body.md`.
:::
The summary goes at the very top of the description as plain prose — NO heading above it, no `### Summary`, nothing. The PR title already serves as the title; do not repeat or re-title it. Only add `###` subheadings further down if the description genuinely has multiple sections worth separating.
Example PR description (good):
```
Persist the user's selected theme across reloads and fix a hero scroll glitch on mobile.
- Read theme from `localStorage` on mount before first paint
- Add `<meta name="theme-color">` per theme so mobile chrome matches
```
Example PR description (BAD — do not do this):
```
## Theme persistence fix ← no, the PR title already exists
accessSummary: Output.interpolate`Granted cluster-admin access on ${cluster.cluster.clusterName} to ${clusterAdmin.principalArn}.`,
workloadSummary: Output.interpolate`Demo workloads are declared in TypeScript and reconciled into namespace ${demoNamespace.name} on ${cluster.cluster.clusterName}.`,
Loaded 100 of 5646 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.