Skip to content

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

Implement server auth bootstrap and pairing flow (#1768)

Julius Marmingeb7559c467803
diff --git a/.docs/remote-architecture.md b/.docs/remote-architecture.md
new file mode 100644
index 000000000..32e35d7ca
--- /dev/null
+++ b/.docs/remote-architecture.md
@@ -0,0 +1,302 @@
+# Remote Architecture
+
+This document describes the target architecture for first-class remote environments in T3 Code.
+
+It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
+
+## Goals
+
+- Treat remote environments as first-class product primitives, not special cases.
+- Support multiple ways to reach the same environment.
+- Keep the T3 server as the execution boundary.
+- Let desktop, mobile, and web all share the same conceptual model.
+- Avoid introducing a local control plane unless product pressure proves it is necessary.
+
+## Non-goals
+
+- Replacing the existing WebSocket server boundary with a custom transport protocol.
+- Making SSH the only remote story.
+- Syncing provider auth across machines.
+- Shipping every access method in the first iteration.
+
+## High-level architecture
+
+T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
+
+Remote support should preserve that boundary.
+
+```text
+┌──────────────────────────────────────────────┐
+│ Client (desktop / mobile / web) │
+│ │
+│ - known environments │
+│ - connection manager │
+│ - environment-aware routing │
+└───────────────┬──────────────────────────────┘
+ │
+ │ resolves one access endpoint
+ │
+┌───────────────▼──────────────────────────────┐
+│ Access method │
+│ │
+│ - direct ws / wss │
+│ - tunneled ws / wss │
+│ - desktop-managed ssh bootstrap + forward │
+└───────────────┬──────────────────────────────┘
+ │
+ │ connects to one T3 server
+ │
+┌───────────────▼──────────────────────────────┐
+│ Execution environment = one T3 server │
+│ │
+│ - environment identity │
+│ - provider state │
+│ - projects / threads / terminals │
+│ - git / filesystem / process runtime │
+└──────────────────────────────────────────────┘
+```
+
+The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
+
+## Domain model
+
+### ExecutionEnvironment
+
+An `ExecutionEnvironment` is one running T3 server instance.
+
+It is the unit that owns:
+
+- provider availability and auth state
+- model availability
+- projects and threads
+- terminal processes
+- filesystem access
+- git operations
+- server settings
+
+It is identified by a stable `environmentId`.
+
+This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
+
+### KnownEnvironment
+
+A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
+
+It is not server-authored. It is local to a device or client profile.
+
+Examples:
+
+- a saved LAN URL
+- a saved public `wss://` endpoint
+- a desktop-managed SSH host entry
+- a saved tunneled environment
+
+A known environment may or may not know the target `environmentId` before first successful connect.
+
+### AccessEndpoint
+
+An `AccessEndpoint` is one concrete way to reach a known environment.
+
+This is the key abstraction that keeps SSH from taking over the model.
+
+A single environment may have many endpoints:
+
+- `wss://t3.example.com`
+- `ws://10.0.0.25:3773`
+- a tunneled relay URL
+- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
+
+The environment stays the same. Only the access path changes.
+
+### RepositoryIdentity
+
+`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
+
+It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
+
+### Workspace / Project
+
+The current `Project` model remains environment-local.
+
+That means:
+
+- a local clone and a remote clone are different projects
+- they may share a `RepositoryIdentity`
+- threads still bind to one project in one environment
+
+## Access methods
+
+Access methods answer one question:
+
+How does the client speak WebSocket to a T3 server?
+
+They do not answer:
+
+- how the server got started
+- who manages the server process
+- whether the environment is local or remote
+
+### 1. Direct WebSocket access
+
+Examples:
+
+- `ws://10.0.0.15:3773`
+- `wss://t3.example.com`
+
+This is the base model and should be the first-class default.
+
+Benefits:
+
+- works for desktop, mobile, and web
+- no client-specific process management required
+- best fit for hosted or self-managed remote T3 deployments
+
+### 2. Tunneled WebSocket access
+
+Examples:
+
+- public relay URLs
+- private network relay URLs
+- local tunnel products such as pipenet
+
+This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
+
+For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
+
+This is especially useful when:
+
+- the host is behind NAT
+- inbound ports are unavailable
+- mobile must reach a desktop-hosted environment
+- a machine should be reachable without exposing raw LAN or public ports
+
+### 3. Desktop-managed SSH access
+
+SSH is an access and launch helper, not a separate environment type.
+
+The desktop main process can use SSH to:
+
+- reach a machine
+- probe it
+- launch or reuse a remote T3 server
+- establish a local port forward
+
+After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
+
+This keeps the renderer transport model consistent with every other access method.
+
+## Launch methods
+
+Launch methods answer a different question:
+
+How does a T3 server come to exist on the target machine?
+
+Launch and access should stay separate in the design.
+
+### 1. Pre-existing server
+
+The simplest launch method is no launch at all.
+
+The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
+
+This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
+
+### 2. Desktop-managed remote launch over SSH
+
+This is the main place where Zed is a useful reference.
+
+Useful ideas to borrow from Zed:
+
+- remote probing
+- platform detection
+- session directories with pid/log metadata
+- reconnect-friendly launcher behavior
+- desktop-owned connection UX
+
+What should be different in T3:
+
+- no custom stdio/socket proxy protocol between renderer and remote runtime
+- no attempt to make the remote runtime look like an editor transport
+- keep the final client-to-server connection as WebSocket
+
+The recommended T3 flow is:
+
+1. Desktop connects over SSH.
+2. Desktop probes the remote machine and verifies T3 availability.
+3. Desktop launches or reuses a remote T3 server.
+4. Desktop establishes local port forwarding.
+5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
+
+### 3. Client-managed local publish
+
+This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
+
+This is useful for:
+
+- exposing a desktop-hosted environment to mobile
+- temporary remote access without changing router or firewall settings
+
+This is still a launch concern, not a new environment kind.
+
+## Why access and launch must stay separate
+
+These concerns are easy to conflate, but separating them prevents architectural drift.
+
+Examples:
+
+- A manually hosted T3 server might be reached through direct `wss`.
+- The same server might also be reachable through a tunnel.
+- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
+- A local desktop server might be published through a tunnel for mobile.
+
+In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
+
+Only the launch and access paths differ.
+
+## Security model
+
+Remote support must assume that some environments will be reachable over untrusted networks.
+
+That means:
+
+- remote-capable environments should require explicit authentication
+- tunnel exposure should not rely on obscurity
+- client-saved endpoints should carry enough auth metadata to reconnect safely
+
+T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
+
+For publicly reachable environments, authenticated access should be treated as required.
+
+## Relationship to Zed
+
+Zed is a useful reference implementation for managed remote launch and reconnect behavior.
+
+The relevant lessons are:
+
+- remote bootstrap should be explicit
+- reconnect should be first-class
+- connection UX belongs in the client shell
+- runtime ownership should stay clearly on the remote host
+
+The important mismatch is transport shape.
+
+Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
+
+T3 should not copy that part.
+
+T3 already has the right runtime boundary:
+
+- one T3 server per environment
+- ordinary HTTP/WebSocket between client and environment
+
+So T3 should borrow Zed's launch discipline, not its transport protocol.
+
+## Recommended rollout
+
+1. First-class known environments and access endpoints.
+2. Direct `ws` / `wss` remote environments.
+3. Authenticated tunnel-backed environments.
+4. Desktop-managed SSH launch and forwarding.
+5. Multi-environment UI improvements after the base runtime path is proven.
+
+This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f521ced14..5c2d2c838 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -72,7 +72,7 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
- grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
+ grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index a3e32c979..776d11b80 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -9,7 +9,8 @@
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
- "apps/web/public/mockServiceWorker.js"
+ "apps/web/public/mockServiceWorker.js",
+ "apps/web/src/lib/vendor/qrcodegen.ts"
],
"sortPackageJson": {}
}
diff --git a/.plans/18-server-auth-model.md b/.plans/18-server-auth-model.md
new file mode 100644
index 000000000..9f8ba8a05
--- /dev/null
+++ b/.plans/18-server-auth-model.md
@@ -0,0 +1,823 @@
+# Server Auth Model Plan
+
+## Purpose
+
+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.
+
+Safe default expectations:
+
+- local desktop-managed: auto-pair allowed
+- loopback browser access: explicit bootstrap allowed
+- non-loopback bind: auth required
+- tunnel/public endpoint: auth required, explicit enablement required
+
+### 5. Browser and native clients may use different session credentials
+
+The auth model should support more than one session credential type even if only one ships first.
+
+Examples:
+
+- browser session cookie
+- native bearer/device token
+
+This should be represented in the model now, even if browser cookies are the first implementation.
+
+## Target auth domain
+
+### Route classes
+
+Every route or transport entrypoint should be classified as one of:
+
+1. `public`
+2. `bootstrap`
+3. `authenticated`
+
+#### `public`
+
+Unauthenticated by definition.
+
+Should be extremely small. Examples:
+
+- static shell needed to render the pairing/login UI
+- favicon/assets required for the pairing screen
+- a minimal server health/version endpoint if needed
+
+#### `bootstrap`
+
+Used only to exchange a bootstrap credential for a session.
+
+Examples:
+
+- Initial bootstrap envelope over file descriptor at startup
+- `POST /api/auth/bootstrap`
+- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
+
+#### `authenticated`
+
+Everything that reveals machine state or mutates it.
+
+Examples:
+
+- WebSocket upgrade
+- orchestration snapshot and events
+- terminal open/write/close
+- project search and file writes
+- git routes
+- attachments
+- project favicon lookup
+- server settings
+
+The default stance should be: if it touches the machine, it is authenticated.
+
+## Credential model
+
+### Bootstrap credentials
+
+Initial credential types to model:
+
+- `desktop-bootstrap`
+- `one-time-token`
+
+Possible future credential types:
+
+- `device-code`
+- `passkey-assertion`
+- `external-identity`
+
+#### `desktop-bootstrap`
+
+Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
+
+Properties:
+
+- launcher-provided
+- short-lived
+- one-time or bounded-use
+- never shown to the user as a reusable password
+
+#### `one-time-token`
+
+Used for explicit browser/mobile pairing flows.
+
+Properties:
+
+- short TTL
+- one-time use
+- safe to embed in a pairing URL fragment
+- exchanged for a session credential
+
+### Session credentials
+
+Initial credential types to model:
+
+- `browser-session-cookie`
+- `bearer-session-token`
+
+#### `browser-session-cookie`
+
+Primary browser credential.
+
+Properties:
+
+- signed
+- `HttpOnly`
+- bounded lifetime
+- revocable by server key rotation or session invalidation
+
+#### `bearer-session-token`
+
+Reserved for native/mobile or non-browser clients.
+
+Properties:
+
+- opaque token, not a bootstrap secret
+- long enough lifetime to survive reconnects
+- stored in secure client storage when available
+
+## Auth policy model
+
+Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
+
+### Policy examples
+
+#### `DesktopManagedLocalPolicy`
+
+Default for desktop-managed local server.
+
+Allowed bootstrap methods:
+
+- `desktop-bootstrap`
+
+Allowed session methods:
+
+- `browser-session-cookie`
+
+Disabled by default:
+
+- `one-time-token`
+- `bearer-session-token`
+- password login
+- public pairing
+
+#### `LoopbackBrowserPolicy`
+
+Used for browser access on localhost without desktop-managed bootstrap.
+
+Allowed bootstrap methods:
+
+- `one-time-token`
+
+Allowed session methods:
+
+- `browser-session-cookie`
+
+#### `RemoteReachablePolicy`
+
+Used when binding non-loopback or using an explicit remote/tunnel workflow.
+
+Allowed bootstrap methods:
+
+- `one-time-token`
+- possibly `desktop-bootstrap` when a desktop shell is brokering access
+
+Allowed session methods:
+
+- `browser-session-cookie`
+- `bearer-session-token`
+
+#### `UnsafeNoAuthPolicy`
+
+Should exist only as an explicit escape hatch.
+
+Requirements:
+
+- explicit opt-in flag
+- loud startup warnings
+- never defaulted automatically
+
+## Effect-native service model
+
+### `ServerAuth`
+
+The main auth facade used by HTTP routes and WebSocket upgrade handling.
+
+Responsibilities:
+
+- classify requests
+- authenticate requests
+- authorize bootstrap attempts
+- create sessions from bootstrap credentials
+- enforce policy by environment mode
+
+Sketch:
+
+```ts
+export interface ServerAuthShape {
+ readonly getCapabilities: Effect.Effect<AuthCapabilities>;
+ readonly authenticateHttpRequest: (
+ request: HttpServerRequest.HttpServerRequest,
+ routeClass: RouteAuthClass,
+ ) => Effect.Effect<AuthContext, AuthError>;
+ readonly authenticateWebSocketUpgrade: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthContext, AuthError>;
+ readonly exchangeBootstrapCredential: (
+ input: BootstrapExchangeInput,
+ ) => Effect.Effect<SessionGrant, AuthError>;
+}
+
+export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
+ "t3/ServerAuth",
+) {}
+```
+
+### `BootstrapCredentialService`
+
+Owns issuance, storage, validation, and consumption of bootstrap credentials.
+
+Responsibilities:
+
+- issue desktop bootstrap grants
+- issue one-time pairing tokens
+- validate TTL and single-use semantics
+- consume bootstrap grants atomically
+
+Sketch:
+
+```ts
+export interface BootstrapCredentialServiceShape {
+ readonly issueDesktopBootstrap: (
+ input: IssueDesktopBootstrapInput,
+ ) => Effect.Effect<BootstrapCredential>;
+ readonly issueOneTimeToken: (
+ input: IssueOneTimeTokenInput,
+ ) => Effect.Effect<BootstrapCredential>;
+ readonly consume: (
+ presented: PresentedBootstrapCredential,
+ ) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
+}
+```
+
+### `SessionCredentialService`
+
+Owns creation and validation of authenticated sessions.
+
+Responsibilities:
+
+- mint cookie sessions
+- mint bearer sessions
+- validate active session credentials
+- revoke sessions if needed later
+
+Sketch:
+
+```ts
+export interface SessionCredentialServiceShape {
+ readonly createBrowserSession: (
+ input: CreateSessionFromBootstrapInput,
+ ) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
+ readonly createBearerSession: (
+ input: CreateSessionFromBootstrapInput,
+ ) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
+ readonly authenticateCookie: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthContext, SessionCredentialError>;
+ readonly authenticateBearer: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthContext, SessionCredentialError>;
+}
+```
+
+### `ServerAuthPolicy`
+
+Pure policy/config service that decides which credential types are allowed.
+
+Responsibilities:
+
+- map runtime mode and bind/exposure settings to allowed auth methods
+- answer whether a route can be public
+- answer whether remote exposure requires auth
+
+This should stay mostly pure and cheap to test.
+
+### `ServerSecretStore`
+
+Owns long-lived server signing keys and secrets.
+
+Responsibilities:
+
+- get or create signing key
+- rotate signing key
+- abstract secure OS-backed storage vs filesystem fallback
+
+Important:
+
+- prefer platform secure storage when available
+- support hardened filesystem fallback for headless/server-only environments
+
+### `BrowserSessionCookieCodec`
+
+Focused utility service for cookie encode/decode/signing behavior.
+
+This should not own policy. It should only own the cookie format.
+
+### `AuthRouteGuards`
+
+Thin helper layer used by routes to enforce auth consistently.
+
+Responsibilities:
+
+- require auth for HTTP route handlers
+- classify route auth mode
+- convert auth failures into `401` / `403`
+
+This prevents every route from re-implementing the same pattern.
+
+Integrates with `HttpRouter.middleware` to enforce auth consistently.
+
+## Suggested layer graph
+
+```text
+ServerSecretStore
+ ├─> BootstrapCredentialService
+ ├─> BrowserSessionCookieCodec
+ └─> SessionCredentialService
+
+ServerAuthPolicy
+ ├─> BootstrapCredentialService
+ ├─> SessionCredentialService
+ └─> ServerAuth
+
+ServerAuth
+ └─> AuthRouteGuards
+```
+
+Layer naming should follow existing repo style:
+
+- `ServerSecretStoreLive`
+- `BootstrapCredentialServiceLive`
+- `SessionCredentialServiceLive`
+- `ServerAuthPolicyLive`
+- `ServerAuthLive`
+- `AuthRouteGuardsLive`
+
+## High-level implementation examples
+
+### Example: WebSocket upgrade auth
+
+Current state:
+
+- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
+
+Target shape:
+
+```ts
+const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ yield* serverAuth.authenticateWebSocketUpgrade(request);
+ return yield* httpApp;
+ }),
+);
+```
+
+Then the `/ws` route becomes:
+
+```ts
+export const websocketRpcRouteLayer = HttpRouter.add(
+ "GET",
+ "/ws",
+ rpcWebSocketHttpEffect.pipe(
+ websocketUpgradeAuth,
+ Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
+ ),
+);
+```
+
+This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
+
+### Example: authenticated HTTP route
+
+For routes like attachments or project favicon:
+
+```ts
+const authenticatedRoute = (routeClass: RouteAuthClass) =>
+ HttpMiddleware.make((httpApp) =>
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ yield* serverAuth.authenticateHttpRequest(request, routeClass);
+ return yield* httpApp;
+ }),
+ );
+```
+
+Then:
+
+```ts
+export const attachmentsRouteLayer = HttpRouter.add(
+ "GET",
+ `${ATTACHMENTS_ROUTE_PREFIX}/*`,
+ serveAttachment.pipe(
+ authenticatedRoute(RouteAuthClass.Authenticated),
+ Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
+ ),
+);
+```
+
+### Example: desktop bootstrap exchange
+
+The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
+
+That grant is then exchanged for a browser cookie session when the renderer loads.
+
+Sketch:
+
+```ts
+const pairDesktopRenderer = Effect.gen(function* () {
+ const bootstrapService = yield* BootstrapCredentialService;
+ const credential = yield* bootstrapService.issueDesktopBootstrap({
+ audience: "desktop-renderer",
+ ttlMs: 30_000,
+ });
+ return credential;
+});
+```
+
+The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
+
+### Example: one-time pairing URL
+
+For browser-driven pairing:
+
+```ts
+const createPairingToken = Effect.gen(function* () {
+ const bootstrapService = yield* BootstrapCredentialService;
+ return yield* bootstrapService.issueOneTimeToken({
+ ttlMs: 5 * 60_000,
+ audience: "browser",
+ });
+});
+```
+
+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.
+
+```text
+Participants:
+ DesktopMain = Electron main
+ SecretStore = secure local secret backend
+ T3Server = local backend child process
+ Frontend = desktop renderer
+
+DesktopMain -> SecretStore : getOrCreate("server-signing-key")
+SecretStore --> DesktopMain : signing key available
+
+DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
+DesktopMain -> T3Server : send desktop bootstrap envelope
+note over T3Server : policy = DesktopManagedLocalPolicy
+note over T3Server : allowed pairing = desktop-bootstrap only
+
+Frontend -> DesktopMain : request local bootstrap grant
+DesktopMain --> Frontend : short-lived desktop bootstrap grant
+
+Frontend -> T3Server : POST /api/auth/bootstrap
+T3Server -> T3Server : validate desktop bootstrap grant
+T3Server -> T3Server : create browser session
+T3Server --> Frontend : Set-Cookie: session=...
+
+Frontend -> T3Server : GET /ws + authenticated cookie
+T3Server -> T3Server : validate cookie session
+T3Server --> Frontend : websocket accepted
+```
+
+### `npx t3` user
+
+This is the standalone local server flow.
+
+There is no trusted desktop shell here, so pairing should be explicit.
+
+```text
+Participants:
+ UserShell = npx t3 launcher
+ T3Server = standalone local server
+ Browser = browser tab
+
+UserShell -> T3Server : start server
+T3Server -> T3Server : getOrCreate("server-signing-key")
+note over T3Server : policy = LoopbackBrowserPolicy
+
+UserShell -> T3Server : issue one-time pairing token
+T3Server --> UserShell : pairing URL or pairing token
+
+UserShell --> Browser : open /pair?token=...
+
+Browser -> T3Server : GET /pair?token=...
+T3Server -> T3Server : validate one-time token
+T3Server -> T3Server : create browser session
+T3Server --> Browser : Set-Cookie: session=...
+T3Server --> Browser : redirect to app
+
+Browser -> T3Server : GET /ws + authenticated cookie
+T3Server --> Browser : websocket accepted
+```
+
+### Phone user with tunneled host
+
+This is the explicit remote access flow for a browser on another device.
+
+The tunnel only provides reachability. It must not imply trust.
+
+Recommended UX:
+
+- desktop shows a QR code
+- desktop also shows a copyable pairing URL
+- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
+
+```text
+Participants:
+ DesktopUser = user at the host machine
+ DesktopMain = desktop app
+ Tunnel = tunnel provider
+ T3Server = T3 server
+ PhoneBrowser = mobile browser
+
+DesktopUser -> DesktopMain : enable remote access via tunnel
+DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
+DesktopMain -> Tunnel : publish local T3 endpoint
+Tunnel --> DesktopMain : public https/wss URL
+
+DesktopMain -> T3Server : issue one-time pairing token
+T3Server --> DesktopMain : pairing token
+DesktopMain -> DesktopUser : show QR code / shareable URL
+
+DesktopUser -> PhoneBrowser : scan QR / open URL
+PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
+Tunnel -> T3Server : forward request
+T3Server -> T3Server : validate one-time token
+T3Server -> T3Server : create mobile browser session
+T3Server --> PhoneBrowser : Set-Cookie: session=...
+T3Server --> PhoneBrowser : redirect to app
+
+PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
+Tunnel -> T3Server : forward websocket upgrade
+T3Server --> PhoneBrowser : websocket accepted
+```
+
+### Phone user with private network
+
+This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
+
+The auth flow should stay the same.
+
+```text
+Participants:
+ DesktopUser = user at the host machine
+ T3Server = T3 server
+ PrivateNet = tailscale / private LAN
+ PhoneBrowser = mobile browser
+
+DesktopUser -> T3Server : enable private-network access
+T3Server -> T3Server : switch policy to RemoteReachablePolicy
+DesktopUser -> T3Server : issue one-time pairing token
+T3Server --> DesktopUser : pairing URL / QR
+
+DesktopUser -> PhoneBrowser : open private-network URL
+PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
+PrivateNet -> T3Server : route request
+T3Server -> T3Server : validate one-time token
+T3Server -> T3Server : create mobile browser session
+T3Server --> PhoneBrowser : Set-Cookie: session=...
+T3Server --> PhoneBrowser : redirect to app
+
+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
+RemoteHost --> SSH : launch result JSON
+SSH --> DesktopMain : remote server details
+
+DesktopMain -> SSH : establish local port forward
+SSH --> DesktopMain : localhost:FORWARDED_PORT ready
+
+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.
+4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
+
+## What to defer
+
+- passkeys / WebAuthn
+- iCloud Keychain / Face ID-specific UX
+- multi-user permissions
+- collaboration roles
+- OAuth / SSO
+- polished session management UI
+- complex device approval flows
+
+These can all sit on top of the same bootstrap/session/service split.
+
+## Relationship to future remote environments
+
+Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
+
+Keep the design focused on:
+
+- one T3 server
+- one auth policy
+- multiple credential types
+- multiple future access methods
+
+That keeps the server auth model stable even as access methods expand later.
+
+## Recommended implementation order
+
+### Phase 1
+
+- Introduce route auth classes.
+- Add `ServerAuth` and `AuthRouteGuards`.
+- Move existing `authToken` check behind `ServerAuth`.
+- Require auth for all privileged HTTP routes as well as WebSocket.
+
+### Phase 2
+
+- Add `ServerSecretStore` service with platform-specific layer implementations.
+ - `layerOSXKeychain`, `layer
+- Add bootstrap/session split.
+- Add browser session cookie support.
+- Add one-time bootstrap exchange endpoint.
+
+### Phase 3
+
+- Add desktop bootstrap flow on top of the same services.
+- Make desktop-managed local environments default to bootstrap-only pairing.
+- Surface auth capabilities in shared contracts and renderer bootstrap.
+
+### Phase 4
+
+- Add non-browser bearer session support if mobile/native needs it.
+- Add richer policy modes for remote-reachable environments.
+
+## Acceptance criteria
+
+- No privileged HTTP or WebSocket path bypasses auth policy.
+- Local desktop-managed flows still avoid a visible login screen.
+- Non-loopback or published environments require explicit authenticated pairing by default.
+- Bootstrap and session credentials are distinct in code and in behavior.
+- Auth logic is centralized in Effect services/layers rather than route-local branching.
diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs
index 5244d51db..7c0d55ac9 100644
--- a/apps/desktop/scripts/dev-electron.mjs
+++ b/apps/desktop/scripts/dev-electron.mjs
@@ -5,8 +5,17 @@ import { join } from "node:path";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
-const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
-const devServerUrl = `http://localhost:${port}`;
+const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
+if (!devServerUrl) {
+ throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
+}
+
+const devServer = new URL(devServerUrl);
+const port = Number.parseInt(devServer.port, 10);
+if (!Number.isInteger(port) || port <= 0) {
+ throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
+}
+
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
@@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200;
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
+ tcpHost: devServer.hostname,
tcpPort: port,
});
@@ -62,10 +72,7 @@ function startApp() {
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
- env: {
- ...childEnv,
- VITE_DEV_SERVER_URL: devServerUrl,
- },
+ env: childEnv,
stdio: "inherit",
},
);
diff --git a/apps/desktop/src/backendReadiness.test.ts b/apps/desktop/src/backendReadiness.test.ts
new file mode 100644
index 000000000..fd6180b5d
--- /dev/null
+++ b/apps/desktop/src/backendReadiness.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ BackendReadinessAbortedError,
+ isBackendReadinessAborted,
+ waitForHttpReady,
+} from "./backendReadiness";
+
+describe("waitForHttpReady", () => {
+ it("returns once the backend reports a successful session endpoint", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response(null, { status: 503 }))
+ .mockResolvedValueOnce(new Response(null, { status: 200 }));
+
+ await waitForHttpReady("http://127.0.0.1:3773", {
+ fetchImpl,
+ timeoutMs: 1_000,
+ intervalMs: 0,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+
+ it("retries after a readiness request stalls past the per-request timeout", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockImplementationOnce(
+ (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ "abort",
+ () => {
+ reject(new Error("request timed out"));
+ },
+ { once: true },
+ );
+ }) as ReturnType<typeof fetch>,
+ )
+ .mockResolvedValueOnce(new Response(null, { status: 200 }));
+
+ await waitForHttpReady("http://127.0.0.1:3773", {
+ fetchImpl,
+ timeoutMs: 100,
+ intervalMs: 0,
+ requestTimeoutMs: 1,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+
+ it("aborts an in-flight readiness wait", async () => {
+ const controller = new AbortController();
+ const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
+ () =>
+ new Promise((_resolve, reject) => {
+ controller.signal.addEventListener(
+ "abort",
+ () => {
+ reject(new BackendReadinessAbortedError());
+ },
+ { once: true },
+ );
+ }) as ReturnType<typeof fetch>,
+ );
+
+ const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
+ fetchImpl,
+ timeoutMs: 1_000,
+ intervalMs: 0,
+ signal: controller.signal,
+ });
+
+ controller.abort();
+
+ await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
+ });
+
+ it("recognizes aborted readiness errors", () => {
+ expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
+ expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/backendReadiness.ts b/apps/desktop/src/backendReadiness.ts
new file mode 100644
index 000000000..cd5a3c023
--- /dev/null
+++ b/apps/desktop/src/backendReadiness.ts
@@ -0,0 +1,103 @@
+export interface WaitForHttpReadyOptions {
+ readonly timeoutMs?: number;
+ readonly intervalMs?: number;
+ readonly requestTimeoutMs?: number;
+ readonly fetchImpl?: typeof fetch;
+ readonly signal?: AbortSignal;
+}
+
+const DEFAULT_TIMEOUT_MS = 10_000;
+const DEFAULT_INTERVAL_MS = 100;
+const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
+
+export class BackendReadinessAbortedError extends Error {
+ constructor() {
+ super("Backend readiness wait was aborted.");
+ this.name = "BackendReadinessAbortedError";
+ }
+}
+
+function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ cleanup();
+ resolve();
+ }, ms);
+
+ const onAbort = () => {
+ cleanup();
+ reject(new BackendReadinessAbortedError());
+ };
+
+ const cleanup = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ };
+
+ if (signal?.aborted) {
+ cleanup();
+ reject(new BackendReadinessAbortedError());
+ return;
+ }
+
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
+ return error instanceof BackendReadinessAbortedError;
+}
+
+export async function waitForHttpReady(
+ baseUrl: string,
+ options?: WaitForHttpReadyOptions,
+): Promise<void> {
+ const fetchImpl = options?.fetchImpl ?? fetch;
+ const signal = options?.signal;
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
+ const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
+ const deadline = Date.now() + timeoutMs;
+
+ for (;;) {
+ if (signal?.aborted) {
+ throw new BackendReadinessAbortedError();
+ }
+
+ const requestController = new AbortController();
+ const requestTimeout = setTimeout(() => {
+ requestController.abort();
+ }, requestTimeoutMs);
+ const abortRequest = () => {
+ requestController.abort();
+ };
+ signal?.addEventListener("abort", abortRequest, { once: true });
+
+ try {
+ const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
+ redirect: "manual",
+ signal: requestController.signal,
+ });
+ if (response.ok) {
+ return;
+ }
+ } catch (error) {
+ if (isBackendReadinessAborted(error)) {
+ throw error;
+ }
+ if (signal?.aborted) {
+ throw new BackendReadinessAbortedError();
+ }
+ // Retry until the backend becomes reachable or the deadline expires.
+ } finally {
+ clearTimeout(requestTimeout);
+ signal?.removeEventListener("abort", abortRequest);
+ }
+
+ if (Date.now() >= deadline) {
+ throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
+ }
+
+ await delay(intervalMs, signal);
+ }
+}
diff --git a/apps/desktop/src/desktopSettings.test.ts b/apps/desktop/src/desktopSettings.test.ts
new file mode 100644
index 000000000..e687bf544
--- /dev/null
+++ b/apps/desktop/src/desktopSettings.test.ts
@@ -0,0 +1,64 @@
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ DEFAULT_DESKTOP_SETTINGS,
+ readDesktopSettings,
+ setDesktopServerExposurePreference,
+ writeDesktopSettings,
+} from "./desktopSettings";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeSettingsPath() {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
+ tempDirectories.push(directory);
+ return path.join(directory, "desktop-settings.json");
+}
+
+describe("desktopSettings", () => {
+ it("returns defaults when no settings file exists", () => {
+ expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
+ });
+
+ it("persists and reloads the configured server exposure mode", () => {
+ const settingsPath = makeSettingsPath();
+
+ writeDesktopSettings(settingsPath, {
+ serverExposureMode: "network-accessible",
+ });
+
+ expect(readDesktopSettings(settingsPath)).toEqual({
+ serverExposureMode: "network-accessible",
+ });
+ });
+
+ it("preserves the requested network-accessible preference across temporary fallback", () => {
+ expect(
+ setDesktopServerExposurePreference(
+ {
+ serverExposureMode: "local-only",
+ },
+ "network-accessible",
+ ),
+ ).toEqual({
+ serverExposureMode: "network-accessible",
+ });
+ });
+
+ it("falls back to defaults when the settings file is malformed", () => {
+ const settingsPath = makeSettingsPath();
+ fs.writeFileSync(settingsPath, "{not-json", "utf8");
+
+ expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
+ });
+});
diff --git a/apps/desktop/src/desktopSettings.ts b/apps/desktop/src/desktopSettings.ts
new file mode 100644
index 000000000..80ef229ea
--- /dev/null
+++ b/apps/desktop/src/desktopSettings.ts
@@ -0,0 +1,51 @@
+import * as FS from "node:fs";
+import * as Path from "node:path";
+import type { DesktopServerExposureMode } from "@t3tools/contracts";
+
+export interface DesktopSettings {
+ readonly serverExposureMode: DesktopServerExposureMode;
+}
+
+export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
+ serverExposureMode: "local-only",
+};
+
+export function setDesktopServerExposurePreference(
+ settings: DesktopSettings,
+ requestedMode: DesktopServerExposureMode,
+): DesktopSettings {
+ return settings.serverExposureMode === requestedMode
+ ? settings
+ : {
+ ...settings,
+ serverExposureMode: requestedMode,
+ };
+}
+
+export function readDesktopSettings(settingsPath: string): DesktopSettings {
+ try {
+ if (!FS.existsSync(settingsPath)) {
+ return DEFAULT_DESKTOP_SETTINGS;
+ }
+
+ const raw = FS.readFileSync(settingsPath, "utf8");
+ const parsed = JSON.parse(raw) as {
+ readonly serverExposureMode?: unknown;
+ };
+
+ return {
+ serverExposureMode:
+ parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
+ };
+ } catch {
+ return DEFAULT_DESKTOP_SETTINGS;
+ }
+}
+
+export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
+ const directory = Path.dirname(settingsPath);
+ const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
+ FS.mkdirSync(directory, { recursive: true });
+ FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
+ FS.renameSync(tempPath, settingsPath);
+}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index de327d0ff..9377752e6 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -19,6 +19,8 @@ import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
DesktopTheme,
+ DesktopServerExposureMode,
+ DesktopServerExposureState,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
@@ -29,7 +31,15 @@ import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
+import {
+ DEFAULT_DESKTOP_SETTINGS,
+ readDesktopSettings,
+ setDesktopServerExposurePreference,
+ writeDesktopSettings,
+} from "./desktopSettings";
+import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
+import { resolveDesktopServerExposure } from "./serverExposure";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
@@ -59,10 +69,12 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
-const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
+const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
+const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
+const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -83,6 +95,7 @@ const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
+const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
type LinuxDesktopNamedApp = Electron.App & {
@@ -92,8 +105,13 @@ type LinuxDesktopNamedApp = Electron.App & {
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
let backendPort = 0;
-let backendAuthToken = "";
+let backendBindHost = DESKTOP_LOOPBACK_HOST;
+let backendBootstrapToken = "";
+let backendHttpUrl = "";
let backendWsUrl = "";
+let backendEndpointUrl: string | null = null;
+let backendAdvertisedHost: string | null = null;
+let backendReadinessAbortController: AbortController | null = null;
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
@@ -103,6 +121,8 @@ let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
+let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
+let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
@@ -141,17 +161,120 @@ function readPersistedBackendObservabilitySettings(): {
}
}
+function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined {
+ if (!rawPort) {
+ return undefined;
+ }
+
+ const parsedPort = Number.parseInt(rawPort, 10);
+ if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) {
+ return undefined;
+ }
+
+ return parsedPort;
+}
+
+function resolveDesktopDevServerUrl(): string {
+ const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
+ if (!devServerUrl) {
+ throw new Error("VITE_DEV_SERVER_URL is required in desktop development.");
+ }
+
+ return devServerUrl;
+}
+
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
- delete env.T3CODE_AUTH_TOKEN;
delete env.T3CODE_MODE;
delete env.T3CODE_NO_BROWSER;
delete env.T3CODE_HOST;
delete env.T3CODE_DESKTOP_WS_URL;
+ delete env.T3CODE_DESKTOP_LAN_ACCESS;
+ delete env.T3CODE_DESKTOP_LAN_HOST;
return env;
}
+function getDesktopServerExposureState(): DesktopServerExposureState {
+ return {
+ mode: desktopServerExposureMode,
+ endpointUrl: backendEndpointUrl,
+ advertisedHost: backendAdvertisedHost,
+ };
+}
+
+function resolveAdvertisedHostOverride(): string | undefined {
+ const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
+ return override && override.length > 0 ? override : undefined;
+}
+
+async function applyDesktopServerExposureMode(
+ mode: DesktopServerExposureMode,
+ options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
+): Promise<DesktopServerExposureState> {
+ const advertisedHostOverride = resolveAdvertisedHostOverride();
+ const requestedMode = mode;
+ let exposure = resolveDesktopServerExposure({
+ mode,
+ port: backendPort,
+ networkInterfaces: OS.networkInterfaces(),
+ ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
+ });
+
+ if (requestedMode === "network-accessible" && exposure.endpointUrl === null) {
+ if (options?.rejectIfUnavailable) {
+ throw new Error("No reachable network address is available for this desktop right now.");
+ }
+ exposure = resolveDesktopServerExposure({
+ mode: "local-only",
+ port: backendPort,
+ networkInterfaces: OS.networkInterfaces(),
+ ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
+ });
+ }
+
+ desktopServerExposureMode = exposure.mode;
+ desktopSettings = setDesktopServerExposurePreference(desktopSettings, requestedMode);
+ backendBindHost = exposure.bindHost;
+ backendHttpUrl = exposure.localHttpUrl;
+ backendWsUrl = exposure.localWsUrl;
+ backendEndpointUrl = exposure.endpointUrl;
+ backendAdvertisedHost = exposure.advertisedHost;
+
+ if (options?.persist) {
+ writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
+ }
+
+ return getDesktopServerExposureState();
+}
+
+function relaunchDesktopApp(reason: string): void {
+ writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
+ setImmediate(() => {
+ isQuitting = true;
+ clearUpdatePollTimer();
+ cancelBackendReadinessWait();
+ void stopBackendAndWaitForExit()
+ .catch((error) => {
+ writeDesktopLogHeader(
+ `desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
+ );
+ })
+ .finally(() => {
+ restoreStdIoCapture?.();
+ if (isDevelopment) {
+ app.exit(75);
+ return;
+ }
+ app.relaunch({
+ execPath: process.execPath,
+ args: process.argv.slice(1),
+ });
+ app.exit(0);
+ });
+ });
+}
+
function writeDesktopLogHeader(message: string): void {
if (!desktopLogSink) return;
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
@@ -199,6 +322,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
return null;
}
+async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
+ cancelBackendReadinessWait();
+ const controller = new AbortController();
+ backendReadinessAbortController = controller;
+
+ try {
+ await waitForHttpReady(baseUrl, {
+ signal: controller.signal,
+ });
+ } finally {
+ if (backendReadinessAbortController === controller) {
+ backendReadinessAbortController = null;
+ }
+ }
+}
+
+function cancelBackendReadinessWait(): void {
+ backendReadinessAbortController?.abort();
+ backendReadinessAbortController = null;
+}
+
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -543,10 +687,7 @@ function dispatchMenuAction(action: string): void {
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
- if (!targetWindow.isVisible()) {
- targetWindow.show();
- }
- targetWindow.focus();
+ revealWindow(targetWindow);
};
if (targetWindow.webContents.isLoadingMainFrame()) {
@@ -767,6 +908,26 @@ function clearUpdatePollTimer(): void {
}
}
+function revealWindow(window: BrowserWindow): void {
+ if (window.isDestroyed()) {
+ return;
+ }
+
+ if (window.isMinimized()) {
+ window.restore();
+ }
+
+ if (!window.isVisible()) {
+ window.show();
+ }
+
+ if (process.platform === "darwin") {
+ app.focus({ steal: true });
+ }
+
+ window.focus();
+}
+
function emitUpdateState(): void {
for (const window of BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) continue;
@@ -1036,7 +1197,8 @@ function startBackend(): void {
noBrowser: true,
port: backendPort,
t3Home: BASE_DIR,
- authToken: backendAuthToken,
+ host: backendBindHost,
+ desktopBootstrapToken: backendBootstrapToken,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
@@ -1095,6 +1257,7 @@ function startBackend(): void {
}
function stopBackend(): void {
+ cancelBackendReadinessWait();
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
@@ -1116,6 +1279,7 @@ function stopBackend(): void {
}
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
+ cancelBackendReadinessWait();
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
@@ -1168,19 +1332,38 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
- ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
- ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
- event.returnValue = backendWsUrl;
- });
-
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
event.returnValue = {
label: "Local environment",
- wsUrl: backendWsUrl || null,
+ httpBaseUrl: backendHttpUrl || null,
+ wsBaseUrl: backendWsUrl || null,
+ bootstrapToken: backendBootstrapToken || undefined,
} as const;
});
+ ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
+ ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
+
+ ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL);
+ ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => {
+ if (rawMode !== "local-only" && rawMode !== "network-accessible") {
+ throw new Error("Invalid desktop server exposure input.");
+ }
+
+ const nextMode = rawMode as DesktopServerExposureMode;
+ if (nextMode === desktopServerExposureMode) {
+ return getDesktopServerExposureState();
+ }
+
+ const nextState = await applyDesktopServerExposureMode(nextMode, {
+ persist: true,
+ rejectIfUnavailable: true,
+ });
+ relaunchDesktopApp(`serverExposureMode=${nextMode}`);
+ return nextState;
+ });
+
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -1346,14 +1529,19 @@ function getIconOption(): { icon: string } | Record<string, never> {
return iconPath ? { icon: iconPath } : {};
}
+function getInitialWindowBackgroundColor(): string {
+ return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
+}
+
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
- show: false,
+ show: isDevelopment,
autoHideMenuBar: true,
+ backgroundColor: getInitialWindowBackgroundColor(),
...getIconOption(),
title: APP_DISPLAY_NAME,
titleBarStyle: "hiddenInset",
@@ -1410,15 +1598,20 @@ function createWindow(): BrowserWindow {
window.setTitle(APP_DISPLAY_NAME);
emitUpdateState();
});
- window.once("ready-to-show", () => {
- window.show();
- });
+ if (!isDevelopment) {
+ window.once("ready-to-show", () => {
+ revealWindow(window);
+ });
+ }
if (isDevelopment) {
- void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
+ void window.loadURL(resolveDesktopDevServerUrl());
window.webContents.openDevTools({ mode: "detach" });
+ setImmediate(() => {
+ revealWindow(window);
+ });
} else {
- void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
+ void window.loadURL(resolveDesktopWindowUrl());
}
window.on("closed", () => {
@@ -1430,6 +1623,14 @@ function createWindow(): BrowserWindow {
return window;
}
+function resolveDesktopWindowUrl(): string {
+ if (backendHttpUrl) {
+ return backendHttpUrl;
+ }
+
+ return `${DESKTOP_SCHEME}://app`;
+}
+
// Override Electron's userData path before the `ready` event so that
// Chromium session data uses a filesystem-friendly directory name.
// Must be called synchronously at the top level — before `app.whenReady()`.
@@ -1439,21 +1640,72 @@ configureAppIdentity();
async function bootstrap(): Promise<void> {
writeDesktopLogHeader("bootstrap start");
- backendPort = await Effect.service(NetService).pipe(
- Effect.flatMap((net) => net.reserveLoopbackPort()),
- Effect.provide(NetService.layer),
- Effect.runPromise,
+ const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
+ if (isDevelopment && configuredBackendPort === undefined) {
+ throw new Error("T3CODE_PORT is required in desktop development.");
+ }
+
+ backendPort =
+ configuredBackendPort ??
+ (await Effect.service(NetService).pipe(
+ Effect.flatMap((net) => net.reserveLoopbackPort(DESKTOP_LOOPBACK_HOST)),
+ Effect.provide(NetService.layer),
+ Effect.runPromise,
+ ));
+ writeDesktopLogHeader(
+ configuredBackendPort === undefined
+ ? `reserved backend port via NetService port=${backendPort}`
+ : `using configured backend port port=${backendPort}`,
);
- writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
- backendAuthToken = Crypto.randomBytes(24).toString("hex");
- const baseUrl = `ws://127.0.0.1:${backendPort}`;
- backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
- writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
+ backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
+ if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
+ writeDesktopLogHeader(
+ `bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
+ );
+ }
+ const serverExposureState = await applyDesktopServerExposureMode(
+ desktopSettings.serverExposureMode,
+ {
+ persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
+ },
+ );
+ writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`);
+ if (serverExposureState.endpointUrl) {
+ writeDesktopLogHeader(
+ `bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`,
+ );
+ } else if (desktopSettings.serverExposureMode === "network-accessible") {
+ writeDesktopLogHeader(
+ "bootstrap fell back to local-only because no advertised network host was available",
+ );
+ }
registerIpcHandlers();
writeDesktopLogHeader("bootstrap ipc handlers registered");
startBackend();
writeDesktopLogHeader("bootstrap backend start requested");
+
+ if (isDevelopment) {
+ mainWindow = createWindow();
+ writeDesktopLogHeader("bootstrap main window created");
+ void waitForBackendHttpReady(backendHttpUrl)
+ .then(() => {
+ writeDesktopLogHeader("bootstrap backend ready");
+ })
+ .catch((error) => {
+ if (isBackendReadinessAborted(error)) {
+ return;
+ }
+ writeDesktopLogHeader(
+ `bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
+ );
+ console.warn("[desktop] backend readiness check timed out during dev bootstrap", error);
+ });
+ return;
+ }
+
+ await waitForBackendHttpReady(backendHttpUrl);
+ writeDesktopLogHeader("bootstrap backend ready");
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
}
@@ -1463,6 +1715,7 @@ app.on("before-quit", () => {
updateInstallInFlight = false;
writeDesktopLogHeader("before-quit received");
clearUpdatePollTimer();
+ cancelBackendReadinessWait();
stopBackend();
restoreStdIoCapture?.();
});
@@ -1476,13 +1729,19 @@ app
registerDesktopProtocol();
configureAutoUpdater();
void bootstrap().catch((error) => {
+ if (isBackendReadinessAborted(error) && isQuitting) {
+ return;
+ }
handleFatalStartupError("bootstrap", error);
});
app.on("activate", () => {
- if (BrowserWindow.getAllWindows().length === 0) {
- mainWindow = createWindow();
+ const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
+ if (existingWindow) {
+ revealWindow(existingWindow);
+ return;
}
+ mainWindow = createWindow();
});
})
.catch((error) => {
@@ -1501,6 +1760,7 @@ if (process.platform !== "win32") {
isQuitting = true;
writeDesktopLogHeader("SIGINT received");
clearUpdatePollTimer();
+ cancelBackendReadinessWait();
stopBackend();
restoreStdIoCapture?.();
app.quit();
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index bd678844e..60392f7db 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -12,14 +12,11 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
-const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
+const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
+const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
contextBridge.exposeInMainWorld("desktopBridge", {
- getWsUrl: () => {
- const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
- return typeof result === "string" ? result : null;
- },
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
@@ -27,6 +24,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
+ getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
+ setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
diff --git a/apps/desktop/src/serverExposure.test.ts b/apps/desktop/src/serverExposure.test.ts
new file mode 100644
index 000000000..b1ae4bef4
--- /dev/null
+++ b/apps/desktop/src/serverExposure.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
+
+describe("resolveLanAdvertisedHost", () => {
+ it("prefers an explicit host override", () => {
+ expect(
+ resolveLanAdvertisedHost(
+ {
+ en0: [
+ {
+ address: "192.168.1.44",
+ family: "IPv4",
+ internal: false,
+ netmask: "255.255.255.0",
+ cidr: "192.168.1.44/24",
+ mac: "00:00:00:00:00:00",
+ },
+ ],
+ },
+ "10.0.0.9",
+ ),
+ ).toBe("10.0.0.9");
+ });
+
+ it("returns the first usable non-internal IPv4 address", () => {
+ expect(
+ resolveLanAdvertisedHost(
+ {
+ lo0: [
+ {
+ address: "127.0.0.1",
+ family: "IPv4",
+ internal: true,
+ netmask: "255.0.0.0",
+ cidr: "127.0.0.1/8",
+ mac: "00:00:00:00:00:00",
+ },
+ ],
+ en0: [
+ {
+ address: "192.168.1.44",
+ family: "IPv4",
+ internal: false,
+ netmask: "255.255.255.0",
+ cidr: "192.168.1.44/24",
+ mac: "00:00:00:00:00:00",
+ },
+ ],
+ },
+ undefined,
+ ),
+ ).toBe("192.168.1.44");
+ });
+
+ it("returns null when no usable network address is available", () => {
+ expect(
+ resolveLanAdvertisedHost(
+ {
+ lo0: [
+ {
+ address: "127.0.0.1",
+ family: "IPv4",
+ internal: true,
+ netmask: "255.0.0.0",
+ cidr: "127.0.0.1/8",
+ mac: "00:00:00:00:00:00",
+ },
+ ],
+ },
+ undefined,
+ ),
+ ).toBeNull();
+ });
+});
+
+describe("resolveDesktopServerExposure", () => {
+ it("keeps the desktop server loopback-only when local-only mode is selected", () => {
+ expect(
+ resolveDesktopServerExposure({
+ mode: "local-only",
+ port: 3773,
+ networkInterfaces: {},
+ }),
+ ).toEqual({
+ mode: "local-only",
+ bindHost: "127.0.0.1",
+ localHttpUrl: "http://127.0.0.1:3773",
+ localWsUrl: "ws://127.0.0.1:3773",
+ endpointUrl: null,
+ advertisedHost: null,
+ });
+ });
+
+ it("binds to all interfaces in network-accessible mode", () => {
+ expect(
+ resolveDesktopServerExposure({
+ mode: "network-accessible",
+ port: 3773,
+ networkInterfaces: {
+ en0: [
+ {
+ address: "192.168.1.44",
+ family: "IPv4",
+ internal: false,
+ netmask: "255.255.255.0",
+ cidr: "192.168.1.44/24",
+ mac: "00:00:00:00:00:00",
+ },
+ ],
+ },
+ }),
+ ).toEqual({
+ mode: "network-accessible",
+ bindHost: "0.0.0.0",
+ localHttpUrl: "http://127.0.0.1:3773",
+ localWsUrl: "ws://127.0.0.1:3773",
+ endpointUrl: "http://192.168.1.44:3773",
+ advertisedHost: "192.168.1.44",
+ });
+ });
+
+ it("stays network-accessible even when no LAN address is currently detectable", () => {
+ expect(
+ resolveDesktopServerExposure({
+ mode: "network-accessible",
+ port: 3773,
+ networkInterfaces: {},
+ }),
+ ).toEqual({
+ mode: "network-accessible",
+ bindHost: "0.0.0.0",
+ localHttpUrl: "http://127.0.0.1:3773",
+ localWsUrl: "ws://127.0.0.1:3773",
+ endpointUrl: null,
+ advertisedHost: null,
+ });
+ });
+});
diff --git a/apps/desktop/src/serverExposure.ts b/apps/desktop/src/serverExposure.ts
new file mode 100644
index 000000000..65c99b60e
--- /dev/null
+++ b/apps/desktop/src/serverExposure.ts
@@ -0,0 +1,80 @@
+import type { NetworkInterfaceInfo } from "node:os";
+import type { DesktopServerExposureMode } from "@t3tools/contracts";
+
+const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
+const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
+
+export interface DesktopServerExposure {
+ readonly mode: DesktopServerExposureMode;
+ readonly bindHost: string;
+ readonly localHttpUrl: string;
+ readonly localWsUrl: string;
+ readonly endpointUrl: string | null;
+ readonly advertisedHost: string | null;
+}
+
+const normalizeOptionalHost = (value: string | undefined): string | undefined => {
+ const normalized = value?.trim();
+ return normalized && normalized.length > 0 ? normalized : undefined;
+};
+
+const isUsableLanIpv4Address = (address: string): boolean =>
+ !address.startsWith("127.") && !address.startsWith("169.254.");
+
+export function resolveLanAdvertisedHost(
+ networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
+ explicitHost: string | undefined,
+): string | null {
+ const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
+ if (normalizedExplicitHost) {
+ return normalizedExplicitHost;
+ }
+
+ for (const interfaceAddresses of Object.values(networkInterfaces)) {
+ if (!interfaceAddresses) continue;
+
+ for (const address of interfaceAddresses) {
+ if (address.internal) continue;
+ if (address.family !== "IPv4") continue;
+ if (!isUsableLanIpv4Address(address.address)) continue;
+ return address.address;
+ }
+ }
+
+ return null;
+}
+
+export function resolveDesktopServerExposure(input: {
+ readonly mode: DesktopServerExposureMode;
+ readonly port: number;
+ readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
+ readonly advertisedHostOverride?: string;
+}): DesktopServerExposure {
+ const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
+ const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
+
+ if (input.mode === "local-only") {
+ return {
+ mode: input.mode,
+ bindHost: DESKTOP_LOOPBACK_HOST,
+ localHttpUrl,
+ localWsUrl,
+ endpointUrl: null,
+ advertisedHost: null,
+ };
+ }
+
+ const advertisedHost = resolveLanAdvertisedHost(
+ input.networkInterfaces,
+ input.advertisedHostOverride,
+ );
+
+ return {
+ mode: input.mode,
+ bindHost: DESKTOP_LAN_BIND_HOST,
+ localHttpUrl,
+ localWsUrl,
+ endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
+ advertisedHost,
+ };
+}
diff --git a/apps/server/src/auth/Layers/AuthControlPlane.test.ts b/apps/server/src/auth/Layers/AuthControlPlane.test.ts
new file mode 100644
index 000000000..9fc091124
--- /dev/null
+++ b/apps/server/src/auth/Layers/AuthControlPlane.test.ts
@@ -0,0 +1,111 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Effect, Layer } from "effect";
+
+import { ServerConfigShape } from "../../config.ts";
+import { ServerConfig } from "../../config.ts";
+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
+import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
+import { makeAuthControlPlane } from "./AuthControlPlane.ts";
+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
+
+const makeServerConfigLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ Layer.effect(
+ ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ return {
+ ...config,
+ ...overrides,
+ } satisfies ServerConfigShape;
+ }),
+ ).pipe(
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
+ );
+
+const makeAuthControlPlaneLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
+ Layer.provideMerge(BootstrapCredentialServiceLive),
+ Layer.provideMerge(SessionCredentialServiceLive),
+ Layer.provideMerge(ServerSecretStoreLive),
+ Layer.provideMerge(SqlitePersistenceMemory),
+ Layer.provide(makeServerConfigLayer(overrides)),
+ );
+
+it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
+ it.effect("creates, lists, and revokes client pairing links", () =>
+ Effect.gen(function* () {
+ const authControlPlane = yield* AuthControlPlane;
+
+ const created = yield* authControlPlane.createPairingLink({
+ role: "client",
+ subject: "one-time-token",
+ label: "CI phone",
+ });
+ const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
+ const revoked = yield* authControlPlane.revokePairingLink(created.id);
+ const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
+
+ expect(created.role).toBe("client");
+ expect(created.credential.length).toBeGreaterThan(0);
+ expect(listedBeforeRevoke).toHaveLength(1);
+ expect(listedBeforeRevoke[0]?.id).toBe(created.id);
+ expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
+ expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
+ expect(revoked).toBe(true);
+ expect(listedAfterRevoke).toHaveLength(0);
+ }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
+ );
+
+ it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
+ Effect.gen(function* () {
+ const authControlPlane = yield* AuthControlPlane;
+ const sessionCredentials = yield* SessionCredentialService;
+
+ const issued = yield* authControlPlane.issueSession({
+ label: "deploy-bot",
+ });
+ const verified = yield* sessionCredentials.verify(issued.token);
+ const listedBeforeRevoke = yield* authControlPlane.listSessions();
+ const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
+ const listedAfterRevoke = yield* authControlPlane.listSessions();
+
+ expect(issued.method).toBe("bearer-session-token");
+ expect(issued.role).toBe("owner");
+ expect(issued.client.deviceType).toBe("bot");
+ expect(issued.client.label).toBe("deploy-bot");
+ expect(verified.sessionId).toBe(issued.sessionId);
+ expect(verified.role).toBe("owner");
+ expect(verified.method).toBe("bearer-session-token");
+ expect(listedBeforeRevoke).toHaveLength(1);
+ expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
+ expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
+ expect(revoked).toBe(true);
+ expect(listedAfterRevoke).toHaveLength(0);
+ }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
+ );
+
+ it.effect("surfaces lastConnectedAt through the listed session view", () =>
+ Effect.gen(function* () {
+ const authControlPlane = yield* AuthControlPlane;
+ const sessionCredentials = yield* SessionCredentialService;
+
+ const issued = yield* authControlPlane.issueSession({
+ label: "remote-ipad",
+ });
+ const beforeConnect = yield* authControlPlane.listSessions();
+ yield* sessionCredentials.markConnected(issued.sessionId);
+ const afterConnect = yield* authControlPlane.listSessions();
+
+ expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
+ expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
+ }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
+ );
+});
diff --git a/apps/server/src/auth/Layers/AuthControlPlane.ts b/apps/server/src/auth/Layers/AuthControlPlane.ts
new file mode 100644
index 000000000..98b210780
--- /dev/null
+++ b/apps/server/src/auth/Layers/AuthControlPlane.ts
@@ -0,0 +1,176 @@
+import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
+import { DateTime, Effect, Layer } from "effect";
+
+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
+import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
+import {
+ AuthControlPlane,
+ AuthControlPlaneError,
+ AuthControlPlaneShape,
+ DEFAULT_SESSION_SUBJECT,
+ IssuedBearerSession,
+ IssuedPairingLink,
+} from "../Services/AuthControlPlane.ts";
+
+const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
+ if (left.role !== right.role) {
+ return left.role === "owner" ? -1 : 1;
+ }
+ if (left.connected !== right.connected) {
+ return left.connected ? -1 : 1;
+ }
+ return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
+};
+
+const toAuthControlPlaneError =
+ (message: string) =>
+ (cause: unknown): AuthControlPlaneError =>
+ new AuthControlPlaneError({
+ message,
+ cause,
+ });
+
+export const makeAuthControlPlane = Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const sessions = yield* SessionCredentialService;
+
+ const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
+ Effect.gen(function* () {
+ const createdAt = yield* DateTime.now;
+ const issued = yield* bootstrapCredentials.issueOneTimeToken({
+ role: input?.role ?? "client",
+ subject: input?.subject ?? "one-time-token",
+ ...(input?.ttl ? { ttl: input.ttl } : {}),
+ ...(input?.label ? { label: input.label } : {}),
+ });
+ return {
+ id: issued.id,
+ credential: issued.credential,
+ role: input?.role ?? "client",
+ subject: input?.subject ?? "one-time-token",
+ ...(issued.label ? { label: issued.label } : {}),
+ createdAt: DateTime.toUtc(createdAt),
+ expiresAt: DateTime.toUtc(issued.expiresAt),
+ } satisfies IssuedPairingLink;
+ }).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
+
+ const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
+ bootstrapCredentials.listActive().pipe(
+ Effect.map((pairingLinks) =>
+ pairingLinks
+ .filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
+ .filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
+ .map((pairingLink) =>
+ pairingLink.label
+ ? ({
+ id: pairingLink.id,
+ credential: pairingLink.credential,
+ role: pairingLink.role,
+ subject: pairingLink.subject,
+ label: pairingLink.label,
+ createdAt: pairingLink.createdAt,
+ expiresAt: pairingLink.expiresAt,
+ } satisfies AuthPairingLink)
+ : ({
+ id: pairingLink.id,
+ credential: pairingLink.credential,
+ role: pairingLink.role,
+ subject: pairingLink.subject,
+ createdAt: pairingLink.createdAt,
+ expiresAt: pairingLink.expiresAt,
+ } satisfies AuthPairingLink),
+ )
+ .toSorted(
+ (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
+ ),
+ ),
+ Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
+ );
+
+ const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
+ bootstrapCredentials
+ .revoke(id)
+ .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
+
+ const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
+ sessions
+ .issue({
+ subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
+ method: "bearer-session-token",
+ role: input?.role ?? "owner",
+ client: {
+ ...(input?.label ? { label: input.label } : {}),
+ deviceType: "bot",
+ },
+ ...(input?.ttl ? { ttl: input.ttl } : {}),
+ })
+ .pipe(
+ Effect.flatMap((issued) => {
+ if (issued.method !== "bearer-session-token") {
+ return Effect.fail(
+ new AuthControlPlaneError({
+ message: "CLI session issuance produced an unexpected session method.",
+ }),
+ );
+ }
+
+ return Effect.succeed({
+ sessionId: issued.sessionId,
+ token: issued.token,
+ method: "bearer-session-token" as const,
+ role: issued.role,
+ subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
+ client: issued.client,
+ expiresAt: DateTime.toUtc(issued.expiresAt),
+ } satisfies IssuedBearerSession);
+ }),
+ Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
+ );
+
+ const listSessions: AuthControlPlaneShape["listSessions"] = () =>
+ sessions.listActive().pipe(
+ Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
+ Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
+ );
+
+ const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
+ sessions
+ .revoke(sessionId)
+ .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
+
+ const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
+ sessionId,
+ ) =>
+ sessions
+ .revokeAllExcept(sessionId)
+ .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
+
+ return {
+ createPairingLink,
+ listPairingLinks,
+ revokePairingLink,
+ issueSession,
+ listSessions,
+ revokeSession,
+ revokeOtherSessionsExcept,
+ } satisfies AuthControlPlaneShape;
+});
+
+export const AuthCoreLive = Layer.mergeAll(
+ BootstrapCredentialServiceLive,
+ SessionCredentialServiceLive,
+);
+
+export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
+
+export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
+
+export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
+
+export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
+ Layer.provideMerge(AuthRuntimeLive),
+);
diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts
new file mode 100644
index 000000000..ec110ee96
--- /dev/null
+++ b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts
@@ -0,0 +1,151 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Duration, Effect, Layer } from "effect";
+import { TestClock } from "effect/testing";
+
+import type { ServerConfigShape } from "../../config.ts";
+import { ServerConfig } from "../../config.ts";
+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
+
+const makeServerConfigLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ Layer.effect(
+ ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ return {
+ ...config,
+ ...overrides,
+ } satisfies ServerConfigShape;
+ }),
+ ).pipe(
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
+ );
+
+const makeBootstrapCredentialLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ BootstrapCredentialServiceLive.pipe(
+ Layer.provide(SqlitePersistenceMemory),
+ Layer.provide(makeServerConfigLayer(overrides)),
+ );
+
+it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
+ it.effect("issues pairing tokens in a short manual-entry format", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const issued = yield* bootstrapCredentials.issueOneTimeToken();
+
+ expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
+ }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
+ );
+
+ it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
+ const first = yield* bootstrapCredentials.consume(issued.credential);
+ const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
+
+ expect(first.method).toBe("one-time-token");
+ expect(first.role).toBe("client");
+ expect(first.subject).toBe("one-time-token");
+ expect(first.label).toBe("Julius iPhone");
+ expect(issued.label).toBe("Julius iPhone");
+ expect(second._tag).toBe("BootstrapCredentialError");
+ expect(second.message).toContain("Unknown bootstrap credential");
+ }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
+ );
+
+ it.effect("atomically consumes a one-time token when multiple requests race", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const token = yield* bootstrapCredentials.issueOneTimeToken();
+ const results = yield* Effect.all(
+ Array.from({ length: 8 }, () =>
+ Effect.result(bootstrapCredentials.consume(token.credential)),
+ ),
+ {
+ concurrency: "unbounded",
+ },
+ );
+
+ const successes = results.filter((result) => result._tag === "Success");
+ const failures = results.filter((result) => result._tag === "Failure");
+
+ expect(successes).toHaveLength(1);
+ expect(failures).toHaveLength(7);
+ for (const failure of failures) {
+ expect(failure.failure._tag).toBe("BootstrapCredentialError");
+ expect(failure.failure.message).toContain("Unknown bootstrap credential");
+ }
+ }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
+ );
+
+ it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
+ const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
+
+ expect(first.method).toBe("desktop-bootstrap");
+ expect(first.role).toBe("owner");
+ expect(first.subject).toBe("desktop-bootstrap");
+ expect(second._tag).toBe("BootstrapCredentialError");
+ expect(second.status).toBe(401);
+ }).pipe(
+ Effect.provide(
+ makeBootstrapCredentialLayer({
+ desktopBootstrapToken: "desktop-bootstrap-token",
+ }),
+ ),
+ ),
+ );
+
+ it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+
+ yield* TestClock.adjust(Duration.minutes(6));
+ const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
+
+ expect(expired._tag).toBe("BootstrapCredentialError");
+ expect(expired.status).toBe(401);
+ expect(expired.message).toContain("Bootstrap credential expired");
+ }).pipe(
+ Effect.provide(
+ Layer.merge(
+ makeBootstrapCredentialLayer({
+ desktopBootstrapToken: "desktop-bootstrap-token",
+ }),
+ TestClock.layer(),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("lists and revokes active pairing links", () =>
+ Effect.gen(function* () {
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const first = yield* bootstrapCredentials.issueOneTimeToken();
+ const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
+
+ const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
+ expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
+ expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
+
+ const revoked = yield* bootstrapCredentials.revoke(first.id);
+ const activeAfterRevoke = yield* bootstrapCredentials.listActive();
+ const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
+
+ expect(revoked).toBe(true);
+ expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
+ expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
+ expect(revokedConsume.message).toContain("no longer available");
+ expect(revokedConsume.status).toBe(401);
+ }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
+ );
+});
diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.ts
new file mode 100644
index 000000000..5539f62c7
--- /dev/null
+++ b/apps/server/src/auth/Layers/BootstrapCredentialService.ts
@@ -0,0 +1,296 @@
+import type { AuthPairingLink } from "@t3tools/contracts";
+import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
+import { Option } from "effect";
+
+import { ServerConfig } from "../../config.ts";
+import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
+import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
+import {
+ BootstrapCredentialError,
+ BootstrapCredentialService,
+ type BootstrapCredentialChange,
+ type BootstrapCredentialServiceShape,
+ type BootstrapGrant,
+ type IssuedBootstrapCredential,
+} from "../Services/BootstrapCredentialService.ts";
+
+interface StoredBootstrapGrant extends BootstrapGrant {
+ readonly remainingUses: number | "unbounded";
+}
+
+type ConsumeResult =
+ | {
+ readonly _tag: "error";
+ readonly reason: "not-found" | "expired";
+ readonly error: BootstrapCredentialError;
+ }
+ | {
+ readonly _tag: "success";
+ readonly grant: BootstrapGrant;
+ };
+
+const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
+const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
+const PAIRING_TOKEN_LENGTH = 12;
+
+const generatePairingToken = (): string => {
+ const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
+
+ return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
+};
+
+export const makeBootstrapCredentialService = Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ const pairingLinks = yield* AuthPairingLinkRepository;
+ const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
+ const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
+
+ const invalidBootstrapCredentialError = (message: string) =>
+ new BootstrapCredentialError({
+ message,
+ status: 401,
+ });
+
+ const internalBootstrapCredentialError = (message: string, cause: unknown) =>
+ new BootstrapCredentialError({
+ message,
+ status: 500,
+ cause,
+ });
+
+ const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
+ Ref.update(seededGrantsRef, (current) => {
+ const next = new Map(current);
+ next.set(credential, grant);
+ return next;
+ });
+
+ const emitUpsert = (pairingLink: AuthPairingLink) =>
+ PubSub.publish(changesPubSub, {
+ type: "pairingLinkUpserted",
+ pairingLink,
+ }).pipe(Effect.asVoid);
+
+ const emitRemoved = (id: string) =>
+ PubSub.publish(changesPubSub, {
+ type: "pairingLinkRemoved",
+ id,
+ }).pipe(Effect.asVoid);
+
+ if (config.desktopBootstrapToken) {
+ const now = yield* DateTime.now;
+ yield* seedGrant(config.desktopBootstrapToken, {
+ method: "desktop-bootstrap",
+ role: "owner",
+ subject: "desktop-bootstrap",
+ expiresAt: DateTime.add(now, {
+ milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
+ }),
+ remainingUses: 1,
+ });
+ }
+
+ const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
+ internalBootstrapCredentialError(message, cause);
+
+ const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
+ Effect.gen(function* () {
+ const now = yield* DateTime.now;
+ const rows = yield* pairingLinks.listActive({ now });
+
+ return rows.map((row) =>
+ row.label
+ ? ({
+ id: row.id,
+ credential: row.credential,
+ role: row.role,
+ subject: row.subject,
+ label: row.label,
+ createdAt: row.createdAt,
+ expiresAt: row.expiresAt,
+ } satisfies AuthPairingLink)
+ : ({
+ id: row.id,
+ credential: row.credential,
+ role: row.role,
+ subject: row.subject,
+ createdAt: row.createdAt,
+ expiresAt: row.expiresAt,
+ } satisfies AuthPairingLink),
+ );
+ }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
+
+ const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
+ Effect.gen(function* () {
+ const revokedAt = yield* DateTime.now;
+ const revoked = yield* pairingLinks.revoke({
+ id,
+ revokedAt,
+ });
+ if (revoked) {
+ yield* emitRemoved(id);
+ }
+ return revoked;
+ }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
+
+ const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
+ Effect.gen(function* () {
+ const id = crypto.randomUUID();
+ const credential = generatePairingToken();
+ const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
+ const now = yield* DateTime.now;
+ const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
+ const issued: IssuedBootstrapCredential = {
+ id,
+ credential,
+ ...(input?.label ? { label: input.label } : {}),
+ expiresAt,
+ };
+ yield* pairingLinks.create({
+ id,
+ credential,
+ method: "one-time-token",
+ role: input?.role ?? "client",
+ subject: input?.subject ?? "one-time-token",
+ label: input?.label ?? null,
+ createdAt: now,
+ expiresAt: expiresAt,
+ });
+ yield* emitUpsert({
+ id,
+ credential,
+ role: input?.role ?? "client",
+ subject: input?.subject ?? "one-time-token",
+ ...(input?.label ? { label: input.label } : {}),
+ createdAt: now,
+ expiresAt,
+ });
+ return issued;
+ }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
+
+ const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
+ Effect.gen(function* () {
+ const now = yield* DateTime.now;
+ const seededResult: ConsumeResult = yield* Ref.modify(
+ seededGrantsRef,
+ (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
+ const grant = current.get(credential);
+ if (!grant) {
+ return [
+ {
+ _tag: "error",
+ reason: "not-found",
+ error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
+ },
+ current,
+ ];
+ }
+
+ const next = new Map(current);
+ if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
+ next.delete(credential);
+ return [
+ {
+ _tag: "error",
+ reason: "expired",
+ error: invalidBootstrapCredentialError("Bootstrap credential expired."),
+ },
+ next,
+ ];
+ }
+
+ const remainingUses = grant.remainingUses;
+ if (typeof remainingUses === "number") {
+ if (remainingUses <= 1) {
+ next.delete(credential);
+ } else {
+ next.set(credential, {
+ ...grant,
+ remainingUses: remainingUses - 1,
+ });
+ }
+ }
+
+ return [
+ {
+ _tag: "success",
+ grant: {
+ method: grant.method,
+ role: grant.role,
+ subject: grant.subject,
+ ...(grant.label ? { label: grant.label } : {}),
+ expiresAt: grant.expiresAt,
+ } satisfies BootstrapGrant,
+ },
+ next,
+ ];
+ },
+ );
+
+ if (seededResult._tag === "success") {
+ return seededResult.grant;
+ }
+ if (seededResult.reason !== "not-found") {
+ return yield* seededResult.error;
+ }
+
+ const consumed = yield* pairingLinks.consumeAvailable({
+ credential,
+ consumedAt: now,
+ now,
+ });
+
+ if (Option.isSome(consumed)) {
+ yield* emitRemoved(consumed.value.id);
+ return {
+ method: consumed.value.method,
+ role: consumed.value.role,
+ subject: consumed.value.subject,
+ ...(consumed.value.label ? { label: consumed.value.label } : {}),
+ expiresAt: consumed.value.expiresAt,
+ } satisfies BootstrapGrant;
+ }
+
+ const matching = yield* pairingLinks.getByCredential({ credential });
+ if (Option.isNone(matching)) {
+ return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
+ }
+
+ if (matching.value.revokedAt !== null) {
+ return yield* invalidBootstrapCredentialError(
+ "Bootstrap credential is no longer available.",
+ );
+ }
+
+ if (matching.value.consumedAt !== null) {
+ return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
+ }
+
+ if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
+ return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
+ }
+
+ return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
+ }).pipe(
+ Effect.mapError((cause) =>
+ cause instanceof BootstrapCredentialError
+ ? cause
+ : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
+ ),
+ );
+
+ return {
+ issueOneTimeToken,
+ listActive,
+ get streamChanges() {
+ return Stream.fromPubSub(changesPubSub);
+ },
+ revoke,
+ consume,
+ } satisfies BootstrapCredentialServiceShape;
+});
+
+export const BootstrapCredentialServiceLive = Layer.effect(
+ BootstrapCredentialService,
+ makeBootstrapCredentialService,
+).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
diff --git a/apps/server/src/auth/Layers/ServerAuth.test.ts b/apps/server/src/auth/Layers/ServerAuth.test.ts
new file mode 100644
index 000000000..0c3d71cc9
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerAuth.test.ts
@@ -0,0 +1,182 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Effect, Layer } from "effect";
+
+import type { ServerConfigShape } from "../../config.ts";
+import { ServerConfig } from "../../config.ts";
+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
+import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
+import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
+import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
+
+const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
+ Layer.effect(
+ ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ return {
+ ...config,
+ ...overrides,
+ } satisfies ServerConfigShape;
+ }),
+ ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
+
+const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
+ ServerAuthLive.pipe(
+ Layer.provide(SqlitePersistenceMemory),
+ Layer.provide(ServerSecretStoreLive),
+ Layer.provide(makeServerConfigLayer(overrides)),
+ );
+
+const makeCookieRequest = (
+ sessionToken: string,
+): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
+ ({
+ cookies: {
+ t3_session: sessionToken,
+ },
+ headers: {},
+ }) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
+
+const requestMetadata = {
+ deviceType: "desktop" as const,
+ os: "macOS",
+ browser: "Chrome",
+ ipAddress: "192.168.1.23",
+};
+
+it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
+ it.effect("maps invalid bootstrap credential failures to 401", () =>
+ Effect.sync(() => {
+ const error = toBootstrapExchangeAuthError(
+ new BootstrapCredentialError({
+ message: "Unknown bootstrap credential.",
+ status: 401,
+ }),
+ );
+
+ expect(error.status).toBe(401);
+ expect(error.message).toBe("Invalid bootstrap credential.");
+ }),
+ );
+
+ it.effect("maps unexpected bootstrap failures to 500", () =>
+ Effect.sync(() => {
+ const error = toBootstrapExchangeAuthError(
+ new BootstrapCredentialError({
+ message: "Failed to consume bootstrap credential.",
+ status: 500,
+ cause: new Error("sqlite is unavailable"),
+ }),
+ );
+
+ expect(error.status).toBe(500);
+ expect(error.message).toBe("Failed to validate bootstrap credential.");
+ }),
+ );
+
+ it.effect("issues client pairing credentials by default", () =>
+ Effect.gen(function* () {
+ const serverAuth = yield* ServerAuth;
+
+ const pairingCredential = yield* serverAuth.issuePairingCredential();
+ const exchanged = yield* serverAuth.exchangeBootstrapCredential(
+ pairingCredential.credential,
+ requestMetadata,
+ );
+ const verified = yield* serverAuth.authenticateHttpRequest(
+ makeCookieRequest(exchanged.sessionToken),
+ );
+
+ expect(verified.sessionId.length).toBeGreaterThan(0);
+ expect(verified.role).toBe("client");
+ expect(verified.subject).toBe("one-time-token");
+ }).pipe(Effect.provide(makeServerAuthLayer())),
+ );
+
+ it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
+ Effect.gen(function* () {
+ const serverAuth = yield* ServerAuth;
+
+ const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
+ const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
+ const listedPairingLinks = yield* serverAuth.listPairingLinks();
+ expect(token).toBeTruthy();
+ expect(
+ listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
+ ).toBe(false);
+
+ const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
+ const verified = yield* serverAuth.authenticateHttpRequest(
+ makeCookieRequest(exchanged.sessionToken),
+ );
+
+ expect(verified.role).toBe("owner");
+ expect(verified.subject).toBe("owner-bootstrap");
+ }).pipe(Effect.provide(makeServerAuthLayer())),
+ );
+
+ it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
+ Effect.gen(function* () {
+ const serverAuth = yield* ServerAuth;
+
+ const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
+ "desktop-bootstrap-token",
+ requestMetadata,
+ );
+ const ownerSession = yield* serverAuth.authenticateHttpRequest(
+ makeCookieRequest(ownerExchange.sessionToken),
+ );
+ const pairingCredential = yield* serverAuth.issuePairingCredential({
+ label: "Julius iPhone",
+ });
+ const listedPairingLinks = yield* serverAuth.listPairingLinks();
+ const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
+ pairingCredential.credential,
+ {
+ ...requestMetadata,
+ deviceType: "mobile",
+ os: "iOS",
+ browser: "Safari",
+ ipAddress: "192.168.1.88",
+ },
+ );
+ const clientSession = yield* serverAuth.authenticateHttpRequest(
+ makeCookieRequest(clientExchange.sessionToken),
+ );
+ const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
+ const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
+ const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
+
+ expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
+ expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
+ "Julius iPhone",
+ );
+ expect(clientsBeforeRevoke).toHaveLength(2);
+ expect(
+ clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
+ ).toBe(true);
+ expect(
+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
+ ).toBe(false);
+ expect(
+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
+ .label,
+ ).toBe("Julius iPhone");
+ expect(
+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
+ .deviceType,
+ ).toBe("mobile");
+ expect(revokedCount).toBe(1);
+ expect(clientsAfterRevoke).toHaveLength(1);
+ expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
+ }).pipe(
+ Effect.provide(
+ makeServerAuthLayer({
+ desktopBootstrapToken: "desktop-bootstrap-token",
+ }),
+ ),
+ ),
+ );
+});
diff --git a/apps/server/src/auth/Layers/ServerAuth.ts b/apps/server/src/auth/Layers/ServerAuth.ts
new file mode 100644
index 000000000..fa7191110
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerAuth.ts
@@ -0,0 +1,385 @@
+import {
+ type AuthBearerBootstrapResult,
+ type AuthClientSession,
+ type AuthBootstrapResult,
+ type AuthPairingCredentialResult,
+ type AuthSessionState,
+ type AuthWebSocketTokenResult,
+} from "@t3tools/contracts";
+import { DateTime, Effect, Layer, Option } from "effect";
+import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
+
+import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
+import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
+import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
+import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
+import {
+ ServerAuth,
+ type AuthenticatedSession,
+ AuthError,
+ type ServerAuthShape,
+} from "../Services/ServerAuth.ts";
+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
+import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
+
+type BootstrapExchangeResult = {
+ readonly response: AuthBootstrapResult;
+ readonly sessionToken: string;
+};
+
+const AUTHORIZATION_PREFIX = "Bearer ";
+const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
+
+export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
+ if (cause.status === 500) {
+ return new AuthError({
+ message: "Failed to validate bootstrap credential.",
+ status: 500,
+ cause,
+ });
+ }
+
+ return new AuthError({
+ message: "Invalid bootstrap credential.",
+ status: 401,
+ cause,
+ });
+}
+
+function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
+ const header = request.headers["authorization"];
+ if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
+ return null;
+ }
+ const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
+ return token.length > 0 ? token : null;
+}
+
+export const makeServerAuth = Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const authControlPlane = yield* AuthControlPlane;
+ const sessions = yield* SessionCredentialService;
+ const descriptor = yield* policy.getDescriptor();
+
+ const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
+ sessions.verify(token).pipe(
+ Effect.map((session) => ({
+ sessionId: session.sessionId,
+ subject: session.subject,
+ method: session.method,
+ role: session.role,
+ ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
+ })),
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Unauthorized request.",
+ status: 401,
+ cause,
+ }),
+ ),
+ );
+
+ const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
+ const cookieToken = request.cookies[sessions.cookieName];
+ const bearerToken = parseBearerToken(request);
+ const credential = cookieToken ?? bearerToken;
+ if (!credential) {
+ return Effect.fail(
+ new AuthError({
+ message: "Authentication required.",
+ status: 401,
+ }),
+ );
+ }
+ return authenticateToken(credential);
+ };
+
+ const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
+ authenticateRequest(request).pipe(
+ Effect.map(
+ (session) =>
+ ({
+ authenticated: true,
+ auth: descriptor,
+ role: session.role,
+ sessionMethod: session.method,
+ ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
+ }) satisfies AuthSessionState,
+ ),
+ Effect.catchTag("AuthError", () =>
+ Effect.succeed({
+ authenticated: false,
+ auth: descriptor,
+ } satisfies AuthSessionState),
+ ),
+ );
+
+ const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
+ credential,
+ requestMetadata,
+ ) =>
+ bootstrapCredentials.consume(credential).pipe(
+ Effect.mapError(toBootstrapExchangeAuthError),
+ Effect.flatMap((grant) =>
+ sessions
+ .issue({
+ method: "browser-session-cookie",
+ subject: grant.subject,
+ role: grant.role,
+ client: {
+ ...requestMetadata,
+ ...(grant.label ? { label: grant.label } : {}),
+ },
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to issue authenticated session.",
+ cause,
+ }),
+ ),
+ ),
+ ),
+ Effect.map(
+ (session) =>
+ ({
+ response: {
+ authenticated: true,
+ role: session.role,
+ sessionMethod: session.method,
+ expiresAt: DateTime.toUtc(session.expiresAt),
+ } satisfies AuthBootstrapResult,
+ sessionToken: session.token,
+ }) satisfies BootstrapExchangeResult,
+ ),
+ );
+
+ const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
+ (credential, requestMetadata) =>
+ bootstrapCredentials.consume(credential).pipe(
+ Effect.mapError(toBootstrapExchangeAuthError),
+ Effect.flatMap((grant) =>
+ sessions
+ .issue({
+ method: "bearer-session-token",
+ subject: grant.subject,
+ role: grant.role,
+ client: {
+ ...requestMetadata,
+ ...(grant.label ? { label: grant.label } : {}),
+ },
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to issue authenticated session.",
+ cause,
+ }),
+ ),
+ ),
+ ),
+ Effect.map(
+ (session) =>
+ ({
+ authenticated: true,
+ role: session.role,
+ sessionMethod: "bearer-session-token",
+ expiresAt: DateTime.toUtc(session.expiresAt),
+ sessionToken: session.token,
+ }) satisfies AuthBearerBootstrapResult,
+ ),
+ );
+
+ const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
+ authControlPlane
+ .createPairingLink({
+ role: input?.role ?? "client",
+ subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
+ ...(input?.label ? { label: input.label } : {}),
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to issue pairing credential.",
+ cause,
+ }),
+ ),
+ Effect.map(
+ (issued) =>
+ ({
+ id: issued.id,
+ credential: issued.credential,
+ ...(issued.label ? { label: issued.label } : {}),
+ expiresAt: issued.expiresAt,
+ }) satisfies AuthPairingCredentialResult,
+ ),
+ );
+
+ const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
+ authControlPlane
+ .listPairingLinks({
+ role: "client",
+ excludeSubjects: ["owner-bootstrap"],
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to load pairing links.",
+ cause,
+ }),
+ ),
+ );
+
+ const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
+ authControlPlane.revokePairingLink(id).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to revoke pairing link.",
+ cause,
+ }),
+ ),
+ );
+
+ const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
+ authControlPlane.listSessions().pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to load paired clients.",
+ cause,
+ }),
+ ),
+ Effect.map((clientSessions) =>
+ clientSessions.map(
+ (clientSession): AuthClientSession => ({
+ ...clientSession,
+ current: clientSession.sessionId === currentSessionId,
+ }),
+ ),
+ ),
+ );
+
+ const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
+ currentSessionId,
+ targetSessionId,
+ ) =>
+ Effect.gen(function* () {
+ if (currentSessionId === targetSessionId) {
+ return yield* new AuthError({
+ message: "Use revoke other clients to keep the current owner session active.",
+ status: 403,
+ });
+ }
+ return yield* authControlPlane.revokeSession(targetSessionId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to revoke client session.",
+ cause,
+ }),
+ ),
+ );
+ });
+
+ const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
+ currentSessionId,
+ ) =>
+ authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to revoke other client sessions.",
+ cause,
+ }),
+ ),
+ );
+
+ const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
+ issuePairingCredential({ role: "owner" }).pipe(
+ Effect.map((issued) => {
+ const url = new URL(baseUrl);
+ url.pathname = "/pair";
+ url.searchParams.delete("token");
+ url.hash = new URLSearchParams([["token", issued.credential]]).toString();
+ return url.toString();
+ }),
+ );
+
+ const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
+ sessions.issueWebSocketToken(session.sessionId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Failed to issue websocket token.",
+ cause,
+ }),
+ ),
+ Effect.map(
+ (issued) =>
+ ({
+ token: issued.token,
+ expiresAt: DateTime.toUtc(issued.expiresAt),
+ }) satisfies AuthWebSocketTokenResult,
+ ),
+ );
+
+ const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
+ Effect.gen(function* () {
+ const requestUrl = HttpServerRequest.toURL(request);
+ if (Option.isSome(requestUrl)) {
+ const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
+ if (websocketToken && websocketToken.trim().length > 0) {
+ return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
+ Effect.map((session) => ({
+ sessionId: session.sessionId,
+ subject: session.subject,
+ method: session.method,
+ role: session.role,
+ ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
+ })),
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Unauthorized request.",
+ status: 401,
+ cause,
+ }),
+ ),
+ );
+ }
+ }
+
+ return yield* authenticateRequest(request);
+ });
+
+ return {
+ getDescriptor: () => Effect.succeed(descriptor),
+ getSessionState,
+ exchangeBootstrapCredential,
+ exchangeBootstrapCredentialForBearerSession,
+ issuePairingCredential,
+ listPairingLinks,
+ revokePairingLink,
+ listClientSessions,
+ revokeClientSession,
+ revokeOtherClientSessions,
+ authenticateHttpRequest: authenticateRequest,
+ authenticateWebSocketUpgrade,
+ issueWebSocketToken,
+ issueStartupPairingUrl,
+ } satisfies ServerAuthShape;
+});
+
+export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
+ Layer.provideMerge(AuthControlPlaneLive),
+ Layer.provideMerge(AuthCoreLive),
+ Layer.provideMerge(ServerAuthPolicyLive),
+);
diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts
new file mode 100644
index 000000000..640cc030f
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts
@@ -0,0 +1,111 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Effect, Layer } from "effect";
+
+import type { ServerConfigShape } from "../../config.ts";
+import { ServerConfig } from "../../config.ts";
+import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
+import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
+
+const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
+ ServerAuthPolicyLive.pipe(
+ Layer.provide(
+ Layer.effect(
+ ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ return {
+ ...config,
+ ...overrides,
+ } satisfies ServerConfigShape;
+ }),
+ ).pipe(
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
+ ),
+ ),
+ );
+
+it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
+ it.effect("uses desktop-managed-local policy for desktop mode", () =>
+ Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const descriptor = yield* policy.getDescriptor();
+
+ expect(descriptor.policy).toBe("desktop-managed-local");
+ expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
+ }).pipe(
+ Effect.provide(
+ makeServerAuthPolicyLayer({
+ mode: "desktop",
+ }),
+ ),
+ ),
+ );
+
+ it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
+ Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const descriptor = yield* policy.getDescriptor();
+
+ expect(descriptor.policy).toBe("remote-reachable");
+ expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
+ }).pipe(
+ Effect.provide(
+ makeServerAuthPolicyLayer({
+ mode: "desktop",
+ host: "0.0.0.0",
+ }),
+ ),
+ ),
+ );
+
+ it.effect("uses loopback-browser policy for loopback web hosts", () =>
+ Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const descriptor = yield* policy.getDescriptor();
+
+ expect(descriptor.policy).toBe("loopback-browser");
+ expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
+ }).pipe(
+ Effect.provide(
+ makeServerAuthPolicyLayer({
+ mode: "web",
+ host: "127.0.0.1",
+ }),
+ ),
+ ),
+ );
+
+ it.effect("uses remote-reachable policy for wildcard web hosts", () =>
+ Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const descriptor = yield* policy.getDescriptor();
+
+ expect(descriptor.policy).toBe("remote-reachable");
+ expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
+ }).pipe(
+ Effect.provide(
+ makeServerAuthPolicyLayer({
+ mode: "web",
+ host: "0.0.0.0",
+ }),
+ ),
+ ),
+ );
+
+ it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
+ Effect.gen(function* () {
+ const policy = yield* ServerAuthPolicy;
+ const descriptor = yield* policy.getDescriptor();
+
+ expect(descriptor.policy).toBe("remote-reachable");
+ }).pipe(
+ Effect.provide(
+ makeServerAuthPolicyLayer({
+ mode: "web",
+ host: "192.168.1.50",
+ }),
+ ),
+ ),
+ );
+});
diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.ts
new file mode 100644
index 000000000..eaddf968f
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerAuthPolicy.ts
@@ -0,0 +1,57 @@
+import type { ServerAuthDescriptor } from "@t3tools/contracts";
+import { Effect, Layer } from "effect";
+
+import { ServerConfig } from "../../config.ts";
+import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
+import { SESSION_COOKIE_NAME } from "../utils.ts";
+
+const isWildcardHost = (host: string | undefined): boolean =>
+ host === "0.0.0.0" || host === "::" || host === "[::]";
+
+const isLoopbackHost = (host: string | undefined): boolean => {
+ if (!host || host.length === 0) {
+ return true;
+ }
+
+ return (
+ host === "localhost" ||
+ host === "127.0.0.1" ||
+ host === "::1" ||
+ host === "[::1]" ||
+ host.startsWith("127.")
+ );
+};
+
+export const makeServerAuthPolicy = Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
+
+ const policy =
+ config.mode === "desktop"
+ ? isRemoteReachable
+ ? "remote-reachable"
+ : "desktop-managed-local"
+ : isRemoteReachable
+ ? "remote-reachable"
+ : "loopback-browser";
+
+ const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
+ policy === "desktop-managed-local"
+ ? ["desktop-bootstrap"]
+ : config.mode === "desktop" && policy === "remote-reachable"
+ ? ["desktop-bootstrap", "one-time-token"]
+ : ["one-time-token"];
+
+ const descriptor: ServerAuthDescriptor = {
+ policy,
+ bootstrapMethods,
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: SESSION_COOKIE_NAME,
+ };
+
+ return {
+ getDescriptor: () => Effect.succeed(descriptor),
+ } satisfies ServerAuthPolicyShape;
+});
+
+export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
diff --git a/apps/server/src/auth/Layers/ServerSecretStore.test.ts b/apps/server/src/auth/Layers/ServerSecretStore.test.ts
new file mode 100644
index 000000000..7e6352eec
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerSecretStore.test.ts
@@ -0,0 +1,263 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
+import * as PlatformError from "effect/PlatformError";
+
+import { ServerConfig } from "../../config.ts";
+import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
+
+const makeServerConfigLayer = () =>
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
+
+const makeServerSecretStoreLayer = () =>
+ Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
+
+const PermissionDeniedFileSystemLayer = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+
+ return {
+ ...fileSystem,
+ readFile: (path) =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "PermissionDenied",
+ module: "FileSystem",
+ method: "readFile",
+ pathOrDescriptor: path,
+ description: "Permission denied while reading secret file.",
+ }),
+ ),
+ } satisfies FileSystem.FileSystem;
+ }),
+).pipe(Layer.provide(NodeServices.layer));
+
+const makePermissionDeniedSecretStoreLayer = () =>
+ ServerSecretStoreLive.pipe(
+ Layer.provide(makeServerConfigLayer()),
+ Layer.provideMerge(PermissionDeniedFileSystemLayer),
+ );
+
+const RenameFailureFileSystemLayer = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+
+ return {
+ ...fileSystem,
+ rename: (from, to) =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "PermissionDenied",
+ module: "FileSystem",
+ method: "rename",
+ pathOrDescriptor: `${String(from)} -> ${String(to)}`,
+ description: "Permission denied while persisting secret file.",
+ }),
+ ),
+ } satisfies FileSystem.FileSystem;
+ }),
+).pipe(Layer.provide(NodeServices.layer));
+
+const makeRenameFailureSecretStoreLayer = () =>
+ ServerSecretStoreLive.pipe(
+ Layer.provide(makeServerConfigLayer()),
+ Layer.provideMerge(RenameFailureFileSystemLayer),
+ );
+
+const RemoveFailureFileSystemLayer = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+
+ return {
+ ...fileSystem,
+ remove: (path, options) =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "PermissionDenied",
+ module: "FileSystem",
+ method: "remove",
+ pathOrDescriptor: String(path),
+ description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
+ }),
+ ),
+ } satisfies FileSystem.FileSystem;
+ }),
+).pipe(Layer.provide(NodeServices.layer));
+
+const makeRemoveFailureSecretStoreLayer = () =>
+ ServerSecretStoreLive.pipe(
+ Layer.provide(makeServerConfigLayer()),
+ Layer.provideMerge(RemoveFailureFileSystemLayer),
+ );
+
+const ConcurrentReadMissFileSystemLayer = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const readCountRef = yield* Ref.make(0);
+ const readBarrier = yield* Deferred.make<void>();
+
+ return {
+ ...fileSystem,
+ readFile: (path) =>
+ String(path).endsWith("/session-signing-key.bin")
+ ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
+ Effect.flatMap((count) => {
+ if (count > 2) {
+ return fileSystem.readFile(path);
+ }
+ return Effect.gen(function* () {
+ if (count === 2) {
+ yield* Deferred.succeed(readBarrier, void 0);
+ }
+ yield* Deferred.await(readBarrier);
+ return yield* Effect.failCause(
+ Cause.fail(
+ PlatformError.systemError({
+ _tag: "NotFound",
+ module: "FileSystem",
+ method: "readFile",
+ pathOrDescriptor: String(path),
+ description: "Secret file does not exist yet.",
+ }),
+ ),
+ );
+ });
+ }),
+ )
+ : fileSystem.readFile(path),
+ } satisfies FileSystem.FileSystem;
+ }),
+).pipe(Layer.provide(NodeServices.layer));
+
+const makeConcurrentCreateSecretStoreLayer = () =>
+ ServerSecretStoreLive.pipe(
+ Layer.provide(makeServerConfigLayer()),
+ Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
+ );
+
+it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
+ it.effect("returns null when a secret file does not exist", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const secret = yield* secretStore.get("missing-secret");
+
+ expect(secret).toBeNull();
+ }).pipe(Effect.provide(makeServerSecretStoreLayer())),
+ );
+
+ it.effect("reuses an existing secret instead of regenerating it", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
+ const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
+
+ expect(Array.from(second)).toEqual(Array.from(first));
+ }).pipe(Effect.provide(makeServerSecretStoreLayer())),
+ );
+
+ it.effect("returns the persisted secret when concurrent creators race", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const [first, second] = yield* Effect.all(
+ [
+ secretStore.getOrCreateRandom("session-signing-key", 32),
+ secretStore.getOrCreateRandom("session-signing-key", 32),
+ ],
+ { concurrency: "unbounded" },
+ );
+ const persisted = yield* secretStore.get("session-signing-key");
+
+ expect(persisted).not.toBeNull();
+ expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
+ expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
+ }).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
+ );
+
+ it.effect("uses restrictive permissions for the secret directory and files", () =>
+ Effect.gen(function* () {
+ const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
+ const recordingFileSystemLayer = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+
+ return {
+ ...fileSystem,
+ makeDirectory: () => Effect.void,
+ writeFile: () => Effect.void,
+ rename: () => Effect.void,
+ chmod: (path, mode) =>
+ Effect.sync(() => {
+ chmodCalls.push({ path: String(path), mode });
+ }),
+ } satisfies FileSystem.FileSystem;
+ }),
+ ).pipe(Layer.provide(NodeServices.layer));
+
+ const secretStore = yield* Effect.service(ServerSecretStore).pipe(
+ Effect.provide(
+ ServerSecretStoreLive.pipe(
+ Layer.provide(makeServerConfigLayer()),
+ Layer.provideMerge(recordingFileSystemLayer),
+ ),
+ ),
+ );
+
+ yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
+
+ expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
+ true,
+ );
+ expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("propagates read failures other than missing-file errors", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
+
+ expect(error).toBeInstanceOf(SecretStoreError);
+ expect(error.message).toContain("Failed to read secret session-signing-key.");
+ expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
+ expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
+ }).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
+ );
+
+ it.effect("propagates write failures instead of treating them as success", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const error = yield* Effect.flip(
+ secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
+ );
+
+ expect(error).toBeInstanceOf(SecretStoreError);
+ expect(error.message).toContain("Failed to persist secret session-signing-key.");
+ expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
+ expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
+ }).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
+ );
+
+ it.effect("propagates remove failures other than missing-file errors", () =>
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+
+ const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
+
+ expect(error).toBeInstanceOf(SecretStoreError);
+ expect(error.message).toContain("Failed to remove secret session-signing-key.");
+ expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
+ expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
+ }).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
+ );
+});
diff --git a/apps/server/src/auth/Layers/ServerSecretStore.ts b/apps/server/src/auth/Layers/ServerSecretStore.ts
new file mode 100644
index 000000000..a106d15fd
--- /dev/null
+++ b/apps/server/src/auth/Layers/ServerSecretStore.ts
@@ -0,0 +1,151 @@
+import * as Crypto from "node:crypto";
+
+import { Effect, FileSystem, Layer, Path } from "effect";
+import * as PlatformError from "effect/PlatformError";
+
+import { ServerConfig } from "../../config.ts";
+import {
+ SecretStoreError,
+ ServerSecretStore,
+ type ServerSecretStoreShape,
+} from "../Services/ServerSecretStore.ts";
+
+export const makeServerSecretStore = Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const serverConfig = yield* ServerConfig;
+
+ yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
+ yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
+ Effect.mapError(
+ (cause) =>
+ new SecretStoreError({
+ message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
+ cause,
+ }),
+ ),
+ );
+
+ const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
+
+ const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
+ cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
+
+ const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
+ cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
+
+ const get: ServerSecretStoreShape["get"] = (name) =>
+ fileSystem.readFile(resolveSecretPath(name)).pipe(
+ Effect.map((bytes) => Uint8Array.from(bytes)),
+ Effect.catch((cause) =>
+ isMissingSecretFileError(cause)
+ ? Effect.succeed(null)
+ : Effect.fail(
+ new SecretStoreError({
+ message: `Failed to read secret ${name}.`,
+ cause,
+ }),
+ ),
+ ),
+ );
+
+ const set: ServerSecretStoreShape["set"] = (name, value) => {
+ const secretPath = resolveSecretPath(name);
+ const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
+ return Effect.gen(function* () {
+ yield* fileSystem.writeFile(tempPath, value);
+ yield* fileSystem.chmod(tempPath, 0o600);
+ yield* fileSystem.rename(tempPath, secretPath);
+ yield* fileSystem.chmod(secretPath, 0o600);
+ }).pipe(
+ Effect.catch((cause) =>
+ fileSystem.remove(tempPath).pipe(
+ Effect.ignore,
+ Effect.flatMap(() =>
+ Effect.fail(
+ new SecretStoreError({
+ message: `Failed to persist secret ${name}.`,
+ cause,
+ }),
+ ),
+ ),
+ ),
+ ),
+ );
+ };
+
+ const create: ServerSecretStoreShape["set"] = (name, value) => {
+ const secretPath = resolveSecretPath(name);
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const file = yield* fileSystem.open(secretPath, {
+ flag: "wx",
+ mode: 0o600,
+ });
+ yield* file.writeAll(value);
+ yield* file.sync;
+ yield* fileSystem.chmod(secretPath, 0o600);
+ }),
+ ).pipe(
+ Effect.mapError(
+ (cause) =>
+ new SecretStoreError({
+ message: `Failed to persist secret ${name}.`,
+ cause,
+ }),
+ ),
+ );
+ };
+
+ const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
+ get(name).pipe(
+ Effect.flatMap((existing) => {
+ if (existing) {
+ return Effect.succeed(existing);
+ }
+
+ const generated = Crypto.randomBytes(bytes);
+ return create(name, generated).pipe(
+ Effect.as(Uint8Array.from(generated)),
+ Effect.catchTag("SecretStoreError", (error) =>
+ isAlreadyExistsSecretFileError(error.cause)
+ ? get(name).pipe(
+ Effect.flatMap((created) =>
+ created !== null
+ ? Effect.succeed(created)
+ : Effect.fail(
+ new SecretStoreError({
+ message: `Failed to read secret ${name} after concurrent creation.`,
+ }),
+ ),
+ ),
+ )
+ : Effect.fail(error),
+ ),
+ );
+ }),
+ );
+
+ const remove: ServerSecretStoreShape["remove"] = (name) =>
+ fileSystem.remove(resolveSecretPath(name)).pipe(
+ Effect.catch((cause) =>
+ isMissingSecretFileError(cause)
+ ? Effect.void
+ : Effect.fail(
+ new SecretStoreError({
+ message: `Failed to remove secret ${name}.`,
+ cause,
+ }),
+ ),
+ ),
+ );
+
+ return {
+ get,
+ set,
+ getOrCreateRandom,
+ remove,
+ } satisfies ServerSecretStoreShape;
+});
+
+export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
diff --git a/apps/server/src/auth/Layers/SessionCredentialService.test.ts b/apps/server/src/auth/Layers/SessionCredentialService.test.ts
new file mode 100644
index 000000000..bafd9c85c
--- /dev/null
+++ b/apps/server/src/auth/Layers/SessionCredentialService.test.ts
@@ -0,0 +1,191 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import { Duration, Effect, Layer } from "effect";
+import { TestClock } from "effect/testing";
+
+import type { ServerConfigShape } from "../../config.ts";
+import { ServerConfig } from "../../config.ts";
+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
+
+const makeServerConfigLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ Layer.effect(
+ ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ return {
+ ...config,
+ ...overrides,
+ } satisfies ServerConfigShape;
+ }),
+ ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
+
+const makeSessionCredentialLayer = (
+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
+) =>
+ SessionCredentialServiceLive.pipe(
+ Layer.provide(SqlitePersistenceMemory),
+ Layer.provide(ServerSecretStoreLive),
+ Layer.provide(makeServerConfigLayer(overrides)),
+ );
+
+it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
+ it.effect("issues and verifies signed browser session tokens", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const issued = yield* sessions.issue({
+ subject: "desktop-bootstrap",
+ role: "owner",
+ client: {
+ label: "Desktop app",
+ deviceType: "desktop",
+ os: "macOS",
+ browser: "Electron",
+ ipAddress: "127.0.0.1",
+ },
+ });
+ const verified = yield* sessions.verify(issued.token);
+
+ expect(verified.method).toBe("browser-session-cookie");
+ expect(verified.subject).toBe("desktop-bootstrap");
+ expect(verified.role).toBe("owner");
+ expect(verified.client.label).toBe("Desktop app");
+ expect(verified.client.browser).toBe("Electron");
+ expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
+ }).pipe(Effect.provide(makeSessionCredentialLayer())),
+ );
+ it.effect("rejects malformed session tokens", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
+
+ expect(error._tag).toBe("SessionCredentialError");
+ expect(error.message).toContain("Malformed session token");
+ }).pipe(Effect.provide(makeSessionCredentialLayer())),
+ );
+ it.effect("verifies session tokens against the Effect clock", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const issued = yield* sessions.issue({
+ method: "bearer-session-token",
+ subject: "test-clock",
+ });
+ const verified = yield* sessions.verify(issued.token);
+
+ expect(verified.method).toBe("bearer-session-token");
+ expect(verified.subject).toBe("test-clock");
+ expect(verified.role).toBe("client");
+ }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
+ );
+
+ it.effect("rejects websocket tokens once the parent session has expired", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const issued = yield* sessions.issue({
+ method: "bearer-session-token",
+ subject: "short-lived",
+ ttl: Duration.seconds(1),
+ });
+ const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
+
+ yield* TestClock.adjust(Duration.seconds(2));
+
+ const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
+ expect(error.message).toContain("expired");
+ }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
+ );
+
+ it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const owner = yield* sessions.issue({
+ subject: "desktop-bootstrap",
+ role: "owner",
+ client: {
+ label: "Desktop app",
+ deviceType: "desktop",
+ os: "macOS",
+ browser: "Electron",
+ },
+ });
+ const client = yield* sessions.issue({
+ subject: "one-time-token",
+ role: "client",
+ client: {
+ label: "Julius iPhone",
+ deviceType: "mobile",
+ os: "iOS",
+ browser: "Safari",
+ ipAddress: "192.168.1.88",
+ },
+ });
+
+ yield* sessions.markConnected(client.sessionId);
+ const beforeRevoke = yield* sessions.listActive();
+ const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
+ const afterRevoke = yield* sessions.listActive();
+ const revokedClient = yield* Effect.flip(sessions.verify(client.token));
+
+ expect(beforeRevoke).toHaveLength(2);
+ expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
+ true,
+ );
+ expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
+ "Julius iPhone",
+ );
+ expect(
+ beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
+ ).toBe("desktop");
+ expect(revokedCount).toBe(1);
+ expect(afterRevoke).toHaveLength(1);
+ expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
+ expect(revokedClient.message).toContain("revoked");
+ }).pipe(Effect.provide(makeSessionCredentialLayer())),
+ );
+
+ it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionCredentialService;
+ const issued = yield* sessions.issue({
+ subject: "reconnect-test",
+ method: "bearer-session-token",
+ });
+
+ const beforeConnect = yield* sessions.listActive();
+ expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
+
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* sessions.markConnected(issued.sessionId);
+ const firstConnect = yield* sessions.listActive();
+ const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
+
+ expect(firstConnect[0]?.connected).toBe(true);
+ expect(firstConnectedAt).not.toBeNull();
+
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* sessions.markConnected(issued.sessionId);
+ const stillConnected = yield* sessions.listActive();
+
+ expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
+
+ yield* sessions.markDisconnected(issued.sessionId);
+ yield* sessions.markDisconnected(issued.sessionId);
+ const afterDisconnect = yield* sessions.listActive();
+
+ expect(afterDisconnect[0]?.connected).toBe(false);
+ expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
+
+ yield* TestClock.adjust(Duration.seconds(1));
+ yield* sessions.markConnected(issued.sessionId);
+ const afterReconnect = yield* sessions.listActive();
+
+ expect(afterReconnect[0]?.connected).toBe(true);
+ expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
+ expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
+ }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
+ );
+});
diff --git a/apps/server/src/auth/Layers/SessionCredentialService.ts b/apps/server/src/auth/Layers/SessionCredentialService.ts
new file mode 100644
index 000000000..e8d034aff
--- /dev/null
+++ b/apps/server/src/auth/Layers/SessionCredentialService.ts
@@ -0,0 +1,493 @@
+import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
+import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
+import { Option } from "effect";
+
+import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
+import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
+import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
+import { SESSION_COOKIE_NAME } from "../utils.ts";
+import {
+ SessionCredentialError,
+ SessionCredentialService,
+ type IssuedSession,
+ type SessionCredentialChange,
+ type SessionCredentialServiceShape,
+ type VerifiedSession,
+} from "../Services/SessionCredentialService.ts";
+import {
+ base64UrlDecodeUtf8,
+ base64UrlEncode,
+ signPayload,
+ timingSafeEqualBase64Url,
+} from "../utils.ts";
+
+const SIGNING_SECRET_NAME = "server-signing-key";
+const DEFAULT_SESSION_TTL = Duration.days(30);
+const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
+
+const SessionClaims = Schema.Struct({
+ v: Schema.Literal(1),
+ kind: Schema.Literal("session"),
+ sid: AuthSessionId,
+ sub: Schema.String,
+ role: Schema.Literals(["owner", "client"]),
+ method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
+ iat: Schema.Number,
+ exp: Schema.Number,
+});
+type SessionClaims = typeof SessionClaims.Type;
+
+const WebSocketClaims = Schema.Struct({
+ v: Schema.Literal(1),
+ kind: Schema.Literal("websocket"),
+ sid: AuthSessionId,
+ iat: Schema.Number,
+ exp: Schema.Number,
+});
+type WebSocketClaims = typeof WebSocketClaims.Type;
+
+function createDefaultClientMetadata(): AuthClientMetadata {
+ return {
+ deviceType: "unknown",
+ };
+}
+
+function toClientMetadata(record: {
+ readonly label: string | null;
+ readonly ipAddress: string | null;
+ readonly userAgent: string | null;
+ readonly deviceType: AuthClientMetadata["deviceType"];
+ readonly os: string | null;
+ readonly browser: string | null;
+}): AuthClientMetadata {
+ return {
+ ...(record.label ? { label: record.label } : {}),
+ ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
+ ...(record.userAgent ? { userAgent: record.userAgent } : {}),
+ deviceType: record.deviceType,
+ ...(record.os ? { os: record.os } : {}),
+ ...(record.browser ? { browser: record.browser } : {}),
+ };
+}
+
+function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
+ return {
+ ...input,
+ current: false,
+ };
+}
+
+export const makeSessionCredentialService = Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+ const authSessions = yield* AuthSessionRepository;
+ const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
+ const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
+ const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
+
+ const toSessionCredentialError = (message: string) => (cause: unknown) =>
+ new SessionCredentialError({
+ message,
+ cause,
+ });
+
+ const emitUpsert = (clientSession: AuthClientSession) =>
+ PubSub.publish(changesPubSub, {
+ type: "clientUpserted",
+ clientSession,
+ }).pipe(Effect.asVoid);
+
+ const emitRemoved = (sessionId: AuthSessionId) =>
+ PubSub.publish(changesPubSub, {
+ type: "clientRemoved",
+ sessionId,
+ }).pipe(Effect.asVoid);
+
+ const loadActiveSession = (sessionId: AuthSessionId) =>
+ Effect.gen(function* () {
+ const row = yield* authSessions.getById({ sessionId });
+ if (Option.isNone(row) || row.value.revokedAt !== null) {
+ return Option.none<AuthClientSession>();
+ }
+
+ const connectedSessions = yield* Ref.get(connectedSessionsRef);
+ return Option.some(
+ toAuthClientSession({
+ sessionId: row.value.sessionId,
+ subject: row.value.subject,
+ role: row.value.role,
+ method: row.value.method,
+ client: toClientMetadata(row.value.client),
+ issuedAt: row.value.issuedAt,
+ expiresAt: row.value.expiresAt,
+ lastConnectedAt: row.value.lastConnectedAt,
+ connected: connectedSessions.has(row.value.sessionId),
+ }),
+ );
+ });
+
+ const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
+ Ref.modify(connectedSessionsRef, (current) => {
+ const next = new Map(current);
+ const wasDisconnected = !next.has(sessionId);
+ next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
+ return [wasDisconnected, next] as const;
+ }).pipe(
+ Effect.flatMap((wasDisconnected) =>
+ wasDisconnected
+ ? DateTime.now.pipe(
+ Effect.flatMap((lastConnectedAt) =>
+ authSessions.setLastConnectedAt({
+ sessionId,
+ lastConnectedAt,
+ }),
+ ),
+ )
+ : Effect.void,
+ ),
+ Effect.flatMap(() => loadActiveSession(sessionId)),
+ Effect.flatMap((session) =>
+ Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
+ ),
+ Effect.catchCause((cause) =>
+ Effect.logError("Failed to publish connected-session auth update.").pipe(
+ Effect.annotateLogs({
+ sessionId,
+ cause,
+ }),
+ ),
+ ),
+ );
+
+ const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
+ Ref.update(connectedSessionsRef, (current) => {
+ const next = new Map(current);
+ const remaining = (next.get(sessionId) ?? 0) - 1;
+ if (remaining > 0) {
+ next.set(sessionId, remaining);
+ } else {
+ next.delete(sessionId);
+ }
+ return next;
+ }).pipe(
+ Effect.flatMap(() => loadActiveSession(sessionId)),
+ Effect.flatMap((session) =>
+ Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
+ ),
+ Effect.catchCause((cause) =>
+ Effect.logError("Failed to publish disconnected-session auth update.").pipe(
+ Effect.annotateLogs({
+ sessionId,
+ cause,
+ }),
+ ),
+ ),
+ );
+
+ const issue: SessionCredentialServiceShape["issue"] = (input) =>
+ Effect.gen(function* () {
+ const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
+ const issuedAt = yield* DateTime.now;
+ const expiresAt = DateTime.add(issuedAt, {
+ milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
+ });
+ const claims: SessionClaims = {
+ v: 1,
+ kind: "session",
+ sid: sessionId,
+ sub: input?.subject ?? "browser",
+ role: input?.role ?? "client",
+ method: input?.method ?? "browser-session-cookie",
+ iat: issuedAt.epochMilliseconds,
+ exp: expiresAt.epochMilliseconds,
+ };
+ const encodedPayload = base64UrlEncode(JSON.stringify(claims));
+ const signature = signPayload(encodedPayload, signingSecret);
+ const client = input?.client ?? createDefaultClientMetadata();
+ yield* authSessions.create({
+ sessionId,
+ subject: claims.sub,
+ role: claims.role,
+ method: claims.method,
+ client: {
+ label: client.label ?? null,
+ ipAddress: client.ipAddress ?? null,
+ userAgent: client.userAgent ?? null,
+ deviceType: client.deviceType,
+ os: client.os ?? null,
+ browser: client.browser ?? null,
+ },
+ issuedAt,
+ expiresAt,
+ });
+ yield* emitUpsert(
+ toAuthClientSession({
+ sessionId,
+ subject: claims.sub,
+ role: claims.role,
+ method: claims.method,
+ client,
+ issuedAt,
+ expiresAt,
+ lastConnectedAt: null,
+ connected: false,
+ }),
+ );
+
+ return {
+ sessionId,
+ token: `${encodedPayload}.${signature}`,
+ method: claims.method,
+ client,
+ expiresAt: expiresAt,
+ role: claims.role,
+ } satisfies IssuedSession;
+ }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
+
+ const verify: SessionCredentialServiceShape["verify"] = (token) =>
+ Effect.gen(function* () {
+ const [encodedPayload, signature] = token.split(".");
+ if (!encodedPayload || !signature) {
+ return yield* new SessionCredentialError({
+ message: "Malformed session token.",
+ });
+ }
+
+ const expectedSignature = signPayload(encodedPayload, signingSecret);
+ if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
+ return yield* new SessionCredentialError({
+ message: "Invalid session token signature.",
+ });
+ }
+
+ const claims = yield* Effect.try({
+ try: () =>
+ Schema.decodeUnknownSync(SessionClaims)(JSON.parse(base64UrlDecodeUtf8(encodedPayload))),
+ catch: (cause) =>
+ new SessionCredentialError({
+ message: "Invalid session token payload.",
+ cause,
+ }),
+ });
+
+ const now = yield* Clock.currentTimeMillis;
+ if (claims.exp <= now) {
+ return yield* new SessionCredentialError({
+ message: "Session token expired.",
+ });
+ }
+
+ const row = yield* authSessions.getById({ sessionId: claims.sid });
+ if (Option.isNone(row)) {
+ return yield* new SessionCredentialError({
+ message: "Unknown session token.",
+ });
+ }
+ if (row.value.revokedAt !== null) {
+ return yield* new SessionCredentialError({
+ message: "Session token revoked.",
+ });
+ }
+
+ return {
+ sessionId: claims.sid,
+ token,
+ method: claims.method,
+ client: toClientMetadata(row.value.client),
+ expiresAt: DateTime.makeUnsafe(claims.exp),
+ subject: claims.sub,
+ role: claims.role,
+ } satisfies VerifiedSession;
+ }).pipe(
+ Effect.mapError((cause) =>
+ cause instanceof SessionCredentialError
+ ? cause
+ : new SessionCredentialError({
+ message: "Failed to verify session credential.",
+ cause,
+ }),
+ ),
+ );
+
+ const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
+ sessionId,
+ input,
+ ) =>
+ Effect.gen(function* () {
+ const issuedAt = yield* DateTime.now;
+ const expiresAt = DateTime.add(issuedAt, {
+ milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
+ });
+ const claims: WebSocketClaims = {
+ v: 1,
+ kind: "websocket",
+ sid: sessionId,
+ iat: issuedAt.epochMilliseconds,
+ exp: expiresAt.epochMilliseconds,
+ };
+ const encodedPayload = base64UrlEncode(JSON.stringify(claims));
+ const signature = signPayload(encodedPayload, signingSecret);
+ return {
+ token: `${encodedPayload}.${signature}`,
+ expiresAt,
+ };
+ }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
+
+ const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
+ Effect.gen(function* () {
+ const [encodedPayload, signature] = token.split(".");
+ if (!encodedPayload || !signature) {
+ return yield* new SessionCredentialError({
+ message: "Malformed websocket token.",
+ });
+ }
+
+ const expectedSignature = signPayload(encodedPayload, signingSecret);
+ if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
+ return yield* new SessionCredentialError({
+ message: "Invalid websocket token signature.",
+ });
+ }
+
+ const claims = yield* Effect.try({
+ try: () =>
+ Schema.decodeUnknownSync(WebSocketClaims)(
+ JSON.parse(base64UrlDecodeUtf8(encodedPayload)),
+ ),
+ catch: (cause) =>
+ new SessionCredentialError({
+ message: "Invalid websocket token payload.",
+ cause,
+ }),
+ });
+
+ const now = yield* Clock.currentTimeMillis;
+ if (claims.exp <= now) {
+ return yield* new SessionCredentialError({
+ message: "Websocket token expired.",
+ });
+ }
+
+ const row = yield* authSessions.getById({ sessionId: claims.sid });
+ if (Option.isNone(row)) {
+ return yield* new SessionCredentialError({
+ message: "Unknown websocket session.",
+ });
+ }
+ if (row.value.expiresAt.epochMilliseconds <= now) {
+ return yield* new SessionCredentialError({
+ message: "Websocket session expired.",
+ });
+ }
+ if (row.value.revokedAt !== null) {
+ return yield* new SessionCredentialError({
+ message: "Websocket session revoked.",
+ });
+ }
+
+ return {
+ sessionId: row.value.sessionId,
+ token,
+ method: row.value.method,
+ client: toClientMetadata(row.value.client),
+ expiresAt: row.value.expiresAt,
+ subject: row.value.subject,
+ role: row.value.role,
+ } satisfies VerifiedSession;
+ }).pipe(
+ Effect.mapError((cause) =>
+ cause instanceof SessionCredentialError
+ ? cause
+ : new SessionCredentialError({
+ message: "Failed to verify websocket token.",
+ cause,
+ }),
+ ),
+ );
+
+ const listActive: SessionCredentialServiceShape["listActive"] = () =>
+ Effect.gen(function* () {
+ const now = yield* DateTime.now;
+ const connectedSessions = yield* Ref.get(connectedSessionsRef);
+ const rows = yield* authSessions.listActive({ now });
+
+ return rows.map((row) =>
+ toAuthClientSession({
+ sessionId: row.sessionId,
+ subject: row.subject,
+ role: row.role,
+ method: row.method,
+ client: toClientMetadata(row.client),
+ issuedAt: row.issuedAt,
+ expiresAt: row.expiresAt,
+ lastConnectedAt: row.lastConnectedAt,
+ connected: connectedSessions.has(row.sessionId),
+ }),
+ );
+ }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
+
+ const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
+ Effect.gen(function* () {
+ const revokedAt = yield* DateTime.now;
+ const revoked = yield* authSessions.revoke({
+ sessionId,
+ revokedAt,
+ });
+ if (revoked) {
+ yield* Ref.update(connectedSessionsRef, (current) => {
+ const next = new Map(current);
+ next.delete(sessionId);
+ return next;
+ });
+ yield* emitRemoved(sessionId);
+ }
+ return revoked;
+ }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
+
+ const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
+ Effect.gen(function* () {
+ const revokedAt = yield* DateTime.now;
+ const revokedSessionIds = yield* authSessions.revokeAllExcept({
+ currentSessionId: sessionId,
+ revokedAt,
+ });
+ if (revokedSessionIds.length > 0) {
+ yield* Ref.update(connectedSessionsRef, (current) => {
+ const next = new Map(current);
+ for (const revokedSessionId of revokedSessionIds) {
+ next.delete(revokedSessionId);
+ }
+ return next;
+ });
+ yield* Effect.forEach(
+ revokedSessionIds,
+ (revokedSessionId) => emitRemoved(revokedSessionId),
+ {
+ concurrency: "unbounded",
+ discard: true,
+ },
+ );
+ }
+ return revokedSessionIds.length;
+ }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
+
+ return {
+ cookieName: SESSION_COOKIE_NAME,
+ issue,
+ verify,
+ issueWebSocketToken,
+ verifyWebSocketToken,
+ listActive,
+ get streamChanges() {
+ return Stream.fromPubSub(changesPubSub);
+ },
+ revoke,
+ revokeAllExcept,
+ markConnected,
+ markDisconnected,
+ } satisfies SessionCredentialServiceShape;
+});
+
+export const SessionCredentialServiceLive = Layer.effect(
+ SessionCredentialService,
+ makeSessionCredentialService,
+).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
diff --git a/apps/server/src/auth/Services/AuthControlPlane.ts b/apps/server/src/auth/Services/AuthControlPlane.ts
new file mode 100644
index 000000000..cbaaf98fd
--- /dev/null
+++ b/apps/server/src/auth/Services/AuthControlPlane.ts
@@ -0,0 +1,69 @@
+import type {
+ AuthClientMetadata,
+ AuthClientSession,
+ AuthPairingLink,
+ AuthSessionId,
+} from "@t3tools/contracts";
+import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
+import { SessionRole } from "./SessionCredentialService";
+
+export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
+
+export interface IssuedPairingLink {
+ readonly id: string;
+ readonly credential: string;
+ readonly role: SessionRole;
+ readonly subject: string;
+ readonly label?: string;
+ readonly createdAt: DateTime.Utc;
+ readonly expiresAt: DateTime.Utc;
+}
+
+export interface IssuedBearerSession {
+ readonly sessionId: AuthSessionId;
+ readonly token: string;
+ readonly method: "bearer-session-token";
+ readonly role: SessionRole;
+ readonly subject: string;
+ readonly client: AuthClientMetadata;
+ readonly expiresAt: DateTime.Utc;
+}
+
+export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
+ readonly message: string;
+ readonly cause?: unknown;
+}> {}
+
+export interface AuthControlPlaneShape {
+ readonly createPairingLink: (input?: {
+ readonly ttl?: Duration.Duration;
+ readonly label?: string;
+ readonly role?: SessionRole;
+ readonly subject?: string;
+ }) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
+ readonly listPairingLinks: (input?: {
+ readonly role?: SessionRole;
+ readonly excludeSubjects?: ReadonlyArray<string>;
+ }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
+ readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
+ readonly issueSession: (input?: {
+ readonly ttl?: Duration.Duration;
+ readonly subject?: string;
+ readonly role?: SessionRole;
+ readonly label?: string;
+ }) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
+ readonly listSessions: () => Effect.Effect<
+ ReadonlyArray<AuthClientSession>,
+ AuthControlPlaneError
+ >;
+ readonly revokeSession: (
+ sessionId: AuthSessionId,
+ ) => Effect.Effect<boolean, AuthControlPlaneError>;
+ readonly revokeOtherSessionsExcept: (
+ sessionId: AuthSessionId,
+ ) => Effect.Effect<number, AuthControlPlaneError>;
+}
+
+export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
+ "t3/AuthControlPlane",
+) {}
diff --git a/apps/server/src/auth/Services/BootstrapCredentialService.ts b/apps/server/src/auth/Services/BootstrapCredentialService.ts
new file mode 100644
index 000000000..4f5cf4fda
--- /dev/null
+++ b/apps/server/src/auth/Services/BootstrapCredentialService.ts
@@ -0,0 +1,57 @@
+import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
+import { Data, DateTime, Duration, ServiceMap } from "effect";
+import type { Effect, Stream } from "effect";
+
+export type BootstrapCredentialRole = "owner" | "client";
+
+export interface BootstrapGrant {
+ readonly method: ServerAuthBootstrapMethod;
+ readonly role: BootstrapCredentialRole;
+ readonly subject: string;
+ readonly label?: string;
+ readonly expiresAt: DateTime.DateTime;
+}
+
+export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
+ readonly message: string;
+ readonly status?: 401 | 500;
+ readonly cause?: unknown;
+}> {}
+
+export interface IssuedBootstrapCredential {
+ readonly id: string;
+ readonly credential: string;
+ readonly label?: string;
+ readonly expiresAt: DateTime.Utc;
+}
+
+export type BootstrapCredentialChange =
+ | {
+ readonly type: "pairingLinkUpserted";
+ readonly pairingLink: AuthPairingLink;
+ }
+ | {
+ readonly type: "pairingLinkRemoved";
+ readonly id: string;
+ };
+
+export interface BootstrapCredentialServiceShape {
+ readonly issueOneTimeToken: (input?: {
+ readonly ttl?: Duration.Duration;
+ readonly role?: BootstrapCredentialRole;
+ readonly subject?: string;
+ readonly label?: string;
+ }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
+ readonly listActive: () => Effect.Effect<
+ ReadonlyArray<AuthPairingLink>,
+ BootstrapCredentialError
+ >;
+ readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
+ readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
+ readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
+}
+
+export class BootstrapCredentialService extends ServiceMap.Service<
+ BootstrapCredentialService,
+ BootstrapCredentialServiceShape
+>()("t3/auth/Services/BootstrapCredentialService") {}
diff --git a/apps/server/src/auth/Services/ServerAuth.ts b/apps/server/src/auth/Services/ServerAuth.ts
new file mode 100644
index 000000000..0e38679b8
--- /dev/null
+++ b/apps/server/src/auth/Services/ServerAuth.ts
@@ -0,0 +1,84 @@
+import type {
+ AuthBearerBootstrapResult,
+ AuthBootstrapResult,
+ AuthClientMetadata,
+ AuthClientSession,
+ AuthCreatePairingCredentialInput,
+ AuthPairingLink,
+ AuthPairingCredentialResult,
+ AuthSessionId,
+ AuthSessionState,
+ ServerAuthDescriptor,
+ ServerAuthSessionMethod,
+ AuthWebSocketTokenResult,
+} from "@t3tools/contracts";
+import { Data, DateTime, ServiceMap } from "effect";
+import type { Effect } from "effect";
+import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
+import type { SessionRole } from "./SessionCredentialService.ts";
+
+export interface AuthenticatedSession {
+ readonly sessionId: AuthSessionId;
+ readonly subject: string;
+ readonly method: ServerAuthSessionMethod;
+ readonly role: SessionRole;
+ readonly expiresAt?: DateTime.DateTime;
+}
+
+export class AuthError extends Data.TaggedError("AuthError")<{
+ readonly message: string;
+ readonly status?: 400 | 401 | 403 | 500;
+ readonly cause?: unknown;
+}> {}
+
+export interface ServerAuthShape {
+ readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
+ readonly getSessionState: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthSessionState, never>;
+ readonly exchangeBootstrapCredential: (
+ credential: string,
+ requestMetadata: AuthClientMetadata,
+ ) => Effect.Effect<
+ {
+ readonly response: AuthBootstrapResult;
+ readonly sessionToken: string;
+ },
+ AuthError
+ >;
+ readonly exchangeBootstrapCredentialForBearerSession: (
+ credential: string,
+ requestMetadata: AuthClientMetadata,
+ ) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
+ readonly issuePairingCredential: (
+ input?: AuthCreatePairingCredentialInput & {
+ readonly role?: SessionRole;
+ },
+ ) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
+ readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
+ readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
+ readonly listClientSessions: (
+ currentSessionId: AuthSessionId,
+ ) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
+ readonly revokeClientSession: (
+ currentSessionId: AuthSessionId,
+ targetSessionId: AuthSessionId,
+ ) => Effect.Effect<boolean, AuthError>;
+ readonly revokeOtherClientSessions: (
+ currentSessionId: AuthSessionId,
+ ) => Effect.Effect<number, AuthError>;
+ readonly authenticateHttpRequest: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthenticatedSession, AuthError>;
+ readonly authenticateWebSocketUpgrade: (
+ request: HttpServerRequest.HttpServerRequest,
+ ) => Effect.Effect<AuthenticatedSession, AuthError>;
+ readonly issueWebSocketToken: (
+ session: AuthenticatedSession,
+ ) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
+ readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
+}
+
+export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
+ "t3/auth/Services/ServerAuth",
+) {}
diff --git a/apps/server/src/auth/Services/ServerAuthPolicy.ts b/apps/server/src/auth/Services/ServerAuthPolicy.ts
new file mode 100644
index 000000000..43dae6ca6
--- /dev/null
+++ b/apps/server/src/auth/Services/ServerAuthPolicy.ts
@@ -0,0 +1,11 @@
+import type { ServerAuthDescriptor } from "@t3tools/contracts";
+import { ServiceMap } from "effect";
+import type { Effect } from "effect";
+
+export interface ServerAuthPolicyShape {
+ readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
+}
+
+export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
+ "t3/auth/Services/ServerAuthPolicy",
+) {}
diff --git a/apps/server/src/auth/Services/ServerSecretStore.ts b/apps/server/src/auth/Services/ServerSecretStore.ts
new file mode 100644
index 000000000..376527aea
--- /dev/null
+++ b/apps/server/src/auth/Services/ServerSecretStore.ts
@@ -0,0 +1,22 @@
+import { Data, ServiceMap } from "effect";
+import type { Effect } from "effect";
+
+export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
+ readonly message: string;
+ readonly cause?: unknown;
+}> {}
+
+export interface ServerSecretStoreShape {
+ readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
+ readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
+ readonly getOrCreateRandom: (
+ name: string,
+ bytes: number,
+ ) => Effect.Effect<Uint8Array, SecretStoreError>;
+ readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
+}
+
+export class ServerSecretStore extends ServiceMap.Service<
+ ServerSecretStore,
+ ServerSecretStoreShape
+>()("t3/auth/Services/ServerSecretStore") {}
diff --git a/apps/server/src/auth/Services/SessionCredentialService.ts b/apps/server/src/auth/Services/SessionCredentialService.ts
new file mode 100644
index 000000000..591504766
--- /dev/null
+++ b/apps/server/src/auth/Services/SessionCredentialService.ts
@@ -0,0 +1,87 @@
+import type {
+ AuthClientMetadata,
+ AuthClientSession,
+ AuthSessionId,
+ ServerAuthSessionMethod,
+} from "@t3tools/contracts";
+import { Data, DateTime, Duration, ServiceMap } from "effect";
+import type { Effect, Stream } from "effect";
+
+export type SessionRole = "owner" | "client";
+
+export interface IssuedSession {
+ readonly sessionId: AuthSessionId;
+ readonly token: string;
+ readonly method: ServerAuthSessionMethod;
+ readonly client: AuthClientMetadata;
+ readonly expiresAt: DateTime.DateTime;
+ readonly role: SessionRole;
+}
+
+export interface VerifiedSession {
+ readonly sessionId: AuthSessionId;
+ readonly token: string;
+ readonly method: ServerAuthSessionMethod;
+ readonly client: AuthClientMetadata;
+ readonly expiresAt?: DateTime.DateTime;
+ readonly subject: string;
+ readonly role: SessionRole;
+}
+
+export type SessionCredentialChange =
+ | {
+ readonly type: "clientUpserted";
+ readonly clientSession: AuthClientSession;
+ }
+ | {
+ readonly type: "clientRemoved";
+ readonly sessionId: AuthSessionId;
+ };
+
+export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
+ readonly message: string;
+ readonly cause?: unknown;
+}> {}
+
+export interface SessionCredentialServiceShape {
+ readonly cookieName: string;
+ readonly issue: (input?: {
+ readonly ttl?: Duration.Duration;
+ readonly subject?: string;
+ readonly method?: ServerAuthSessionMethod;
+ readonly role?: SessionRole;
+ readonly client?: AuthClientMetadata;
+ }) => Effect.Effect<IssuedSession, SessionCredentialError>;
+ readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
+ readonly issueWebSocketToken: (
+ sessionId: AuthSessionId,
+ input?: {
+ readonly ttl?: Duration.Duration;
+ },
+ ) => Effect.Effect<
+ {
+ readonly token: string;
+ readonly expiresAt: DateTime.DateTime;
+ },
+ SessionCredentialError
+ >;
+ readonly verifyWebSocketToken: (
+ token: string,
+ ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
+ readonly listActive: () => Effect.Effect<
+ ReadonlyArray<AuthClientSession>,
+ SessionCredentialError
+ >;
+ readonly streamChanges: Stream.Stream<SessionCredentialChange>;
+ readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
+ readonly revokeAllExcept: (
+ sessionId: AuthSessionId,
+ ) => Effect.Effect<number, SessionCredentialError>;
+ readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
+ readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
+}
+
+export class SessionCredentialService extends ServiceMap.Service<
+ SessionCredentialService,
+ SessionCredentialServiceShape
+>()("t3/auth/Services/SessionCredentialService") {}
diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts
new file mode 100644
index 000000000..76c14646e
--- /dev/null
+++ b/apps/server/src/auth/http.ts
@@ -0,0 +1,254 @@
+import {
+ type AuthBearerBootstrapResult,
+ AuthBootstrapInput,
+ AuthCreatePairingCredentialInput,
+ AuthRevokeClientSessionInput,
+ AuthRevokePairingLinkInput,
+ type AuthWebSocketTokenResult,
+} from "@t3tools/contracts";
+import { DateTime, Effect, Schema } from "effect";
+import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
+
+import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
+import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
+import { deriveAuthClientMetadata } from "./utils.ts";
+
+export const respondToAuthError = (error: AuthError) =>
+ Effect.gen(function* () {
+ if ((error.status ?? 500) >= 500) {
+ yield* Effect.logError("auth route failed", {
+ message: error.message,
+ cause: error.cause,
+ });
+ }
+ return HttpServerResponse.jsonUnsafe(
+ {
+ error: error.message,
+ },
+ { status: error.status ?? 500 },
+ );
+ });
+
+export const authSessionRouteLayer = HttpRouter.add(
+ "GET",
+ "/api/auth/session",
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ const session = yield* serverAuth.getSessionState(request);
+ return HttpServerResponse.jsonUnsafe(session, { status: 200 });
+ }),
+);
+
+const PairingCredentialRequestHeaders = Schema.Struct({
+ "content-length": Schema.optionalKey(Schema.String),
+ "content-type": Schema.optionalKey(Schema.String),
+ "transfer-encoding": Schema.optionalKey(Schema.String),
+});
+
+function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
+ const contentLengthHeader = headers["content-length"];
+ if (typeof contentLengthHeader === "string") {
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
+ if (Number.isFinite(contentLength)) {
+ return contentLength > 0;
+ }
+ }
+ return typeof headers["transfer-encoding"] === "string";
+}
+
+export const authBootstrapRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/bootstrap",
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ const sessions = yield* SessionCredentialService;
+ const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid bootstrap payload.",
+ status: 400,
+ cause,
+ }),
+ ),
+ );
+ const result = yield* serverAuth.exchangeBootstrapCredential(
+ payload.credential,
+ deriveAuthClientMetadata({ request }),
+ );
+
+ return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
+ HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
+ expires: DateTime.toDate(result.response.expiresAt),
+ httpOnly: true,
+ path: "/",
+ sameSite: "lax",
+ }),
+ );
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authBearerBootstrapRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/bootstrap/bearer",
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid bootstrap payload.",
+ status: 400,
+ cause,
+ }),
+ ),
+ );
+ const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
+ payload.credential,
+ deriveAuthClientMetadata({ request }),
+ );
+ return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
+ status: 200,
+ });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authWebSocketTokenRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/ws-token",
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ const session = yield* serverAuth.authenticateHttpRequest(request);
+ const result = yield* serverAuth.issueWebSocketToken(session);
+ return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
+ status: 200,
+ });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authPairingCredentialRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/pairing-token",
+ Effect.gen(function* () {
+ const serverAuth = yield* ServerAuth;
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const session = yield* serverAuth.authenticateHttpRequest(request);
+ if (session.role !== "owner") {
+ return yield* new AuthError({
+ message: "Only owner sessions can create pairing credentials.",
+ status: 403,
+ });
+ }
+ const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid pairing credential request headers.",
+ status: 400,
+ cause,
+ }),
+ ),
+ );
+ const payload = hasRequestBody(headers)
+ ? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid pairing credential payload.",
+ status: 400,
+ cause,
+ }),
+ ),
+ )
+ : {};
+ const result = yield* serverAuth.issuePairingCredential(payload);
+ return HttpServerResponse.jsonUnsafe(result, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+const authenticateOwnerSession = Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ const session = yield* serverAuth.authenticateHttpRequest(request);
+ if (session.role !== "owner") {
+ return yield* new AuthError({
+ message: "Only owner sessions can manage network access.",
+ status: 403,
+ });
+ }
+ return { serverAuth, session } as const;
+});
+
+export const authPairingLinksRouteLayer = HttpRouter.add(
+ "GET",
+ "/api/auth/pairing-links",
+ Effect.gen(function* () {
+ const { serverAuth } = yield* authenticateOwnerSession;
+ const pairingLinks = yield* serverAuth.listPairingLinks();
+ return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/pairing-links/revoke",
+ Effect.gen(function* () {
+ const { serverAuth } = yield* authenticateOwnerSession;
+ const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid revoke pairing link payload.",
+ status: 400,
+ cause,
+ }),
+ ),
+ );
+ const revoked = yield* serverAuth.revokePairingLink(payload.id);
+ return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authClientsRouteLayer = HttpRouter.add(
+ "GET",
+ "/api/auth/clients",
+ Effect.gen(function* () {
+ const { serverAuth, session } = yield* authenticateOwnerSession;
+ const clients = yield* serverAuth.listClientSessions(session.sessionId);
+ return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authClientsRevokeRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/clients/revoke",
+ Effect.gen(function* () {
+ const { serverAuth, session } = yield* authenticateOwnerSession;
+ const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
+ Effect.mapError(
+ (cause) =>
+ new AuthError({
+ message: "Invalid revoke client payload.",
+ status: 400,
+ cause,
+ }),
+ ),
+ );
+ const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
+ return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
+
+export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
+ "POST",
+ "/api/auth/clients/revoke-others",
+ Effect.gen(function* () {
+ const { serverAuth, session } = yield* authenticateOwnerSession;
+ const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
+ return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
+ }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
+);
diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts
new file mode 100644
index 000000000..a767b77de
--- /dev/null
+++ b/apps/server/src/auth/utils.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+
+import { deriveAuthClientMetadata } from "./utils";
+
+describe("deriveAuthClientMetadata", () => {
+ it("labels Electron user agents as Electron instead of Chrome", () => {
+ const metadata = deriveAuthClientMetadata({
+ request: {
+ headers: {
+ "user-agent":
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
+ },
+ source: {
+ remoteAddress: "::ffff:127.0.0.1",
+ },
+ } as never,
+ });
+
+ expect(metadata).toMatchObject({
+ browser: "Electron",
+ deviceType: "desktop",
+ ipAddress: "127.0.0.1",
+ os: "macOS",
+ });
+ });
+});
diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts
new file mode 100644
index 000000000..e87c66c6b
--- /dev/null
+++ b/apps/server/src/auth/utils.ts
@@ -0,0 +1,121 @@
+import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
+import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
+import * as Crypto from "node:crypto";
+
+export const SESSION_COOKIE_NAME = "t3_session";
+
+export function base64UrlEncode(input: string | Uint8Array): string {
+ const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
+ return buffer.toString("base64url");
+}
+
+export function base64UrlDecodeUtf8(input: string): string {
+ return Buffer.from(input, "base64url").toString("utf8");
+}
+
+export function signPayload(payload: string, secret: Uint8Array): string {
+ return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
+}
+
+export function timingSafeEqualBase64Url(left: string, right: string): boolean {
+ const leftBuffer = Buffer.from(left, "base64url");
+ const rightBuffer = Buffer.from(right, "base64url");
+ if (leftBuffer.length !== rightBuffer.length) {
+ return false;
+ }
+ return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
+}
+
+function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
+ if (typeof value !== "string") {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function normalizeIpAddress(value: string | null | undefined): string | undefined {
+ const normalized = normalizeNonEmptyString(value);
+ if (!normalized) {
+ return undefined;
+ }
+ return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
+}
+
+function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
+ if (!userAgent) {
+ return "unknown";
+ }
+
+ const normalized = userAgent.toLowerCase();
+ if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
+ return "bot";
+ }
+ if (/ipad|tablet/.test(normalized)) {
+ return "tablet";
+ }
+ if (/iphone|android.+mobile|mobile/.test(normalized)) {
+ return "mobile";
+ }
+ return "desktop";
+}
+
+function inferBrowser(userAgent: string | undefined): string | undefined {
+ if (!userAgent) {
+ return undefined;
+ }
+ const normalized = userAgent.toLowerCase();
+ if (/edg\//.test(normalized)) return "Edge";
+ if (/opr\//.test(normalized)) return "Opera";
+ if (/firefox\//.test(normalized)) return "Firefox";
+ if (/electron\//.test(normalized)) return "Electron";
+ if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
+ if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
+ return undefined;
+}
+
+function inferOs(userAgent: string | undefined): string | undefined {
+ if (!userAgent) {
+ return undefined;
+ }
+ const normalized = userAgent.toLowerCase();
+ if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
+ if (/android/.test(normalized)) return "Android";
+ if (/mac os x|macintosh/.test(normalized)) return "macOS";
+ if (/windows nt/.test(normalized)) return "Windows";
+ if (/linux/.test(normalized)) return "Linux";
+ return undefined;
+}
+
+function readRemoteAddressFromSource(source: unknown): string | undefined {
+ if (!source || typeof source !== "object") {
+ return undefined;
+ }
+
+ const candidate = source as {
+ readonly remoteAddress?: string | null;
+ readonly socket?: {
+ readonly remoteAddress?: string | null;
+ };
+ };
+
+ return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
+}
+
+export function deriveAuthClientMetadata(input: {
+ readonly request: HttpServerRequest.HttpServerRequest;
+ readonly label?: string;
+}): AuthClientMetadata {
+ const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
+ const ipAddress = readRemoteAddressFromSource(input.request.source);
+ const os = inferOs(userAgent);
+ const browser = inferBrowser(userAgent);
+ return {
+ ...(input.label ? { label: input.label } : {}),
+ ...(ipAddress ? { ipAddress } : {}),
+ ...(userAgent ? { userAgent } : {}),
+ deviceType: inferDeviceType(userAgent),
+ ...(os ? { os } : {}),
+ ...(browser ? { browser } : {}),
+ };
+}
diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts
index ef2f9f55d..6dd48c5d2 100644
--- a/apps/server/src/cli-config.test.ts
+++ b/apps/server/src/cli-config.test.ts
@@ -43,7 +43,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
- authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
@@ -62,7 +61,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "true",
- T3CODE_AUTH_TOKEN: "env-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
},
@@ -85,7 +83,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
- authToken: "env-token",
+ desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
@@ -106,7 +104,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(true),
- authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
@@ -125,7 +122,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "false",
- T3CODE_AUTH_TOKEN: "ignored-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "false",
},
@@ -148,7 +144,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
- authToken: "flag-token",
+ desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
@@ -166,7 +162,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
t3Home: baseDir,
devUrl: "http://127.0.0.1:5173",
noBrowser: true,
- authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
otlpTracesUrl: "http://localhost:4318/v1/traces",
@@ -183,7 +178,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
- authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
@@ -218,7 +212,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
- authToken: "bootstrap-token",
+ desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
@@ -242,7 +236,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.some(customCwd),
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
noBrowser: Option.none(),
- authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
@@ -285,7 +278,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
t3Home: "/tmp/t3-bootstrap-home",
devUrl: "http://127.0.0.1:5173",
noBrowser: false,
- authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
@@ -300,7 +292,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.none(),
- authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
@@ -338,7 +329,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
- authToken: "flag-token",
+ desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
@@ -371,7 +362,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
- authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
@@ -402,7 +392,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
- authToken: undefined,
+ desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts
index fbbe26e6c..4840fecc9 100644
--- a/apps/server/src/cli.test.ts
+++ b/apps/server/src/cli.test.ts
@@ -1,28 +1,41 @@
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as CliError from "effect/unstable/cli/CliError";
+import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "./cli.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
+const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
+const runCliWithRuntime = (args: ReadonlyArray<string>) =>
+ runCli(args).pipe(Effect.provide(CliRuntimeLayer));
+
+const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ Effect.gen(function* () {
+ const result = yield* effect;
+ const output =
+ (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
+ "";
+ return { result, output };
+ }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
+
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
- Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
- Effect.provide(CliRuntimeLayer),
- ),
+ runCliWithRuntime(["--log-level", "debug", "--version"]),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
- const error = yield* Command.runWith(cli, { version: "0.0.0" })([
- "--log-level",
- "Debug",
- ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
+ const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
@@ -34,4 +47,87 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
assert.equal(error.value, "Debug");
}),
);
+
+ it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
+ Effect.gen(function* () {
+ const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
+
+ const createdOutput = yield* captureStdout(
+ runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
+ );
+ const created = JSON.parse(createdOutput.output) as {
+ readonly id: string;
+ readonly credential: string;
+ };
+ const listedOutput = yield* captureStdout(
+ runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
+ );
+ const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
+ readonly id: string;
+ readonly credential?: string;
+ }>;
+
+ assert.equal(typeof created.id, "string");
+ assert.equal(typeof created.credential, "string");
+ assert.equal(created.credential.length > 0, true);
+ assert.equal(listed.length, 1);
+ assert.equal(listed[0]?.id, created.id);
+ assert.equal("credential" in (listed[0] ?? {}), false);
+ }),
+ );
+
+ it.effect("executes auth session subcommands and redacts secrets from list output", () =>
+ Effect.gen(function* () {
+ const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
+
+ const issuedOutput = yield* captureStdout(
+ runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
+ );
+ const issued = JSON.parse(issuedOutput.output) as {
+ readonly sessionId: string;
+ readonly token: string;
+ readonly role: string;
+ };
+ const listedOutput = yield* captureStdout(
+ runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
+ );
+ const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
+ readonly sessionId: string;
+ readonly token?: string;
+ readonly role: string;
+ }>;
+
+ assert.equal(typeof issued.sessionId, "string");
+ assert.equal(typeof issued.token, "string");
+ assert.equal(issued.role, "owner");
+ assert.equal(listed.length, 1);
+ assert.equal(listed[0]?.sessionId, issued.sessionId);
+ assert.equal(listed[0]?.role, "owner");
+ assert.equal("token" in (listed[0] ?? {}), false);
+ }),
+ );
+
+ it.effect("rejects invalid ttl values before running auth commands", () =>
+ Effect.gen(function* () {
+ const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
+ Effect.flip,
+ );
+
+ if (!CliError.isCliError(error)) {
+ assert.fail(`Expected CliError, got ${String(error)}`);
+ }
+ if (error._tag !== "ShowHelp") {
+ assert.fail(`Expected ShowHelp, got ${error._tag}`);
+ }
+ assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
+ const ttlError = error.errors[0] as CliError.CliError | undefined;
+ if (!ttlError || ttlError._tag !== "InvalidValue") {
+ assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
+ }
+ assert.equal(ttlError.option, "ttl");
+ assert.equal(ttlError.value, "soon");
+ assert.isTrue(ttlError.message.includes("Invalid duration"));
+ assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
+ }),
+ );
});
diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts
index 9ece02a0d..01fd30054 100644
--- a/apps/server/src/cli.ts
+++ b/apps/server/src/cli.ts
@@ -1,6 +1,20 @@
import { NetService } from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
-import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect";
+import { AuthSessionId } from "@t3tools/contracts";
+import {
+ Config,
+ Console,
+ Duration,
+ Effect,
+ FileSystem,
+ LogLevel,
+ Option,
+ Path,
+ References,
+ Schema,
+ SchemaIssue,
+ SchemaTransformation,
+} from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
@@ -15,6 +29,14 @@ import {
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
+import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
+import {
+ formatIssuedPairingCredential,
+ formatIssuedSession,
+ formatPairingCredentialList,
+ formatSessionList,
+} from "./cliAuthFormat";
+import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -25,7 +47,7 @@ const BootstrapEnvelopeSchema = Schema.Struct({
t3Home: Schema.optional(Schema.String),
devUrl: Schema.optional(Schema.URLFromString),
noBrowser: Schema.optional(Schema.Boolean),
- authToken: Schema.optional(Schema.String),
+ desktopBootstrapToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
otlpTracesUrl: Schema.optional(Schema.String),
@@ -58,11 +80,6 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
Flag.withDescription("Disable automatic browser opening."),
Flag.optional,
);
-const authTokenFlag = Flag.string("auth-token").pipe(
- Flag.withDescription("Auth token required for WebSocket connections."),
- Flag.withAlias("token"),
- Flag.optional,
-);
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
Flag.withSchema(Schema.Int),
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
@@ -117,10 +134,6 @@ const EnvServerConfig = Config.all({
Config.option,
Config.map(Option.getOrUndefined),
),
- authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
- Config.option,
- Config.map(Option.getOrUndefined),
- ),
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -143,12 +156,16 @@ interface CliServerFlags {
readonly cwd: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
- readonly authToken: Option.Option<string>;
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
}
+interface CliAuthLocationFlags {
+ readonly baseDir: Option.Option<string>;
+ readonly devUrl: Option.Option<URL>;
+}
+
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
@@ -248,13 +265,9 @@ export const resolveServerConfig = (
() => mode === "desktop",
),
);
- const authToken = Option.getOrUndefined(
- resolveOptionPrecedence(
- flags.authToken,
- Option.fromUndefinedOr(env.authToken),
- Option.flatMap(bootstrapEnvelope, (bootstrap) =>
- Option.fromUndefinedOr(bootstrap.authToken),
- ),
+ const desktopBootstrapToken = Option.getOrUndefined(
+ Option.flatMap(bootstrapEnvelope, (bootstrap) =>
+ Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
),
);
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
@@ -327,7 +340,7 @@ export const resolveServerConfig = (
staticDir,
devUrl,
noBrowser,
- authToken,
+ desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
};
@@ -335,6 +348,110 @@ export const resolveServerConfig = (
return config;
});
+const resolveCliAuthConfig = (
+ flags: CliAuthLocationFlags,
+ cliLogLevel: Option.Option<LogLevel.LogLevel>,
+) =>
+ resolveServerConfig(
+ {
+ mode: Option.none(),
+ port: Option.none(),
+ host: Option.none(),
+ baseDir: flags.baseDir,
+ cwd: Option.none(),
+ devUrl: flags.devUrl,
+ noBrowser: Option.none(),
+ bootstrapFd: Option.none(),
+ autoBootstrapProjectFromCwd: Option.none(),
+ logWebSocketEvents: Option.none(),
+ },
+ cliLogLevel,
+ );
+
+const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
+
+const parseDurationInput = (value: string): Duration.Duration | null => {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) return null;
+
+ const shorthand = DurationShorthandPattern.exec(trimmed);
+ const normalizedInput = shorthand?.groups
+ ? (() => {
+ const amountText = shorthand.groups.value;
+ const unitText = shorthand.groups.unit;
+ if (typeof amountText !== "string" || typeof unitText !== "string") {
+ return null;
+ }
+
+ const amount = Number.parseInt(amountText, 10);
+ if (!Number.isFinite(amount)) return null;
+
+ switch (unitText.toLowerCase()) {
+ case "ms":
+ return `${amount} millis`;
+ case "s":
+ return `${amount} seconds`;
+ case "m":
+ return `${amount} minutes`;
+ case "h":
+ return `${amount} hours`;
+ case "d":
+ return `${amount} days`;
+ case "w":
+ return `${amount} weeks`;
+ default:
+ return null;
+ }
+ })()
+ : (trimmed as Duration.Input);
+
+ if (normalizedInput === null) return null;
+
+ const decoded = Duration.fromInput(normalizedInput as Duration.Input);
+ return Option.isSome(decoded) ? decoded.value : null;
+};
+
+const DurationFromString = Schema.String.pipe(
+ Schema.decodeTo(
+ Schema.Duration,
+ SchemaTransformation.transformOrFail({
+ decode: (value) => {
+ const duration = parseDurationInput(value);
+ if (duration !== null) {
+ return Effect.succeed(duration);
+ }
+ return Effect.fail(
+ new SchemaIssue.InvalidValue(Option.some(value), {
+ message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
+ }),
+ );
+ },
+ encode: (duration) => Effect.succeed(Duration.format(duration)),
+ }),
+ ),
+);
+
+const runWithAuthControlPlane = <A, E>(
+ flags: CliAuthLocationFlags,
+ run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
+ options?: {
+ readonly quietLogs?: boolean;
+ },
+) =>
+ Effect.gen(function* () {
+ const logLevel = yield* GlobalFlag.LogLevel;
+ const config = yield* resolveCliAuthConfig(flags, logLevel);
+ const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
+ return yield* Effect.gen(function* () {
+ const authControlPlane = yield* AuthControlPlane;
+ return yield* run(authControlPlane);
+ }).pipe(
+ Effect.provide(AuthControlPlaneRuntimeLive),
+ Effect.provideService(ServerConfig, config),
+ Effect.provideService(References.MinimumLogLevel, minimumLogLevel),
+ );
+ });
+
const commandFlags = {
mode: modeFlag,
port: portFlag,
@@ -348,13 +465,216 @@ const commandFlags = {
),
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
- authToken: authTokenFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
} as const;
-const rootCommand = Command.make("t3", commandFlags).pipe(
+const authLocationFlags = {
+ baseDir: baseDirFlag,
+ devUrl: devUrlFlag,
+} as const;
+
+const ttlFlag = Flag.string("ttl").pipe(
+ Flag.withSchema(DurationFromString),
+ Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
+ Flag.optional,
+);
+
+const jsonFlag = Flag.boolean("json").pipe(
+ Flag.withDescription("Emit JSON instead of human-readable output."),
+ Flag.withDefault(false),
+);
+
+const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
+ Flag.withDescription("Role for the issued bearer session."),
+ Flag.withDefault("owner"),
+);
+
+const labelFlag = Flag.string("label").pipe(
+ Flag.withDescription("Optional human-readable label."),
+ Flag.optional,
+);
+
+const subjectFlag = Flag.string("subject").pipe(
+ Flag.withDescription("Optional session subject."),
+ Flag.optional,
+);
+
+const baseUrlFlag = Flag.string("base-url").pipe(
+ Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
+ Flag.optional,
+);
+
+const tokenOnlyFlag = Flag.boolean("token-only").pipe(
+ Flag.withDescription("Print only the issued bearer token."),
+ Flag.withDefault(false),
+);
+
+const pairingCreateCommand = Command.make("create", {
+ ...authLocationFlags,
+ ttl: ttlFlag,
+ label: labelFlag,
+ baseUrl: baseUrlFlag,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("Issue a new client pairing token."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(
+ flags,
+ (authControlPlane) =>
+ Effect.gen(function* () {
+ const issued = yield* authControlPlane.createPairingLink({
+ role: "client",
+ subject: "one-time-token",
+ ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
+ ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
+ });
+ const output = formatIssuedPairingCredential(issued, {
+ json: flags.json,
+ ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
+ });
+ yield* Console.log(output);
+ }),
+ {
+ quietLogs: flags.json,
+ },
+ ),
+ ),
+);
+
+const pairingListCommand = Command.make("list", {
+ ...authLocationFlags,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("List active client pairing tokens without revealing their secrets."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(
+ flags,
+ (authControlPlane) =>
+ Effect.gen(function* () {
+ const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
+ yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
+ }),
+ {
+ quietLogs: flags.json,
+ },
+ ),
+ ),
+);
+
+const pairingRevokeCommand = Command.make("revoke", {
+ ...authLocationFlags,
+ id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
+}).pipe(
+ Command.withDescription("Revoke an active client pairing token."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(flags, (authControlPlane) =>
+ Effect.gen(function* () {
+ const revoked = yield* authControlPlane.revokePairingLink(flags.id);
+ yield* Console.log(
+ revoked
+ ? `Revoked pairing credential ${flags.id}.\n`
+ : `No active pairing credential found for ${flags.id}.\n`,
+ );
+ }),
+ ),
+ ),
+);
+
+const pairingCommand = Command.make("pairing").pipe(
+ Command.withDescription("Manage one-time client pairing tokens."),
+ Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
+);
+
+const sessionIssueCommand = Command.make("issue", {
+ ...authLocationFlags,
+ ttl: ttlFlag,
+ role: sessionRoleFlag,
+ label: labelFlag,
+ subject: subjectFlag,
+ tokenOnly: tokenOnlyFlag,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("Issue a bearer session token for headless or remote clients."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(
+ flags,
+ (authControlPlane) =>
+ Effect.gen(function* () {
+ const issued = yield* authControlPlane.issueSession({
+ role: flags.role,
+ ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
+ ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
+ ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
+ });
+ yield* Console.log(
+ formatIssuedSession(issued, {
+ json: flags.json,
+ tokenOnly: flags.tokenOnly,
+ }),
+ );
+ }),
+ {
+ quietLogs: flags.json || flags.tokenOnly,
+ },
+ ),
+ ),
+);
+
+const sessionListCommand = Command.make("list", {
+ ...authLocationFlags,
+ json: jsonFlag,
+}).pipe(
+ Command.withDescription("List active sessions without revealing bearer tokens."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(
+ flags,
+ (authControlPlane) =>
+ Effect.gen(function* () {
+ const sessions = yield* authControlPlane.listSessions();
+ yield* Console.log(formatSessionList(sessions, { json: flags.json }));
+ }),
+ {
+ quietLogs: flags.json,
+ },
+ ),
+ ),
+);
+
+const sessionRevokeCommand = Command.make("revoke", {
+ ...authLocationFlags,
+ sessionId: Argument.string("session-id").pipe(
+ Argument.withDescription("Session id to revoke."),
+ Argument.withSchema(AuthSessionId),
+ ),
+}).pipe(
+ Command.withDescription("Revoke an active session."),
+ Command.withHandler((flags) =>
+ runWithAuthControlPlane(flags, (authControlPlane) =>
+ Effect.gen(function* () {
+ const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
+ yield* Console.log(
+ revoked
+ ? `Revoked session ${flags.sessionId}.\n`
+ : `No active session found for ${flags.sessionId}.\n`,
+ );
+ }),
+ ),
+ ),
+);
+
+const sessionCommand = Command.make("session").pipe(
+ Command.withDescription("Manage bearer sessions."),
+ Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
+);
+
+const authCommand = Command.make("auth").pipe(
+ Command.withDescription("Manage the local auth control plane for headless deployments."),
+ Command.withSubcommands([pairingCommand, sessionCommand]),
+);
+
+const startCommand = Command.make("start", commandFlags).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) =>
Effect.gen(function* () {
@@ -365,4 +685,14 @@ const rootCommand = Command.make("t3", commandFlags).pipe(
),
);
-export const cli = rootCommand;
+export const cli = Command.make("t3", commandFlags).pipe(
+ Command.withDescription("Run the T3 Code server."),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const logLevel = yield* GlobalFlag.LogLevel;
+ const config = yield* resolveServerConfig(flags, logLevel);
+ return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
+ }),
+ ),
+ Command.withSubcommands([startCommand, authCommand]),
+);
diff --git a/apps/server/src/cliAuthFormat.test.ts b/apps/server/src/cliAuthFormat.test.ts
new file mode 100644
index 000000000..017ced97e
--- /dev/null
+++ b/apps/server/src/cliAuthFormat.test.ts
@@ -0,0 +1,88 @@
+import { expect, it } from "@effect/vitest";
+import { DateTime } from "effect";
+
+import {
+ formatIssuedPairingCredential,
+ formatIssuedSession,
+ formatPairingCredentialList,
+ formatSessionList,
+} from "./cliAuthFormat.ts";
+
+it("formats issued pairing credentials with the secret and optional pair URL", () => {
+ const output = formatIssuedPairingCredential(
+ {
+ id: "pairing-1",
+ credential: "secret-pairing-token",
+ role: "client",
+ subject: "one-time-token",
+ createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
+ expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
+ },
+ { baseUrl: "https://example.com", json: false },
+ );
+
+ expect(output).toContain("secret-pairing-token");
+ expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
+});
+
+it("formats pairing listings without exposing the secret token", () => {
+ const output = formatPairingCredentialList(
+ [
+ {
+ id: "pairing-1",
+ credential: "secret-pairing-token",
+ subject: "one-time-token",
+ label: "Phone",
+ role: "client",
+ createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
+ expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
+ },
+ ],
+ { json: false },
+ );
+
+ expect(output).toContain("pairing-1");
+ expect(output).not.toContain("secret-pairing-token");
+});
+
+it("formats issued sessions with the bearer token but omits tokens from listings", () => {
+ const issuedOutput = formatIssuedSession(
+ {
+ sessionId: "session-1" as never,
+ token: "secret-session-token",
+ method: "bearer-session-token",
+ role: "owner",
+ subject: "cli-issued-session",
+ client: {
+ label: "deploy-bot",
+ deviceType: "bot",
+ },
+ expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
+ },
+ { json: false },
+ );
+
+ const listedOutput = formatSessionList(
+ [
+ {
+ sessionId: "session-1" as never,
+ method: "bearer-session-token",
+ role: "owner",
+ subject: "cli-issued-session",
+ client: {
+ label: "deploy-bot",
+ deviceType: "bot",
+ },
+ connected: false,
+ current: false,
+ issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
+ expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
+ lastConnectedAt: null,
+ },
+ ],
+ { json: false },
+ );
+
+ expect(issuedOutput).toContain("secret-session-token");
+ expect(listedOutput).not.toContain("secret-session-token");
+});
diff --git a/apps/server/src/cliAuthFormat.ts b/apps/server/src/cliAuthFormat.ts
new file mode 100644
index 000000000..44356c5a8
--- /dev/null
+++ b/apps/server/src/cliAuthFormat.ts
@@ -0,0 +1,190 @@
+import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
+import { DateTime } from "effect";
+
+import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
+
+const newline = "\n";
+
+function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
+ return values.filter((value): value is string => typeof value === "string" && value.length > 0);
+}
+
+function formatClientMetadata(metadata: AuthClientMetadata): string {
+ const details = serializeOptionalFields([
+ metadata.label,
+ metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
+ metadata.os,
+ metadata.browser,
+ metadata.ipAddress,
+ ]);
+ return details.length > 0 ? details.join(" | ") : "unlabeled client";
+}
+
+function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
+ return DateTime.formatIso(DateTime.toUtc(value));
+}
+
+export function formatIssuedPairingCredential(
+ credential: IssuedPairingLink,
+ options?: {
+ readonly json?: boolean;
+ readonly baseUrl?: string;
+ },
+): string {
+ const pairUrl =
+ options?.baseUrl != null && options.baseUrl.length > 0
+ ? (() => {
+ const url = new URL("/pair", options.baseUrl);
+ url.searchParams.delete("token");
+ url.hash = new URLSearchParams([["token", credential.credential]]).toString();
+ return url.toString();
+ })()
+ : undefined;
+
+ if (options?.json) {
+ return `${JSON.stringify(
+ {
+ id: credential.id,
+ credential: credential.credential,
+ ...(credential.label ? { label: credential.label } : {}),
+ role: credential.role,
+ expiresAt: toIsoString(credential.expiresAt),
+ ...(pairUrl ? { pairUrl } : {}),
+ },
+ null,
+ 2,
+ )}${newline}`;
+ }
+
+ return (
+ [
+ `Issued client pairing token ${credential.id}.`,
+ `Token: ${credential.credential}`,
+ ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
+ `Expires at: ${credential.expiresAt}`,
+ ].join(newline) + newline
+ );
+}
+
+export function formatPairingCredentialList(
+ credentials: ReadonlyArray<AuthPairingLink>,
+ options?: {
+ readonly json?: boolean;
+ },
+): string {
+ if (options?.json) {
+ return `${JSON.stringify(
+ credentials.map((credential) => ({
+ id: credential.id,
+ ...(credential.label ? { label: credential.label } : {}),
+ role: credential.role,
+ createdAt: toIsoString(credential.createdAt),
+ expiresAt: toIsoString(credential.expiresAt),
+ })),
+ null,
+ 2,
+ )}${newline}`;
+ }
+
+ if (credentials.length === 0) {
+ return `No active pairing credentials.${newline}`;
+ }
+
+ return (
+ credentials
+ .map((credential) =>
+ [
+ `${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
+ ` role: ${credential.role}`,
+ ` created: ${toIsoString(credential.createdAt)}`,
+ ` expires: ${toIsoString(credential.expiresAt)}`,
+ ].join(newline),
+ )
+ .join(`${newline}${newline}`) + newline
+ );
+}
+
+export function formatIssuedSession(
+ session: IssuedBearerSession,
+ options?: {
+ readonly json?: boolean;
+ readonly tokenOnly?: boolean;
+ },
+): string {
+ if (options?.tokenOnly) {
+ return `${session.token}${newline}`;
+ }
+
+ if (options?.json) {
+ return `${JSON.stringify(
+ {
+ sessionId: session.sessionId,
+ token: session.token,
+ method: session.method,
+ role: session.role,
+ subject: session.subject,
+ client: session.client,
+ expiresAt: toIsoString(session.expiresAt),
+ },
+ null,
+ 2,
+ )}${newline}`;
+ }
+
+ return (
+ [
+ `Issued ${session.role} bearer session ${session.sessionId}.`,
+ `Token: ${session.token}`,
+ `Subject: ${session.subject}`,
+ `Client: ${formatClientMetadata(session.client)}`,
+ `Expires at: ${toIsoString(session.expiresAt)}`,
+ ].join(newline) + newline
+ );
+}
+
+export function formatSessionList(
+ sessions: ReadonlyArray<AuthClientSession>,
+ options?: {
+ readonly json?: boolean;
+ },
+): string {
+ if (options?.json) {
+ return `${JSON.stringify(
+ sessions.map((session) => ({
+ sessionId: session.sessionId,
+ method: session.method,
+ role: session.role,
+ subject: session.subject,
+ client: session.client,
+ connected: session.connected,
+ issuedAt: toIsoString(session.issuedAt),
+ expiresAt: toIsoString(session.expiresAt),
+ lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
+ })),
+ null,
+ 2,
+ )}${newline}`;
+ }
+
+ if (sessions.length === 0) {
+ return `No active sessions.${newline}`;
+ }
+
+ return (
+ sessions
+ .map((session) =>
+ [
+ `${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,
+ ` method: ${session.method}`,
+ ` subject: ${session.subject}`,
+ ` client: ${formatClientMetadata(session.client)}`,
+ ` issued: ${toIsoString(session.issuedAt)}`,
+ ` last connected: ${
+ session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
+ }`,
+ ` expires: ${toIsoString(session.expiresAt)}`,
+ ].join(newline),
+ )
+ .join(`${newline}${newline}`) + newline
+ );
+}
diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts
index 887eb11c4..14c34b833 100644
--- a/apps/server/src/config.ts
+++ b/apps/server/src/config.ts
@@ -31,6 +31,7 @@ export interface ServerDerivedPaths {
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
readonly environmentIdPath: string;
+ readonly secretsDir: string;
}
/**
@@ -55,7 +56,7 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
- readonly authToken: string | undefined;
+ readonly desktopBootstrapToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
}
@@ -85,6 +86,7 @@ export const deriveServerPaths = Effect.fn(function* (
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
environmentIdPath: join(stateDir, "environment-id"),
+ secretsDir: join(stateDir, "secrets"),
};
});
@@ -147,7 +149,7 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
logWebSocketEvents: false,
port: 0,
host: undefined,
- authToken: undefined,
+ desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl,
noBrowser: false,
diff --git a/apps/server/src/environment/Layers/ServerEnvironment.test.ts b/apps/server/src/environment/Layers/ServerEnvironment.test.ts
index a9668760f..7505e2ccf 100644
--- a/apps/server/src/environment/Layers/ServerEnvironment.test.ts
+++ b/apps/server/src/environment/Layers/ServerEnvironment.test.ts
@@ -32,7 +32,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
logWebSocketEvents: false,
port: 0,
host: undefined,
- authToken: undefined,
+ desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl: undefined,
noBrowser: false,
diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts
index fd58425de..58102378c 100644
--- a/apps/server/src/environment/Layers/ServerEnvironment.ts
+++ b/apps/server/src/environment/Layers/ServerEnvironment.ts
@@ -4,6 +4,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import { version } from "../../../package.json" with { type: "json" };
+import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
switch (process.platform) {
@@ -65,12 +66,9 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
- const label =
- serverConfig.mode === "desktop"
- ? "Local environment"
- : cwdBaseName.length > 0
- ? cwdBaseName
- : "T3 environment";
+ const label = yield* resolveServerEnvironmentLabel({
+ cwdBaseName,
+ });
const descriptor: ExecutionEnvironmentDescriptor = {
environmentId,
diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts
new file mode 100644
index 000000000..3d4471351
--- /dev/null
+++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, describe, expect, it } from "@effect/vitest";
+import { Effect, FileSystem } from "effect";
+import { vi } from "vitest";
+
+vi.mock("../../processRunner.ts", () => ({
+ runProcess: vi.fn(),
+}));
+
+import { runProcess } from "../../processRunner.ts";
+import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
+
+const mockedRunProcess = vi.mocked(runProcess);
+const NoopFileSystemLayer = FileSystem.layerNoop({});
+
+afterEach(() => {
+ mockedRunProcess.mockReset();
+});
+
+describe("resolveServerEnvironmentLabel", () => {
+ it.effect("uses hostname fallback regardless of launch mode", () =>
+ Effect.gen(function* () {
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "win32",
+ hostname: "macbook-pro",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("macbook-pro");
+ }),
+ );
+
+ it.effect("prefers the macOS ComputerName", () =>
+ Effect.gen(function* () {
+ mockedRunProcess.mockResolvedValueOnce({
+ stdout: " Julius's MacBook Pro \n",
+ stderr: "",
+ code: 0,
+ signal: null,
+ timedOut: false,
+ });
+
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "darwin",
+ hostname: "macbook-pro",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("Julius's MacBook Pro");
+ expect(mockedRunProcess).toHaveBeenCalledWith(
+ "scutil",
+ ["--get", "ComputerName"],
+ expect.objectContaining({ allowNonZeroExit: true }),
+ );
+ }),
+ );
+
+ it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
+ Effect.gen(function* () {
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "linux",
+ hostname: "buildbox",
+ }).pipe(
+ Effect.provide(
+ FileSystem.layerNoop({
+ exists: (path) => Effect.succeed(path === "/etc/machine-info"),
+ readFileString: (path) =>
+ path === "/etc/machine-info"
+ ? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
+ : Effect.succeed(""),
+ }),
+ ),
+ );
+
+ expect(result).toBe("Build Agent 01");
+ expect(mockedRunProcess).not.toHaveBeenCalled();
+ }),
+ );
+
+ it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
+ Effect.gen(function* () {
+ mockedRunProcess.mockResolvedValueOnce({
+ stdout: "CI Runner\n",
+ stderr: "",
+ code: 0,
+ signal: null,
+ timedOut: false,
+ });
+
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "linux",
+ hostname: "runner-01",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("CI Runner");
+ expect(mockedRunProcess).toHaveBeenCalledWith(
+ "hostnamectl",
+ ["--pretty"],
+ expect.objectContaining({ allowNonZeroExit: true }),
+ );
+ }),
+ );
+
+ it.effect("falls back to the hostname when friendly labels are unavailable", () =>
+ Effect.gen(function* () {
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "win32",
+ hostname: "JULIUS-LAPTOP",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("JULIUS-LAPTOP");
+ }),
+ );
+
+ it.effect("falls back to the hostname when the friendly-label command is missing", () =>
+ Effect.gen(function* () {
+ mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
+
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "darwin",
+ hostname: "macbook-pro",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("macbook-pro");
+ }),
+ );
+
+ it.effect("falls back to the cwd basename when the hostname is blank", () =>
+ Effect.gen(function* () {
+ mockedRunProcess.mockResolvedValueOnce({
+ stdout: " ",
+ stderr: "",
+ code: 0,
+ signal: null,
+ timedOut: false,
+ });
+
+ const result = yield* resolveServerEnvironmentLabel({
+ cwdBaseName: "t3code",
+ platform: "linux",
+ hostname: " ",
+ }).pipe(Effect.provide(NoopFileSystemLayer));
+
+ expect(result).toBe("t3code");
+ }),
+ );
+});
diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts
new file mode 100644
index 000000000..a5f77c509
--- /dev/null
+++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts
@@ -0,0 +1,104 @@
+import * as OS from "node:os";
+
+import { Effect, FileSystem } from "effect";
+
+import { runProcess } from "../../processRunner.ts";
+
+interface ResolveServerEnvironmentLabelInput {
+ readonly cwdBaseName: string;
+ readonly platform?: NodeJS.Platform;
+ readonly hostname?: string | null;
+}
+
+function normalizeLabel(value: string | null | undefined): string | null {
+ const trimmed = value?.trim();
+ return trimmed && trimmed.length > 0 ? trimmed : null;
+}
+
+function parseMachineInfoValue(raw: string, key: string): string | null {
+ for (const line of raw.split(/\r?\n/g)) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
+ continue;
+ }
+ const value = trimmed.slice(key.length + 1).trim();
+ if (
+ (value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'"))
+ ) {
+ return normalizeLabel(value.slice(1, -1));
+ }
+ return normalizeLabel(value);
+ }
+ return null;
+}
+
+const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const exists = yield* fileSystem
+ .exists("/etc/machine-info")
+ .pipe(Effect.orElseSucceed(() => false));
+ if (!exists) {
+ return null;
+ }
+
+ return yield* fileSystem
+ .readFileString("/etc/machine-info")
+ .pipe(Effect.orElseSucceed(() => null));
+});
+
+const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
+ command: string,
+ args: readonly string[],
+) {
+ const result = yield* Effect.tryPromise(() =>
+ runProcess(command, args, {
+ allowNonZeroExit: true,
+ }),
+ ).pipe(Effect.orElseSucceed(() => null));
+
+ if (!result || result.code !== 0) {
+ return null;
+ }
+
+ return normalizeLabel(result.stdout);
+});
+
+const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
+ platform: NodeJS.Platform,
+) {
+ if (platform === "darwin") {
+ return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
+ }
+
+ if (platform === "linux") {
+ const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
+ if (machineInfo) {
+ const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
+ if (prettyHostname) {
+ return prettyHostname;
+ }
+ }
+
+ return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
+ }
+
+ return null;
+});
+
+export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
+ input: ResolveServerEnvironmentLabelInput,
+) {
+ const platform = input.platform ?? process.platform;
+ const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
+ if (friendlyHostLabel) {
+ return friendlyHostLabel;
+ }
+
+ const hostname = normalizeLabel(input.hostname ?? OS.hostname());
+ if (hostname) {
+ return hostname;
+ }
+
+ return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
+});
diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts
new file mode 100644
index 000000000..de861cc66
--- /dev/null
+++ b/apps/server/src/http.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
+
+describe("http dev routing", () => {
+ it("treats localhost and loopback addresses as local", () => {
+ expect(isLoopbackHostname("127.0.0.1")).toBe(true);
+ expect(isLoopbackHostname("localhost")).toBe(true);
+ expect(isLoopbackHostname("::1")).toBe(true);
+ expect(isLoopbackHostname("[::1]")).toBe(true);
+ });
+
+ it("does not treat LAN addresses as local", () => {
+ expect(isLoopbackHostname("192.168.86.35")).toBe(false);
+ expect(isLoopbackHostname("10.0.0.24")).toBe(false);
+ expect(isLoopbackHostname("example.local")).toBe(false);
+ });
+
+ it("preserves path and query when redirecting to the dev server", () => {
+ const devUrl = new URL("http://127.0.0.1:5173/");
+ const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
+
+ expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
+ "http://127.0.0.1:5173/pair?token=test-token",
+ );
+ });
+});
diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts
index ca4a2c22e..ed4038942 100644
--- a/apps/server/src/http.ts
+++ b/apps/server/src/http.ts
@@ -1,5 +1,5 @@
import Mime from "@effect/platform-node/Mime";
-import { Data, Effect, FileSystem, Layer, Option, Path } from "effect";
+import { Data, Effect, FileSystem, Option, Path } from "effect";
import { cast } from "effect/Function";
import {
HttpBody,
@@ -17,14 +17,57 @@ import {
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import { resolveAttachmentPathById } from "./attachmentStore";
-import { ServerConfig } from "./config";
+import { resolveStaticDir, ServerConfig } from "./config";
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
+import { ServerAuth } from "./auth/Services/ServerAuth.ts";
+import { respondToAuthError } from "./auth/http.ts";
+import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
+
+export const browserApiCorsLayer = HttpRouter.cors({
+ allowedMethods: ["GET", "POST", "OPTIONS"],
+ allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
+ maxAge: 600,
+});
+
+export function isLoopbackHostname(hostname: string): boolean {
+ const normalizedHostname = hostname
+ .trim()
+ .toLowerCase()
+ .replace(/^\[(.*)\]$/, "$1");
+ return LOOPBACK_HOSTNAMES.has(normalizedHostname);
+}
+
+export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
+ const redirectUrl = new URL(devUrl.toString());
+ redirectUrl.pathname = requestUrl.pathname;
+ redirectUrl.search = requestUrl.search;
+ redirectUrl.hash = requestUrl.hash;
+ return redirectUrl.toString();
+}
+
+const requireAuthenticatedRequest = Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const serverAuth = yield* ServerAuth;
+ yield* serverAuth.authenticateHttpRequest(request);
+});
+
+export const serverEnvironmentRouteLayer = HttpRouter.add(
+ "GET",
+ "/.well-known/t3/environment",
+ Effect.gen(function* () {
+ const descriptor = yield* Effect.service(ServerEnvironment).pipe(
+ Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
+ );
+ return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
+ }),
+);
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
readonly cause: unknown;
@@ -35,6 +78,7 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
"POST",
OTLP_TRACES_PROXY_PATH,
Effect.gen(function* () {
+ yield* requireAuthenticatedRequest;
const request = yield* HttpServerRequest.HttpServerRequest;
const config = yield* ServerConfig;
const otlpTracesUrl = config.otlpTracesUrl;
@@ -76,21 +120,14 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
),
);
- }),
-).pipe(
- Layer.provide(
- HttpRouter.cors({
- allowedMethods: ["POST", "OPTIONS"],
- allowedHeaders: ["content-type"],
- maxAge: 600,
- }),
- ),
+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
);
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
+ yield* requireAuthenticatedRequest;
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
@@ -139,13 +176,14 @@ export const attachmentsRouteLayer = HttpRouter.add(
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
- }),
+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
);
export const projectFaviconRouteLayer = HttpRouter.add(
"GET",
"/api/project-favicon",
Effect.gen(function* () {
+ yield* requireAuthenticatedRequest;
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
@@ -179,7 +217,7 @@ export const projectFaviconRouteLayer = HttpRouter.add(
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
- }),
+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
);
export const staticAndDevRouteLayer = HttpRouter.add(
@@ -193,11 +231,14 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const config = yield* ServerConfig;
- if (config.devUrl) {
- return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
+ if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
+ return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
+ status: 302,
+ });
}
- if (!config.staticDir) {
+ const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
+ if (!staticDir) {
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
status: 503,
});
@@ -205,7 +246,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
- const staticRoot = path.resolve(config.staticDir);
+ const staticRoot = path.resolve(staticDir);
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index 8eda0ca85..e3f190ff0 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -2,7 +2,7 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
-import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
+import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config";
import {
@@ -149,6 +149,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}),
);
+ it.effect("formats invalid resolved keybinding rules with the custom message", () =>
+ Effect.sync(() => {
+ const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({
+ key: "mod+shift+d+o",
+ command: "terminal.new",
+ });
+
+ if (result._tag !== "Failure") {
+ assert.fail("Expected invalid keybinding decode to fail");
+ }
+
+ const detail = Cause.pretty(result.cause);
+ assert.isTrue(detail.includes("Invalid keybinding rule"));
+ assert.isFalse(detail.includes("Invalid data"));
+ }),
+ );
+
it.effect("bootstraps default keybindings when config file is missing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
index 086d795c0..1d0ab812f 100644
--- a/apps/server/src/keybindings.ts
+++ b/apps/server/src/keybindings.ts
@@ -322,7 +322,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Predicate.isNotNull,
() =>
new SchemaIssue.InvalidValue(Option.some(rule), {
- title: "Invalid keybinding rule",
+ message: "Invalid keybinding rule",
}),
),
Effect.map((resolved) => resolved),
@@ -334,7 +334,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
if (!key) {
return yield* Effect.fail(
new SchemaIssue.InvalidValue(Option.some(resolved), {
- title: "Resolved shortcut cannot be encoded to key string",
+ message: "Resolved shortcut cannot be encoded to key string",
}),
);
}
diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.ts
index cb1cb2f3f..eb05bf5ae 100644
--- a/apps/server/src/persistence/Errors.ts
+++ b/apps/server/src/persistence/Errors.ts
@@ -101,5 +101,7 @@ export type OrchestrationCommandReceiptRepositoryError =
| PersistenceDecodeError;
export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;
+export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;
+export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
diff --git a/apps/server/src/persistence/Layers/AuthPairingLinks.ts b/apps/server/src/persistence/Layers/AuthPairingLinks.ts
new file mode 100644
index 000000000..9767f2499
--- /dev/null
+++ b/apps/server/src/persistence/Layers/AuthPairingLinks.ts
@@ -0,0 +1,209 @@
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+import * as SqlSchema from "effect/unstable/sql/SqlSchema";
+import { Effect, Layer, Schema } from "effect";
+
+import {
+ toPersistenceDecodeError,
+ toPersistenceSqlError,
+ type AuthPairingLinkRepositoryError,
+} from "../Errors.ts";
+import {
+ AuthPairingLinkRecord,
+ AuthPairingLinkRepository,
+ type AuthPairingLinkRepositoryShape,
+ ConsumeAuthPairingLinkInput,
+ CreateAuthPairingLinkInput,
+ GetAuthPairingLinkByCredentialInput,
+ ListActiveAuthPairingLinksInput,
+ RevokeAuthPairingLinkInput,
+} from "../Services/AuthPairingLinks.ts";
+
+function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
+ return (cause: unknown): AuthPairingLinkRepositoryError =>
+ Schema.isSchemaError(cause)
+ ? toPersistenceDecodeError(decodeOperation)(cause)
+ : toPersistenceSqlError(sqlOperation)(cause);
+}
+
+const makeAuthPairingLinkRepository = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const createPairingLinkRow = SqlSchema.void({
+ Request: CreateAuthPairingLinkInput,
+ execute: (input) =>
+ sql`
+ INSERT INTO auth_pairing_links (
+ id,
+ credential,
+ method,
+ role,
+ subject,
+ label,
+ created_at,
+ expires_at,
+ consumed_at,
+ revoked_at
+ )
+ VALUES (
+ ${input.id},
+ ${input.credential},
+ ${input.method},
+ ${input.role},
+ ${input.subject},
+ ${input.label},
+ ${input.createdAt},
+ ${input.expiresAt},
+ NULL,
+ NULL
+ )
+ `,
+ });
+
+ const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
+ Request: ConsumeAuthPairingLinkInput,
+ Result: AuthPairingLinkRecord,
+ execute: ({ credential, consumedAt, now }) =>
+ sql`
+ UPDATE auth_pairing_links
+ SET consumed_at = ${consumedAt}
+ WHERE credential = ${credential}
+ AND revoked_at IS NULL
+ AND consumed_at IS NULL
+ AND expires_at > ${now}
+ RETURNING
+ id AS "id",
+ credential AS "credential",
+ method AS "method",
+ role AS "role",
+ subject AS "subject",
+ label AS "label",
+ created_at AS "createdAt",
+ expires_at AS "expiresAt",
+ consumed_at AS "consumedAt",
+ revoked_at AS "revokedAt"
+ `,
+ });
+
+ const listActivePairingLinkRows = SqlSchema.findAll({
+ Request: ListActiveAuthPairingLinksInput,
+ Result: AuthPairingLinkRecord,
+ execute: ({ now }) =>
+ sql`
+ SELECT
+ id AS "id",
+ credential AS "credential",
+ method AS "method",
+ role AS "role",
+ subject AS "subject",
+ label AS "label",
+ created_at AS "createdAt",
+ expires_at AS "expiresAt",
+ consumed_at AS "consumedAt",
+ revoked_at AS "revokedAt"
+ FROM auth_pairing_links
+ WHERE revoked_at IS NULL
+ AND consumed_at IS NULL
+ AND expires_at > ${now}
+ ORDER BY created_at DESC, id DESC
+ `,
+ });
+
+ const revokePairingLinkRow = SqlSchema.findAll({
+ Request: RevokeAuthPairingLinkInput,
+ Result: Schema.Struct({ id: Schema.String }),
+ execute: ({ id, revokedAt }) =>
+ sql`
+ UPDATE auth_pairing_links
+ SET revoked_at = ${revokedAt}
+ WHERE id = ${id}
+ AND revoked_at IS NULL
+ AND consumed_at IS NULL
+ RETURNING id AS "id"
+ `,
+ });
+
+ const getPairingLinkRowByCredential = SqlSchema.findOneOption({
+ Request: GetAuthPairingLinkByCredentialInput,
+ Result: AuthPairingLinkRecord,
+ execute: ({ credential }) =>
+ sql`
+ SELECT
+ id AS "id",
+ credential AS "credential",
+ method AS "method",
+ role AS "role",
+ subject AS "subject",
+ label AS "label",
+ created_at AS "createdAt",
+ expires_at AS "expiresAt",
+ consumed_at AS "consumedAt",
+ revoked_at AS "revokedAt"
+ FROM auth_pairing_links
+ WHERE credential = ${credential}
+ `,
+ });
+
+ const create: AuthPairingLinkRepositoryShape["create"] = (input) =>
+ createPairingLinkRow(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthPairingLinkRepository.create:query",
+ "AuthPairingLinkRepository.create:encodeRequest",
+ ),
+ ),
+ );
+
+ const consumeAvailable: AuthPairingLinkRepositoryShape["consumeAvailable"] = (input) =>
+ consumeAvailablePairingLinkRow(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthPairingLinkRepository.consumeAvailable:query",
+ "AuthPairingLinkRepository.consumeAvailable:decodeRow",
+ ),
+ ),
+ );
+
+ const listActive: AuthPairingLinkRepositoryShape["listActive"] = (input) =>
+ listActivePairingLinkRows(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthPairingLinkRepository.listActive:query",
+ "AuthPairingLinkRepository.listActive:decodeRows",
+ ),
+ ),
+ );
+
+ const revoke: AuthPairingLinkRepositoryShape["revoke"] = (input) =>
+ revokePairingLinkRow(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthPairingLinkRepository.revoke:query",
+ "AuthPairingLinkRepository.revoke:decodeRows",
+ ),
+ ),
+ Effect.map((rows) => rows.length > 0),
+ );
+
+ const getByCredential: AuthPairingLinkRepositoryShape["getByCredential"] = (input) =>
+ getPairingLinkRowByCredential(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthPairingLinkRepository.getByCredential:query",
+ "AuthPairingLinkRepository.getByCredential:decodeRow",
+ ),
+ ),
+ );
+
+ return {
+ create,
+ consumeAvailable,
+ listActive,
+ revoke,
+ getByCredential,
+ } satisfies AuthPairingLinkRepositoryShape;
+});
+
+export const AuthPairingLinkRepositoryLive = Layer.effect(
+ AuthPairingLinkRepository,
+ makeAuthPairingLinkRepository,
+);
diff --git a/apps/server/src/persistence/Layers/AuthSessions.ts b/apps/server/src/persistence/Layers/AuthSessions.ts
new file mode 100644
index 000000000..66e02ed2a
--- /dev/null
+++ b/apps/server/src/persistence/Layers/AuthSessions.ts
@@ -0,0 +1,279 @@
+import { AuthSessionId } from "@t3tools/contracts";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+import * as SqlSchema from "effect/unstable/sql/SqlSchema";
+import { Effect, Layer, Option, Schema } from "effect";
+
+import {
+ toPersistenceDecodeError,
+ toPersistenceSqlError,
+ type AuthSessionRepositoryError,
+} from "../Errors.ts";
+import {
+ AuthSessionRecord,
+ AuthSessionRepository,
+ type AuthSessionRepositoryShape,
+ CreateAuthSessionInput,
+ GetAuthSessionByIdInput,
+ ListActiveAuthSessionsInput,
+ RevokeAuthSessionInput,
+ RevokeOtherAuthSessionsInput,
+ SetAuthSessionLastConnectedAtInput,
+} from "../Services/AuthSessions.ts";
+
+const AuthSessionDbRow = Schema.Struct({
+ sessionId: AuthSessionId,
+ subject: Schema.String,
+ role: Schema.Literals(["owner", "client"]),
+ method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
+ clientLabel: Schema.NullOr(Schema.String),
+ clientIpAddress: Schema.NullOr(Schema.String),
+ clientUserAgent: Schema.NullOr(Schema.String),
+ clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
+ clientOs: Schema.NullOr(Schema.String),
+ clientBrowser: Schema.NullOr(Schema.String),
+ issuedAt: Schema.DateTimeUtcFromString,
+ expiresAt: Schema.DateTimeUtcFromString,
+ lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+ revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+});
+
+function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type {
+ return {
+ sessionId: row.sessionId,
+ subject: row.subject,
+ role: row.role,
+ method: row.method,
+ client: {
+ label: row.clientLabel,
+ ipAddress: row.clientIpAddress,
+ userAgent: row.clientUserAgent,
+ deviceType: row.clientDeviceType,
+ os: row.clientOs,
+ browser: row.clientBrowser,
+ },
+ issuedAt: row.issuedAt,
+ expiresAt: row.expiresAt,
+ lastConnectedAt: row.lastConnectedAt,
+ revokedAt: row.revokedAt,
+ };
+}
+
+function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
+ return (cause: unknown): AuthSessionRepositoryError =>
+ Schema.isSchemaError(cause)
+ ? toPersistenceDecodeError(decodeOperation)(cause)
+ : toPersistenceSqlError(sqlOperation)(cause);
+}
+
+const makeAuthSessionRepository = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const createSessionRow = SqlSchema.void({
+ Request: CreateAuthSessionInput,
+ execute: (input) =>
+ sql`
+ INSERT INTO auth_sessions (
+ session_id,
+ subject,
+ role,
+ method,
+ client_label,
+ client_ip_address,
+ client_user_agent,
+ client_device_type,
+ client_os,
+ client_browser,
+ issued_at,
+ expires_at,
+ revoked_at
+ )
+ VALUES (
+ ${input.sessionId},
+ ${input.subject},
+ ${input.role},
+ ${input.method},
+ ${input.client.label},
+ ${input.client.ipAddress},
+ ${input.client.userAgent},
+ ${input.client.deviceType},
+ ${input.client.os},
+ ${input.client.browser},
+ ${input.issuedAt},
+ ${input.expiresAt},
+ NULL
+ )
+ `,
+ });
+
+ const getSessionRowById = SqlSchema.findOneOption({
+ Request: GetAuthSessionByIdInput,
+ Result: AuthSessionDbRow,
+ execute: ({ sessionId }) =>
+ sql`
+ SELECT
+ session_id AS "sessionId",
+ subject AS "subject",
+ role AS "role",
+ method AS "method",
+ client_label AS "clientLabel",
+ client_ip_address AS "clientIpAddress",
+ client_user_agent AS "clientUserAgent",
+ client_device_type AS "clientDeviceType",
+ client_os AS "clientOs",
+ client_browser AS "clientBrowser",
+ issued_at AS "issuedAt",
+ expires_at AS "expiresAt",
+ last_connected_at AS "lastConnectedAt",
+ revoked_at AS "revokedAt"
+ FROM auth_sessions
+ WHERE session_id = ${sessionId}
+ `,
+ });
+
+ const listActiveSessionRows = SqlSchema.findAll({
+ Request: ListActiveAuthSessionsInput,
+ Result: AuthSessionDbRow,
+ execute: ({ now }) =>
+ sql`
+ SELECT
+ session_id AS "sessionId",
+ subject AS "subject",
+ role AS "role",
+ method AS "method",
+ client_label AS "clientLabel",
+ client_ip_address AS "clientIpAddress",
+ client_user_agent AS "clientUserAgent",
+ client_device_type AS "clientDeviceType",
+ client_os AS "clientOs",
+ client_browser AS "clientBrowser",
+ issued_at AS "issuedAt",
+ expires_at AS "expiresAt",
+ last_connected_at AS "lastConnectedAt",
+ revoked_at AS "revokedAt"
+ FROM auth_sessions
+ WHERE revoked_at IS NULL
+ AND expires_at > ${now}
+ ORDER BY issued_at DESC, session_id DESC
+ `,
+ });
+
+ const setLastConnectedAtRow = SqlSchema.void({
+ Request: SetAuthSessionLastConnectedAtInput,
+ execute: ({ sessionId, lastConnectedAt }) =>
+ sql`
+ UPDATE auth_sessions
+ SET last_connected_at = ${lastConnectedAt}
+ WHERE session_id = ${sessionId}
+ AND revoked_at IS NULL
+ `,
+ });
+
+ const revokeSessionRows = SqlSchema.findAll({
+ Request: RevokeAuthSessionInput,
+ Result: Schema.Struct({ sessionId: AuthSessionId }),
+ execute: ({ sessionId, revokedAt }) =>
+ sql`
+ UPDATE auth_sessions
+ SET revoked_at = ${revokedAt}
+ WHERE session_id = ${sessionId}
+ AND revoked_at IS NULL
+ RETURNING session_id AS "sessionId"
+ `,
+ });
+
+ const revokeOtherSessionRows = SqlSchema.findAll({
+ Request: RevokeOtherAuthSessionsInput,
+ Result: Schema.Struct({ sessionId: AuthSessionId }),
+ execute: ({ currentSessionId, revokedAt }) =>
+ sql`
+ UPDATE auth_sessions
+ SET revoked_at = ${revokedAt}
+ WHERE session_id <> ${currentSessionId}
+ AND revoked_at IS NULL
+ RETURNING session_id AS "sessionId"
+ `,
+ });
+
+ const create: AuthSessionRepositoryShape["create"] = (input) =>
+ createSessionRow(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.create:query",
+ "AuthSessionRepository.create:encodeRequest",
+ ),
+ ),
+ );
+
+ const getById: AuthSessionRepositoryShape["getById"] = (input) =>
+ getSessionRowById(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.getById:query",
+ "AuthSessionRepository.getById:decodeRow",
+ ),
+ ),
+ Effect.flatMap((rowOption) =>
+ Option.match(rowOption, {
+ onNone: () => Effect.succeed(Option.none()),
+ onSome: (row) => Effect.succeed(Option.some(toAuthSessionRecord(row))),
+ }),
+ ),
+ );
+
+ const listActive: AuthSessionRepositoryShape["listActive"] = (input) =>
+ listActiveSessionRows(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.listActive:query",
+ "AuthSessionRepository.listActive:decodeRows",
+ ),
+ ),
+ Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))),
+ );
+
+ const revoke: AuthSessionRepositoryShape["revoke"] = (input) =>
+ revokeSessionRows(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.revoke:query",
+ "AuthSessionRepository.revoke:decodeRows",
+ ),
+ ),
+ Effect.map((rows) => rows.length > 0),
+ );
+
+ const revokeAllExcept: AuthSessionRepositoryShape["revokeAllExcept"] = (input) =>
+ revokeOtherSessionRows(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.revokeAllExcept:query",
+ "AuthSessionRepository.revokeAllExcept:decodeRows",
+ ),
+ ),
+ Effect.map((rows) => rows.map((row) => row.sessionId)),
+ );
+
+ const setLastConnectedAt: AuthSessionRepositoryShape["setLastConnectedAt"] = (input) =>
+ setLastConnectedAtRow(input).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "AuthSessionRepository.setLastConnectedAt:query",
+ "AuthSessionRepository.setLastConnectedAt:encodeRequest",
+ ),
+ ),
+ );
+
+ return {
+ create,
+ getById,
+ listActive,
+ revoke,
+ revokeAllExcept,
+ setLastConnectedAt,
+ } satisfies AuthSessionRepositoryShape;
+});
+
+export const AuthSessionRepositoryLive = Layer.effect(
+ AuthSessionRepository,
+ makeAuthSessionRepository,
+);
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index a03c3c2d1..8c9fe4d9f 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -32,6 +32,9 @@ import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
+import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
+import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
+import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
/**
* Migration loader with all migrations defined inline.
@@ -63,6 +66,9 @@ export const migrationEntries = [
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionSnapshotLookupIndexes", Migration0019],
+ [20, "AuthAccessManagement", Migration0020],
+ [21, "AuthSessionClientMetadata", Migration0021],
+ [22, "AuthSessionLastConnectedAt", Migration0022],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
diff --git a/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts
new file mode 100644
index 000000000..1be7fa80f
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts
@@ -0,0 +1,42 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS auth_pairing_links (
+ id TEXT PRIMARY KEY,
+ credential TEXT NOT NULL UNIQUE,
+ method TEXT NOT NULL,
+ role TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ consumed_at TEXT,
+ revoked_at TEXT
+ )
+ `;
+
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS idx_auth_pairing_links_active
+ ON auth_pairing_links(revoked_at, consumed_at, expires_at)
+ `;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS auth_sessions (
+ session_id TEXT PRIMARY KEY,
+ subject TEXT NOT NULL,
+ role TEXT NOT NULL,
+ method TEXT NOT NULL,
+ issued_at TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ revoked_at TEXT
+ )
+ `;
+
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_active
+ ON auth_sessions(revoked_at, expires_at, issued_at)
+ `;
+});
diff --git a/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts
new file mode 100644
index 000000000..3b387fdcf
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts
@@ -0,0 +1,62 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const pairingLinkColumns = yield* sql<{ readonly name: string }>`
+ PRAGMA table_info(auth_pairing_links)
+ `;
+ if (!pairingLinkColumns.some((column) => column.name === "label")) {
+ yield* sql`
+ ALTER TABLE auth_pairing_links
+ ADD COLUMN label TEXT
+ `;
+ }
+
+ const sessionColumns = yield* sql<{ readonly name: string }>`
+ PRAGMA table_info(auth_sessions)
+ `;
+
+ if (!sessionColumns.some((column) => column.name === "client_label")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_label TEXT
+ `;
+ }
+
+ if (!sessionColumns.some((column) => column.name === "client_ip_address")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_ip_address TEXT
+ `;
+ }
+
+ if (!sessionColumns.some((column) => column.name === "client_user_agent")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_user_agent TEXT
+ `;
+ }
+
+ if (!sessionColumns.some((column) => column.name === "client_device_type")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_device_type TEXT NOT NULL DEFAULT 'unknown'
+ `;
+ }
+
+ if (!sessionColumns.some((column) => column.name === "client_os")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_os TEXT
+ `;
+ }
+
+ if (!sessionColumns.some((column) => column.name === "client_browser")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN client_browser TEXT
+ `;
+ }
+});
diff --git a/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts
new file mode 100644
index 000000000..e806a073a
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts
@@ -0,0 +1,17 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const sessionColumns = yield* sql<{ readonly name: string }>`
+ PRAGMA table_info(auth_sessions)
+ `;
+
+ if (!sessionColumns.some((column) => column.name === "last_connected_at")) {
+ yield* sql`
+ ALTER TABLE auth_sessions
+ ADD COLUMN last_connected_at TEXT
+ `;
+ }
+});
diff --git a/apps/server/src/persistence/Services/AuthPairingLinks.ts b/apps/server/src/persistence/Services/AuthPairingLinks.ts
new file mode 100644
index 000000000..76c14a658
--- /dev/null
+++ b/apps/server/src/persistence/Services/AuthPairingLinks.ts
@@ -0,0 +1,76 @@
+import { Option, Schema, ServiceMap } from "effect";
+import type { Effect } from "effect";
+
+import type { AuthPairingLinkRepositoryError } from "../Errors.ts";
+
+export const AuthPairingLinkRecord = Schema.Struct({
+ id: Schema.String,
+ credential: Schema.String,
+ method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
+ role: Schema.Literals(["owner", "client"]),
+ subject: Schema.String,
+ label: Schema.NullOr(Schema.String),
+ createdAt: Schema.DateTimeUtcFromString,
+ expiresAt: Schema.DateTimeUtcFromString,
+ consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+ revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+});
+export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
+
+export const CreateAuthPairingLinkInput = Schema.Struct({
+ id: Schema.String,
+ credential: Schema.String,
+ method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
+ role: Schema.Literals(["owner", "client"]),
+ subject: Schema.String,
+ label: Schema.NullOr(Schema.String),
+ createdAt: Schema.DateTimeUtcFromString,
+ expiresAt: Schema.DateTimeUtcFromString,
+});
+export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
+
+export const ConsumeAuthPairingLinkInput = Schema.Struct({
+ credential: Schema.String,
+ consumedAt: Schema.DateTimeUtcFromString,
+ now: Schema.DateTimeUtcFromString,
+});
+export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
+
+export const ListActiveAuthPairingLinksInput = Schema.Struct({
+ now: Schema.DateTimeUtcFromString,
+});
+export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
+
+export const RevokeAuthPairingLinkInput = Schema.Struct({
+ id: Schema.String,
+ revokedAt: Schema.DateTimeUtcFromString,
+});
+export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
+
+export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
+ credential: Schema.String,
+});
+export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
+
+export interface AuthPairingLinkRepositoryShape {
+ readonly create: (
+ input: CreateAuthPairingLinkInput,
+ ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
+ readonly consumeAvailable: (
+ input: ConsumeAuthPairingLinkInput,
+ ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
+ readonly listActive: (
+ input: ListActiveAuthPairingLinksInput,
+ ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
+ readonly revoke: (
+ input: RevokeAuthPairingLinkInput,
+ ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
+ readonly getByCredential: (
+ input: GetAuthPairingLinkByCredentialInput,
+ ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
+}
+
+export class AuthPairingLinkRepository extends ServiceMap.Service<
+ AuthPairingLinkRepository,
+ AuthPairingLinkRepositoryShape
+>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {}
diff --git a/apps/server/src/persistence/Services/AuthSessions.ts b/apps/server/src/persistence/Services/AuthSessions.ts
new file mode 100644
index 000000000..a4410fa37
--- /dev/null
+++ b/apps/server/src/persistence/Services/AuthSessions.ts
@@ -0,0 +1,93 @@
+import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts";
+import { Option, Schema, ServiceMap } from "effect";
+import type { Effect } from "effect";
+
+import type { AuthSessionRepositoryError } from "../Errors.ts";
+
+export const AuthSessionClientMetadataRecord = Schema.Struct({
+ label: Schema.NullOr(Schema.String),
+ ipAddress: Schema.NullOr(Schema.String),
+ userAgent: Schema.NullOr(Schema.String),
+ deviceType: AuthClientMetadataDeviceType,
+ os: Schema.NullOr(Schema.String),
+ browser: Schema.NullOr(Schema.String),
+});
+export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
+
+export const AuthSessionRecord = Schema.Struct({
+ sessionId: AuthSessionId,
+ subject: Schema.String,
+ role: Schema.Literals(["owner", "client"]),
+ method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
+ client: AuthSessionClientMetadataRecord,
+ issuedAt: Schema.DateTimeUtcFromString,
+ expiresAt: Schema.DateTimeUtcFromString,
+ lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+ revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
+});
+export type AuthSessionRecord = typeof AuthSessionRecord.Type;
+
+export const CreateAuthSessionInput = Schema.Struct({
+ sessionId: AuthSessionId,
+ subject: Schema.String,
+ role: Schema.Literals(["owner", "client"]),
+ method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
+ client: AuthSessionClientMetadataRecord,
+ issuedAt: Schema.DateTimeUtcFromString,
+ expiresAt: Schema.DateTimeUtcFromString,
+});
+export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
+
+export const GetAuthSessionByIdInput = Schema.Struct({
+ sessionId: AuthSessionId,
+});
+export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
+
+export const ListActiveAuthSessionsInput = Schema.Struct({
+ now: Schema.DateTimeUtcFromString,
+});
+export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
+
+export const RevokeAuthSessionInput = Schema.Struct({
+ sessionId: AuthSessionId,
+ revokedAt: Schema.DateTimeUtcFromString,
+});
+export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
+
+export const RevokeOtherAuthSessionsInput = Schema.Struct({
+ currentSessionId: AuthSessionId,
+ revokedAt: Schema.DateTimeUtcFromString,
+});
+export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
+
+export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
+ sessionId: AuthSessionId,
+ lastConnectedAt: Schema.DateTimeUtcFromString,
+});
+export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
+
+export interface AuthSessionRepositoryShape {
+ readonly create: (
+ input: CreateAuthSessionInput,
+ ) => Effect.Effect<void, AuthSessionRepositoryError>;
+ readonly getById: (
+ input: GetAuthSessionByIdInput,
+ ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
+ readonly listActive: (
+ input: ListActiveAuthSessionsInput,
+ ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
+ readonly revoke: (
+ input: RevokeAuthSessionInput,
+ ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
+ readonly revokeAllExcept: (
+ input: RevokeOtherAuthSessionsInput,
+ ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
+ readonly setLastConnectedAt: (
+ input: SetAuthSessionLastConnectedAtInput,
+ ) => Effect.Effect<void, AuthSessionRepositoryError>;
+}
+
+export class AuthSessionRepository extends ServiceMap.Service<
+ AuthSessionRepository,
+ AuthSessionRepositoryShape
+>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {}
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 125cfd103..4e683637e 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -43,6 +43,7 @@ import {
} from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
+import * as Socket from "effect/unstable/socket/Socket";
import { vi } from "vitest";
import type { ServerConfigShape } from "./config.ts";
@@ -68,6 +69,7 @@ import {
type ProjectionSnapshotQueryShape,
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { PersistenceSqlError } from "./persistence/Errors.ts";
+import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import {
ProviderRegistry,
type ProviderRegistryShape,
@@ -96,9 +98,12 @@ import {
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
+import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
+import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
const defaultProjectId = ProjectId.makeUnsafe("project-default");
const defaultThreadId = ThreadId.makeUnsafe("thread-default");
+const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token";
const defaultModelSelection = {
provider: "codex",
model: "gpt-5-codex",
@@ -115,7 +120,6 @@ const testEnvironmentDescriptor = {
repositoryIdentity: true,
},
};
-
const makeDefaultOrchestrationReadModel = () => {
const now = new Date().toISOString();
return {
@@ -174,6 +178,11 @@ const browserOtlpTracingLayer = Layer.mergeAll(
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
);
+const authTestLayer = ServerAuthLive.pipe(
+ Layer.provide(SqlitePersistenceMemory),
+ Layer.provide(ServerSecretStoreLive),
+);
+
const makeBrowserOtlpPayload = (spanName: string) =>
Effect.gen(function* () {
const collector = yield* Effect.acquireRelease(
@@ -313,7 +322,7 @@ const buildAppUnderTest = (options?: {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
- mode: "web",
+ mode: "desktop",
port: 0,
host: "127.0.0.1",
cwd: process.cwd(),
@@ -322,7 +331,7 @@ const buildAppUnderTest = (options?: {
staticDir: undefined,
devUrl,
noBrowser: true,
- authToken: undefined,
+ desktopBootstrapToken: defaultDesktopBootstrapToken,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
...options?.config,
@@ -333,12 +342,16 @@ const buildAppUnderTest = (options?: {
});
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
- const appLayer = HttpRouter.serve(makeRoutesLayer, {
+ const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(
Layer.provide(
Layer.mock(Keybindings)({
+ loadConfigState: Effect.succeed({
+ keybindings: [],
+ issues: [],
+ }),
streamChanges: Stream.empty,
...options?.layers?.keybindings,
}),
@@ -418,6 +431,9 @@ const buildAppUnderTest = (options?: {
...options?.layers?.checkpointDiffQuery,
}),
),
+ );
+
+ const appLayer = servedRoutesLayer.pipe(
Layer.provide(
Layer.mock(BrowserTraceCollector)({
record: () => Effect.void,
@@ -453,6 +469,7 @@ const buildAppUnderTest = (options?: {
...options?.layers?.repositoryIdentityResolver,
}),
),
+ Layer.provideMerge(authTestLayer),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(layerConfig),
@@ -462,11 +479,37 @@ const buildAppUnderTest = (options?: {
return config;
});
-const wsRpcProtocolLayer = (wsUrl: string) =>
- RpcClient.layerProtocolSocket().pipe(
- Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
+const parseSessionCookieFromWsUrl = (
+ wsUrl: string,
+): { readonly cookie: string | null; readonly url: string } => {
+ const next = new URL(wsUrl);
+ const cookie = next.hash.startsWith("#cookie=")
+ ? decodeURIComponent(next.hash.slice("#cookie=".length))
+ : null;
+ next.hash = "";
+ return {
+ cookie,
+ url: next.toString(),
+ };
+};
+
+const wsRpcProtocolLayer = (wsUrl: string) => {
+ const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl);
+ const webSocketConstructorLayer = Layer.succeed(
+ Socket.WebSocketConstructor,
+ (socketUrl, protocols) =>
+ new NodeSocket.NodeWS.WebSocket(
+ socketUrl,
+ protocols,
+ cookie ? { headers: { cookie } } : undefined,
+ ) as unknown as globalThis.WebSocket,
+ );
+
+ return RpcClient.layerProtocolSocket().pipe(
+ Layer.provide(Socket.layerWebSocket(url).pipe(Layer.provide(webSocketConstructorLayer))),
Layer.provide(RpcSerialization.layerJson),
);
+};
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
type WsRpcClient =
@@ -477,6 +520,13 @@ const withWsRpcClient = <A, E, R>(
f: (client: WsRpcClient) => Effect.Effect<A, E, R>,
) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl)));
+const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => {
+ const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url);
+ const next = new URL(url, "http://localhost");
+ next.hash = `cookie=${encodeURIComponent(sessionCookieHeader)}`;
+ return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`;
+};
+
const getHttpServerUrl = (pathname = "") =>
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
@@ -484,11 +534,130 @@ const getHttpServerUrl = (pathname = "") =>
return `http://127.0.0.1:${address.port}${pathname}`;
});
-const getWsServerUrl = (pathname = "") =>
+const bootstrapBrowserSession = (
+ credential = defaultDesktopBootstrapToken,
+ options?: {
+ readonly headers?: Record<string, string>;
+ },
+) =>
+ Effect.gen(function* () {
+ const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap");
+ const response = yield* Effect.promise(() =>
+ fetch(bootstrapUrl, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ ...options?.headers,
+ },
+ body: JSON.stringify({
+ credential,
+ }),
+ }),
+ );
+ const body = (yield* Effect.promise(() => response.json())) as {
+ readonly authenticated: boolean;
+ readonly sessionMethod: string;
+ readonly expiresAt: string;
+ };
+ return {
+ response,
+ body,
+ cookie: response.headers.get("set-cookie"),
+ };
+ });
+
+const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
+ Effect.gen(function* () {
+ const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
+ const response = yield* Effect.promise(() =>
+ fetch(bootstrapUrl, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ credential,
+ }),
+ }),
+ );
+ const body = (yield* Effect.promise(() => response.json())) as {
+ readonly authenticated: boolean;
+ readonly sessionMethod: string;
+ readonly expiresAt: string;
+ readonly sessionToken?: string;
+ readonly error?: string;
+ };
+ return {
+ response,
+ body,
+ };
+ });
+
+const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) =>
+ Effect.gen(function* () {
+ const { response, cookie } = yield* bootstrapBrowserSession(credential);
+ if (!response.ok) {
+ return yield* Effect.fail(
+ new Error(`Expected bootstrap session response to succeed, got ${response.status}`),
+ );
+ }
+
+ if (!cookie) {
+ return yield* Effect.fail(new Error("Expected bootstrap session response to set a cookie."));
+ }
+
+ return cookie.split(";")[0] ?? cookie;
+ });
+
+const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) =>
+ Effect.gen(function* () {
+ const { response, body } = yield* bootstrapBearerSession(credential);
+ if (!response.ok) {
+ return yield* Effect.fail(
+ new Error(`Expected bearer bootstrap response to succeed, got ${response.status}`),
+ );
+ }
+
+ if (!body.sessionToken) {
+ return yield* Effect.fail(
+ new Error("Expected bearer bootstrap response to include a session token."),
+ );
+ }
+
+ return body.sessionToken;
+ });
+
+const extractSessionTokenFromSetCookie = (cookieHeader: string): string => {
+ const [nameValue] = cookieHeader.split(";", 1);
+ const token = nameValue?.split("=", 2)[1];
+ if (!token) {
+ throw new Error("Expected session cookie header to contain a token value.");
+ }
+ return token;
+};
+
+const splitHeaderTokens = (value: string | null) =>
+ (value ?? "")
+ .split(",")
+ .map((token) => token.trim())
+ .filter((token) => token.length > 0)
+ .toSorted();
+
+const getWsServerUrl = (
+ pathname = "",
+ options?: { authenticated?: boolean; credential?: string },
+) =>
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
const address = server.address as HttpServer.TcpAddress;
- return `ws://127.0.0.1:${address.port}${pathname}`;
+ const baseUrl = `ws://127.0.0.1:${address.port}${pathname}`;
+ if (options?.authenticated === false) {
+ return baseUrl;
+ }
+ return appendSessionCookieToWsUrl(
+ baseUrl,
+ yield* getAuthenticatedSessionCookieHeader(options?.credential),
+ );
});
it.layer(NodeServices.layer)("server router seam", (it) => {
@@ -514,11 +683,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
config: { devUrl: new URL("http://127.0.0.1:5173") },
});
- const url = yield* getHttpServerUrl("/foo/bar");
+ const url = yield* getHttpServerUrl("/foo/bar?token=test-token");
const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" }));
assert.equal(response.status, 302);
- assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/");
+ assert.equal(
+ response.headers.get("location"),
+ "http://127.0.0.1:5173/foo/bar?token=test-token",
+ );
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -540,6 +712,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.get(
`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
+ {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ },
);
assert.equal(response.status, 200);
@@ -560,6 +737,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.get(
`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`,
+ {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ },
);
assert.equal(response.status, 200);
@@ -567,6 +749,597 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("serves the public environment descriptor without requiring auth", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const url = yield* getHttpServerUrl("/.well-known/t3/environment");
+ const response = yield* Effect.promise(() => fetch(url));
+ const body = (yield* Effect.promise(() =>
+ response.json(),
+ )) as typeof testEnvironmentDescriptor;
+
+ assert.equal(response.status, 200);
+ assert.deepEqual(body, testEnvironmentDescriptor);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("reports unauthenticated session state without requiring auth", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const url = yield* getHttpServerUrl("/api/auth/session");
+ const response = yield* Effect.promise(() => fetch(url));
+ const body = (yield* Effect.promise(() => response.json())) as {
+ readonly authenticated: boolean;
+ readonly auth: {
+ readonly policy: string;
+ readonly bootstrapMethods: ReadonlyArray<string>;
+ readonly sessionMethods: ReadonlyArray<string>;
+ readonly sessionCookieName: string;
+ };
+ };
+
+ assert.equal(response.status, 200);
+ assert.equal(body.authenticated, false);
+ assert.equal(body.auth.policy, "desktop-managed-local");
+ assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]);
+ assert.deepEqual(body.auth.sessionMethods, [
+ "browser-session-cookie",
+ "bearer-session-token",
+ ]);
+ assert.equal(body.auth.sessionCookieName, "t3_session");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("bootstraps a browser session and authenticates the session endpoint via cookie", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const {
+ response: bootstrapResponse,
+ body: bootstrapBody,
+ cookie: setCookie,
+ } = yield* bootstrapBrowserSession();
+
+ assert.equal(bootstrapResponse.status, 200);
+ assert.equal(bootstrapBody.authenticated, true);
+ assert.equal(bootstrapBody.sessionMethod, "browser-session-cookie");
+ assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken);
+ assert.isDefined(setCookie);
+
+ const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
+ const sessionResponse = yield* Effect.promise(() =>
+ fetch(sessionUrl, {
+ headers: {
+ cookie: setCookie?.split(";")[0] ?? "",
+ },
+ }),
+ );
+ const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
+ readonly authenticated: boolean;
+ readonly sessionMethod?: string;
+ };
+
+ assert.equal(sessionResponse.status, 200);
+ assert.equal(sessionBody.authenticated, true);
+ assert.equal(sessionBody.sessionMethod, "browser-session-cookie");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect(
+ "bootstraps a bearer session and authenticates the session endpoint via authorization header",
+ () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const { response: bootstrapResponse, body: bootstrapBody } =
+ yield* bootstrapBearerSession();
+
+ assert.equal(bootstrapResponse.status, 200);
+ assert.equal(bootstrapBody.authenticated, true);
+ assert.equal(bootstrapBody.sessionMethod, "bearer-session-token");
+ assert.equal(typeof bootstrapBody.sessionToken, "string");
+ assert.isTrue((bootstrapBody.sessionToken?.length ?? 0) > 0);
+
+ const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
+ const sessionResponse = yield* Effect.promise(() =>
+ fetch(sessionUrl, {
+ headers: {
+ authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
+ },
+ }),
+ );
+ const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
+ readonly authenticated: boolean;
+ readonly sessionMethod?: string;
+ };
+
+ assert.equal(sessionResponse.status, 200);
+ assert.equal(sessionBody.authenticated, true);
+ assert.equal(sessionBody.sessionMethod, "bearer-session-token");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("issues short-lived websocket tokens for authenticated bearer sessions", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const bearerToken = yield* getAuthenticatedBearerSessionToken();
+ const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
+ const wsTokenResponse = yield* Effect.promise(() =>
+ fetch(wsTokenUrl, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${bearerToken}`,
+ },
+ }),
+ );
+ const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
+ readonly token: string;
+ readonly expiresAt: string;
+ };
+
+ assert.equal(wsTokenResponse.status, 200);
+ assert.equal(typeof wsTokenBody.token, "string");
+ assert.isTrue(wsTokenBody.token.length > 0);
+ assert.equal(typeof wsTokenBody.expiresAt, "string");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect(
+ "responds to remote auth websocket-token preflight requests with authorization CORS headers",
+ () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
+ const response = yield* Effect.promise(() =>
+ fetch(wsTokenUrl, {
+ method: "OPTIONS",
+ headers: {
+ origin: "http://192.168.86.35:3773",
+ "access-control-request-method": "POST",
+ "access-control-request-headers": "authorization",
+ },
+ }),
+ );
+
+ assert.equal(response.status, 204);
+ assert.equal(response.headers.get("access-control-allow-origin"), "*");
+ assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
+ "GET",
+ "OPTIONS",
+ "POST",
+ ]);
+ assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
+ "authorization",
+ "b3",
+ "content-type",
+ "traceparent",
+ ]);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("includes CORS headers on remote websocket-token auth failures", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
+ const response = yield* Effect.promise(() =>
+ fetch(wsTokenUrl, {
+ method: "POST",
+ headers: {
+ origin: "http://192.168.86.35:3773",
+ },
+ }),
+ );
+ const body = (yield* Effect.promise(() => response.json())) as {
+ readonly error?: string;
+ };
+
+ assert.equal(response.status, 401);
+ assert.equal(response.headers.get("access-control-allow-origin"), "*");
+ assert.equal(body.error, "Authentication required.");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("issues authenticated one-time pairing credentials for additional clients", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const response = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ });
+ const body = (yield* response.json) as {
+ readonly credential: string;
+ readonly expiresAt: string;
+ };
+
+ assert.equal(response.status, 200);
+ assert.equal(typeof body.credential, "string");
+ assert.isTrue(body.credential.length > 0);
+ assert.equal(typeof body.expiresAt, "string");
+
+ const bootstrapResult = yield* bootstrapBrowserSession(body.credential);
+ assert.equal(bootstrapResult.response.status, 200);
+
+ const reusedResult = yield* bootstrapBrowserSession(body.credential);
+ assert.equal(reusedResult.response.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("rejects unauthenticated pairing credential requests", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const response = yield* HttpClient.post("/api/auth/pairing-token");
+ assert.equal(response.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("lists and revokes pairing links for owner sessions", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest({
+ config: {
+ host: "0.0.0.0",
+ },
+ });
+
+ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
+ const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const createdBody = (yield* createdResponse.json) as {
+ readonly id: string;
+ readonly credential: string;
+ };
+
+ const listResponse = yield* HttpClient.get("/api/auth/pairing-links", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const listedLinks = (yield* listResponse.json) as ReadonlyArray<{
+ readonly id: string;
+ readonly credential: string;
+ }>;
+
+ const revokeUrl = yield* getHttpServerUrl("/api/auth/pairing-links/revoke");
+ const revokeResponse = yield* Effect.promise(() =>
+ fetch(revokeUrl, {
+ method: "POST",
+ headers: {
+ cookie: ownerCookie,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ id: createdBody.id }),
+ }),
+ );
+ const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential);
+
+ assert.equal(createdResponse.status, 200);
+ assert.equal(listResponse.status, 200);
+ assert.isTrue(listedLinks.some((entry) => entry.id === createdBody.id));
+ assert.equal(revokeResponse.status, 200);
+ assert.equal(revokedBootstrap.response.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("rejects pairing credential requests from non-owner paired sessions", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest({
+ config: {
+ host: "0.0.0.0",
+ },
+ });
+
+ const ownerResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ });
+ const ownerBody = (yield* ownerResponse.json) as {
+ readonly credential: string;
+ };
+ assert.equal(ownerResponse.status, 200);
+
+ const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(ownerBody.credential);
+ const pairedResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: pairedSessionCookie,
+ },
+ });
+ const pairedBody = (yield* pairedResponse.json) as {
+ readonly error: string;
+ };
+
+ assert.equal(pairedResponse.status, 403);
+ assert.equal(pairedBody.error, "Only owner sessions can create pairing credentials.");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("lists paired clients and revokes other sessions while keeping the owner", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest({
+ config: {
+ host: "0.0.0.0",
+ },
+ });
+
+ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
+ const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token");
+ const ownerPairingResponse = yield* Effect.promise(() =>
+ fetch(pairingTokenUrl, {
+ method: "POST",
+ headers: {
+ cookie: ownerCookie,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ label: "Julius iPhone",
+ }),
+ }),
+ );
+ const ownerPairingBody = (yield* Effect.promise(() => ownerPairingResponse.json())) as {
+ readonly credential: string;
+ readonly label?: string;
+ };
+ assert.equal(ownerPairingResponse.status, 200);
+ const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, {
+ headers: {
+ "user-agent":
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1",
+ },
+ });
+ const pairedSessionCookie = pairedSessionBootstrap.cookie?.split(";")[0];
+ assert.isDefined(pairedSessionCookie);
+
+ const pairedSessionCookieHeader = pairedSessionCookie ?? "";
+ const listClientsUrl = yield* getHttpServerUrl("/api/auth/clients");
+ const listBeforeResponse = yield* Effect.promise(() =>
+ fetch(listClientsUrl, {
+ headers: {
+ cookie: ownerCookie,
+ },
+ }),
+ );
+ const clientsBefore = (yield* Effect.promise(() =>
+ listBeforeResponse.json(),
+ )) as ReadonlyArray<{
+ readonly sessionId: string;
+ readonly current: boolean;
+ readonly client: {
+ readonly label?: string;
+ readonly deviceType: string;
+ readonly ipAddress?: string;
+ readonly os?: string;
+ readonly browser?: string;
+ };
+ }>;
+ const pairedClientBefore = clientsBefore.find((entry) => !entry.current);
+ const pairedSessionId = clientsBefore.find((entry) => !entry.current)?.sessionId;
+
+ const revokeOthersResponse = yield* HttpClient.post("/api/auth/clients/revoke-others", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const revokeOthersBody = (yield* revokeOthersResponse.json) as {
+ readonly revokedCount: number;
+ };
+
+ const listAfterResponse = yield* HttpClient.get("/api/auth/clients", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const clientsAfter = (yield* listAfterResponse.json) as ReadonlyArray<{
+ readonly sessionId: string;
+ readonly current: boolean;
+ }>;
+
+ const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: pairedSessionCookieHeader,
+ },
+ });
+ const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as {
+ readonly error: string;
+ };
+
+ assert.equal(listBeforeResponse.status, 200);
+ assert.equal(ownerPairingBody.label, "Julius iPhone");
+ assert.lengthOf(clientsBefore, 2);
+ assert.isDefined(pairedSessionId);
+ assert.isDefined(pairedClientBefore);
+ assert.deepInclude(pairedClientBefore?.client, {
+ label: "Julius iPhone",
+ deviceType: "mobile",
+ os: "iOS",
+ browser: "Safari",
+ ipAddress: "127.0.0.1",
+ });
+ assert.equal(revokeOthersResponse.status, 200);
+ assert.equal(revokeOthersBody.revokedCount, 1);
+ assert.equal(listAfterResponse.status, 200);
+ assert.lengthOf(clientsAfter, 1);
+ assert.equal(clientsAfter[0]?.current, true);
+ assert.equal(pairedClientPairingResponse.status, 401);
+ assert.equal(pairedClientPairingBody.error, "Unauthorized request.");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("revokes an individual paired client session", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest({
+ config: {
+ host: "0.0.0.0",
+ },
+ });
+
+ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
+ const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const pairingBody = (yield* pairingResponse.json) as {
+ readonly credential: string;
+ };
+ const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(
+ pairingBody.credential,
+ );
+
+ const clientsResponse = yield* HttpClient.get("/api/auth/clients", {
+ headers: {
+ cookie: ownerCookie,
+ },
+ });
+ const clients = (yield* clientsResponse.json) as ReadonlyArray<{
+ readonly sessionId: string;
+ readonly current: boolean;
+ }>;
+ const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId;
+ assert.isDefined(pairedSessionId);
+
+ const revokeUrl = yield* getHttpServerUrl("/api/auth/clients/revoke");
+ const revokeResponse = yield* Effect.promise(() =>
+ fetch(revokeUrl, {
+ method: "POST",
+ headers: {
+ cookie: ownerCookie,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ sessionId: pairedSessionId }),
+ }),
+ );
+ const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: {
+ cookie: pairedSessionCookie,
+ },
+ });
+
+ assert.equal(revokeResponse.status, 200);
+ assert.equal(pairedClientPairingResponse.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("rejects reusing the same bootstrap credential after it has been exchanged", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const first = yield* bootstrapBrowserSession();
+ const second = yield* bootstrapBrowserSession();
+
+ assert.equal(first.response.status, 200);
+ assert.equal(second.response.status, 401);
+ assert.equal(
+ (second.body as { readonly error?: string }).error,
+ "Invalid bootstrap credential.",
+ );
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect(
+ "does not accept session tokens via query parameters on authenticated HTTP routes",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const projectDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-router-project-favicon-query-token-",
+ });
+
+ yield* buildAppUnderTest();
+
+ const { cookie } = yield* bootstrapBrowserSession();
+ assert.isDefined(cookie);
+ const sessionToken = extractSessionTokenFromSetCookie(cookie ?? "");
+
+ const response = yield* HttpClient.get(
+ `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}&token=${encodeURIComponent(sessionToken)}`,
+ );
+
+ assert.equal(response.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession();
+
+ assert.equal(bootstrapResponse.status, 200);
+ assert.isDefined(cookie);
+
+ const wsUrl = appendSessionCookieToWsUrl(
+ yield* getWsServerUrl("/ws", { authenticated: false }),
+ cookie?.split(";")[0] ?? "",
+ );
+ const response = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})),
+ );
+
+ assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId);
+ assert.equal(response.auth.policy, "desktop-managed-local");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect(
+ "rejects websocket rpc handshake when a session token is only provided via query string",
+ () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const { cookie } = yield* bootstrapBrowserSession();
+ assert.isDefined(cookie);
+ const sessionToken = extractSessionTokenFromSetCookie(cookie ?? "");
+ const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?token=${encodeURIComponent(sessionToken)}`;
+
+ const error = yield* Effect.flip(
+ Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))),
+ );
+
+ assert.equal(error._tag, "RpcClientError");
+ assertInclude(String(error), "401");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect(
+ "accepts websocket rpc handshake with a dedicated websocket token in the query string",
+ () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+
+ const bearerToken = yield* getAuthenticatedBearerSessionToken();
+ const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
+ const wsTokenResponse = yield* Effect.promise(() =>
+ fetch(wsTokenUrl, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${bearerToken}`,
+ },
+ }),
+ );
+ const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
+ readonly token: string;
+ };
+ const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsToken=${encodeURIComponent(wsTokenBody.token)}`;
+
+ const response = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})),
+ );
+
+ assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId);
+ assert.equal(response.auth.policy, "desktop-managed-local");
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("serves attachment files from state dir", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -583,7 +1356,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true });
yield* fileSystem.writeFileString(attachmentPath, "attachment-ok");
- const response = yield* HttpClient.get(`/attachments/${attachmentId}`);
+ const response = yield* HttpClient.get(`/attachments/${attachmentId}`, {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ });
assert.equal(response.status, 200);
assert.equal(yield* response.text, "attachment-ok");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
@@ -606,6 +1383,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.get(
"/attachments/thread%20folder/message%20folder/file%20name.png",
+ {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ },
);
assert.equal(response.status, 200);
assert.equal(yield* response.text, "attachment-encoded-ok");
@@ -742,6 +1524,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.post("/api/observability/v1/traces", {
headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
origin: "http://localhost:5733",
},
@@ -815,8 +1598,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(response.status, 204);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
- assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS");
- assert.equal(response.headers.get("access-control-allow-headers"), "content-type");
+ assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
+ "GET",
+ "OPTIONS",
+ "POST",
+ ]);
+ assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
+ "authorization",
+ "b3",
+ "content-type",
+ "traceparent",
+ ]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -850,6 +1642,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.post("/api/observability/v1/traces", {
headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
},
body: HttpBody.text(JSON.stringify(payload), "application/json"),
@@ -897,6 +1690,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const response = yield* HttpClient.get(
"/attachments/missing-11111111-1111-4111-8111-111111111111",
+ {
+ headers: {
+ cookie: yield* getAuthenticatedSessionCookieHeader(),
+ },
+ },
);
assert.equal(response.status, 404);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
@@ -938,7 +1736,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
- it.effect("rejects websocket rpc handshake when auth token is missing", () =>
+ it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -948,13 +1746,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
"export const needle = 1;",
);
- yield* buildAppUnderTest({
- config: {
- authToken: "secret-token",
- },
- });
+ yield* buildAppUnderTest();
- const wsUrl = yield* getWsServerUrl("/ws");
+ const wsUrl = yield* getWsServerUrl("/ws", { authenticated: false });
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.projectsSearchEntries]({
@@ -970,38 +1764,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
- it.effect("accepts websocket rpc handshake when auth token is provided", () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" });
- yield* fs.writeFileString(
- path.join(workspaceDir, "needle-file.ts"),
- "export const needle = 1;",
- );
-
- yield* buildAppUnderTest({
- config: {
- authToken: "secret-token",
- },
- });
-
- const wsUrl = yield* getWsServerUrl("/ws?token=secret-token");
- const response = yield* Effect.scoped(
- withWsRpcClient(wsUrl, (client) =>
- client[WS_METHODS.projectsSearchEntries]({
- cwd: workspaceDir,
- query: "needle",
- limit: 10,
- }),
- ),
- );
-
- assert.isAtLeast(response.entries.length, 1);
- assert.equal(response.truncated, false);
- }).pipe(Effect.provide(NodeHttpServer.layerTest)),
- );
-
it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () =>
Effect.gen(function* () {
const providers = [] as const;
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index d706d79b4..c1581b938 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -6,7 +6,9 @@ import {
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
+ serverEnvironmentRouteLayer,
staticAndDevRouteLayer,
+ browserApiCorsLayer,
} from "./http";
import { fixPath } from "./os-jank";
import { websocketRpcRouteLayer } from "./ws";
@@ -51,6 +53,20 @@ import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";
import { ObservabilityLive } from "./observability/Layers/Observability";
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment";
+import {
+ authBearerBootstrapRouteLayer,
+ authBootstrapRouteLayer,
+ authClientsRevokeOthersRouteLayer,
+ authClientsRevokeRouteLayer,
+ authClientsRouteLayer,
+ authPairingLinksRevokeRouteLayer,
+ authPairingLinksRouteLayer,
+ authPairingCredentialRouteLayer,
+ authSessionRouteLayer,
+ authWebSocketTokenRouteLayer,
+} from "./auth/http";
+import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore";
+import { ServerAuthLive } from "./auth/Layers/ServerAuth";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -188,6 +204,11 @@ const WorkspaceLayerLive = Layer.mergeAll(
),
);
+const AuthLayerLive = ServerAuthLive.pipe(
+ Layer.provideMerge(PersistenceLayerLive),
+ Layer.provide(ServerSecretStoreLive),
+);
+
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
@@ -203,6 +224,7 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ProjectFaviconResolverLive),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerEnvironmentLive),
+ Layer.provideMerge(AuthLayerLive),
// Misc.
Layer.provideMerge(AnalyticsServiceLayerLive),
@@ -215,12 +237,23 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
);
export const makeRoutesLayer = Layer.mergeAll(
+ authBearerBootstrapRouteLayer,
+ authBootstrapRouteLayer,
+ authClientsRevokeOthersRouteLayer,
+ authClientsRevokeRouteLayer,
+ authClientsRouteLayer,
+ authPairingLinksRevokeRouteLayer,
+ authPairingLinksRouteLayer,
+ authPairingCredentialRouteLayer,
+ authSessionRouteLayer,
+ authWebSocketTokenRouteLayer,
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
+ serverEnvironmentRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
-);
+).pipe(Layer.provide(browserApiCorsLayer));
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts
index fc06d7756..c3159cc9d 100644
--- a/apps/server/src/serverRuntimeStartup.test.ts
+++ b/apps/server/src/serverRuntimeStartup.test.ts
@@ -1,14 +1,23 @@
+import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import {
+ getAutoBootstrapDefaultModelSelection,
launchStartupHeartbeat,
makeCommandGate,
ServerRuntimeStartupError,
} from "./serverRuntimeStartup.ts";
+it("uses the canonical Codex default for auto-bootstrapped model selection", () => {
+ assert.deepStrictEqual(getAutoBootstrapDefaultModelSelection(), {
+ provider: "codex",
+ model: DEFAULT_MODEL_BY_PROVIDER.codex,
+ });
+});
+
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index e94c32222..fd43c6b35 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -1,5 +1,6 @@
import {
CommandId,
+ DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ModelSelection,
ProjectId,
@@ -29,6 +30,7 @@ import { ServerLifecycleEvents } from "./serverLifecycleEvents";
import { ServerSettingsService } from "./serverSettings";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
+import { ServerAuth } from "./auth/Services/ServerAuth";
const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
@@ -149,6 +151,11 @@ export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
Effect.asVoid,
);
+export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
+ provider: "codex",
+ model: DEFAULT_MODEL_BY_PROVIDER.codex,
+});
+
const autoBootstrapWelcome = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
@@ -170,10 +177,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
const createdAt = new Date().toISOString();
nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
- nextProjectDefaultModelSelection = {
- provider: "codex",
- model: "gpt-5-codex",
- };
+ nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
@@ -185,10 +189,8 @@ const autoBootstrapWelcome = Effect.gen(function* () {
});
} else {
nextProjectId = existingProject.value.id;
- nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
- provider: "codex",
- model: "gpt-5-codex",
- };
+ nextProjectDefaultModelSelection =
+ existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection();
}
const existingThreadId =
@@ -229,28 +231,39 @@ const autoBootstrapWelcome = Effect.gen(function* () {
} as const;
});
-const maybeOpenBrowser = Effect.gen(function* () {
+const resolveStartupBrowserTarget = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
- if (serverConfig.noBrowser) {
- return;
- }
- const { openBrowser } = yield* Open;
+ const serverAuth = yield* ServerAuth;
const localUrl = `http://localhost:${serverConfig.port}`;
const bindUrl =
serverConfig.host && !isWildcardHost(serverConfig.host)
? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
: localUrl;
- const target = serverConfig.devUrl?.toString() ?? bindUrl;
-
- yield* openBrowser(target).pipe(
- Effect.catch(() =>
- Effect.logInfo("browser auto-open unavailable", {
- hint: `Open ${target} in your browser.`,
- }),
+ const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
+ return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
+ Effect.flatMap((target) =>
+ target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
),
);
});
+const maybeOpenBrowser = (target: string) =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig;
+ if (serverConfig.noBrowser) {
+ return;
+ }
+ const { openBrowser } = yield* Open;
+
+ yield* openBrowser(target).pipe(
+ Effect.catch(() =>
+ Effect.logInfo("browser auto-open unavailable", {
+ hint: `Open ${target} in your browser.`,
+ }),
+ ),
+ );
+ });
+
const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.annotateSpans({ "startup.phase": phase }),
@@ -371,7 +384,13 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
- yield* runStartupPhase("browser.open", maybeOpenBrowser);
+ const startupBrowserTarget = yield* resolveStartupBrowserTarget;
+ if (serverConfig.mode !== "desktop") {
+ yield* Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
+ Effect.annotateLogs({ pairingUrl: startupBrowserTarget }),
+ );
+ }
+ yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
yield* Effect.logDebug("startup phase: complete");
}),
);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 16e853138..8d4f94669 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1,5 +1,7 @@
-import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
+import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect";
import {
+ type AuthAccessStreamEvent,
+ AuthSessionId,
CommandId,
EventId,
type OrchestrationCommand,
@@ -20,7 +22,7 @@ import {
WsRpcGroup,
} from "@t3tools/contracts";
import { clamp } from "effect/Number";
-import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
+import { HttpRouter, HttpServerRequest } from "effect/unstable/http";
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
@@ -49,791 +51,894 @@ import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePat
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
+import { ServerAuth } from "./auth/Services/ServerAuth";
+import {
+ BootstrapCredentialService,
+ type BootstrapCredentialChange,
+} from "./auth/Services/BootstrapCredentialService";
+import {
+ SessionCredentialService,
+ type SessionCredentialChange,
+} from "./auth/Services/SessionCredentialService";
+import { respondToAuthError } from "./auth/http";
-const WsRpcLayer = WsRpcGroup.toLayer(
- Effect.gen(function* () {
- const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
- const orchestrationEngine = yield* OrchestrationEngineService;
- const checkpointDiffQuery = yield* CheckpointDiffQuery;
- const keybindings = yield* Keybindings;
- const open = yield* Open;
- const gitManager = yield* GitManager;
- const git = yield* GitCore;
- const gitStatusBroadcaster = yield* GitStatusBroadcaster;
- const terminalManager = yield* TerminalManager;
- const providerRegistry = yield* ProviderRegistry;
- const config = yield* ServerConfig;
- const lifecycleEvents = yield* ServerLifecycleEvents;
- const serverSettings = yield* ServerSettingsService;
- const startup = yield* ServerRuntimeStartup;
- const workspaceEntries = yield* WorkspaceEntries;
- const workspaceFileSystem = yield* WorkspaceFileSystem;
- const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
- const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
- const serverEnvironment = yield* ServerEnvironment;
- const serverCommandId = (tag: string) =>
- CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
-
- const appendSetupScriptActivity = (input: {
- readonly threadId: ThreadId;
- readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
- readonly summary: string;
- readonly createdAt: string;
- readonly payload: Record<string, unknown>;
- readonly tone: "info" | "error";
- }) =>
- orchestrationEngine.dispatch({
- type: "thread.activity.append",
- commandId: serverCommandId("setup-script-activity"),
- threadId: input.threadId,
- activity: {
- id: EventId.makeUnsafe(crypto.randomUUID()),
- tone: input.tone,
- kind: input.kind,
- summary: input.summary,
- payload: input.payload,
- turnId: null,
- createdAt: input.createdAt,
+function toAuthAccessStreamEvent(
+ change: BootstrapCredentialChange | SessionCredentialChange,
+ revision: number,
+ currentSessionId: AuthSessionId,
+): AuthAccessStreamEvent {
+ switch (change.type) {
+ case "pairingLinkUpserted":
+ return {
+ version: 1,
+ revision,
+ type: "pairingLinkUpserted",
+ payload: change.pairingLink,
+ };
+ case "pairingLinkRemoved":
+ return {
+ version: 1,
+ revision,
+ type: "pairingLinkRemoved",
+ payload: { id: change.id },
+ };
+ case "clientUpserted":
+ return {
+ version: 1,
+ revision,
+ type: "clientUpserted",
+ payload: {
+ ...change.clientSession,
+ current: change.clientSession.sessionId === currentSessionId,
},
- createdAt: input.createdAt,
- });
+ };
+ case "clientRemoved":
+ return {
+ version: 1,
+ revision,
+ type: "clientRemoved",
+ payload: { sessionId: change.sessionId },
+ };
+ }
+}
- const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
- Schema.is(OrchestrationDispatchCommandError)(cause)
- ? cause
- : new OrchestrationDispatchCommandError({
- message: cause instanceof Error ? cause.message : fallbackMessage,
- cause,
- });
+const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
+ WsRpcGroup.toLayer(
+ Effect.gen(function* () {
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
+ const orchestrationEngine = yield* OrchestrationEngineService;
+ const checkpointDiffQuery = yield* CheckpointDiffQuery;
+ const keybindings = yield* Keybindings;
+ const open = yield* Open;
+ const gitManager = yield* GitManager;
+ const git = yield* GitCore;
+ const gitStatusBroadcaster = yield* GitStatusBroadcaster;
+ const terminalManager = yield* TerminalManager;
+ const providerRegistry = yield* ProviderRegistry;
+ const config = yield* ServerConfig;
+ const lifecycleEvents = yield* ServerLifecycleEvents;
+ const serverSettings = yield* ServerSettingsService;
+ const startup = yield* ServerRuntimeStartup;
+ const workspaceEntries = yield* WorkspaceEntries;
+ const workspaceFileSystem = yield* WorkspaceFileSystem;
+ const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
+ const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
+ const serverEnvironment = yield* ServerEnvironment;
+ const serverAuth = yield* ServerAuth;
+ const bootstrapCredentials = yield* BootstrapCredentialService;
+ const sessions = yield* SessionCredentialService;
+ const serverCommandId = (tag: string) =>
+ CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
- const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
- const error = Cause.squash(cause);
- return Schema.is(OrchestrationDispatchCommandError)(error)
- ? error
- : new OrchestrationDispatchCommandError({
- message:
- error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
- cause,
- });
- };
-
- const enrichProjectEvent = (
- event: OrchestrationEvent,
- ): Effect.Effect<OrchestrationEvent, never, never> => {
- switch (event.type) {
- case "project.created":
- return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe(
- Effect.map((repositoryIdentity) => ({
- ...event,
- payload: {
- ...event.payload,
- repositoryIdentity,
- },
- })),
- );
- case "project.meta-updated":
- return Effect.gen(function* () {
- const workspaceRoot =
- event.payload.workspaceRoot ??
- (yield* orchestrationEngine.getReadModel()).projects.find(
- (project) => project.id === event.payload.projectId,
- )?.workspaceRoot ??
- null;
- if (workspaceRoot === null) {
- return event;
- }
+ const loadAuthAccessSnapshot = () =>
+ Effect.all({
+ pairingLinks: serverAuth.listPairingLinks().pipe(Effect.orDie),
+ clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie),
+ });
- const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot);
- return {
- ...event,
- payload: {
- ...event.payload,
- repositoryIdentity,
- },
- } satisfies OrchestrationEvent;
- });
- default:
- return Effect.succeed(event);
- }
- };
+ const appendSetupScriptActivity = (input: {
+ readonly threadId: ThreadId;
+ readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
+ readonly summary: string;
+ readonly createdAt: string;
+ readonly payload: Record<string, unknown>;
+ readonly tone: "info" | "error";
+ }) =>
+ orchestrationEngine.dispatch({
+ type: "thread.activity.append",
+ commandId: serverCommandId("setup-script-activity"),
+ threadId: input.threadId,
+ activity: {
+ id: EventId.makeUnsafe(crypto.randomUUID()),
+ tone: input.tone,
+ kind: input.kind,
+ summary: input.summary,
+ payload: input.payload,
+ turnId: null,
+ createdAt: input.createdAt,
+ },
+ createdAt: input.createdAt,
+ });
- const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
- Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
+ const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
+ Schema.is(OrchestrationDispatchCommandError)(cause)
+ ? cause
+ : new OrchestrationDispatchCommandError({
+ message: cause instanceof Error ? cause.message : fallbackMessage,
+ cause,
+ });
- const dispatchBootstrapTurnStart = (
- command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
- ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
- Effect.gen(function* () {
- const bootstrap = command.bootstrap;
- const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
- let createdThread = false;
- let targetProjectId = bootstrap?.createThread?.projectId;
- let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
- let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
-
- const cleanupCreatedThread = () =>
- createdThread
- ? orchestrationEngine
- .dispatch({
- type: "thread.delete",
- commandId: serverCommandId("bootstrap-thread-delete"),
- threadId: command.threadId,
- })
- .pipe(Effect.ignoreCause({ log: true }))
- : Effect.void;
-
- const recordSetupScriptLaunchFailure = (input: {
- readonly error: unknown;
- readonly requestedAt: string;
- readonly worktreePath: string;
- }) => {
- const detail =
- input.error instanceof Error ? input.error.message : "Unknown setup failure.";
- return appendSetupScriptActivity({
- threadId: command.threadId,
- kind: "setup-script.failed",
- summary: "Setup script failed to start",
- createdAt: input.requestedAt,
- payload: {
- detail,
- worktreePath: input.worktreePath,
- },
- tone: "error",
- }).pipe(
- Effect.ignoreCause({ log: false }),
- Effect.flatMap(() =>
- Effect.logWarning("bootstrap turn start failed to launch setup script", {
- threadId: command.threadId,
- worktreePath: input.worktreePath,
- detail,
- }),
- ),
- );
- };
+ const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
+ const error = Cause.squash(cause);
+ return Schema.is(OrchestrationDispatchCommandError)(error)
+ ? error
+ : new OrchestrationDispatchCommandError({
+ message:
+ error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
+ cause,
+ });
+ };
- const recordSetupScriptStarted = (input: {
- readonly requestedAt: string;
- readonly worktreePath: string;
- readonly scriptId: string;
- readonly scriptName: string;
- readonly terminalId: string;
- }) => {
- const payload = {
- scriptId: input.scriptId,
- scriptName: input.scriptName,
- terminalId: input.terminalId,
- worktreePath: input.worktreePath,
- };
- return Effect.all([
- appendSetupScriptActivity({
+ const enrichProjectEvent = (
+ event: OrchestrationEvent,
+ ): Effect.Effect<OrchestrationEvent, never, never> => {
+ switch (event.type) {
+ case "project.created":
+ return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe(
+ Effect.map((repositoryIdentity) => ({
+ ...event,
+ payload: {
+ ...event.payload,
+ repositoryIdentity,
+ },
+ })),
+ );
+ case "project.meta-updated":
+ return Effect.gen(function* () {
+ const workspaceRoot =
+ event.payload.workspaceRoot ??
+ (yield* orchestrationEngine.getReadModel()).projects.find(
+ (project) => project.id === event.payload.projectId,
+ )?.workspaceRoot ??
+ null;
+ if (workspaceRoot === null) {
+ return event;
+ }
+
+ const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot);
+ return {
+ ...event,
+ payload: {
+ ...event.payload,
+ repositoryIdentity,
+ },
+ } satisfies OrchestrationEvent;
+ });
+ default:
+ return Effect.succeed(event);
+ }
+ };
+
+ const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
+ Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
+
+ const dispatchBootstrapTurnStart = (
+ command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
+ ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
+ Effect.gen(function* () {
+ const bootstrap = command.bootstrap;
+ const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
+ let createdThread = false;
+ let targetProjectId = bootstrap?.createThread?.projectId;
+ let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
+ let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
+
+ const cleanupCreatedThread = () =>
+ createdThread
+ ? orchestrationEngine
+ .dispatch({
+ type: "thread.delete",
+ commandId: serverCommandId("bootstrap-thread-delete"),
+ threadId: command.threadId,
+ })
+ .pipe(Effect.ignoreCause({ log: true }))
+ : Effect.void;
+
+ const recordSetupScriptLaunchFailure = (input: {
+ readonly error: unknown;
+ readonly requestedAt: string;
+ readonly worktreePath: string;
+ }) => {
+ const detail =
+ input.error instanceof Error ? input.error.message : "Unknown setup failure.";
+ return appendSetupScriptActivity({
threadId: command.threadId,
- kind: "setup-script.requested",
- summary: "Starting setup script",
+ kind: "setup-script.failed",
+ summary: "Setup script failed to start",
createdAt: input.requestedAt,
- payload,
- tone: "info",
- }),
- appendSetupScriptActivity({
- threadId: command.threadId,
- kind: "setup-script.started",
- summary: "Setup script started",
- createdAt: new Date().toISOString(),
- payload,
- tone: "info",
- }),
- ]).pipe(
- Effect.asVoid,
- Effect.catch((error) =>
- Effect.logWarning(
- "bootstrap turn start launched setup script but failed to record setup activity",
- {
+ payload: {
+ detail,
+ worktreePath: input.worktreePath,
+ },
+ tone: "error",
+ }).pipe(
+ Effect.ignoreCause({ log: false }),
+ Effect.flatMap(() =>
+ Effect.logWarning("bootstrap turn start failed to launch setup script", {
threadId: command.threadId,
worktreePath: input.worktreePath,
- scriptId: input.scriptId,
- terminalId: input.terminalId,
- detail:
- error instanceof Error
- ? error.message
- : "Unknown setup activity dispatch failure.",
- },
+ detail,
+ }),
),
- ),
- );
- };
+ );
+ };
- const runSetupProgram = () =>
- bootstrap?.runSetupScript && targetWorktreePath
- ? (() => {
- const worktreePath = targetWorktreePath;
- const requestedAt = new Date().toISOString();
- return projectSetupScriptRunner
- .runForThread({
+ const recordSetupScriptStarted = (input: {
+ readonly requestedAt: string;
+ readonly worktreePath: string;
+ readonly scriptId: string;
+ readonly scriptName: string;
+ readonly terminalId: string;
+ }) => {
+ const payload = {
+ scriptId: input.scriptId,
+ scriptName: input.scriptName,
+ terminalId: input.terminalId,
+ worktreePath: input.worktreePath,
+ };
+ return Effect.all([
+ appendSetupScriptActivity({
+ threadId: command.threadId,
+ kind: "setup-script.requested",
+ summary: "Starting setup script",
+ createdAt: input.requestedAt,
+ payload,
+ tone: "info",
+ }),
+ appendSetupScriptActivity({
+ threadId: command.threadId,
+ kind: "setup-script.started",
+ summary: "Setup script started",
+ createdAt: new Date().toISOString(),
+ payload,
+ tone: "info",
+ }),
+ ]).pipe(
+ Effect.asVoid,
+ Effect.catch((error) =>
+ Effect.logWarning(
+ "bootstrap turn start launched setup script but failed to record setup activity",
+ {
threadId: command.threadId,
- ...(targetProjectId ? { projectId: targetProjectId } : {}),
- ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
- worktreePath,
- })
- .pipe(
- Effect.matchEffect({
- onFailure: (error) =>
- recordSetupScriptLaunchFailure({
- error,
- requestedAt,
- worktreePath,
- }),
- onSuccess: (setupResult) => {
- if (setupResult.status !== "started") {
- return Effect.void;
- }
- return recordSetupScriptStarted({
- requestedAt,
- worktreePath,
- scriptId: setupResult.scriptId,
- scriptName: setupResult.scriptName,
- terminalId: setupResult.terminalId,
- });
- },
- }),
- );
- })()
- : Effect.void;
-
- const bootstrapProgram = Effect.gen(function* () {
- if (bootstrap?.createThread) {
- yield* orchestrationEngine.dispatch({
- type: "thread.create",
- commandId: serverCommandId("bootstrap-thread-create"),
- threadId: command.threadId,
- projectId: bootstrap.createThread.projectId,
- title: bootstrap.createThread.title,
- modelSelection: bootstrap.createThread.modelSelection,
- runtimeMode: bootstrap.createThread.runtimeMode,
- interactionMode: bootstrap.createThread.interactionMode,
- branch: bootstrap.createThread.branch,
- worktreePath: bootstrap.createThread.worktreePath,
- createdAt: bootstrap.createThread.createdAt,
- });
- createdThread = true;
- }
-
- if (bootstrap?.prepareWorktree) {
- const worktree = yield* git.createWorktree({
- cwd: bootstrap.prepareWorktree.projectCwd,
- branch: bootstrap.prepareWorktree.baseBranch,
- newBranch: bootstrap.prepareWorktree.branch,
- path: null,
- });
- targetWorktreePath = worktree.worktree.path;
- yield* orchestrationEngine.dispatch({
- type: "thread.meta.update",
- commandId: serverCommandId("bootstrap-thread-meta-update"),
- threadId: command.threadId,
- branch: worktree.worktree.branch,
- worktreePath: targetWorktreePath,
- });
- }
+ worktreePath: input.worktreePath,
+ scriptId: input.scriptId,
+ terminalId: input.terminalId,
+ detail:
+ error instanceof Error
+ ? error.message
+ : "Unknown setup activity dispatch failure.",
+ },
+ ),
+ ),
+ );
+ };
- yield* runSetupProgram();
+ const runSetupProgram = () =>
+ bootstrap?.runSetupScript && targetWorktreePath
+ ? (() => {
+ const worktreePath = targetWorktreePath;
+ const requestedAt = new Date().toISOString();
+ return projectSetupScriptRunner
+ .runForThread({
+ threadId: command.threadId,
+ ...(targetProjectId ? { projectId: targetProjectId } : {}),
+ ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
+ worktreePath,
+ })
+ .pipe(
+ Effect.matchEffect({
+ onFailure: (error) =>
+ recordSetupScriptLaunchFailure({
+ error,
+ requestedAt,
+ worktreePath,
+ }),
+ onSuccess: (setupResult) => {
+ if (setupResult.status !== "started") {
+ return Effect.void;
+ }
+ return recordSetupScriptStarted({
+ requestedAt,
+ worktreePath,
+ scriptId: setupResult.scriptId,
+ scriptName: setupResult.scriptName,
+ terminalId: setupResult.terminalId,
+ });
+ },
+ }),
+ );
+ })()
+ : Effect.void;
- return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
- });
+ const bootstrapProgram = Effect.gen(function* () {
+ if (bootstrap?.createThread) {
+ yield* orchestrationEngine.dispatch({
+ type: "thread.create",
+ commandId: serverCommandId("bootstrap-thread-create"),
+ threadId: command.threadId,
+ projectId: bootstrap.createThread.projectId,
+ title: bootstrap.createThread.title,
+ modelSelection: bootstrap.createThread.modelSelection,
+ runtimeMode: bootstrap.createThread.runtimeMode,
+ interactionMode: bootstrap.createThread.interactionMode,
+ branch: bootstrap.createThread.branch,
+ worktreePath: bootstrap.createThread.worktreePath,
+ createdAt: bootstrap.createThread.createdAt,
+ });
+ createdThread = true;
+ }
- return yield* bootstrapProgram.pipe(
- Effect.catchCause((cause) => {
- const dispatchError = toBootstrapDispatchCommandCauseError(cause);
- if (Cause.hasInterruptsOnly(cause)) {
- return Effect.fail(dispatchError);
+ if (bootstrap?.prepareWorktree) {
+ const worktree = yield* git.createWorktree({
+ cwd: bootstrap.prepareWorktree.projectCwd,
+ branch: bootstrap.prepareWorktree.baseBranch,
+ newBranch: bootstrap.prepareWorktree.branch,
+ path: null,
+ });
+ targetWorktreePath = worktree.worktree.path;
+ yield* orchestrationEngine.dispatch({
+ type: "thread.meta.update",
+ commandId: serverCommandId("bootstrap-thread-meta-update"),
+ threadId: command.threadId,
+ branch: worktree.worktree.branch,
+ worktreePath: targetWorktreePath,
+ });
}
- return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
- }),
- );
- });
- const dispatchNormalizedCommand = (
- normalizedCommand: OrchestrationCommand,
- ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
- const dispatchEffect =
- normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
- ? dispatchBootstrapTurnStart(normalizedCommand)
- : orchestrationEngine
- .dispatch(normalizedCommand)
- .pipe(
- Effect.mapError((cause) =>
- toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
- ),
- );
+ yield* runSetupProgram();
- return startup
- .enqueueCommand(dispatchEffect)
- .pipe(
- Effect.mapError((cause) =>
- toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
- ),
- );
- };
+ return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
+ });
- const loadServerConfig = Effect.gen(function* () {
- const keybindingsConfig = yield* keybindings.loadConfigState;
- const providers = yield* providerRegistry.getProviders;
- const settings = yield* serverSettings.getSettings;
- const environment = yield* serverEnvironment.getDescriptor;
+ return yield* bootstrapProgram.pipe(
+ Effect.catchCause((cause) => {
+ const dispatchError = toBootstrapDispatchCommandCauseError(cause);
+ if (Cause.hasInterruptsOnly(cause)) {
+ return Effect.fail(dispatchError);
+ }
+ return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
+ }),
+ );
+ });
- return {
- environment,
- cwd: config.cwd,
- keybindingsConfigPath: config.keybindingsConfigPath,
- keybindings: keybindingsConfig.keybindings,
- issues: keybindingsConfig.issues,
- providers,
- availableEditors: resolveAvailableEditors(),
- observability: {
- logsDirectoryPath: config.logsDir,
- localTracingEnabled: true,
- ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
- otlpTracesEnabled: config.otlpTracesUrl !== undefined,
- ...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}),
- otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
- },
- settings,
- };
- });
-
- const refreshGitStatus = (cwd: string) =>
- gitStatusBroadcaster
- .refreshStatus(cwd)
- .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
-
- return WsRpcGroup.of({
- [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
- observeRpcEffect(
- ORCHESTRATION_WS_METHODS.getSnapshot,
- projectionSnapshotQuery.getSnapshot().pipe(
- Effect.mapError(
- (cause) =>
- new OrchestrationGetSnapshotError({
- message: "Failed to load orchestration snapshot",
- cause,
- }),
- ),
- ),
- { "rpc.aggregate": "orchestration" },
- ),
- [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
- observeRpcEffect(
- ORCHESTRATION_WS_METHODS.dispatchCommand,
- Effect.gen(function* () {
- const normalizedCommand = yield* normalizeDispatchCommand(command);
- const result = yield* dispatchNormalizedCommand(normalizedCommand);
- if (normalizedCommand.type === "thread.archive") {
- yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
- Effect.catch((error) =>
- Effect.logWarning("failed to close thread terminals after archive", {
- threadId: normalizedCommand.threadId,
- error: error.message,
- }),
- ),
- );
- }
- return result;
- }).pipe(
+ const dispatchNormalizedCommand = (
+ normalizedCommand: OrchestrationCommand,
+ ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
+ const dispatchEffect =
+ normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
+ ? dispatchBootstrapTurnStart(normalizedCommand)
+ : orchestrationEngine
+ .dispatch(normalizedCommand)
+ .pipe(
+ Effect.mapError((cause) =>
+ toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
+ ),
+ );
+
+ return startup
+ .enqueueCommand(dispatchEffect)
+ .pipe(
Effect.mapError((cause) =>
- Schema.is(OrchestrationDispatchCommandError)(cause)
- ? cause
- : new OrchestrationDispatchCommandError({
- message: "Failed to dispatch orchestration command",
+ toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
+ ),
+ );
+ };
+
+ const loadServerConfig = Effect.gen(function* () {
+ const keybindingsConfig = yield* keybindings.loadConfigState;
+ const providers = yield* providerRegistry.getProviders;
+ const settings = yield* serverSettings.getSettings;
+ const environment = yield* serverEnvironment.getDescriptor;
+ const auth = yield* serverAuth.getDescriptor();
+
+ return {
+ environment,
+ auth,
+ cwd: config.cwd,
+ keybindingsConfigPath: config.keybindingsConfigPath,
+ keybindings: keybindingsConfig.keybindings,
+ issues: keybindingsConfig.issues,
+ providers,
+ availableEditors: resolveAvailableEditors(),
+ observability: {
+ logsDirectoryPath: config.logsDir,
+ localTracingEnabled: true,
+ ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
+ otlpTracesEnabled: config.otlpTracesUrl !== undefined,
+ ...(config.otlpMetricsUrl !== undefined
+ ? { otlpMetricsUrl: config.otlpMetricsUrl }
+ : {}),
+ otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
+ },
+ settings,
+ };
+ });
+
+ const refreshGitStatus = (cwd: string) =>
+ gitStatusBroadcaster
+ .refreshStatus(cwd)
+ .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
+
+ return WsRpcGroup.of({
+ [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
+ observeRpcEffect(
+ ORCHESTRATION_WS_METHODS.getSnapshot,
+ projectionSnapshotQuery.getSnapshot().pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestrationGetSnapshotError({
+ message: "Failed to load orchestration snapshot",
cause,
}),
+ ),
),
+ { "rpc.aggregate": "orchestration" },
),
- { "rpc.aggregate": "orchestration" },
- ),
- [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
- observeRpcEffect(
- ORCHESTRATION_WS_METHODS.getTurnDiff,
- checkpointDiffQuery.getTurnDiff(input).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestrationGetTurnDiffError({
- message: "Failed to load turn diff",
- cause,
- }),
+ [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
+ observeRpcEffect(
+ ORCHESTRATION_WS_METHODS.dispatchCommand,
+ Effect.gen(function* () {
+ const normalizedCommand = yield* normalizeDispatchCommand(command);
+ const result = yield* dispatchNormalizedCommand(normalizedCommand);
+ if (normalizedCommand.type === "thread.archive") {
+ yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("failed to close thread terminals after archive", {
+ threadId: normalizedCommand.threadId,
+ error: error.message,
+ }),
+ ),
+ );
+ }
+ return result;
+ }).pipe(
+ Effect.mapError((cause) =>
+ Schema.is(OrchestrationDispatchCommandError)(cause)
+ ? cause
+ : new OrchestrationDispatchCommandError({
+ message: "Failed to dispatch orchestration command",
+ cause,
+ }),
+ ),
),
+ { "rpc.aggregate": "orchestration" },
),
- { "rpc.aggregate": "orchestration" },
- ),
- [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
- observeRpcEffect(
- ORCHESTRATION_WS_METHODS.getFullThreadDiff,
- checkpointDiffQuery.getFullThreadDiff(input).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestrationGetFullThreadDiffError({
- message: "Failed to load full thread diff",
- cause,
- }),
+ [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
+ observeRpcEffect(
+ ORCHESTRATION_WS_METHODS.getTurnDiff,
+ checkpointDiffQuery.getTurnDiff(input).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestrationGetTurnDiffError({
+ message: "Failed to load turn diff",
+ cause,
+ }),
+ ),
),
+ { "rpc.aggregate": "orchestration" },
),
- { "rpc.aggregate": "orchestration" },
- ),
- [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
- observeRpcEffect(
- ORCHESTRATION_WS_METHODS.replayEvents,
- Stream.runCollect(
- orchestrationEngine.readEvents(
- clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
- ),
- ).pipe(
- Effect.map((events) => Array.from(events)),
- Effect.flatMap(enrichOrchestrationEvents),
- Effect.mapError(
- (cause) =>
- new OrchestrationReplayEventsError({
- message: "Failed to replay orchestration events",
- cause,
- }),
+ [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
+ observeRpcEffect(
+ ORCHESTRATION_WS_METHODS.getFullThreadDiff,
+ checkpointDiffQuery.getFullThreadDiff(input).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestrationGetFullThreadDiffError({
+ message: "Failed to load full thread diff",
+ cause,
+ }),
+ ),
),
+ { "rpc.aggregate": "orchestration" },
),
- { "rpc.aggregate": "orchestration" },
- ),
- [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
- observeRpcStreamEffect(
- WS_METHODS.subscribeOrchestrationDomainEvents,
- Effect.gen(function* () {
- const snapshot = yield* orchestrationEngine.getReadModel();
- const fromSequenceExclusive = snapshot.snapshotSequence;
- const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
- orchestrationEngine.readEvents(fromSequenceExclusive),
+ [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
+ observeRpcEffect(
+ ORCHESTRATION_WS_METHODS.replayEvents,
+ Stream.runCollect(
+ orchestrationEngine.readEvents(
+ clamp(input.fromSequenceExclusive, {
+ maximum: Number.MAX_SAFE_INTEGER,
+ minimum: 0,
+ }),
+ ),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.flatMap(enrichOrchestrationEvents),
- Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
- );
- const replayStream = Stream.fromIterable(replayEvents);
- const liveStream = orchestrationEngine.streamDomainEvents.pipe(
- Stream.mapEffect(enrichProjectEvent),
- );
- const source = Stream.merge(replayStream, liveStream);
- type SequenceState = {
- readonly nextSequence: number;
- readonly pendingBySequence: Map<number, OrchestrationEvent>;
- };
- const state = yield* Ref.make<SequenceState>({
- nextSequence: fromSequenceExclusive + 1,
- pendingBySequence: new Map<number, OrchestrationEvent>(),
- });
+ Effect.mapError(
+ (cause) =>
+ new OrchestrationReplayEventsError({
+ message: "Failed to replay orchestration events",
+ cause,
+ }),
+ ),
+ ),
+ { "rpc.aggregate": "orchestration" },
+ ),
+ [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
+ observeRpcStreamEffect(
+ WS_METHODS.subscribeOrchestrationDomainEvents,
+ Effect.gen(function* () {
+ const snapshot = yield* orchestrationEngine.getReadModel();
+ const fromSequenceExclusive = snapshot.snapshotSequence;
+ const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
+ orchestrationEngine.readEvents(fromSequenceExclusive),
+ ).pipe(
+ Effect.map((events) => Array.from(events)),
+ Effect.flatMap(enrichOrchestrationEvents),
+ Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
+ );
+ const replayStream = Stream.fromIterable(replayEvents);
+ const liveStream = orchestrationEngine.streamDomainEvents.pipe(
+ Stream.mapEffect(enrichProjectEvent),
+ );
+ const source = Stream.merge(replayStream, liveStream);
+ type SequenceState = {
+ readonly nextSequence: number;
+ readonly pendingBySequence: Map<number, OrchestrationEvent>;
+ };
+ const state = yield* Ref.make<SequenceState>({
+ nextSequence: fromSequenceExclusive + 1,
+ pendingBySequence: new Map<number, OrchestrationEvent>(),
+ });
- return source.pipe(
- Stream.mapEffect((event) =>
- Ref.modify(
- state,
- ({
- nextSequence,
- pendingBySequence,
- }): [Array<OrchestrationEvent>, SequenceState] => {
- if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
- return [[], { nextSequence, pendingBySequence }];
- }
-
- const updatedPending = new Map(pendingBySequence);
- updatedPending.set(event.sequence, event);
-
- const emit: Array<OrchestrationEvent> = [];
- let expected = nextSequence;
- for (;;) {
- const expectedEvent = updatedPending.get(expected);
- if (!expectedEvent) {
- break;
+ return source.pipe(
+ Stream.mapEffect((event) =>
+ Ref.modify(
+ state,
+ ({
+ nextSequence,
+ pendingBySequence,
+ }): [Array<OrchestrationEvent>, SequenceState] => {
+ if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
+ return [[], { nextSequence, pendingBySequence }];
}
- emit.push(expectedEvent);
- updatedPending.delete(expected);
- expected += 1;
- }
- return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
- },
+ const updatedPending = new Map(pendingBySequence);
+ updatedPending.set(event.sequence, event);
+
+ const emit: Array<OrchestrationEvent> = [];
+ let expected = nextSequence;
+ for (;;) {
+ const expectedEvent = updatedPending.get(expected);
+ if (!expectedEvent) {
+ break;
+ }
+ emit.push(expectedEvent);
+ updatedPending.delete(expected);
+ expected += 1;
+ }
+
+ return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
+ },
+ ),
),
- ),
- Stream.flatMap((events) => Stream.fromIterable(events)),
- );
+ Stream.flatMap((events) => Stream.fromIterable(events)),
+ );
+ }),
+ { "rpc.aggregate": "orchestration" },
+ ),
+ [WS_METHODS.serverGetConfig]: (_input) =>
+ observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
+ "rpc.aggregate": "server",
}),
- { "rpc.aggregate": "orchestration" },
- ),
- [WS_METHODS.serverGetConfig]: (_input) =>
- observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
- "rpc.aggregate": "server",
- }),
- [WS_METHODS.serverRefreshProviders]: (_input) =>
- observeRpcEffect(
- WS_METHODS.serverRefreshProviders,
- providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
- { "rpc.aggregate": "server" },
- ),
- [WS_METHODS.serverUpsertKeybinding]: (rule) =>
- observeRpcEffect(
- WS_METHODS.serverUpsertKeybinding,
- Effect.gen(function* () {
- const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
- return { keybindings: keybindingsConfig, issues: [] };
+ [WS_METHODS.serverRefreshProviders]: (_input) =>
+ observeRpcEffect(
+ WS_METHODS.serverRefreshProviders,
+ providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
+ { "rpc.aggregate": "server" },
+ ),
+ [WS_METHODS.serverUpsertKeybinding]: (rule) =>
+ observeRpcEffect(
+ WS_METHODS.serverUpsertKeybinding,
+ Effect.gen(function* () {
+ const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
+ return { keybindings: keybindingsConfig, issues: [] };
+ }),
+ { "rpc.aggregate": "server" },
+ ),
+ [WS_METHODS.serverGetSettings]: (_input) =>
+ observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
+ "rpc.aggregate": "server",
+ }),
+ [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
+ observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
+ "rpc.aggregate": "server",
}),
- { "rpc.aggregate": "server" },
- ),
- [WS_METHODS.serverGetSettings]: (_input) =>
- observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
- "rpc.aggregate": "server",
- }),
- [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
- observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
- "rpc.aggregate": "server",
- }),
- [WS_METHODS.projectsSearchEntries]: (input) =>
- observeRpcEffect(
- WS_METHODS.projectsSearchEntries,
- workspaceEntries.search(input).pipe(
- Effect.mapError(
- (cause) =>
- new ProjectSearchEntriesError({
- message: `Failed to search workspace entries: ${cause.detail}`,
+ [WS_METHODS.projectsSearchEntries]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.projectsSearchEntries,
+ workspaceEntries.search(input).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProjectSearchEntriesError({
+ message: `Failed to search workspace entries: ${cause.detail}`,
+ cause,
+ }),
+ ),
+ ),
+ { "rpc.aggregate": "workspace" },
+ ),
+ [WS_METHODS.projectsWriteFile]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.projectsWriteFile,
+ workspaceFileSystem.writeFile(input).pipe(
+ Effect.mapError((cause) => {
+ const message = Schema.is(WorkspacePathOutsideRootError)(cause)
+ ? "Workspace file path must stay within the project root."
+ : "Failed to write workspace file";
+ return new ProjectWriteFileError({
+ message,
cause,
- }),
+ });
+ }),
),
+ { "rpc.aggregate": "workspace" },
),
- { "rpc.aggregate": "workspace" },
- ),
- [WS_METHODS.projectsWriteFile]: (input) =>
- observeRpcEffect(
- WS_METHODS.projectsWriteFile,
- workspaceFileSystem.writeFile(input).pipe(
- Effect.mapError((cause) => {
- const message = Schema.is(WorkspacePathOutsideRootError)(cause)
- ? "Workspace file path must stay within the project root."
- : "Failed to write workspace file";
- return new ProjectWriteFileError({
- message,
- cause,
- });
- }),
+ [WS_METHODS.shellOpenInEditor]: (input) =>
+ observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
+ "rpc.aggregate": "workspace",
+ }),
+ [WS_METHODS.subscribeGitStatus]: (input) =>
+ observeRpcStream(
+ WS_METHODS.subscribeGitStatus,
+ gitStatusBroadcaster.streamStatus(input),
+ {
+ "rpc.aggregate": "git",
+ },
),
- { "rpc.aggregate": "workspace" },
- ),
- [WS_METHODS.shellOpenInEditor]: (input) =>
- observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
- "rpc.aggregate": "workspace",
- }),
- [WS_METHODS.subscribeGitStatus]: (input) =>
- observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
- "rpc.aggregate": "git",
- }),
- [WS_METHODS.gitRefreshStatus]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitRefreshStatus,
- gitStatusBroadcaster.refreshStatus(input.cwd),
- {
- "rpc.aggregate": "git",
- },
- ),
- [WS_METHODS.gitPull]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitPull,
- git.pullCurrentBranch(input.cwd).pipe(
- Effect.matchCauseEffect({
- onFailure: (cause) => Effect.failCause(cause),
- onSuccess: (result) =>
- refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
- }),
+ [WS_METHODS.gitRefreshStatus]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitRefreshStatus,
+ gitStatusBroadcaster.refreshStatus(input.cwd),
+ {
+ "rpc.aggregate": "git",
+ },
+ ),
+ [WS_METHODS.gitPull]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitPull,
+ git.pullCurrentBranch(input.cwd).pipe(
+ Effect.matchCauseEffect({
+ onFailure: (cause) => Effect.failCause(cause),
+ onSuccess: (result) =>
+ refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
+ }),
+ ),
+ { "rpc.aggregate": "git" },
),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitRunStackedAction]: (input) =>
- observeRpcStream(
- WS_METHODS.gitRunStackedAction,
- Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
+ [WS_METHODS.gitRunStackedAction]: (input) =>
+ observeRpcStream(
+ WS_METHODS.gitRunStackedAction,
+ Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
+ gitManager
+ .runStackedAction(input, {
+ actionId: input.actionId,
+ progressReporter: {
+ publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
+ },
+ })
+ .pipe(
+ Effect.matchCauseEffect({
+ onFailure: (cause) => Queue.failCause(queue, cause),
+ onSuccess: () =>
+ refreshGitStatus(input.cwd).pipe(
+ Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
+ ),
+ }),
+ ),
+ ),
+ { "rpc.aggregate": "git" },
+ ),
+ [WS_METHODS.gitResolvePullRequest]: (input) =>
+ observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
+ "rpc.aggregate": "git",
+ }),
+ [WS_METHODS.gitPreparePullRequestThread]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitPreparePullRequestThread,
gitManager
- .runStackedAction(input, {
- actionId: input.actionId,
- progressReporter: {
- publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
- },
- })
- .pipe(
- Effect.matchCauseEffect({
- onFailure: (cause) => Queue.failCause(queue, cause),
- onSuccess: () =>
- refreshGitStatus(input.cwd).pipe(
- Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
- ),
- }),
- ),
+ .preparePullRequestThread(input)
+ .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
+ { "rpc.aggregate": "git" },
+ ),
+ [WS_METHODS.gitListBranches]: (input) =>
+ observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
+ "rpc.aggregate": "git",
+ }),
+ [WS_METHODS.gitCreateWorktree]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitCreateWorktree,
+ git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
+ { "rpc.aggregate": "git" },
+ ),
+ [WS_METHODS.gitRemoveWorktree]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitRemoveWorktree,
+ git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
+ { "rpc.aggregate": "git" },
),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitResolvePullRequest]: (input) =>
- observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
- "rpc.aggregate": "git",
- }),
- [WS_METHODS.gitPreparePullRequestThread]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitPreparePullRequestThread,
- gitManager
- .preparePullRequestThread(input)
- .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitListBranches]: (input) =>
- observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
- "rpc.aggregate": "git",
- }),
- [WS_METHODS.gitCreateWorktree]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitCreateWorktree,
- git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitRemoveWorktree]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitRemoveWorktree,
- git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitCreateBranch]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitCreateBranch,
- git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitCheckout]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitCheckout,
- Effect.scoped(git.checkoutBranch(input)).pipe(
- Effect.tap(() => refreshGitStatus(input.cwd)),
+ [WS_METHODS.gitCreateBranch]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitCreateBranch,
+ git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
+ { "rpc.aggregate": "git" },
),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.gitInit]: (input) =>
- observeRpcEffect(
- WS_METHODS.gitInit,
- git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
- { "rpc.aggregate": "git" },
- ),
- [WS_METHODS.terminalOpen]: (input) =>
- observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.terminalWrite]: (input) =>
- observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.terminalResize]: (input) =>
- observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.terminalClear]: (input) =>
- observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.terminalRestart]: (input) =>
- observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.terminalClose]: (input) =>
- observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
- "rpc.aggregate": "terminal",
- }),
- [WS_METHODS.subscribeTerminalEvents]: (_input) =>
- observeRpcStream(
- WS_METHODS.subscribeTerminalEvents,
- Stream.callback<TerminalEvent>((queue) =>
- Effect.acquireRelease(
- terminalManager.subscribe((event) => Queue.offer(queue, event)),
- (unsubscribe) => Effect.sync(unsubscribe),
+ [WS_METHODS.gitCheckout]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitCheckout,
+ Effect.scoped(git.checkoutBranch(input)).pipe(
+ Effect.tap(() => refreshGitStatus(input.cwd)),
),
+ { "rpc.aggregate": "git" },
),
- { "rpc.aggregate": "terminal" },
- ),
- [WS_METHODS.subscribeServerConfig]: (_input) =>
- observeRpcStreamEffect(
- WS_METHODS.subscribeServerConfig,
- Effect.gen(function* () {
- const keybindingsUpdates = keybindings.streamChanges.pipe(
- Stream.map((event) => ({
- version: 1 as const,
- type: "keybindingsUpdated" as const,
- payload: {
- issues: event.issues,
- },
- })),
- );
- const providerStatuses = providerRegistry.streamChanges.pipe(
- Stream.map((providers) => ({
- version: 1 as const,
- type: "providerStatuses" as const,
- payload: { providers },
- })),
- );
- const settingsUpdates = serverSettings.streamChanges.pipe(
- Stream.map((settings) => ({
- version: 1 as const,
- type: "settingsUpdated" as const,
- payload: { settings },
- })),
- );
-
- return Stream.concat(
- Stream.make({
- version: 1 as const,
- type: "snapshot" as const,
- config: yield* loadServerConfig,
- }),
- Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
- );
+ [WS_METHODS.gitInit]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.gitInit,
+ git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
+ { "rpc.aggregate": "git" },
+ ),
+ [WS_METHODS.terminalOpen]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
+ "rpc.aggregate": "terminal",
}),
- { "rpc.aggregate": "server" },
- ),
- [WS_METHODS.subscribeServerLifecycle]: (_input) =>
- observeRpcStreamEffect(
- WS_METHODS.subscribeServerLifecycle,
- Effect.gen(function* () {
- const snapshot = yield* lifecycleEvents.snapshot;
- const snapshotEvents = Array.from(snapshot.events).toSorted(
- (left, right) => left.sequence - right.sequence,
- );
- const liveEvents = lifecycleEvents.stream.pipe(
- Stream.filter((event) => event.sequence > snapshot.sequence),
- );
- return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
+ [WS_METHODS.terminalWrite]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
+ "rpc.aggregate": "terminal",
}),
- { "rpc.aggregate": "server" },
- ),
- });
- }),
-);
+ [WS_METHODS.terminalResize]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
+ "rpc.aggregate": "terminal",
+ }),
+ [WS_METHODS.terminalClear]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
+ "rpc.aggregate": "terminal",
+ }),
+ [WS_METHODS.terminalRestart]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
+ "rpc.aggregate": "terminal",
+ }),
+ [WS_METHODS.terminalClose]: (input) =>
+ observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
+ "rpc.aggregate": "terminal",
+ }),
+ [WS_METHODS.subscribeTerminalEvents]: (_input) =>
+ observeRpcStream(
+ WS_METHODS.subscribeTerminalEvents,
+ Stream.callback<TerminalEvent>((queue) =>
+ Effect.acquireRelease(
+ terminalManager.subscribe((event) => Queue.offer(queue, event)),
+ (unsubscribe) => Effect.sync(unsubscribe),
+ ),
+ ),
+ { "rpc.aggregate": "terminal" },
+ ),
+ [WS_METHODS.subscribeServerConfig]: (_input) =>
+ observeRpcStreamEffect(
+ WS_METHODS.subscribeServerConfig,
+ Effect.gen(function* () {
+ const keybindingsUpdates = keybindings.streamChanges.pipe(
+ Stream.map((event) => ({
+ version: 1 as const,
+ type: "keybindingsUpdated" as const,
+ payload: {
+ issues: event.issues,
+ },
+ })),
+ );
+ const providerStatuses = providerRegistry.streamChanges.pipe(
+ Stream.map((providers) => ({
+ version: 1 as const,
+ type: "providerStatuses" as const,
+ payload: { providers },
+ })),
+ );
+ const settingsUpdates = serverSettings.streamChanges.pipe(
+ Stream.map((settings) => ({
+ version: 1 as const,
+ type: "settingsUpdated" as const,
+ payload: { settings },
+ })),
+ );
+
+ return Stream.concat(
+ Stream.make({
+ version: 1 as const,
+ type: "snapshot" as const,
+ config: yield* loadServerConfig,
+ }),
+ Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
+ );
+ }),
+ { "rpc.aggregate": "server" },
+ ),
+ [WS_METHODS.subscribeServerLifecycle]: (_input) =>
+ observeRpcStreamEffect(
+ WS_METHODS.subscribeServerLifecycle,
+ Effect.gen(function* () {
+ const snapshot = yield* lifecycleEvents.snapshot;
+ const snapshotEvents = Array.from(snapshot.events).toSorted(
+ (left, right) => left.sequence - right.sequence,
+ );
+ const liveEvents = lifecycleEvents.stream.pipe(
+ Stream.filter((event) => event.sequence > snapshot.sequence),
+ );
+ return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
+ }),
+ { "rpc.aggregate": "server" },
+ ),
+ [WS_METHODS.subscribeAuthAccess]: (_input) =>
+ observeRpcStreamEffect(
+ WS_METHODS.subscribeAuthAccess,
+ Effect.gen(function* () {
+ const initialSnapshot = yield* loadAuthAccessSnapshot();
+ const revisionRef = yield* Ref.make(1);
+ const accessChanges: Stream.Stream<
+ BootstrapCredentialChange | SessionCredentialChange
+ > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
+
+ const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
+ Stream.mapEffect((change) =>
+ Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
+ Effect.map((revision) =>
+ toAuthAccessStreamEvent(change, revision, currentSessionId),
+ ),
+ ),
+ ),
+ );
+
+ return Stream.concat(
+ Stream.make({
+ version: 1 as const,
+ revision: 1,
+ type: "snapshot" as const,
+ payload: initialSnapshot,
+ }),
+ liveEvents,
+ );
+ }),
+ { "rpc.aggregate": "auth" },
+ ),
+ });
+ }),
+ );
export const websocketRpcRouteLayer = Layer.unwrap(
- Effect.gen(function* () {
- const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
- spanPrefix: "ws.rpc",
- spanAttributes: {
- "rpc.transport": "websocket",
- "rpc.system": "effect-rpc",
- },
- }).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)));
- return HttpRouter.add(
+ Effect.succeed(
+ HttpRouter.add(
"GET",
"/ws",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
- const config = yield* ServerConfig;
- if (config.authToken) {
- const url = HttpServerRequest.toURL(request);
- if (Option.isNone(url)) {
- return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 });
- }
- const token = url.value.searchParams.get("token");
- if (token !== config.authToken) {
- return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 });
- }
- }
- return yield* rpcWebSocketHttpEffect;
- }),
- );
- }),
+ const serverAuth = yield* ServerAuth;
+ const sessions = yield* SessionCredentialService;
+ const session = yield* serverAuth.authenticateWebSocketUpgrade(request);
+ const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
+ spanPrefix: "ws.rpc",
+ spanAttributes: {
+ "rpc.transport": "websocket",
+ "rpc.system": "effect-rpc",
+ },
+ }).pipe(
+ Effect.provide(
+ makeWsRpcLayer(session.sessionId).pipe(Layer.provideMerge(RpcSerialization.layerJson)),
+ ),
+ );
+ return yield* Effect.acquireUseRelease(
+ sessions.markConnected(session.sessionId),
+ () => rpcWebSocketHttpEffect,
+ () => sessions.markDisconnected(session.sessionId),
+ );
+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
+ ),
+ ),
);
diff --git a/apps/web/index.html b/apps/web/index.html
index 45f30f716..9f0329b60 100644
--- a/apps/web/index.html
+++ b/apps/web/index.html
@@ -2,9 +2,84 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
+ <meta name="theme-color" content="#161616" media="(prefers-color-scheme: dark)" />
+ <meta name="theme-color" content="#161616" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <script>
+ (() => {
+ const LIGHT_BACKGROUND = "#ffffff";
+ const DARK_BACKGROUND = "#161616";
+ const themeColorMeta = document.querySelector('meta[name="theme-color"]');
+ try {
+ const storedTheme = window.localStorage.getItem("t3code:theme");
+ const theme =
+ storedTheme === "light" || storedTheme === "dark" || storedTheme === "system"
+ ? storedTheme
+ : "system";
+ const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+ const isDark = theme === "dark" || (theme === "system" && prefersDark);
+ document.documentElement.classList.toggle("dark", isDark);
+ const chromeColor = isDark ? DARK_BACKGROUND : LIGHT_BACKGROUND;
+ document.documentElement.style.backgroundColor = chromeColor;
+ themeColorMeta?.setAttribute("content", chromeColor);
+ } catch {
+ document.documentElement.classList.add("dark");
+ document.documentElement.style.backgroundColor = DARK_BACKGROUND;
+ themeColorMeta?.setAttribute("content", DARK_BACKGROUND);
+ }
+ })();
+ </script>
+ <style>
+ html,
+ body,
+ #root {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ }
+
+ body {
+ background: #ffffff;
+ color: #262626;
+ font-family:
+ "DM Sans",
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ system-ui,
+ sans-serif;
+ }
+
+ html.dark body {
+ background: #161616;
+ color: #f5f5f5;
+ }
+
+ #boot-shell {
+ display: flex;
+ min-height: 100%;
+ align-items: center;
+ justify-content: center;
+ background: inherit;
+ }
+
+ #boot-shell-card {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 96px;
+ height: 96px;
+ }
+
+ #boot-shell-logo {
+ width: 64px;
+ height: 64px;
+ object-fit: contain;
+ }
+ </style>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
@@ -12,10 +87,15 @@
rel="stylesheet"
/>
<title>T3 Code (Alpha)</title>
- <script crossorigin="anonymous" src="//unpkg.com/react-scan/dist/auto.global.js"></script>
</head>
<body>
- <div id="root"></div>
+ <div id="root">
+ <div id="boot-shell">
+ <div id="boot-shell-card" aria-label="T3 Code splash screen">
+ <img id="boot-shell-logo" src="/apple-touch-icon.png" alt="T3 Code" />
+ </div>
+ </div>
+ </div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts
new file mode 100644
index 000000000..2e12e00f4
--- /dev/null
+++ b/apps/web/src/authBootstrap.test.ts
@@ -0,0 +1,460 @@
+import type { DesktopBridge } from "@t3tools/contracts";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+function jsonResponse(body: unknown, init?: ResponseInit) {
+ return new Response(JSON.stringify(body), {
+ headers: {
+ "content-type": "application/json",
+ },
+ status: 200,
+ ...init,
+ });
+}
+
+type TestWindow = {
+ location: URL;
+ history: {
+ replaceState: (_data: unknown, _unused: string, url: string) => void;
+ };
+ desktopBridge?: DesktopBridge;
+};
+
+function installTestBrowser(url: string) {
+ const testWindow: TestWindow = {
+ location: new URL(url),
+ history: {
+ replaceState: (_data, _unused, nextUrl) => {
+ testWindow.location = new URL(nextUrl, testWindow.location.href);
+ },
+ },
+ };
+
+ vi.stubGlobal("window", testWindow);
+ vi.stubGlobal("document", { title: "T3 Code" });
+
+ return testWindow;
+}
+
+function sessionResponse(body: unknown, init?: ResponseInit) {
+ return jsonResponse(body, init);
+}
+
+describe("resolveInitialServerAuthGateState", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ installTestBrowser("http://localhost/");
+ });
+
+ afterEach(async () => {
+ const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
+ __resetServerAuthBootstrapForTests();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it("reuses an in-flight silent bootstrap attempt", async () => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "desktop-managed-local",
+ bootstrapMethods: ["desktop-bootstrap"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ jsonResponse({
+ authenticated: true,
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ )
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: true,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const testWindow = installTestBrowser("http://localhost/");
+ testWindow.desktopBridge = {
+ getLocalEnvironmentBootstrap: () => ({
+ label: "Local environment",
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ }),
+ } as DesktopBridge;
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost:3773/api/auth/session");
+ expect(fetchMock.mock.calls[1]?.[0]).toBe("http://localhost:3773/api/auth/bootstrap");
+ expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");
+ });
+
+ it("uses https fetch urls when the primary environment uses wss", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
+ vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/session", {
+ credentials: "include",
+ });
+ });
+
+ it("uses the current origin as an auth proxy base for local dev environments", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ installTestBrowser("http://localhost:5735/");
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/api/auth/session", {
+ credentials: "include",
+ });
+ });
+
+ it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+ });
+
+ it("retries transient auth session bootstrap failures after restart", async () => {
+ vi.useFakeTimers();
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
+ .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
+ .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ const gateStatePromise = resolveInitialServerAuthGateState();
+ await vi.advanceTimersByTimeAsync(2_000);
+
+ await expect(gateStatePromise).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+
+ it("takes a pairing token from the location hash and strips it immediately", async () => {
+ const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
+ const { takePairingTokenFromUrl } = await import("./environments/primary");
+
+ expect(takePairingTokenFromUrl()).toBe("pairing-token");
+ expect(testWindow.location.hash).toBe("");
+ expect(testWindow.location.searchParams.get("token")).toBeNull();
+ });
+
+ it("accepts query-string pairing tokens as a backward-compatible fallback", async () => {
+ const testWindow = installTestBrowser("http://localhost/?token=pairing-token");
+ const { takePairingTokenFromUrl } = await import("./environments/primary");
+
+ expect(takePairingTokenFromUrl()).toBe("pairing-token");
+ expect(testWindow.location.searchParams.get("token")).toBeNull();
+ });
+
+ it("allows manual token submission after the initial auth check requires pairing", async () => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ jsonResponse({
+ authenticated: true,
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ )
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: true,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ installTestBrowser("http://localhost/");
+
+ const { resolveInitialServerAuthGateState, submitServerAuthCredential } =
+ await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+ await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined();
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "authenticated",
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
+ vi.useFakeTimers();
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "desktop-managed-local",
+ bootstrapMethods: ["desktop-bootstrap"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ jsonResponse({
+ authenticated: true,
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ )
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "desktop-managed-local",
+ bootstrapMethods: ["desktop-bootstrap"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: true,
+ auth: {
+ policy: "desktop-managed-local",
+ bootstrapMethods: ["desktop-bootstrap"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const testWindow = installTestBrowser("http://localhost/");
+ testWindow.desktopBridge = {
+ getLocalEnvironmentBootstrap: () => ({
+ label: "Local environment",
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ }),
+ } as DesktopBridge;
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ const gateStatePromise = resolveInitialServerAuthGateState();
+ await vi.advanceTimersByTimeAsync(100);
+
+ await expect(gateStatePromise).resolves.toEqual({
+ status: "authenticated",
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");
+ expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
+ });
+
+ it("revalidates the server session state after a previous authenticated result", async () => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: true,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ )
+ .mockResolvedValueOnce(
+ sessionResponse({
+ authenticated: false,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "authenticated",
+ });
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "requires-auth",
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("creates a pairing credential from the authenticated auth endpoint", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
+ jsonResponse({
+ id: "pairing-link-1",
+ credential: "pairing-token",
+ label: "Julius iPhone",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { createServerPairingCredential } = await import("./environments/primary");
+
+ await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({
+ id: "pairing-link-1",
+ credential: "pairing-token",
+ label: "Julius iPhone",
+ expiresAt: "2026-04-05T00:00:00.000Z",
+ });
+ expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", {
+ body: JSON.stringify({ label: "Julius iPhone" }),
+ credentials: "include",
+ headers: {
+ "content-type": "application/json",
+ },
+ method: "POST",
+ });
+ });
+});
diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts
index c9e336bf4..adc649595 100644
--- a/apps/web/src/components/BranchToolbar.logic.ts
+++ b/apps/web/src/components/BranchToolbar.logic.ts
@@ -1,10 +1,17 @@
-import type { GitBranch } from "@t3tools/contracts";
+import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "@t3tools/shared/git";
+export interface EnvironmentOption {
+ environmentId: EnvironmentId;
+ projectId: ProjectId;
+ label: string;
+ isPrimary: boolean;
+}
+
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx
index cbcaf6f2f..94d11ae7b 100644
--- a/apps/web/src/components/BranchToolbar.tsx
+++ b/apps/web/src/components/BranchToolbar.tsx
@@ -1,25 +1,19 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
-import { FolderIcon, GitForkIcon } from "lucide-react";
-import { useCallback, useMemo } from "react";
+import { useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
-import { readEnvironmentApi } from "../environmentApi";
-import { newCommandId } from "../lib/utils";
import { useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import {
- EnvMode,
- resolveDraftEnvModeAfterBranchChange,
+ type EnvMode,
+ type EnvironmentOption,
resolveEffectiveEnvMode,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
-import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
-
-const envModeItems = [
- { value: "local", label: "Local" },
- { value: "worktree", label: "New worktree" },
-] as const;
+import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
+import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
+import { Separator } from "./ui/separator";
interface BranchToolbarProps {
environmentId: EnvironmentId;
@@ -29,9 +23,11 @@ interface BranchToolbarProps {
envLocked: boolean;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
+ availableEnvironments?: readonly EnvironmentOption[];
+ onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
-export default function BranchToolbar({
+export function BranchToolbar({
environmentId,
threadId,
draftId,
@@ -39,6 +35,8 @@ export default function BranchToolbar({
envLocked,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
+ availableEnvironments,
+ onEnvironmentChange,
}: BranchToolbarProps) {
const threadRef = useMemo(
() => scopeThreadRef(environmentId, threadId),
@@ -46,10 +44,7 @@ export default function BranchToolbar({
);
const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
const serverThread = useStore(serverThreadSelector);
- const serverSession = serverThread?.session ?? null;
- const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
- const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const activeProjectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
: draftThread
@@ -60,131 +55,46 @@ export default function BranchToolbar({
[activeProjectRef],
);
const activeProject = useStore(activeProjectSelector);
- const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
- const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
+ const hasActiveThread = serverThread !== undefined || draftThread !== null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
- const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
- const hasServerThread = serverThread !== undefined;
const effectiveEnvMode = resolveEffectiveEnvMode({
activeWorktreePath,
- hasServerThread,
+ hasServerThread: serverThread !== undefined,
draftThreadEnvMode: draftThread?.envMode,
});
- const setThreadBranch = useCallback(
- (branch: string | null, worktreePath: string | null) => {
- if (!activeThreadId || !activeProject) return;
- const api = readEnvironmentApi(environmentId);
- // If the effective cwd is about to change, stop the running session so the
- // next message creates a new one with the correct cwd.
- if (serverSession && worktreePath !== activeWorktreePath && api) {
- void api.orchestration
- .dispatchCommand({
- type: "thread.session.stop",
- commandId: newCommandId(),
- threadId: activeThreadId,
- createdAt: new Date().toISOString(),
- })
- .catch(() => undefined);
- }
- if (api && hasServerThread) {
- void api.orchestration.dispatchCommand({
- type: "thread.meta.update",
- commandId: newCommandId(),
- threadId: activeThreadId,
- branch,
- worktreePath,
- });
- }
- if (hasServerThread) {
- setThreadBranchAction(activeThreadId, branch, worktreePath);
- return;
- }
- const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
- nextWorktreePath: worktreePath,
- currentWorktreePath: activeWorktreePath,
- effectiveEnvMode,
- });
- setDraftThreadContext(draftId ?? threadRef, {
- branch,
- worktreePath,
- envMode: nextDraftEnvMode,
- projectRef: scopeProjectRef(environmentId, activeProject.id),
- });
- },
- [
- activeThreadId,
- activeProject,
- serverSession,
- activeWorktreePath,
- hasServerThread,
- setThreadBranchAction,
- setDraftThreadContext,
- draftId,
- threadRef,
- environmentId,
- effectiveEnvMode,
- ],
- );
+ const showEnvironmentPicker =
+ availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange;
- if (!activeThreadId || !activeProject) return null;
+ if (!hasActiveThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
- {envLocked || activeWorktreePath ? (
- <span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
- {activeWorktreePath ? (
- <>
- <GitForkIcon className="size-3" />
- Worktree
- </>
- ) : (
- <>
- <FolderIcon className="size-3" />
- Local
- </>
- )}
- </span>
- ) : (
- <Select
- value={effectiveEnvMode}
- onValueChange={(value) => onEnvModeChange(value as EnvMode)}
- items={envModeItems}
- >
- <SelectTrigger variant="ghost" size="xs" className="font-medium">
- {effectiveEnvMode === "worktree" ? (
- <GitForkIcon className="size-3" />
- ) : (
- <FolderIcon className="size-3" />
- )}
- <SelectValue />
- </SelectTrigger>
- <SelectPopup>
- <SelectItem value="local">
- <span className="inline-flex items-center gap-1.5">
- <FolderIcon className="size-3" />
- Local
- </span>
- </SelectItem>
- <SelectItem value="worktree">
- <span className="inline-flex items-center gap-1.5">
- <GitForkIcon className="size-3" />
- New worktree
- </span>
- </SelectItem>
- </SelectPopup>
- </Select>
- )}
+ <div className="flex items-center gap-1">
+ {showEnvironmentPicker && (
+ <>
+ <BranchToolbarEnvironmentSelector
+ envLocked={envLocked}
+ environmentId={environmentId}
+ availableEnvironments={availableEnvironments}
+ onEnvironmentChange={onEnvironmentChange}
+ />
+ <Separator orientation="vertical" className="mx-0.5 h-3.5!" />
+ </>
+ )}
+ <BranchToolbarEnvModeSelector
+ envLocked={envLocked}
+ effectiveEnvMode={effectiveEnvMode}
+ activeWorktreePath={activeWorktreePath}
+ onEnvModeChange={onEnvModeChange}
+ />
+ </div>
<BranchToolbarBranchSelector
environmentId={environmentId}
- activeProjectCwd={activeProject.cwd}
- activeThreadBranch={activeThreadBranch}
- activeWorktreePath={activeWorktreePath}
- branchCwd={branchCwd}
- effectiveEnvMode={effectiveEnvMode}
+ threadId={threadId}
+ {...(draftId ? { draftId } : {})}
envLocked={envLocked}
- onSetThreadBranch={setThreadBranch}
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx
index 61a97866f..11c458bbe 100644
--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx
+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx
@@ -1,4 +1,5 @@
-import type { EnvironmentId, GitBranch } from "@t3tools/contracts";
+import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
+import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
@@ -14,15 +15,20 @@ import {
useTransition,
} from "react";
+import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
+import { readEnvironmentApi } from "../environmentApi";
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
-import { readEnvironmentApi } from "../environmentApi";
+import { newCommandId } from "../lib/utils";
import { parsePullRequestReference } from "../pullRequestReference";
+import { useStore } from "../store";
+import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import {
deriveLocalBranchNameFromRemoteRef,
- EnvMode,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
+ resolveDraftEnvModeAfterBranchChange,
+ resolveEffectiveEnvMode,
shouldIncludeBranchPickerItem,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
@@ -40,13 +46,9 @@ import { toastManager } from "./ui/toast";
interface BranchToolbarBranchSelectorProps {
environmentId: EnvironmentId;
- activeProjectCwd: string;
- activeThreadBranch: string | null;
- activeWorktreePath: string | null;
- branchCwd: string | null;
- effectiveEnvMode: EnvMode;
+ threadId: ThreadId;
+ draftId?: DraftId;
envLocked: boolean;
- onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
}
@@ -57,7 +59,7 @@ function toBranchActionErrorMessage(error: unknown): string {
function getBranchTriggerLabel(input: {
activeWorktreePath: string | null;
- effectiveEnvMode: EnvMode;
+ effectiveEnvMode: "local" | "worktree";
resolvedActiveBranch: string | null;
}): string {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
@@ -72,16 +74,109 @@ function getBranchTriggerLabel(input: {
export function BranchToolbarBranchSelector({
environmentId,
- activeProjectCwd,
- activeThreadBranch,
- activeWorktreePath,
- branchCwd,
- effectiveEnvMode,
+ threadId,
+ draftId,
envLocked,
- onSetThreadBranch,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
+ // ---------------------------------------------------------------------------
+ // Thread / project state (pushed down from parent to colocate with mutation)
+ // ---------------------------------------------------------------------------
+ const threadRef = useMemo(
+ () => scopeThreadRef(environmentId, threadId),
+ [environmentId, threadId],
+ );
+ const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
+ const serverThread = useStore(serverThreadSelector);
+ const serverSession = serverThread?.session ?? null;
+ const setThreadBranchAction = useStore((store) => store.setThreadBranch);
+ const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
+ const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
+
+ const activeProjectRef = serverThread
+ ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
+ : draftThread
+ ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
+ : null;
+ const activeProjectSelector = useMemo(
+ () => createProjectSelectorByRef(activeProjectRef),
+ [activeProjectRef],
+ );
+ const activeProject = useStore(activeProjectSelector);
+
+ const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
+ const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
+ const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
+ const activeProjectCwd = activeProject?.cwd ?? null;
+ const branchCwd = activeWorktreePath ?? activeProjectCwd;
+ const hasServerThread = serverThread !== undefined;
+ const effectiveEnvMode = resolveEffectiveEnvMode({
+ activeWorktreePath,
+ hasServerThread,
+ draftThreadEnvMode: draftThread?.envMode,
+ });
+
+ // ---------------------------------------------------------------------------
+ // Thread branch mutation (colocated — only this component calls it)
+ // ---------------------------------------------------------------------------
+ const setThreadBranch = useCallback(
+ (branch: string | null, worktreePath: string | null) => {
+ if (!activeThreadId || !activeProject) return;
+ const api = readEnvironmentApi(environmentId);
+ if (serverSession && worktreePath !== activeWorktreePath && api) {
+ void api.orchestration
+ .dispatchCommand({
+ type: "thread.session.stop",
+ commandId: newCommandId(),
+ threadId: activeThreadId,
+ createdAt: new Date().toISOString(),
+ })
+ .catch(() => undefined);
+ }
+ if (api && hasServerThread) {
+ void api.orchestration.dispatchCommand({
+ type: "thread.meta.update",
+ commandId: newCommandId(),
+ threadId: activeThreadId,
+ branch,
+ worktreePath,
+ });
+ }
+ if (hasServerThread) {
+ setThreadBranchAction(activeThreadId, branch, worktreePath);
+ return;
+ }
+ const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
+ nextWorktreePath: worktreePath,
+ currentWorktreePath: activeWorktreePath,
+ effectiveEnvMode,
+ });
+ setDraftThreadContext(draftId ?? threadRef, {
+ branch,
+ worktreePath,
+ envMode: nextDraftEnvMode,
+ projectRef: scopeProjectRef(environmentId, activeProject.id),
+ });
+ },
+ [
+ activeThreadId,
+ activeProject,
+ serverSession,
+ activeWorktreePath,
+ hasServerThread,
+ setThreadBranchAction,
+ setDraftThreadContext,
+ draftId,
+ threadRef,
+ environmentId,
+ effectiveEnvMode,
+ ],
+ );
+
+ // ---------------------------------------------------------------------------
+ // Git branch queries
+ // ---------------------------------------------------------------------------
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
@@ -183,6 +278,9 @@ export function BranchToolbarBranchSelector({
? `Showing ${branches.length} of ${totalBranchCount} branches`
: null;
+ // ---------------------------------------------------------------------------
+ // Branch actions
+ // ---------------------------------------------------------------------------
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
@@ -194,11 +292,10 @@ export function BranchToolbarBranchSelector({
const selectBranch = (branch: GitBranch) => {
const api = readEnvironmentApi(environmentId);
- if (!api || !branchCwd || isBranchActionPending) return;
+ if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
- // In new-worktree mode, selecting a branch sets the base branch.
if (isSelectingWorktreeBase) {
- onSetThreadBranch(branch.name, null);
+ setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
@@ -210,9 +307,8 @@ export function BranchToolbarBranchSelector({
branch,
});
- // If the branch already lives in a worktree, point the thread there.
if (selectionTarget.reuseExistingWorktree) {
- onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath);
+ setThreadBranch(branch.name, selectionTarget.nextWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
@@ -237,7 +333,7 @@ export function BranchToolbarBranchSelector({
? (checkoutResult.branch ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
- onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
+ setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
@@ -267,7 +363,7 @@ export function BranchToolbarBranchSelector({
checkout: true,
});
setOptimisticBranch(createBranchResult.branch);
- onSetThreadBranch(createBranchResult.branch, activeWorktreePath);
+ setThreadBranch(createBranchResult.branch, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
@@ -288,15 +384,12 @@ export function BranchToolbarBranchSelector({
) {
return;
}
- onSetThreadBranch(currentGitBranch, null);
- }, [
- activeThreadBranch,
- activeWorktreePath,
- currentGitBranch,
- effectiveEnvMode,
- onSetThreadBranch,
- ]);
+ setThreadBranch(currentGitBranch, null);
+ }, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
+ // ---------------------------------------------------------------------------
+ // Combobox / virtualizer plumbing
+ // ---------------------------------------------------------------------------
const handleOpenChange = useCallback(
(open: boolean) => {
setIsBranchMenuOpen(open);
@@ -437,7 +530,7 @@ export function BranchToolbarBranchSelector({
style={style}
onClick={() => createBranch(trimmedBranchQuery)}
>
- <span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
+ <span className="truncate">Create new branch &quot;{trimmedBranchQuery}&quot;</span>
</ComboboxItem>
);
}
@@ -445,7 +538,8 @@ export function BranchToolbarBranchSelector({
const branch = branchByName.get(itemValue);
if (!branch) return null;
- const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd;
+ const hasSecondaryWorktree =
+ branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx
new file mode 100644
index 000000000..e1145f65f
--- /dev/null
+++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx
@@ -0,0 +1,73 @@
+import { FolderIcon, GitForkIcon } from "lucide-react";
+import { memo } from "react";
+
+import type { EnvMode } from "./BranchToolbar.logic";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
+
+const envModeItems = [
+ { value: "local", label: "Local" },
+ { value: "worktree", label: "New worktree" },
+] as const;
+
+interface BranchToolbarEnvModeSelectorProps {
+ envLocked: boolean;
+ effectiveEnvMode: EnvMode;
+ activeWorktreePath: string | null;
+ onEnvModeChange: (mode: EnvMode) => void;
+}
+
+export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
+ envLocked,
+ effectiveEnvMode,
+ activeWorktreePath,
+ onEnvModeChange,
+}: BranchToolbarEnvModeSelectorProps) {
+ if (envLocked || activeWorktreePath) {
+ return (
+ <span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
+ {activeWorktreePath ? (
+ <>
+ <GitForkIcon className="size-3" />
+ Worktree
+ </>
+ ) : (
+ <>
+ <FolderIcon className="size-3" />
+ Local
+ </>
+ )}
+ </span>
+ );
+ }
+
+ return (
+ <Select
+ value={effectiveEnvMode}
+ onValueChange={(value) => onEnvModeChange(value as EnvMode)}
+ items={envModeItems}
+ >
+ <SelectTrigger variant="ghost" size="xs" className="font-medium">
+ {effectiveEnvMode === "worktree" ? (
+ <GitForkIcon className="size-3" />
+ ) : (
+ <FolderIcon className="size-3" />
+ )}
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ <SelectItem value="local">
+ <span className="inline-flex items-center gap-1.5">
+ <FolderIcon className="size-3" />
+ Local
+ </span>
+ </SelectItem>
+ <SelectItem value="worktree">
+ <span className="inline-flex items-center gap-1.5">
+ <GitForkIcon className="size-3" />
+ New worktree
+ </span>
+ </SelectItem>
+ </SelectPopup>
+ </Select>
+ );
+});
diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
new file mode 100644
index 000000000..1725e8e90
--- /dev/null
+++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
@@ -0,0 +1,65 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { CloudIcon, FolderIcon, ServerIcon } from "lucide-react";
+import { memo, useMemo } from "react";
+
+import type { EnvironmentOption } from "./BranchToolbar.logic";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
+
+interface BranchToolbarEnvironmentSelectorProps {
+ envLocked: boolean;
+ environmentId: EnvironmentId;
+ availableEnvironments: readonly EnvironmentOption[];
+ onEnvironmentChange: (environmentId: EnvironmentId) => void;
+}
+
+export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
+ envLocked,
+ environmentId,
+ availableEnvironments,
+ onEnvironmentChange,
+}: BranchToolbarEnvironmentSelectorProps) {
+ const activeEnvironmentLabel = useMemo(() => {
+ return availableEnvironments.find((env) => env.environmentId === environmentId)?.label ?? null;
+ }, [availableEnvironments, environmentId]);
+
+ const environmentItems = useMemo(
+ () =>
+ availableEnvironments.map((env) => ({
+ value: env.environmentId,
+ label: env.label,
+ })),
+ [availableEnvironments],
+ );
+
+ if (envLocked) {
+ return (
+ <span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
+ <ServerIcon className="size-3" />
+ {activeEnvironmentLabel ?? "Environment"}
+ </span>
+ );
+ }
+
+ return (
+ <Select
+ value={environmentId}
+ onValueChange={(value) => onEnvironmentChange(value as EnvironmentId)}
+ items={environmentItems}
+ >
+ <SelectTrigger variant="ghost" size="xs" className="font-medium">
+ <ServerIcon className="size-3" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ {availableEnvironments.map((env) => (
+ <SelectItem key={env.environmentId} value={env.environmentId}>
+ <span className="inline-flex items-center gap-1.5">
+ {env.isPrimary ? <FolderIcon className="size-3" /> : <CloudIcon className="size-3" />}
+ {env.label}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ );
+});
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx
index f0c4a52c5..24de35959 100644
--- a/apps/web/src/components/ChatView.browser.tsx
+++ b/apps/web/src/components/ChatView.browser.tsx
@@ -44,6 +44,7 @@ import { getRouter } from "../router";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
+import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
@@ -148,6 +149,12 @@ function createBaseServerConfig(): ServerConfig {
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -821,6 +828,7 @@ const worker = setupWorker(
void rpcHarness.onMessage(rawData);
});
}),
+ ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth),
http.get("*/attachments/:attachmentId", () =>
HttpResponse.text(ATTACHMENT_SVG, {
headers: {
@@ -2629,10 +2637,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
"Promoted drafts should canonicalize to the server thread route.",
);
- // The empty thread view and composer should still be visible.
- await expect
- .element(page.getByText("Send a message to start the conversation."))
- .toBeInTheDocument();
+ // The composer should remain usable after canonicalization, regardless of
+ // whether the promoted thread is still visibly empty or has already
+ // entered the running state.
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
} finally {
await mounted.cleanup();
@@ -2992,6 +2999,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
const promotedThreadId = draftThreadIdFor(promotedDraftId);
await promoteDraftThreadViaDomainEvent(promotedThreadId);
+ await waitForURL(
+ mounted.router,
+ (path) => path === serverThreadPath(promotedThreadId),
+ "Promoted drafts should canonicalize to the server thread route before a fresh draft is created.",
+ );
+ await vi.waitFor(
+ () => {
+ expect(useComposerDraftStore.getState().getDraftThread(promotedDraftId)).toBeNull();
+ },
+ { timeout: 8_000, interval: 16 },
+ );
const freshThreadPath = await triggerChatNewShortcutUntilPath(
mounted.router,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index cf09dd8a3..53bfe2324 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -38,6 +38,7 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useGitStatus } from "~/lib/gitStatusState";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
+import { usePrimaryEnvironmentId } from "../environments/primary";
import { readEnvironmentApi } from "../environmentApi";
import { isElectron } from "../env";
import { readLocalApi } from "../localApi";
@@ -75,7 +76,11 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
-import { selectThreadsAcrossEnvironments, useStore } from "../store";
+import {
+ selectProjectsAcrossEnvironments,
+ selectThreadsAcrossEnvironments,
+ useStore,
+} from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
@@ -97,7 +102,7 @@ import {
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
-import BranchToolbar from "./BranchToolbar";
+import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
@@ -124,7 +129,6 @@ import {
nextProjectScriptId,
projectScriptIdFromCommand,
} from "~/projectScripts";
-import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import {
getProviderModelCapabilities,
@@ -135,6 +139,10 @@ import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelection } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKey } from "../logicalProject";
+import {
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+} from "../environments/runtime";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerImageAttachment,
@@ -167,6 +175,7 @@ import { MessagesTimeline } from "./chat/MessagesTimeline";
import { ChatHeader } from "./chat/ChatHeader";
import { ContextWindowMeter } from "./chat/ContextWindowMeter";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview";
+import { NoActiveThreadState } from "./NoActiveThreadState";
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions";
@@ -212,7 +221,6 @@ import {
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
-const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -813,7 +821,7 @@ export default function ChatView(props: ChatViewProps) {
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
- const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef<Record<string, number>>({});
+ const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -998,6 +1006,54 @@ export default function ChatView(props: ChatViewProps) {
useMemo(() => createProjectSelectorByRef(activeProjectRef), [activeProjectRef]),
);
+ // Compute the list of environments this logical project spans, used to
+ // drive the environment picker in BranchToolbar.
+ const allProjects = useStore(useShallow(selectProjectsAcrossEnvironments));
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
+ const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
+ const logicalProjectEnvironments = useMemo(() => {
+ if (!activeProject) return [];
+ const logicalKey = deriveLogicalProjectKey(activeProject);
+ const memberProjects = allProjects.filter((p) => deriveLogicalProjectKey(p) === logicalKey);
+ const seen = new Set<string>();
+ const envs: Array<{
+ environmentId: EnvironmentId;
+ projectId: ProjectId;
+ label: string;
+ isPrimary: boolean;
+ }> = [];
+ for (const p of memberProjects) {
+ if (seen.has(p.environmentId)) continue;
+ seen.add(p.environmentId);
+ const isPrimary = p.environmentId === primaryEnvironmentId;
+ const savedRecord = savedEnvironmentRegistry[p.environmentId];
+ const runtimeState = savedEnvironmentRuntimeById[p.environmentId];
+ const label = isPrimary
+ ? "Local"
+ : (runtimeState?.descriptor?.label ?? savedRecord?.label ?? p.environmentId);
+ envs.push({
+ environmentId: p.environmentId,
+ projectId: p.id,
+ label,
+ isPrimary,
+ });
+ }
+ // Sort: primary first, then alphabetical
+ envs.sort((a, b) => {
+ if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;
+ return a.label.localeCompare(b.label);
+ });
+ return envs;
+ }, [
+ activeProject,
+ allProjects,
+ primaryEnvironmentId,
+ savedEnvironmentRegistry,
+ savedEnvironmentRuntimeById,
+ ]);
+ const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
+
const openPullRequestDialog = useCallback(
(reference?: string) => {
if (!canCheckoutPullRequestIntoThread) {
@@ -1127,7 +1183,17 @@ export default function ChatView(props: ChatViewProps) {
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
- const serverConfig = useServerConfig();
+ const primaryServerConfig = useServerConfig();
+ const activeEnvRuntimeState = useSavedEnvironmentRuntimeStore((s) =>
+ activeThread?.environmentId ? s.byId[activeThread.environmentId] : null,
+ );
+ // Use the server config for the thread's environment. For the primary
+ // environment fall back to the global atom; for remote environments use
+ // the runtime state stored by the environment manager.
+ const serverConfig =
+ primaryEnvironmentId && activeThread?.environmentId === primaryEnvironmentId
+ ? primaryServerConfig
+ : (activeEnvRuntimeState?.serverConfig ?? primaryServerConfig);
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
const unlockedSelectedProvider = resolveSelectableProvider(
providerStatuses,
@@ -1338,11 +1404,28 @@ export default function ChatView(props: ChatViewProps) {
useEffect(() => {
attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
}, [attachmentPreviewHandoffByMessageId]);
+ const clearAttachmentPreviewHandoff = useCallback(
+ (messageId: MessageId, previewUrls?: ReadonlyArray<string>) => {
+ delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
+ const currentPreviewUrls =
+ previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
+ setAttachmentPreviewHandoffByMessageId((existing) => {
+ if (!(messageId in existing)) {
+ return existing;
+ }
+ const next = { ...existing };
+ delete next[messageId];
+ attachmentPreviewHandoffByMessageIdRef.current = next;
+ return next;
+ });
+ for (const previewUrl of currentPreviewUrls) {
+ revokeBlobPreviewUrl(previewUrl);
+ }
+ },
+ [],
+ );
const clearAttachmentPreviewHandoffs = useCallback(() => {
- for (const timeoutId of Object.values(attachmentPreviewHandoffTimeoutByMessageIdRef.current)) {
- window.clearTimeout(timeoutId);
- }
- attachmentPreviewHandoffTimeoutByMessageIdRef.current = {};
+ attachmentPreviewPromotionInFlightByMessageIdRef.current = {};
for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
for (const previewUrl of previewUrls) {
revokeBlobPreviewUrl(previewUrl);
@@ -1376,29 +1459,89 @@ export default function ChatView(props: ChatViewProps) {
attachmentPreviewHandoffByMessageIdRef.current = next;
return next;
});
-
- const existingTimeout = attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
- if (typeof existingTimeout === "number") {
- window.clearTimeout(existingTimeout);
+ }, []);
+ const serverMessages = activeThread?.messages;
+ useEffect(() => {
+ if (typeof Image === "undefined" || !serverMessages || serverMessages.length === 0) {
+ return;
}
- attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId] = window.setTimeout(() => {
- const currentPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId];
- if (currentPreviewUrls) {
- for (const previewUrl of currentPreviewUrls) {
- revokeBlobPreviewUrl(previewUrl);
- }
+
+ const cleanups: Array<() => void> = [];
+
+ for (const [messageId, handoffPreviewUrls] of Object.entries(
+ attachmentPreviewHandoffByMessageId,
+ )) {
+ if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) {
+ continue;
}
- setAttachmentPreviewHandoffByMessageId((existing) => {
- if (!(messageId in existing)) return existing;
- const next = { ...existing };
- delete next[messageId];
- attachmentPreviewHandoffByMessageIdRef.current = next;
- return next;
+
+ const serverMessage = serverMessages.find(
+ (message) => message.id === messageId && message.role === "user",
+ );
+ if (!serverMessage?.attachments || serverMessage.attachments.length === 0) {
+ continue;
+ }
+
+ const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) =>
+ attachment.type === "image" && attachment.previewUrl ? [attachment.previewUrl] : [],
+ );
+ if (
+ serverPreviewUrls.length === 0 ||
+ serverPreviewUrls.length !== handoffPreviewUrls.length ||
+ serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:"))
+ ) {
+ continue;
+ }
+
+ attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true;
+
+ let cancelled = false;
+ const imageInstances: HTMLImageElement[] = [];
+
+ const preloadServerPreviews = Promise.all(
+ serverPreviewUrls.map(
+ (previewUrl) =>
+ new Promise<void>((resolve, reject) => {
+ const image = new Image();
+ imageInstances.push(image);
+ const handleLoad = () => resolve();
+ const handleError = () =>
+ reject(new Error(`Failed to load server preview for ${messageId}.`));
+ image.addEventListener("load", handleLoad, { once: true });
+ image.addEventListener("error", handleError, { once: true });
+ image.src = previewUrl;
+ }),
+ ),
+ );
+
+ void preloadServerPreviews
+ .then(() => {
+ if (cancelled) {
+ return;
+ }
+ clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls);
+ })
+ .catch(() => {
+ if (!cancelled) {
+ delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
+ }
+ });
+
+ cleanups.push(() => {
+ cancelled = true;
+ delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
+ for (const image of imageInstances) {
+ image.src = "";
+ }
});
- delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
- }, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
- }, []);
- const serverMessages = activeThread?.messages;
+ }
+
+ return () => {
+ for (const cleanup of cleanups) {
+ cleanup();
+ }
+ };
+ }, [attachmentPreviewHandoffByMessageId, clearAttachmentPreviewHandoff, serverMessages]);
const timelineMessages = useMemo(() => {
const messages = serverMessages ?? [];
const serverMessagesWithPreviewHandoff =
@@ -1537,7 +1680,9 @@ export default function ChatView(props: ChatViewProps) {
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
- const modelOptionsByProvider = useMemo(
+ const modelOptionsByProvider = useMemo<
+ Record<ProviderKind, ReadonlyArray<ServerProvider["models"][number]>>
+ >(
() => ({
codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [],
claudeAgent:
@@ -1730,6 +1875,47 @@ export default function ChatView(props: ChatViewProps) {
(activeThread.messages.length > 0 ||
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
+
+ // Handle environment change for draft threads. When the user picks a
+ // different environment we update the draft context to point at the physical
+ // project in that environment while keeping the same logical project.
+ const onEnvironmentChange = useCallback(
+ (nextEnvironmentId: EnvironmentId) => {
+ if (envLocked || !draftId) return;
+ const target = logicalProjectEnvironments.find(
+ (env) => env.environmentId === nextEnvironmentId,
+ );
+ if (!target) return;
+ setDraftThreadContext(draftId, {
+ projectRef: scopeProjectRef(target.environmentId, target.projectId),
+ });
+ },
+ [draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext],
+ );
+
+ // Auto-correct the draft model selection when the environment changes and
+ // the previously-selected provider/model is no longer available. This keeps
+ // the stored draft state consistent with the resolved picker values and
+ // prevents stale model references when the user sends a message.
+ const prevEnvironmentIdRef = useRef(activeThread?.environmentId);
+ useEffect(() => {
+ const currentEnvId = activeThread?.environmentId;
+ if (!currentEnvId || envLocked || prevEnvironmentIdRef.current === currentEnvId) {
+ prevEnvironmentIdRef.current = currentEnvId;
+ return;
+ }
+ prevEnvironmentIdRef.current = currentEnvId;
+
+ // The resolved provider/model already account for the new environment's
+ // provider list. Persist that resolved selection into the draft.
+ if (activeThread) {
+ setComposerDraftModelSelection(scopeThreadRef(activeThread.environmentId, activeThread.id), {
+ provider: selectedProvider,
+ model: selectedModel,
+ });
+ }
+ }, [activeThread, envLocked, selectedModel, selectedProvider, setComposerDraftModelSelection]);
+
const activeTerminalGroup =
terminalState.terminalGroups.find(
(group) => group.id === terminalState.activeTerminalGroupId,
@@ -4113,28 +4299,7 @@ export default function ChatView(props: ChatViewProps) {
// Empty state: no active thread
if (!activeThread) {
- return (
- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
- {!isElectron && (
- <header className="border-b border-border px-3 py-2 md:hidden">
- <div className="flex items-center gap-2">
- <SidebarTrigger className="size-7 shrink-0" />
- <span className="text-sm font-medium text-foreground">Threads</span>
- </div>
- </header>
- )}
- {isElectron && (
- <div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
- <span className="text-xs text-muted-foreground/50">No active thread</span>
- </div>
- )}
- <div className="flex flex-1 items-center justify-center">
- <div className="text-center">
- <p className="text-sm">Select a thread or create a new one to get started.</p>
- </div>
- </div>
- </div>
- );
+ return <NoActiveThreadState />;
}
return (
@@ -4636,6 +4801,12 @@ export default function ChatView(props: ChatViewProps) {
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
+ {...(hasMultipleEnvironments
+ ? {
+ availableEnvironments: logicalProjectEnvironments,
+ onEnvironmentChange,
+ }
+ : {})}
/>
)}
{pullRequestDialogState ? (
diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx
index 1a1bd714f..29a2f178a 100644
--- a/apps/web/src/components/GitActionsControl.browser.tsx
+++ b/apps/web/src/components/GitActionsControl.browser.tsx
@@ -44,8 +44,12 @@ const {
toastUpdateSpy: vi.fn(),
}));
-vi.mock("@tanstack/react-query", () => {
+vi.mock("@tanstack/react-query", async () => {
+ const actual =
+ await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
+
return {
+ ...actual,
useIsMutating: vi.fn(() => 0),
useMutation: vi.fn((options: { __kind?: string }) => {
if (options.__kind === "run-stacked-action") {
@@ -133,6 +137,19 @@ vi.mock("~/store", () => ({
}
return environmentState;
},
+ selectProjectsForEnvironment: () => [],
+ selectProjectsAcrossEnvironments: () => [],
+ selectThreadsForEnvironment: () => [],
+ selectThreadsAcrossEnvironments: () => [],
+ selectThreadShellsAcrossEnvironments: () => [],
+ selectSidebarThreadsAcrossEnvironments: () => [],
+ selectSidebarThreadsForProjectRef: () => [],
+ selectSidebarThreadsForProjectRefs: () => [],
+ selectBootstrapCompleteForActiveEnvironment: () => true,
+ selectProjectByRef: () => null,
+ selectThreadByRef: () => null,
+ selectSidebarThreadSummaryByRef: () => null,
+ selectThreadIdsByProjectRef: () => [],
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx
index 6ec450d66..f1239ffec 100644
--- a/apps/web/src/components/KeybindingsToast.browser.tsx
+++ b/apps/web/src/components/KeybindingsToast.browser.tsx
@@ -22,8 +22,10 @@ import { useComposerDraftStore } from "../composerDraftStore";
import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
+import { getWsConnectionStatus } from "../rpc/wsConnectionState";
import { getRouter } from "../router";
import { useStore } from "../store";
+import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
vi.mock("../lib/gitStatusState", () => ({
@@ -58,6 +60,12 @@ function createBaseServerConfig(): ServerConfig {
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -210,6 +218,7 @@ const worker = setupWorker(
void rpcHarness.onMessage(rawData);
});
}),
+ ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth),
http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
);
@@ -250,6 +259,22 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
);
}
+async function waitForToastViewport(): Promise<HTMLElement> {
+ return waitForElement(
+ () => document.querySelector<HTMLElement>('[data-slot="toast-viewport"]'),
+ "App should render the toast viewport before server config updates are pushed",
+ );
+}
+
+async function waitForWsConnection(): Promise<void> {
+ await vi.waitFor(
+ () => {
+ expect(getWsConnectionStatus().phase).toBe("connected");
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+}
+
async function waitForToast(title: string, count = 1): Promise<void> {
await vi.waitFor(
() => {
@@ -269,6 +294,20 @@ async function waitForNoToast(title: string): Promise<void> {
);
}
+async function waitForNoToasts(): Promise<void> {
+ await vi.waitFor(
+ () => {
+ expect(queryToastTitles()).toHaveLength(0);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+}
+
+async function warmServerConfigUpdateStream(): Promise<void> {
+ sendServerConfigUpdatedPush([]);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+}
+
async function waitForInitialWsSubscriptions(): Promise<void> {
await vi.waitFor(
() => {
@@ -313,8 +352,11 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
{ container: host },
);
await waitForComposerEditor();
+ await waitForToastViewport();
await waitForInitialWsSubscriptions();
+ await waitForWsConnection();
await waitForServerConfigSnapshot();
+ await waitForNoToasts();
return {
cleanup: async () => {
@@ -387,6 +429,8 @@ describe("Keybindings update toast", () => {
const mounted = await mountApp();
try {
+ await warmServerConfigUpdateStream();
+
sendServerConfigUpdatedPush([]);
await waitForToast("Keybindings updated", 1);
diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx
new file mode 100644
index 000000000..39aa4e2f7
--- /dev/null
+++ b/apps/web/src/components/NoActiveThreadState.tsx
@@ -0,0 +1,41 @@
+import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty";
+import { SidebarInset, SidebarTrigger } from "./ui/sidebar";
+import { isElectron } from "../env";
+import { cn } from "~/lib/utils";
+
+export function NoActiveThreadState() {
+ return (
+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
+ <header
+ className={cn(
+ "border-b border-border px-3 sm:px-5",
+ isElectron ? "drag-region flex h-[52px] items-center" : "py-2 sm:py-3",
+ )}
+ >
+ {isElectron ? (
+ <span className="text-xs text-muted-foreground/50">No active thread</span>
+ ) : (
+ <div className="flex items-center gap-2">
+ <SidebarTrigger className="size-7 shrink-0 md:hidden" />
+ <span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
+ No active thread
+ </span>
+ </div>
+ )}
+ </header>
+
+ <Empty className="flex-1">
+ <div className="w-full max-w-lg rounded-3xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
+ <EmptyHeader className="max-w-none">
+ <EmptyTitle className="text-foreground text-xl">Pick a thread to continue</EmptyTitle>
+ <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
+ Select an existing thread or create a new one to get started.
+ </EmptyDescription>
+ </EmptyHeader>
+ </div>
+ </Empty>
+ </div>
+ </SidebarInset>
+ );
+}
diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx
index 58426f50b..38e07f59c 100644
--- a/apps/web/src/components/ProjectFavicon.tsx
+++ b/apps/web/src/components/ProjectFavicon.tsx
@@ -1,14 +1,19 @@
+import type { EnvironmentId } from "@t3tools/contracts";
import { FolderIcon } from "lucide-react";
import { useState } from "react";
-import { resolveServerUrl } from "~/lib/utils";
+import { resolveEnvironmentHttpUrl } from "../environments/runtime";
const loadedProjectFaviconSrcs = new Set<string>();
-export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) {
- const src = resolveServerUrl({
- protocol: "http",
+export function ProjectFavicon(input: {
+ environmentId: EnvironmentId;
+ cwd: string;
+ className?: string;
+}) {
+ const src = resolveEnvironmentHttpUrl({
+ environmentId: input.environmentId,
pathname: "/api/project-favicon",
- searchParams: { cwd },
+ searchParams: { cwd: input.cwd },
});
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
@@ -17,12 +22,14 @@ export function ProjectFavicon({ cwd, className }: { cwd: string; className?: st
return (
<>
{status !== "loaded" ? (
- <FolderIcon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />
+ <FolderIcon
+ className={`size-3.5 shrink-0 text-muted-foreground/50 ${input.className ?? ""}`}
+ />
) : null}
<img
src={src}
alt=""
- className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
+ className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${input.className ?? ""}`}
onLoad={() => {
loadedProjectFaviconSrcs.add(src);
setStatus("loaded");
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 918143454..6dbd5605c 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -2,6 +2,7 @@ import {
ArchiveIcon,
ArrowUpDownIcon,
ChevronRightIcon,
+ CloudIcon,
FolderIcon,
GitPullRequestIcon,
PlusIcon,
@@ -34,6 +35,7 @@ import {
type DesktopUpdateState,
type EnvironmentId,
ProjectId,
+ type ScopedProjectRef,
type ScopedThreadRef,
type ThreadEnvMode,
ThreadId,
@@ -50,13 +52,16 @@ import {
type SidebarProjectSortOrder,
type SidebarThreadSortOrder,
} from "@t3tools/contracts/settings";
+import { usePrimaryEnvironmentId } from "../environments/primary";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
import {
+ selectProjectByRef,
selectProjectsAcrossEnvironments,
selectSidebarThreadsForProjectRef,
+ selectSidebarThreadsForProjectRefs,
selectSidebarThreadsAcrossEnvironments,
selectThreadByRef,
useStore,
@@ -103,7 +108,6 @@ import {
SidebarFooter,
SidebarGroup,
SidebarHeader,
- SidebarMenuAction,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
@@ -135,6 +139,11 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { readEnvironmentApi } from "../environmentApi";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "../rpc/serverState";
+import { deriveLogicalProjectKey } from "../logicalProject";
+import {
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+} from "../environments/runtime";
import type { Project, SidebarThreadSummary } from "../types";
const THREAD_PREVIEW_LIMIT = 6;
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
@@ -200,8 +209,14 @@ function buildThreadJumpLabelMap(input: {
return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS;
}
+type EnvironmentPresence = "local-only" | "remote-only" | "mixed";
+
type SidebarProjectSnapshot = Project & {
projectKey: string;
+ environmentPresence: EnvironmentPresence;
+ memberProjectRefs: readonly ScopedProjectRef[];
+ /** Labels for remote environments this project lives in. */
+ remoteEnvironmentLabels: readonly string[];
};
interface TerminalStatusIndicator {
label: "Terminal process running";
@@ -381,7 +396,30 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
(state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).runningTerminalIds,
);
- const gitCwd = thread.worktreePath ?? props.projectCwd;
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const isRemoteThread =
+ primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
+ const remoteEnvLabel = useSavedEnvironmentRuntimeStore(
+ (s) => s.byId[thread.environmentId]?.descriptor?.label ?? null,
+ );
+ const remoteEnvSavedLabel = useSavedEnvironmentRegistryStore(
+ (s) => s.byId[thread.environmentId]?.label ?? null,
+ );
+ const threadEnvironmentLabel = isRemoteThread
+ ? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote")
+ : null;
+ // For grouped projects, the thread may belong to a different environment
+ // than the representative project. Look up the thread's own project cwd
+ // so git status (and thus PR detection) queries the correct path.
+ const threadProjectCwd = useStore(
+ useMemo(
+ () => (state: import("../store").AppState) =>
+ selectProjectByRef(state, scopeProjectRef(thread.environmentId, thread.projectId))?.cwd ??
+ null,
+ [thread.environmentId, thread.projectId],
+ ),
+ );
+ const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
const gitStatus = useGitStatus({
environmentId: thread.environmentId,
cwd: thread.branch != null ? gitCwd : null,
@@ -673,24 +711,41 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
)
) : null}
<span className={threadMetaClassName}>
- {jumpLabel ? (
- <span
- className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
- title={jumpLabel}
- >
- {jumpLabel}
- </span>
- ) : (
- <span
- className={`text-[10px] ${
- isHighlighted
- ? "text-foreground/72 dark:text-foreground/82"
- : "text-muted-foreground/40"
- }`}
- >
- {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
- </span>
- )}
+ <span className="inline-flex items-center gap-1">
+ {isRemoteThread && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ aria-label={threadEnvironmentLabel ?? "Remote"}
+ className="inline-flex items-center justify-center"
+ />
+ }
+ >
+ <CloudIcon className="size-3 text-muted-foreground/40" />
+ </TooltipTrigger>
+ <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
+ </Tooltip>
+ )}
+ {jumpLabel ? (
+ <span
+ className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
+ title={jumpLabel}
+ >
+ {jumpLabel}
+ </span>
+ ) : (
+ <span
+ className={`text-[10px] ${
+ isHighlighted
+ ? "text-foreground/72 dark:text-foreground/82"
+ : "text-muted-foreground/40"
+ }`}
+ >
+ {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
+ </span>
+ )}
+ </span>
</span>
</div>
</div>
@@ -998,7 +1053,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const sidebarThreads = useStore(
useShallow(
useMemo(
- () => (state) =>
+ () => (state: import("../store").AppState) =>
selectSidebarThreadsForProjectRef(
state,
scopeProjectRef(project.environmentId, project.id),
@@ -1007,25 +1062,45 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
),
),
);
+ // For grouped projects that span multiple environments, also fetch
+ // threads from the other member project refs.
+ const otherMemberRefs = useMemo(
+ () =>
+ project.memberProjectRefs.filter(
+ (ref) => ref.environmentId !== project.environmentId || ref.projectId !== project.id,
+ ),
+ [project.memberProjectRefs, project.environmentId, project.id],
+ );
+ const otherMemberThreads = useStore(
+ useShallow(
+ useMemo(
+ () =>
+ otherMemberRefs.length === 0
+ ? () => [] as SidebarThreadSummary[]
+ : (state: import("../store").AppState) =>
+ selectSidebarThreadsForProjectRefs(state, otherMemberRefs),
+ [otherMemberRefs],
+ ),
+ ),
+ );
+ const allSidebarThreads = useMemo(
+ () =>
+ otherMemberThreads.length === 0 ? sidebarThreads : [...sidebarThreads, ...otherMemberThreads],
+ [sidebarThreads, otherMemberThreads],
+ );
const sidebarThreadByKey = useMemo(
() =>
new Map(
- sidebarThreads.map(
+ allSidebarThreads.map(
(thread) =>
[scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
),
),
- [sidebarThreads],
- );
- const projectThreads = useMemo(
- () =>
- sidebarThreads.filter(
- (thread) =>
- scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)) ===
- project.projectKey,
- ),
- [project.projectKey, sidebarThreads],
+ [allSidebarThreads],
);
+ // All threads from the representative + other member environments are
+ // already fetched into allSidebarThreads, so we can use them directly.
+ const projectThreads = allSidebarThreads;
const projectExpanded = useUiStateStore(
(state) => state.projectExpandedById[project.projectKey] ?? true,
);
@@ -1639,28 +1714,49 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}`}
/>
)}
- <ProjectFavicon cwd={project.cwd} />
+ <ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
</SidebarMenuButton>
+ {/* Environment badge – visible by default, crossfades with the
+ "new thread" button on hover using the same pointer-events +
+ opacity pattern as the thread row archive/timestamp swap. */}
+ {project.environmentPresence === "remote-only" && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ aria-label={
+ project.environmentPresence === "remote-only"
+ ? "Remote project"
+ : "Available in multiple environments"
+ }
+ className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/50 transition-opacity duration-150 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0"
+ />
+ }
+ >
+ <CloudIcon className="size-3" />
+ </TooltipTrigger>
+ <TooltipPopup side="top">
+ Remote environment: {project.remoteEnvironmentLabels.join(", ")}
+ </TooltipPopup>
+ </Tooltip>
+ )}
<Tooltip>
<TooltipTrigger
render={
- <SidebarMenuAction
- render={
- <button
- type="button"
- aria-label={`Create new thread in ${project.name}`}
- data-testid="new-thread-button"
- />
- }
- showOnHover
- className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
- onClick={handleCreateThreadClick}
- >
- <SquarePenIcon className="size-3.5" />
- </SidebarMenuAction>
+ <div className="pointer-events-none absolute top-1 right-1.5 opacity-0 transition-opacity duration-150 group-hover/project-header:pointer-events-auto group-hover/project-header:opacity-100 group-focus-within/project-header:pointer-events-auto group-focus-within/project-header:opacity-100">
+ <button
+ type="button"
+ aria-label={`Create new thread in ${project.name}`}
+ data-testid="new-thread-button"
+ className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/70 hover:bg-secondary hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
+ onClick={handleCreateThreadClick}
+ >
+ <SquarePenIcon className="size-3.5" />
+ </button>
+ </div>
}
/>
<TooltipPopup side="top">
@@ -2238,7 +2334,9 @@ export default function Sidebar() {
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const isOnSettings = pathname.startsWith("/settings");
- const appSettings = useSettings();
+ const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
+ const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
+ const defaultThreadEnvMode = useSettings((s) => s.defaultThreadEnvMode);
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useHandleNewThread();
const { archiveThread, deleteThread } = useThreadActions();
@@ -2269,6 +2367,9 @@ export default function Sidebar() {
const platform = navigator.platform;
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
+ const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
@@ -2276,14 +2377,89 @@ export default function Sidebar() {
getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
});
}, [projectOrder, projects]);
- const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(
- () =>
- orderedProjects.map((project) => ({
- ...project,
- projectKey: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
- })),
- [orderedProjects],
- );
+
+ // Build a mapping from physical project key → logical project key for
+ // cross-environment grouping. Projects that share a repositoryIdentity
+ // canonicalKey are treated as one logical project in the sidebar.
+ const physicalToLogicalKey = useMemo(() => {
+ const mapping = new Map<string, string>();
+ for (const project of orderedProjects) {
+ const physicalKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
+ mapping.set(physicalKey, deriveLogicalProjectKey(project));
+ }
+ return mapping;
+ }, [orderedProjects]);
+
+ const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(() => {
+ // Group projects by logical key while preserving insertion order from
+ // orderedProjects.
+ const groupedMembers = new Map<string, Project[]>();
+ for (const project of orderedProjects) {
+ const logicalKey = deriveLogicalProjectKey(project);
+ const existing = groupedMembers.get(logicalKey);
+ if (existing) {
+ existing.push(project);
+ } else {
+ groupedMembers.set(logicalKey, [project]);
+ }
+ }
+
+ const result: SidebarProjectSnapshot[] = [];
+ const seen = new Set<string>();
+ for (const project of orderedProjects) {
+ const logicalKey = deriveLogicalProjectKey(project);
+ if (seen.has(logicalKey)) continue;
+ seen.add(logicalKey);
+
+ const members = groupedMembers.get(logicalKey)!;
+ // Prefer the primary environment's project as the representative.
+ const representative: Project | undefined =
+ (primaryEnvironmentId
+ ? members.find((p) => p.environmentId === primaryEnvironmentId)
+ : undefined) ?? members[0];
+ if (!representative) continue;
+ const hasLocal =
+ primaryEnvironmentId !== null &&
+ members.some((p) => p.environmentId === primaryEnvironmentId);
+ const hasRemote =
+ primaryEnvironmentId !== null
+ ? members.some((p) => p.environmentId !== primaryEnvironmentId)
+ : false;
+
+ const refs = members.map((p) => scopeProjectRef(p.environmentId, p.id));
+ const remoteLabels = members
+ .filter((p) => primaryEnvironmentId !== null && p.environmentId !== primaryEnvironmentId)
+ .map((p) => {
+ const rt = savedEnvironmentRuntimeById[p.environmentId];
+ const saved = savedEnvironmentRegistry[p.environmentId];
+ return rt?.descriptor?.label ?? saved?.label ?? p.environmentId;
+ });
+ const snapshot: SidebarProjectSnapshot = {
+ id: representative.id,
+ environmentId: representative.environmentId,
+ name: representative.name,
+ cwd: representative.cwd,
+ repositoryIdentity: representative.repositoryIdentity ?? null,
+ defaultModelSelection: representative.defaultModelSelection,
+ createdAt: representative.createdAt,
+ updatedAt: representative.updatedAt,
+ scripts: representative.scripts,
+ projectKey: logicalKey,
+ environmentPresence:
+ hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only",
+ memberProjectRefs: refs,
+ remoteEnvironmentLabels: remoteLabels,
+ };
+ result.push(snapshot);
+ }
+ return result;
+ }, [
+ orderedProjects,
+ primaryEnvironmentId,
+ savedEnvironmentRegistry,
+ savedEnvironmentRuntimeById,
+ ]);
+
const sidebarProjectByKey = useMemo(
() => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)),
[sidebarProjects],
@@ -2298,28 +2474,36 @@ export default function Sidebar() {
),
[sidebarThreads],
);
+ // Resolve the active route's project key to a logical key so it matches the
+ // sidebar's grouped project entries.
const activeRouteProjectKey = useMemo(() => {
if (!routeThreadKey) {
return null;
}
const activeThread = sidebarThreadByKey.get(routeThreadKey);
- return activeThread
- ? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId))
- : null;
- }, [routeThreadKey, sidebarThreadByKey]);
+ if (!activeThread) return null;
+ const physicalKey = scopedProjectKey(
+ scopeProjectRef(activeThread.environmentId, activeThread.projectId),
+ );
+ return physicalToLogicalKey.get(physicalKey) ?? physicalKey;
+ }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey]);
+
+ // Group threads by logical project key so all threads from grouped projects
+ // are displayed together.
const threadsByProjectKey = useMemo(() => {
const next = new Map<string, SidebarThreadSummary[]>();
for (const thread of sidebarThreads) {
- const projectKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
- const existing = next.get(projectKey);
+ const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
+ const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
+ const existing = next.get(logicalKey);
if (existing) {
existing.push(thread);
} else {
- next.set(projectKey, [thread]);
+ next.set(logicalKey, [thread]);
}
}
return next;
- }, [sidebarThreads]);
+ }, [sidebarThreads, physicalToLogicalKey]);
const getCurrentSidebarShortcutContext = useCallback(
() => ({
terminalFocus: isTerminalFocused(),
@@ -2347,12 +2531,13 @@ export default function Sidebar() {
shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions);
const focusMostRecentThreadForProject = useCallback(
(projectRef: { environmentId: EnvironmentId; projectId: ProjectId }) => {
- const projectKey = scopedProjectKey(
+ const physicalKey = scopedProjectKey(
scopeProjectRef(projectRef.environmentId, projectRef.projectId),
);
+ const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
const latestThread = sortThreadsForSidebar(
- (threadsByProjectKey.get(projectKey) ?? []).filter((thread) => thread.archivedAt === null),
- appSettings.sidebarThreadSortOrder,
+ (threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null),
+ sidebarThreadSortOrder,
)[0];
if (!latestThread) return;
@@ -2361,7 +2546,7 @@ export default function Sidebar() {
params: buildThreadRouteParams(scopeThreadRef(latestThread.environmentId, latestThread.id)),
});
},
- [appSettings.sidebarThreadSortOrder, navigate, threadsByProjectKey],
+ [sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey],
);
const addProjectFromPath = useCallback(
@@ -2407,7 +2592,7 @@ export default function Sidebar() {
});
if (activeEnvironmentId !== null) {
await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), {
- envMode: appSettings.defaultThreadEnvMode,
+ envMode: defaultThreadEnvMode,
}).catch(() => undefined);
}
} catch (error) {
@@ -2434,7 +2619,7 @@ export default function Sidebar() {
isAddingProject,
projects,
shouldBrowseForProjectImmediately,
- appSettings.defaultThreadEnvMode,
+ defaultThreadEnvMode,
],
);
@@ -2501,7 +2686,7 @@ export default function Sidebar() {
const handleProjectDragEnd = useCallback(
(event: DragEndEvent) => {
- if (appSettings.sidebarProjectSortOrder !== "manual") {
+ if (sidebarProjectSortOrder !== "manual") {
dragInProgressRef.current = false;
return;
}
@@ -2513,18 +2698,18 @@ export default function Sidebar() {
if (!activeProject || !overProject) return;
reorderProjects(activeProject.projectKey, overProject.projectKey);
},
- [appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects],
+ [sidebarProjectSortOrder, reorderProjects, sidebarProjects],
);
const handleProjectDragStart = useCallback(
(_event: DragStartEvent) => {
- if (appSettings.sidebarProjectSortOrder !== "manual") {
+ if (sidebarProjectSortOrder !== "manual") {
return;
}
dragInProgressRef.current = true;
suppressProjectClickAfterDragRef.current = true;
},
- [appSettings.sidebarProjectSortOrder],
+ [sidebarProjectSortOrder],
);
const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => {
@@ -2558,22 +2743,29 @@ export default function Sidebar() {
...project,
id: project.projectKey,
}));
- const sortableThreads = visibleThreads.map((thread) => ({
- ...thread,
- projectId: scopedProjectKey(
- scopeProjectRef(thread.environmentId, thread.projectId),
- ) as ProjectId,
- }));
+ const sortableThreads = visibleThreads.map((thread) => {
+ const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
+ return {
+ ...thread,
+ projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId,
+ };
+ });
return sortProjectsForSidebar(
sortableProjects,
sortableThreads,
- appSettings.sidebarProjectSortOrder,
+ sidebarProjectSortOrder,
).flatMap((project) => {
const resolvedProject = sidebarProjectByKey.get(project.id);
return resolvedProject ? [resolvedProject] : [];
});
- }, [appSettings.sidebarProjectSortOrder, sidebarProjectByKey, sidebarProjects, visibleThreads]);
- const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
+ }, [
+ sidebarProjectSortOrder,
+ physicalToLogicalKey,
+ sidebarProjectByKey,
+ sidebarProjects,
+ visibleThreads,
+ ]);
+ const isManualProjectSorting = sidebarProjectSortOrder === "manual";
const visibleSidebarThreadKeys = useMemo(
() =>
sortedProjects.flatMap((project) => {
@@ -2581,7 +2773,7 @@ export default function Sidebar() {
(threadsByProjectKey.get(project.projectKey) ?? []).filter(
(thread) => thread.archivedAt === null,
),
- appSettings.sidebarThreadSortOrder,
+ sidebarThreadSortOrder,
);
const projectExpanded = projectExpandedById[project.projectKey] ?? true;
const activeThreadKey = routeThreadKey ?? undefined;
@@ -2609,7 +2801,7 @@ export default function Sidebar() {
);
}),
[
- appSettings.sidebarThreadSortOrder,
+ sidebarThreadSortOrder,
expandedThreadListsByProject,
projectExpandedById,
routeThreadKey,
@@ -2910,8 +3102,8 @@ export default function Sidebar() {
desktopUpdateButtonAction={desktopUpdateButtonAction}
desktopUpdateButtonDisabled={desktopUpdateButtonDisabled}
handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}
- projectSortOrder={appSettings.sidebarProjectSortOrder}
- threadSortOrder={appSettings.sidebarThreadSortOrder}
+ projectSortOrder={sidebarProjectSortOrder}
+ threadSortOrder={sidebarThreadSortOrder}
updateSettings={updateSettings}
shouldShowProjectPathEntry={shouldShowProjectPathEntry}
handleStartAddProject={handleStartAddProject}
diff --git a/apps/web/src/components/SplashScreen.tsx b/apps/web/src/components/SplashScreen.tsx
new file mode 100644
index 000000000..a0b593a95
--- /dev/null
+++ b/apps/web/src/components/SplashScreen.tsx
@@ -0,0 +1,9 @@
+export function SplashScreen() {
+ return (
+ <div className="flex min-h-screen items-center justify-center bg-background">
+ <div className="flex size-24 items-center justify-center" aria-label="T3 Code splash screen">
+ <img alt="T3 Code" className="size-16 object-contain" src="/apple-touch-icon.png" />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx
index 5f01e53af..d35f4602a 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx
@@ -141,11 +141,25 @@ function createEnvironmentApi() {
};
}
-async function mountTerminalViewport(props: { threadRef: ReturnType<typeof scopeThreadRef> }) {
+async function mountTerminalViewport(props: {
+ threadRef: ReturnType<typeof scopeThreadRef>;
+ drawerBackgroundColor?: string;
+ drawerTextColor?: string;
+}) {
+ const drawer = document.createElement("div");
+ drawer.className = "thread-terminal-drawer";
+ if (props.drawerBackgroundColor) {
+ drawer.style.backgroundColor = props.drawerBackgroundColor;
+ }
+ if (props.drawerTextColor) {
+ drawer.style.color = props.drawerTextColor;
+ }
+
const host = document.createElement("div");
host.style.width = "800px";
host.style.height = "400px";
- document.body.append(host);
+ drawer.append(host);
+ document.body.append(drawer);
const screen = await render(
<TerminalViewport
@@ -184,7 +198,7 @@ async function mountTerminalViewport(props: { threadRef: ReturnType<typeof scope
},
cleanup: async () => {
await screen.unmount();
- host.remove();
+ drawer.remove();
},
};
}
@@ -244,4 +258,32 @@ describe("TerminalViewport", () => {
await mounted.cleanup();
}
});
+
+ it("uses the drawer surface colors for the terminal theme", async () => {
+ const environment = createEnvironmentApi();
+ environmentApiById.set("environment-a", environment);
+
+ const mounted = await mountTerminalViewport({
+ threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
+ drawerBackgroundColor: "rgb(24, 28, 36)",
+ drawerTextColor: "rgb(228, 232, 240)",
+ });
+
+ try {
+ await vi.waitFor(() => {
+ expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
+ });
+
+ expect(terminalConstructorSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ theme: expect.objectContaining({
+ background: "rgb(24, 28, 36)",
+ foreground: "rgb(228, 232, 240)",
+ }),
+ }),
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index de40cc0bf..9aac8ad6c 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -76,12 +76,37 @@ export function selectPendingTerminalEventEntries(
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
}
-function terminalThemeFromApp(): ITheme {
+function normalizeComputedColor(value: string | null | undefined, fallback: string): string {
+ const normalizedValue = value?.trim().toLowerCase();
+ if (
+ !normalizedValue ||
+ normalizedValue === "transparent" ||
+ normalizedValue === "rgba(0, 0, 0, 0)" ||
+ normalizedValue === "rgba(0 0 0 / 0)"
+ ) {
+ return fallback;
+ }
+ return value ?? fallback;
+}
+
+function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme {
const isDark = document.documentElement.classList.contains("dark");
+ const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)";
+ const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)";
+ const drawerSurface =
+ mountElement?.closest(".thread-terminal-drawer") ??
+ document.querySelector(".thread-terminal-drawer") ??
+ document.body;
+ const drawerStyles = getComputedStyle(drawerSurface);
const bodyStyles = getComputedStyle(document.body);
- const background =
- bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
- const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
+ const background = normalizeComputedColor(
+ drawerStyles.backgroundColor,
+ normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground),
+ );
+ const foreground = normalizeComputedColor(
+ drawerStyles.color,
+ normalizeComputedColor(bodyStyles.color, fallbackForeground),
+ );
if (isDark) {
return {
@@ -275,7 +300,7 @@ export function TerminalViewport({
fontSize: 12,
scrollback: 5_000,
fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
- theme: terminalThemeFromApp(),
+ theme: terminalThemeFromApp(mount),
});
terminal.loadAddon(fitAddon);
terminal.open(mount);
@@ -488,7 +513,7 @@ export function TerminalViewport({
const themeObserver = new MutationObserver(() => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
- activeTerminal.options.theme = terminalThemeFromApp();
+ activeTerminal.options.theme = terminalThemeFromApp(containerRef.current);
activeTerminal.refresh(0, activeTerminal.rows - 1);
});
themeObserver.observe(document.documentElement, {
@@ -720,7 +745,10 @@ export function TerminalViewport({
};
}, [drawerHeight, resizeEpoch, terminalId, threadId, threadRef]);
return (
- <div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
+ <div
+ ref={containerRef}
+ className="relative h-full w-full overflow-hidden rounded-[4px] bg-background"
+ />
);
}
diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx
index 1855046a6..17d514ae7 100644
--- a/apps/web/src/components/WebSocketConnectionSurface.tsx
+++ b/apps/web/src/components/WebSocketConnectionSurface.tsx
@@ -1,9 +1,6 @@
-import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react";
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
-import { APP_DISPLAY_NAME } from "../branding";
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
-import { useServerConfig } from "../rpc/serverState";
import {
exhaustWsReconnectIfStillWaiting,
getWsConnectionStatus,
@@ -14,9 +11,8 @@ import {
useWsConnectionStatus,
WS_RECONNECT_MAX_ATTEMPTS,
} from "../rpc/wsConnectionState";
-import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
-import { getWsRpcClient } from "~/wsRpcClient";
+import { getPrimaryEnvironmentConnection } from "../environments/runtime";
const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
type WsAutoReconnectTrigger = "focus" | "online";
@@ -58,11 +54,7 @@ function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
-function buildReconnectTitle(status: WsConnectionStatus): string {
- if (status.nextRetryAt === null) {
- return "Disconnected from T3 Server";
- }
-
+function buildReconnectTitle(_status: WsConnectionStatus): string {
return "Disconnected from T3 Server";
}
@@ -113,155 +105,6 @@ export function shouldAutoReconnect(
);
}
-function buildBlockingCopy(
- uiState: WsConnectionUiState,
- status: WsConnectionStatus,
-): {
- readonly description: string;
- readonly eyebrow: string;
- readonly title: string;
-} {
- if (uiState === "connecting") {
- return {
- description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`,
- eyebrow: "Starting Session",
- title: `Connecting to ${APP_DISPLAY_NAME}`,
- };
- }
-
- if (uiState === "offline") {
- return {
- description:
- "Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.",
- eyebrow: "Offline",
- title: "WebSocket connection unavailable",
- };
- }
-
- if (status.lastError?.trim()) {
- return {
- description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`,
- eyebrow: "Connection Error",
- title: "Cannot reach the T3 server",
- };
- }
-
- return {
- description:
- "The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.",
- eyebrow: "Connection Error",
- title: "Cannot reach the T3 server",
- };
-}
-
-function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string {
- const details = [
- `state: ${uiState}`,
- `online: ${status.online ? "yes" : "no"}`,
- `attempts: ${status.attemptCount}`,
- ];
-
- if (status.socketUrl) {
- details.push(`socket: ${status.socketUrl}`);
- }
- if (status.connectedAt) {
- details.push(`connectedAt: ${status.connectedAt}`);
- }
- if (status.disconnectedAt) {
- details.push(`disconnectedAt: ${status.disconnectedAt}`);
- }
- if (status.lastErrorAt) {
- details.push(`lastErrorAt: ${status.lastErrorAt}`);
- }
- if (status.lastError) {
- details.push(`lastError: ${status.lastError}`);
- }
- if (status.closeCode !== null) {
- details.push(`closeCode: ${status.closeCode}`);
- }
- if (status.closeReason) {
- details.push(`closeReason: ${status.closeReason}`);
- }
-
- return details.join("\n");
-}
-
-function WebSocketBlockingState({
- status,
- uiState,
-}: {
- readonly status: WsConnectionStatus;
- readonly uiState: WsConnectionUiState;
-}) {
- const copy = buildBlockingCopy(uiState, status);
- const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt);
- const Icon =
- uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle;
-
- return (
- <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
- <div className="pointer-events-none absolute inset-0 opacity-90">
- <div className="absolute inset-x-0 top-0 h-56 bg-[radial-gradient(48rem_18rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
- <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
- </div>
-
- <section className="relative w-full max-w-xl rounded-[1.75rem] border border-border/80 bg-card/92 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
- <div className="flex items-start justify-between gap-4">
- <div>
- <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
- {copy.eyebrow}
- </p>
- <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{copy.title}</h1>
- </div>
- <div className="rounded-2xl border border-border/70 bg-background/80 p-3 text-foreground shadow-sm">
- <Icon className={uiState === "connecting" ? "size-5 animate-spin" : "size-5"} />
- </div>
- </div>
-
- <p className="mt-3 text-sm leading-relaxed text-muted-foreground">{copy.description}</p>
-
- <div className="mt-5 grid gap-3 rounded-2xl border border-border/70 bg-background/60 p-4 text-sm sm:grid-cols-2">
- <div>
- <p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
- Connection
- </p>
- <p className="mt-1 font-medium text-foreground">
- {uiState === "connecting"
- ? "Opening WebSocket"
- : uiState === "offline"
- ? "Waiting for network"
- : "Retrying server connection"}
- </p>
- </div>
- <div>
- <p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
- Latest Event
- </p>
- <p className="mt-1 font-medium text-foreground">{disconnectedAt ?? "Pending"}</p>
- </div>
- </div>
-
- <div className="mt-5 flex flex-wrap gap-2">
- <Button size="sm" onClick={() => window.location.reload()}>
- <RotateCw />
- Reload app
- </Button>
- </div>
-
- <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
- <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
- <span className="group-open:hidden">Show connection details</span>
- <span className="hidden group-open:inline">Hide connection details</span>
- </summary>
- <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
- {buildConnectionDetails(status, uiState)}
- </pre>
- </details>
- </section>
- </div>
- );
-}
-
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
const [nowMs, setNowMs] = useState(() => Date.now());
@@ -277,7 +120,7 @@ export function WebSocketConnectionCoordinator() {
toastResetTimerRef.current = null;
}
lastForcedReconnectAtRef.current = Date.now();
- void getWsRpcClient()
+ void getPrimaryEnvironmentConnection()
.reconnect()
.catch((error) => {
if (!showFailureToast) {
@@ -527,18 +370,5 @@ export function SlowRpcAckToastCoordinator() {
}
export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) {
- const serverConfig = useServerConfig();
- const status = useWsConnectionStatus();
-
- if (serverConfig === null) {
- const uiState = getWsConnectionUiState(status);
- return (
- <WebSocketBlockingState
- status={status}
- uiState={uiState === "connected" ? "connecting" : uiState}
- />
- );
- }
-
return children;
}
diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx
new file mode 100644
index 000000000..f583af72e
--- /dev/null
+++ b/apps/web/src/components/auth/PairingRouteSurface.tsx
@@ -0,0 +1,195 @@
+import type { AuthSessionState } from "@t3tools/contracts";
+import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";
+
+import { APP_DISPLAY_NAME } from "../../branding";
+import {
+ peekPairingTokenFromUrl,
+ stripPairingTokenFromUrl,
+ submitServerAuthCredential,
+} from "../../environments/primary";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+
+export function PairingPendingSurface() {
+ return (
+ <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
+ <div className="pointer-events-none absolute inset-0 opacity-80">
+ <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-emerald-500)_14%,transparent),transparent)]" />
+ <div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-sky-500)_10%,transparent),transparent)]" />
+ <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
+ </div>
+
+ <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
+ <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
+ {APP_DISPLAY_NAME}
+ </p>
+ <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
+ Pairing with this environment
+ </h1>
+ <p className="mt-2 text-sm leading-relaxed text-muted-foreground">
+ Validating the pairing link and preparing your session.
+ </p>
+ </section>
+ </div>
+ );
+}
+
+export function PairingRouteSurface({
+ auth,
+ initialErrorMessage,
+ onAuthenticated,
+}: {
+ auth: AuthSessionState["auth"];
+ initialErrorMessage?: string;
+ onAuthenticated: () => void;
+}) {
+ const autoPairTokenRef = useRef<string | null>(peekPairingTokenFromUrl());
+ const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? "");
+ const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? "");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const autoSubmitAttemptedRef = useRef(false);
+
+ const submitCredential = useCallback(
+ async (nextCredential: string) => {
+ setIsSubmitting(true);
+ setErrorMessage("");
+
+ const submitError = await submitServerAuthCredential(nextCredential).then(
+ () => null,
+ (error) => errorMessageFromUnknown(error),
+ );
+
+ setIsSubmitting(false);
+
+ if (submitError) {
+ setErrorMessage(submitError);
+ return;
+ }
+
+ startTransition(() => {
+ onAuthenticated();
+ });
+ },
+ [onAuthenticated],
+ );
+
+ const handleSubmit = useCallback(
+ async (event?: React.SubmitEvent<HTMLFormElement>) => {
+ event?.preventDefault();
+ await submitCredential(credential);
+ },
+ [submitCredential, credential],
+ );
+
+ useEffect(() => {
+ const token = autoPairTokenRef.current;
+ if (!token || autoSubmitAttemptedRef.current) {
+ return;
+ }
+
+ autoSubmitAttemptedRef.current = true;
+ stripPairingTokenFromUrl();
+ void submitCredential(token);
+ }, [submitCredential]);
+
+ return (
+ <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
+ <div className="pointer-events-none absolute inset-0 opacity-80">
+ <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-emerald-500)_14%,transparent),transparent)]" />
+ <div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-sky-500)_10%,transparent),transparent)]" />
+ <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
+ </div>
+
+ <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
+ <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
+ {APP_DISPLAY_NAME}
+ </p>
+ <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
+ Pair with this environment
+ </h1>
+ <p className="mt-2 text-sm leading-relaxed text-muted-foreground">
+ {describeAuthGate(auth.bootstrapMethods)}
+ </p>
+
+ <form className="mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
+ <div className="space-y-2">
+ <label className="text-sm font-medium" htmlFor="pairing-token">
+ Pairing token
+ </label>
+ <Input
+ id="pairing-token"
+ autoCapitalize="none"
+ autoComplete="off"
+ autoCorrect="off"
+ disabled={isSubmitting}
+ nativeInput
+ onChange={(event) => setCredential(event.currentTarget.value)}
+ placeholder="Paste a one-time token or pairing secret"
+ spellCheck={false}
+ value={credential}
+ />
+ </div>
+
+ {errorMessage ? (
+ <div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
+ {errorMessage}
+ </div>
+ ) : null}
+
+ <div className="flex flex-wrap gap-2">
+ <Button disabled={isSubmitting} size="sm" type="submit">
+ {isSubmitting ? "Pairing..." : "Continue"}
+ </Button>
+ <Button
+ disabled={isSubmitting}
+ onClick={() => window.location.reload()}
+ size="sm"
+ variant="outline"
+ >
+ Reload app
+ </Button>
+ </div>
+ </form>
+
+ <div className="mt-6 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
+ {describeSupportedMethods(auth.bootstrapMethods)}
+ </div>
+ </section>
+ </div>
+ );
+}
+
+function errorMessageFromUnknown(error: unknown): string {
+ if (error instanceof Error && error.message.trim().length > 0) {
+ return error.message;
+ }
+
+ if (typeof error === "string" && error.trim().length > 0) {
+ return error;
+ }
+
+ return "Authentication failed.";
+}
+
+function describeAuthGate(bootstrapMethods: ReadonlyArray<string>): string {
+ if (bootstrapMethods.includes("desktop-bootstrap")) {
+ return "This environment expects a trusted pairing credential before the app can connect.";
+ }
+
+ return "Enter a pairing token to start a session with this environment.";
+}
+
+function describeSupportedMethods(bootstrapMethods: ReadonlyArray<string>): string {
+ if (
+ bootstrapMethods.includes("desktop-bootstrap") &&
+ bootstrapMethods.includes("one-time-token")
+ ) {
+ return "Desktop-managed pairing and one-time pairing tokens are both accepted for this environment.";
+ }
+
+ if (bootstrapMethods.includes("desktop-bootstrap")) {
+ return "This environment is desktop-managed. Open it from the desktop app or paste a bootstrap credential if one was issued explicitly.";
+ }
+
+ return "This environment accepts one-time pairing tokens. Pairing links can open this page directly, or you can paste the token here.";
+}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
new file mode 100644
index 000000000..396f255f7
--- /dev/null
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -0,0 +1,1441 @@
+import { PlusIcon, QrCodeIcon } from "lucide-react";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ type AuthClientSession,
+ type AuthPairingLink,
+ type DesktopServerExposureState,
+ type EnvironmentId,
+} from "@t3tools/contracts";
+import { DateTime } from "effect";
+
+import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
+import { cn } from "../../lib/utils";
+import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
+import {
+ SettingsPageContainer,
+ SettingsRow,
+ SettingsSection,
+ useRelativeTimeTick,
+} from "./settingsLayout";
+import { Input } from "../ui/input";
+import {
+ Dialog,
+ DialogFooter,
+ DialogDescription,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+ DialogTrigger,
+} from "../ui/dialog";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import { QRCodeSvg } from "../ui/qr-code";
+import { Spinner } from "../ui/spinner";
+import { Switch } from "../ui/switch";
+import { toastManager } from "../ui/toast";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { Button } from "../ui/button";
+import { Textarea } from "../ui/textarea";
+import { setPairingTokenOnUrl } from "../../pairingUrl";
+import {
+ createServerPairingCredential,
+ fetchSessionState,
+ revokeOtherServerClientSessions,
+ revokeServerClientSession,
+ revokeServerPairingLink,
+ type ServerClientSessionRecord,
+ type ServerPairingLinkRecord,
+} from "../../environments/primary";
+import type { WsRpcClient } from "~/rpc/wsRpcClient";
+import {
+ type SavedEnvironmentRecord,
+ type SavedEnvironmentRuntimeState,
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+ addSavedEnvironment,
+ getPrimaryEnvironmentConnection,
+ reconnectSavedEnvironment,
+ removeSavedEnvironment,
+} from "../../environments/runtime";
+
+const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+});
+
+function formatAccessTimestamp(value: string): string {
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) {
+ return value;
+ }
+ return accessTimestampFormatter.format(parsed);
+}
+
+type ConnectionStatusDotProps = {
+ tooltipText?: string | null;
+ dotClassName: string;
+ pingClassName?: string | null;
+};
+
+function ConnectionStatusDot({
+ tooltipText,
+ dotClassName,
+ pingClassName,
+}: ConnectionStatusDotProps) {
+ const dotContent = (
+ <>
+ {pingClassName ? (
+ <span
+ className={cn(
+ "absolute inline-flex h-full w-full animate-ping rounded-full",
+ pingClassName,
+ )}
+ />
+ ) : null}
+ <span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
+ </>
+ );
+
+ if (!tooltipText) {
+ return (
+ <span className="relative flex size-3 shrink-0 items-center justify-center">
+ {dotContent}
+ </span>
+ );
+ }
+
+ const dot = (
+ <button
+ type="button"
+ title={tooltipText}
+ aria-label={tooltipText}
+ className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
+ >
+ {dotContent}
+ </button>
+ );
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={dot} />
+ <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
+ {tooltipText}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
+function getSavedBackendStatusTooltip(
+ runtime: SavedEnvironmentRuntimeState | null,
+ record: SavedEnvironmentRecord,
+ nowMs: number,
+) {
+ const connectionState = runtime?.connectionState ?? "disconnected";
+
+ if (connectionState === "connected") {
+ const connectedAt = runtime?.connectedAt ?? record.lastConnectedAt;
+ return connectedAt ? `Connected for ${formatElapsedDurationLabel(connectedAt, nowMs)}` : null;
+ }
+
+ if (connectionState === "connecting") {
+ return null;
+ }
+
+ if (connectionState === "error") {
+ return runtime?.lastError ?? "An unknown connection error occurred.";
+ }
+
+ return record.lastConnectedAt
+ ? `Last connected at ${formatAccessTimestamp(record.lastConnectedAt)}`
+ : "Not connected yet.";
+}
+
+/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
+const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
+
+const ITEM_ROW_INNER_CLASSNAME =
+ "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
+
+function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
+ return [...links].toSorted(
+ (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
+ );
+}
+
+function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
+ return [...sessions].toSorted((left, right) => {
+ if (left.current !== right.current) {
+ return left.current ? -1 : 1;
+ }
+ if (left.connected !== right.connected) {
+ return left.connected ? -1 : 1;
+ }
+ return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
+ });
+}
+
+function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
+ return {
+ ...pairingLink,
+ createdAt: DateTime.formatIso(pairingLink.createdAt),
+ expiresAt: DateTime.formatIso(pairingLink.expiresAt),
+ };
+}
+
+function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerClientSessionRecord {
+ return {
+ ...clientSession,
+ issuedAt: DateTime.formatIso(clientSession.issuedAt),
+ expiresAt: DateTime.formatIso(clientSession.expiresAt),
+ lastConnectedAt:
+ clientSession.lastConnectedAt === null
+ ? null
+ : DateTime.formatIso(clientSession.lastConnectedAt),
+ };
+}
+
+function upsertDesktopPairingLink(
+ current: ReadonlyArray<ServerPairingLinkRecord>,
+ next: ServerPairingLinkRecord,
+) {
+ const existingIndex = current.findIndex((pairingLink) => pairingLink.id === next.id);
+ if (existingIndex === -1) {
+ return sortDesktopPairingLinks([...current, next]);
+ }
+ const updated = [...current];
+ updated[existingIndex] = next;
+ return sortDesktopPairingLinks(updated);
+}
+
+function removeDesktopPairingLink(current: ReadonlyArray<ServerPairingLinkRecord>, id: string) {
+ return current.filter((pairingLink) => pairingLink.id !== id);
+}
+
+function upsertDesktopClientSession(
+ current: ReadonlyArray<ServerClientSessionRecord>,
+ next: ServerClientSessionRecord,
+) {
+ const existingIndex = current.findIndex(
+ (clientSession) => clientSession.sessionId === next.sessionId,
+ );
+ if (existingIndex === -1) {
+ return sortDesktopClientSessions([...current, next]);
+ }
+ const updated = [...current];
+ updated[existingIndex] = next;
+ return sortDesktopClientSessions(updated);
+}
+
+function removeDesktopClientSession(
+ current: ReadonlyArray<ServerClientSessionRecord>,
+ sessionId: ServerClientSessionRecord["sessionId"],
+) {
+ return current.filter((clientSession) => clientSession.sessionId !== sessionId);
+}
+
+function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string {
+ const url = new URL(endpointUrl);
+ url.pathname = "/pair";
+ return setPairingTokenOnUrl(url, credential).toString();
+}
+
+function resolveCurrentOriginPairingUrl(credential: string): string {
+ const url = new URL("/pair", window.location.href);
+ return setPairingTokenOnUrl(url, credential).toString();
+}
+
+function isLoopbackHostname(hostname: string): boolean {
+ const normalized = hostname.trim().toLowerCase();
+ return (
+ normalized === "localhost" ||
+ normalized === "127.0.0.1" ||
+ normalized === "::1" ||
+ normalized === "[::1]"
+ );
+}
+
+type PairingLinkListRowProps = {
+ pairingLink: ServerPairingLinkRecord;
+ endpointUrl: string | null | undefined;
+ revokingPairingLinkId: string | null;
+ onRevoke: (id: string) => void;
+};
+
+const PairingLinkListRow = memo(function PairingLinkListRow({
+ pairingLink,
+ endpointUrl,
+ revokingPairingLinkId,
+ onRevoke,
+}: PairingLinkListRowProps) {
+ const nowMs = useRelativeTimeTick(1_000);
+ const expiresAtMs = useMemo(
+ () => new Date(pairingLink.expiresAt).getTime(),
+ [pairingLink.expiresAt],
+ );
+ const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
+
+ const currentOriginPairingUrl = useMemo(
+ () => resolveCurrentOriginPairingUrl(pairingLink.credential),
+ [pairingLink.credential],
+ );
+ const shareablePairingUrl =
+ endpointUrl != null && endpointUrl !== ""
+ ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)
+ : isLoopbackHostname(window.location.hostname)
+ ? null
+ : currentOriginPairingUrl;
+ const copyValue = shareablePairingUrl ?? pairingLink.credential;
+ const canCopyToClipboard =
+ typeof window !== "undefined" &&
+ window.isSecureContext &&
+ navigator.clipboard?.writeText != null;
+
+ const { copyToClipboard, isCopied } = useCopyToClipboard({
+ onCopy: () => {
+ toastManager.add({
+ type: "success",
+ title: shareablePairingUrl ? "Pairing URL copied" : "Pairing token copied",
+ description: shareablePairingUrl
+ ? "Open it in the client you want to pair to this environment."
+ : "Paste it into another client with this backend's reachable host.",
+ });
+ },
+ onError: (error) => {
+ setIsRevealDialogOpen(true);
+ toastManager.add({
+ type: "error",
+ title: canCopyToClipboard ? "Could not copy pairing URL" : "Clipboard copy unavailable",
+ description: canCopyToClipboard ? error.message : "Showing the full value instead.",
+ });
+ },
+ });
+
+ const handleCopy = useCallback(() => {
+ copyToClipboard(copyValue, undefined);
+ }, [copyToClipboard, copyValue]);
+
+ const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
+
+ const roleLabel = pairingLink.role === "owner" ? "Owner" : "Client";
+ const primaryLabel = pairingLink.label ?? `${roleLabel} link`;
+
+ if (expiresAtMs <= nowMs) {
+ return null;
+ }
+
+ return (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <div className={ITEM_ROW_INNER_CLASSNAME}>
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex min-h-5 items-center gap-1.5">
+ <ConnectionStatusDot
+ tooltipText={`Link created at ${formatAccessTimestamp(pairingLink.createdAt)}`}
+ dotClassName="bg-amber-400"
+ />
+ <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
+ <Popover>
+ {shareablePairingUrl ? (
+ <>
+ <PopoverTrigger
+ openOnHover
+ delay={250}
+ closeDelay={100}
+ render={
+ <button
+ type="button"
+ className="inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground/50 outline-none hover:text-foreground"
+ aria-label="Show QR code"
+ />
+ }
+ >
+ <QrCodeIcon aria-hidden className="size-3" />
+ </PopoverTrigger>
+ <PopoverPopup side="top" align="start" tooltipStyle className="w-max">
+ <QRCodeSvg
+ value={shareablePairingUrl}
+ size={88}
+ level="M"
+ marginSize={2}
+ title="Pairing link — scan to open on another device"
+ />
+ </PopoverPopup>
+ </>
+ ) : null}
+ </Popover>
+ </div>
+ <p className="text-xs text-muted-foreground" title={expiresAbsolute}>
+ {[roleLabel, formatExpiresInLabel(pairingLink.expiresAt, nowMs)].join(" · ")}
+ </p>
+ {shareablePairingUrl === null ? (
+ <p className="text-[11px] text-muted-foreground/70">
+ Copy the token and pair from another client using this backend&apos;s reachable host.
+ </p>
+ ) : null}
+ </div>
+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
+ <Dialog open={isRevealDialogOpen} onOpenChange={setIsRevealDialogOpen}>
+ {canCopyToClipboard ? (
+ <Button size="xs" variant="outline" onClick={handleCopy}>
+ {isCopied ? "Copied" : shareablePairingUrl ? "Copy" : "Copy token"}
+ </Button>
+ ) : (
+ <DialogTrigger render={<Button size="xs" variant="outline" />}>
+ {shareablePairingUrl ? "Show link" : "Show token"}
+ </DialogTrigger>
+ )}
+ <DialogPopup className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{shareablePairingUrl ? "Pairing link" : "Pairing token"}</DialogTitle>
+ <DialogDescription>
+ {shareablePairingUrl
+ ? "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect."
+ : "Clipboard copy is unavailable here. Manually copy this token and pair from another client using this backend's reachable host."}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogPanel className="space-y-4">
+ <Textarea
+ readOnly
+ value={copyValue}
+ rows={shareablePairingUrl ? 4 : 3}
+ className="text-xs leading-relaxed"
+ onFocus={(event) => event.currentTarget.select()}
+ onClick={(event) => event.currentTarget.select()}
+ />
+ {shareablePairingUrl ? (
+ <div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
+ <QRCodeSvg
+ value={shareablePairingUrl}
+ size={132}
+ level="M"
+ marginSize={2}
+ title="Pairing link — scan to open on another device"
+ />
+ </div>
+ ) : null}
+ </DialogPanel>
+ <DialogFooter variant="bare">
+ <Button variant="outline" onClick={() => setIsRevealDialogOpen(false)}>
+ Done
+ </Button>
+ {canCopyToClipboard ? (
+ <Button variant="outline" size="xs" onClick={handleCopy}>
+ {isCopied ? "Copied" : "Copy again"}
+ </Button>
+ ) : null}
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
+ <Button
+ size="xs"
+ variant="destructive-outline"
+ disabled={revokingPairingLinkId === pairingLink.id}
+ onClick={() => void onRevoke(pairingLink.id)}
+ >
+ {revokingPairingLinkId === pairingLink.id ? "Revoking…" : "Revoke"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+});
+
+type ConnectedClientListRowProps = {
+ clientSession: ServerClientSessionRecord;
+ revokingClientSessionId: string | null;
+ onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
+};
+
+const ConnectedClientListRow = memo(function ConnectedClientListRow({
+ clientSession,
+ revokingClientSessionId,
+ onRevokeSession,
+}: ConnectedClientListRowProps) {
+ const nowMs = useRelativeTimeTick(1_000);
+ const isLive = clientSession.current || clientSession.connected;
+ const lastConnectedAt = clientSession.lastConnectedAt;
+ const statusTooltip = isLive
+ ? lastConnectedAt
+ ? `Connected for ${formatElapsedDurationLabel(lastConnectedAt, nowMs)}`
+ : "Connected"
+ : lastConnectedAt
+ ? `Last connected at ${formatAccessTimestamp(lastConnectedAt)}`
+ : "Not connected yet.";
+ const roleLabel = clientSession.role === "owner" ? "Owner" : "Client";
+ const deviceInfoBits = [
+ clientSession.client.deviceType !== "unknown"
+ ? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)
+ : null,
+ clientSession.client.os ?? null,
+ clientSession.client.browser ?? null,
+ clientSession.client.ipAddress ?? null,
+ ].filter((value): value is string => value !== null);
+ const primaryLabel =
+ clientSession.client.label ??
+ ([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") ||
+ clientSession.subject);
+
+ return (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <div className={ITEM_ROW_INNER_CLASSNAME}>
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex min-h-5 items-center gap-1.5">
+ <ConnectionStatusDot
+ tooltipText={statusTooltip}
+ dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"}
+ pingClassName={isLive ? "bg-success/60 duration-2000" : null}
+ />
+ <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
+ {clientSession.current ? (
+ <span className="text-[10px] text-muted-foreground/80 rounded-md border border-border/50 bg-muted/50 px-1 py-0.5">
+ This device
+ </span>
+ ) : null}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {[roleLabel, ...deviceInfoBits].join(" · ")}
+ </p>
+ </div>
+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
+ {!clientSession.current ? (
+ <Button
+ size="xs"
+ variant="destructive-outline"
+ disabled={revokingClientSessionId === clientSession.sessionId}
+ onClick={() => void onRevokeSession(clientSession.sessionId)}
+ >
+ {revokingClientSessionId === clientSession.sessionId ? "Revoking…" : "Revoke"}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+});
+
+type AuthorizedClientsHeaderActionProps = {
+ clientSessions: ReadonlyArray<ServerClientSessionRecord>;
+ isRevokingOtherClients: boolean;
+ onRevokeOtherClients: () => void;
+};
+
+const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
+ clientSessions,
+ isRevokingOtherClients,
+ onRevokeOtherClients,
+}: AuthorizedClientsHeaderActionProps) {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [pairingLabel, setPairingLabel] = useState("");
+ const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
+
+ const handleCreatePairingLink = useCallback(async () => {
+ setIsCreatingPairingLink(true);
+ try {
+ await createServerPairingCredential(pairingLabel);
+ setPairingLabel("");
+ setDialogOpen(false);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to create pairing URL.";
+ toastManager.add({
+ type: "error",
+ title: "Could not create pairing URL",
+ description: message,
+ });
+ } finally {
+ setIsCreatingPairingLink(false);
+ }
+ }, [pairingLabel]);
+
+ return (
+ <div className="flex items-center gap-2">
+ <Button
+ size="xs"
+ variant="destructive-outline"
+ disabled={
+ isRevokingOtherClients || clientSessions.every((clientSession) => clientSession.current)
+ }
+ onClick={() => void onRevokeOtherClients()}
+ >
+ {isRevokingOtherClients ? "Revoking…" : "Revoke others"}
+ </Button>
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ setDialogOpen(open);
+ if (!open) {
+ setPairingLabel("");
+ }
+ }}
+ >
+ <DialogTrigger
+ render={
+ <Button size="xs" variant="default">
+ <PlusIcon className="size-3" />
+ Create link
+ </Button>
+ }
+ />
+ <DialogPopup className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Create pairing link</DialogTitle>
+ <DialogDescription>
+ Generate a one-time link that another device can use to pair with this backend as an
+ authorized client.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogPanel>
+ <label className="block">
+ <span className="mb-1.5 block text-xs font-medium text-foreground">
+ Client label (optional)
+ </span>
+ <Input
+ value={pairingLabel}
+ onChange={(event) => setPairingLabel(event.target.value)}
+ placeholder="e.g. Living room iPad"
+ disabled={isCreatingPairingLink}
+ autoFocus
+ />
+ </label>
+ </DialogPanel>
+ <DialogFooter variant="bare">
+ <Button
+ variant="outline"
+ disabled={isCreatingPairingLink}
+ onClick={() => setDialogOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button disabled={isCreatingPairingLink} onClick={() => void handleCreatePairingLink()}>
+ {isCreatingPairingLink ? "Creating…" : "Create link"}
+ </Button>
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
+ </div>
+ );
+});
+
+type PairingClientsListProps = {
+ endpointUrl: string | null | undefined;
+ isLoading: boolean;
+ pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
+ clientSessions: ReadonlyArray<ServerClientSessionRecord>;
+ revokingPairingLinkId: string | null;
+ revokingClientSessionId: string | null;
+ onRevokePairingLink: (id: string) => void;
+ onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
+};
+
+const PairingClientsList = memo(function PairingClientsList({
+ endpointUrl,
+ isLoading,
+ pairingLinks,
+ clientSessions,
+ revokingPairingLinkId,
+ revokingClientSessionId,
+ onRevokePairingLink,
+ onRevokeClientSession,
+}: PairingClientsListProps) {
+ return (
+ <>
+ {pairingLinks.map((pairingLink) => (
+ <PairingLinkListRow
+ key={pairingLink.id}
+ pairingLink={pairingLink}
+ endpointUrl={endpointUrl}
+ revokingPairingLinkId={revokingPairingLinkId}
+ onRevoke={onRevokePairingLink}
+ />
+ ))}
+
+ {clientSessions.map((clientSession) => (
+ <ConnectedClientListRow
+ key={clientSession.sessionId}
+ clientSession={clientSession}
+ revokingClientSessionId={revokingClientSessionId}
+ onRevokeSession={onRevokeClientSession}
+ />
+ ))}
+
+ {pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <p className="text-xs text-muted-foreground/60">No pairing links or client sessions.</p>
+ </div>
+ ) : null}
+ </>
+ );
+});
+
+type SavedBackendListRowProps = {
+ environmentId: EnvironmentId;
+ reconnectingEnvironmentId: EnvironmentId | null;
+ removingEnvironmentId: EnvironmentId | null;
+ onReconnect: (environmentId: EnvironmentId) => void;
+ onRemove: (environmentId: EnvironmentId) => void;
+};
+
+function SavedBackendListRow({
+ environmentId,
+ reconnectingEnvironmentId,
+ removingEnvironmentId,
+ onReconnect,
+ onRemove,
+}: SavedBackendListRowProps) {
+ const nowMs = useRelativeTimeTick(1_000);
+ const record = useSavedEnvironmentRegistryStore((state) => state.byId[environmentId] ?? null);
+ const runtime = useSavedEnvironmentRuntimeStore((state) => state.byId[environmentId] ?? null);
+
+ if (!record) {
+ return null;
+ }
+
+ const connectionState = runtime?.connectionState ?? "disconnected";
+ const stateDotClassName =
+ connectionState === "connected"
+ ? "bg-success"
+ : connectionState === "connecting"
+ ? "bg-warning"
+ : connectionState === "error"
+ ? "bg-destructive"
+ : "bg-muted-foreground/40";
+ const roleLabel = runtime?.role ? (runtime.role === "owner" ? "Owner" : "Client") : null;
+ const descriptorLabel = runtime?.descriptor?.label ?? null;
+ const statusTooltip = getSavedBackendStatusTooltip(runtime, record, nowMs);
+ const metadataBits = [
+ roleLabel,
+ record.lastConnectedAt
+ ? `Last connected ${formatAccessTimestamp(record.lastConnectedAt)}`
+ : null,
+ ].filter((value): value is string => value !== null);
+
+ return (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <div className={ITEM_ROW_INNER_CLASSNAME}>
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex min-h-5 items-center gap-1.5">
+ <ConnectionStatusDot
+ tooltipText={statusTooltip}
+ dotClassName={stateDotClassName}
+ pingClassName={
+ connectionState === "connecting" ? "bg-warning/60 duration-2000" : null
+ }
+ />
+ <h3 className="text-sm font-medium text-foreground">{record.label}</h3>
+ </div>
+ {metadataBits.length > 0 ? (
+ <p className="text-xs text-muted-foreground">{metadataBits.join(" · ")}</p>
+ ) : null}
+ {descriptorLabel && descriptorLabel !== record.label ? (
+ <p className="text-xs text-muted-foreground">Server label: {descriptorLabel}</p>
+ ) : null}
+ </div>
+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={reconnectingEnvironmentId === environmentId}
+ onClick={() => void onReconnect(environmentId)}
+ >
+ {reconnectingEnvironmentId === environmentId ? "Reconnecting…" : "Reconnect"}
+ </Button>
+ <Button
+ size="xs"
+ variant="destructive-outline"
+ disabled={removingEnvironmentId === environmentId}
+ onClick={() => void onRemove(environmentId)}
+ >
+ {removingEnvironmentId === environmentId ? "Removing…" : "Remove"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function ConnectionsSettings() {
+ const desktopBridge = window.desktopBridge;
+ const [currentSessionRole, setCurrentSessionRole] = useState<"owner" | "client" | null>(
+ desktopBridge ? "owner" : null,
+ );
+ const [currentAuthPolicy, setCurrentAuthPolicy] = useState<
+ "desktop-managed-local" | "loopback-browser" | "remote-reachable" | "unsafe-no-auth" | null
+ >(desktopBridge ? null : null);
+ const savedEnvironmentsById = useSavedEnvironmentRegistryStore((state) => state.byId);
+ const savedEnvironmentIds = useMemo(
+ () =>
+ Object.values(savedEnvironmentsById)
+ .toSorted((left, right) => left.label.localeCompare(right.label))
+ .map((record) => record.environmentId),
+ [savedEnvironmentsById],
+ );
+
+ const [desktopServerExposureState, setDesktopServerExposureState] =
+ useState<DesktopServerExposureState | null>(null);
+ const [desktopServerExposureError, setDesktopServerExposureError] = useState<string | null>(null);
+ const [desktopPairingLinks, setDesktopPairingLinks] = useState<
+ ReadonlyArray<ServerPairingLinkRecord>
+ >([]);
+ const [desktopClientSessions, setDesktopClientSessions] = useState<
+ ReadonlyArray<ServerClientSessionRecord>
+ >([]);
+ const [desktopAccessManagementError, setDesktopAccessManagementError] = useState<string | null>(
+ null,
+ );
+ const [isLoadingDesktopAccessManagement, setIsLoadingDesktopAccessManagement] = useState(false);
+ const [revokingDesktopPairingLinkId, setRevokingDesktopPairingLinkId] = useState<string | null>(
+ null,
+ );
+ const [revokingDesktopClientSessionId, setRevokingDesktopClientSessionId] = useState<
+ string | null
+ >(null);
+ const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
+ const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
+ const [savedBackendMode, setSavedBackendMode] = useState<"pairing-url" | "host-code">(
+ "pairing-url",
+ );
+ const [savedBackendLabel, setSavedBackendLabel] = useState("");
+ const [savedBackendPairingUrl, setSavedBackendPairingUrl] = useState("");
+ const [savedBackendHost, setSavedBackendHost] = useState("");
+ const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
+ const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
+ const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false);
+ const [reconnectingSavedEnvironmentId, setReconnectingSavedEnvironmentId] =
+ useState<EnvironmentId | null>(null);
+ const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
+ useState<EnvironmentId | null>(null);
+ const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
+ const [pendingDesktopServerExposureMode, setPendingDesktopServerExposureMode] = useState<
+ DesktopServerExposureState["mode"] | null
+ >(null);
+ const canManageLocalBackend = currentSessionRole === "owner";
+ const isLocalBackendNetworkAccessible = desktopBridge
+ ? desktopServerExposureState?.mode === "network-accessible"
+ : currentAuthPolicy === "remote-reachable";
+
+ const handleDesktopServerExposureChange = useCallback(
+ async (checked: boolean) => {
+ if (!desktopBridge) return;
+ setIsUpdatingDesktopServerExposure(true);
+ setDesktopServerExposureError(null);
+ try {
+ const nextState = await desktopBridge.setServerExposureMode(
+ checked ? "network-accessible" : "local-only",
+ );
+ setDesktopServerExposureState(nextState);
+ setPendingDesktopServerExposureMode(null);
+ setIsUpdatingDesktopServerExposure(false);
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "Failed to update network exposure.";
+ setPendingDesktopServerExposureMode(null);
+ setDesktopServerExposureError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not update network access",
+ description: message,
+ });
+ setIsUpdatingDesktopServerExposure(false);
+ }
+ },
+ [desktopBridge],
+ );
+
+ const handleConfirmDesktopServerExposureChange = useCallback(() => {
+ if (pendingDesktopServerExposureMode === null) return;
+ const checked = pendingDesktopServerExposureMode === "network-accessible";
+ void handleDesktopServerExposureChange(checked);
+ }, [handleDesktopServerExposureChange, pendingDesktopServerExposureMode]);
+
+ const handleRevokeDesktopPairingLink = useCallback(async (id: string) => {
+ setRevokingDesktopPairingLinkId(id);
+ setDesktopAccessManagementError(null);
+ try {
+ await revokeServerPairingLink(id);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to revoke pairing link.";
+ setDesktopAccessManagementError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not revoke pairing link",
+ description: message,
+ });
+ } finally {
+ setRevokingDesktopPairingLinkId(null);
+ }
+ }, []);
+
+ const handleRevokeDesktopClientSession = useCallback(
+ async (sessionId: ServerClientSessionRecord["sessionId"]) => {
+ setRevokingDesktopClientSessionId(sessionId);
+ setDesktopAccessManagementError(null);
+ try {
+ await revokeServerClientSession(sessionId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to revoke client access.";
+ setDesktopAccessManagementError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not revoke client access",
+ description: message,
+ });
+ } finally {
+ setRevokingDesktopClientSessionId(null);
+ }
+ },
+ [],
+ );
+
+ const handleRevokeOtherDesktopClients = useCallback(async () => {
+ setIsRevokingOtherDesktopClients(true);
+ setDesktopAccessManagementError(null);
+ try {
+ const revokedCount = await revokeOtherServerClientSessions();
+ toastManager.add({
+ type: "success",
+ title: revokedCount === 1 ? "Revoked 1 other client" : `Revoked ${revokedCount} clients`,
+ description: "Other paired clients will need a new pairing link before reconnecting.",
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to revoke other clients.";
+ setDesktopAccessManagementError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not revoke other clients",
+ description: message,
+ });
+ } finally {
+ setIsRevokingOtherDesktopClients(false);
+ }
+ }, []);
+
+ const handleAddSavedBackend = useCallback(async () => {
+ setIsAddingSavedBackend(true);
+ setSavedBackendError(null);
+ try {
+ const record = await addSavedEnvironment({
+ label: savedBackendLabel,
+ ...(savedBackendMode === "pairing-url"
+ ? { pairingUrl: savedBackendPairingUrl }
+ : {
+ host: savedBackendHost,
+ pairingCode: savedBackendPairingCode,
+ }),
+ });
+ setSavedBackendLabel("");
+ setSavedBackendPairingUrl("");
+ setSavedBackendHost("");
+ setSavedBackendPairingCode("");
+ setAddBackendDialogOpen(false);
+ toastManager.add({
+ type: "success",
+ title: "Backend added",
+ description: `${record.label} is now saved and will reconnect on app startup.`,
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to add backend.";
+ setSavedBackendError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not add backend",
+ description: message,
+ });
+ } finally {
+ setIsAddingSavedBackend(false);
+ }
+ }, [
+ savedBackendHost,
+ savedBackendLabel,
+ savedBackendMode,
+ savedBackendPairingCode,
+ savedBackendPairingUrl,
+ ]);
+
+ const handleReconnectSavedBackend = useCallback(async (environmentId: EnvironmentId) => {
+ setReconnectingSavedEnvironmentId(environmentId);
+ setSavedBackendError(null);
+ try {
+ await reconnectSavedEnvironment(environmentId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to reconnect backend.";
+ setSavedBackendError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not reconnect backend",
+ description: message,
+ });
+ } finally {
+ setReconnectingSavedEnvironmentId(null);
+ }
+ }, []);
+
+ const handleRemoveSavedBackend = useCallback(async (environmentId: EnvironmentId) => {
+ setRemovingSavedEnvironmentId(environmentId);
+ setSavedBackendError(null);
+ try {
+ await removeSavedEnvironment(environmentId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to remove backend.";
+ setSavedBackendError(message);
+ toastManager.add({
+ type: "error",
+ title: "Could not remove backend",
+ description: message,
+ });
+ } finally {
+ setRemovingSavedEnvironmentId(null);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (desktopBridge) {
+ setCurrentSessionRole("owner");
+ return;
+ }
+
+ let cancelled = false;
+ void fetchSessionState()
+ .then((session) => {
+ if (cancelled) return;
+ setCurrentSessionRole(session.authenticated ? (session.role ?? null) : null);
+ setCurrentAuthPolicy(session.auth.policy);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setCurrentSessionRole(null);
+ setCurrentAuthPolicy(null);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [desktopBridge]);
+
+ useEffect(() => {
+ if (!canManageLocalBackend) return;
+
+ let cancelled = false;
+ setIsLoadingDesktopAccessManagement(true);
+ type AuthAccessEvent = Parameters<
+ Parameters<WsRpcClient["server"]["subscribeAuthAccess"]>[0]
+ >[0];
+ const unsubscribeAuthAccess =
+ getPrimaryEnvironmentConnection().client.server.subscribeAuthAccess(
+ (event: AuthAccessEvent) => {
+ if (cancelled) {
+ return;
+ }
+
+ switch (event.type) {
+ case "snapshot":
+ setDesktopPairingLinks(
+ sortDesktopPairingLinks(
+ event.payload.pairingLinks.map((pairingLink: AuthPairingLink) =>
+ toDesktopPairingLinkRecord(pairingLink),
+ ),
+ ),
+ );
+ setDesktopClientSessions(
+ sortDesktopClientSessions(
+ event.payload.clientSessions.map((clientSession: AuthClientSession) =>
+ toDesktopClientSessionRecord(clientSession),
+ ),
+ ),
+ );
+ break;
+ case "pairingLinkUpserted":
+ setDesktopPairingLinks((current) =>
+ upsertDesktopPairingLink(current, toDesktopPairingLinkRecord(event.payload)),
+ );
+ break;
+ case "pairingLinkRemoved":
+ setDesktopPairingLinks((current) =>
+ removeDesktopPairingLink(current, event.payload.id),
+ );
+ break;
+ case "clientUpserted":
+ setDesktopClientSessions((current) =>
+ upsertDesktopClientSession(current, toDesktopClientSessionRecord(event.payload)),
+ );
+ break;
+ case "clientRemoved":
+ setDesktopClientSessions((current) =>
+ removeDesktopClientSession(current, event.payload.sessionId),
+ );
+ break;
+ }
+
+ setDesktopAccessManagementError(null);
+ setIsLoadingDesktopAccessManagement(false);
+ },
+ {
+ onResubscribe: () => {
+ if (!cancelled) {
+ setIsLoadingDesktopAccessManagement(true);
+ }
+ },
+ },
+ );
+ if (desktopBridge) {
+ void desktopBridge
+ .getServerExposureState()
+ .then((state) => {
+ if (cancelled) return;
+ setDesktopServerExposureState(state);
+ })
+ .catch((error: unknown) => {
+ if (cancelled) return;
+ const message =
+ error instanceof Error ? error.message : "Failed to load network exposure state.";
+ setDesktopServerExposureError(message);
+ });
+ } else {
+ setDesktopServerExposureState(null);
+ setDesktopServerExposureError(null);
+ }
+
+ return () => {
+ cancelled = true;
+ unsubscribeAuthAccess();
+ };
+ }, [canManageLocalBackend, desktopBridge]);
+
+ useEffect(() => {
+ if (canManageLocalBackend) return;
+ setIsLoadingDesktopAccessManagement(false);
+ setDesktopPairingLinks([]);
+ setDesktopClientSessions([]);
+ setDesktopAccessManagementError(null);
+ setDesktopServerExposureState(null);
+ setDesktopServerExposureError(null);
+ }, [canManageLocalBackend]);
+ const visibleDesktopPairingLinks = useMemo(
+ () => desktopPairingLinks.filter((pairingLink) => pairingLink.role === "client"),
+ [desktopPairingLinks],
+ );
+ return (
+ <SettingsPageContainer>
+ {canManageLocalBackend ? (
+ <>
+ <SettingsSection title="Manage local backend">
+ {desktopBridge ? (
+ <SettingsRow
+ title="Network access"
+ description={
+ desktopServerExposureState?.endpointUrl
+ ? `Reachable at ${desktopServerExposureState.endpointUrl}`
+ : desktopServerExposureState?.mode === "network-accessible"
+ ? desktopServerExposureState.advertisedHost
+ ? `Exposed on all interfaces. Pairing links use ${desktopServerExposureState.advertisedHost}.`
+ : "Exposed on all interfaces."
+ : desktopServerExposureState
+ ? "Limited to this machine."
+ : "Loading…"
+ }
+ status={
+ desktopServerExposureError ? (
+ <span className="block text-destructive">{desktopServerExposureError}</span>
+ ) : null
+ }
+ control={
+ <AlertDialog
+ open={pendingDesktopServerExposureMode !== null}
+ onOpenChange={(open) => {
+ if (isUpdatingDesktopServerExposure) return;
+ if (!open) setPendingDesktopServerExposureMode(null);
+ }}
+ >
+ <Switch
+ checked={desktopServerExposureState?.mode === "network-accessible"}
+ disabled={!desktopServerExposureState || isUpdatingDesktopServerExposure}
+ onCheckedChange={(checked) => {
+ setPendingDesktopServerExposureMode(
+ checked ? "network-accessible" : "local-only",
+ );
+ }}
+ aria-label="Enable network access"
+ />
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {pendingDesktopServerExposureMode === "network-accessible"
+ ? "Enable network access?"
+ : "Disable network access?"}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {pendingDesktopServerExposureMode === "network-accessible"
+ ? "T3 Code will restart to expose this environment over the network."
+ : "T3 Code will restart and limit this environment back to this machine."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ disabled={isUpdatingDesktopServerExposure}
+ render={
+ <Button variant="outline" disabled={isUpdatingDesktopServerExposure} />
+ }
+ >
+ Cancel
+ </AlertDialogClose>
+ <Button
+ onClick={handleConfirmDesktopServerExposureChange}
+ disabled={
+ pendingDesktopServerExposureMode === null ||
+ isUpdatingDesktopServerExposure
+ }
+ >
+ {isUpdatingDesktopServerExposure ? (
+ <>
+ <Spinner className="size-3.5" />
+ Restarting…
+ </>
+ ) : pendingDesktopServerExposureMode === "network-accessible" ? (
+ "Restart and enable"
+ ) : (
+ "Restart and disable"
+ )}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ }
+ />
+ ) : (
+ <SettingsRow
+ title="Network access"
+ description={
+ currentAuthPolicy === "remote-reachable"
+ ? "This backend is already configured for remote access. Network exposure changes must be made where the server is launched."
+ : "This backend is only reachable on this machine. Restart it with a non-loopback host to enable remote pairing."
+ }
+ control={
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="inline-flex">
+ <Switch
+ checked={isLocalBackendNetworkAccessible}
+ disabled
+ aria-label="Enable network access"
+ />
+ </span>
+ }
+ />
+ <TooltipPopup side="top">
+ Network exposure changes restart the backend and must be controlled where the
+ server process is launched.
+ </TooltipPopup>
+ </Tooltip>
+ }
+ />
+ )}
+ </SettingsSection>
+
+ {isLocalBackendNetworkAccessible ? (
+ <SettingsSection
+ title="Authorized clients"
+ headerAction={
+ <AuthorizedClientsHeaderAction
+ clientSessions={desktopClientSessions}
+ isRevokingOtherClients={isRevokingOtherDesktopClients}
+ onRevokeOtherClients={handleRevokeOtherDesktopClients}
+ />
+ }
+ >
+ {desktopAccessManagementError ? (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <p className="text-xs text-destructive">{desktopAccessManagementError}</p>
+ </div>
+ ) : null}
+ <PairingClientsList
+ endpointUrl={desktopServerExposureState?.endpointUrl}
+ isLoading={isLoadingDesktopAccessManagement}
+ pairingLinks={visibleDesktopPairingLinks}
+ clientSessions={desktopClientSessions}
+ revokingPairingLinkId={revokingDesktopPairingLinkId}
+ revokingClientSessionId={revokingDesktopClientSessionId}
+ onRevokePairingLink={handleRevokeDesktopPairingLink}
+ onRevokeClientSession={handleRevokeDesktopClientSession}
+ />
+ </SettingsSection>
+ ) : null}
+ </>
+ ) : (
+ <SettingsSection title="Local backend access">
+ <SettingsRow
+ title="Owner tools"
+ description="Pairing links and client-session management are only available to owner sessions for this backend."
+ />
+ </SettingsSection>
+ )}
+
+ <SettingsSection
+ title="Remote environments"
+ headerAction={
+ <Dialog
+ open={addBackendDialogOpen}
+ onOpenChange={(open) => {
+ setAddBackendDialogOpen(open);
+ if (!open) {
+ setSavedBackendError(null);
+ }
+ }}
+ >
+ <DialogTrigger
+ render={
+ <Button size="xs" variant="outline">
+ <PlusIcon className="size-3" />
+ Add environment
+ </Button>
+ }
+ />
+ <DialogPopup>
+ <DialogHeader>
+ <DialogTitle>Add Environment</DialogTitle>
+ <DialogDescription>Pair another environment to this client.</DialogDescription>
+ <div className="flex gap-1 rounded-lg border border-border/60 bg-muted/50 p-1">
+ <button
+ type="button"
+ className={cn(
+ "flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
+ savedBackendMode === "pairing-url"
+ ? "bg-background text-foreground shadow-xs"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ disabled={isAddingSavedBackend}
+ onClick={() => setSavedBackendMode("pairing-url")}
+ >
+ Pairing URL
+ </button>
+ <button
+ type="button"
+ className={cn(
+ "flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
+ savedBackendMode === "host-code"
+ ? "bg-background text-foreground shadow-xs"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ disabled={isAddingSavedBackend}
+ onClick={() => setSavedBackendMode("host-code")}
+ >
+ Host + code
+ </button>
+ </div>
+ </DialogHeader>
+ <DialogPanel>
+ <div className="space-y-4">
+ {savedBackendMode === "pairing-url" ? (
+ <p className="text-xs text-muted-foreground">
+ Enter the full pairing URL from the environment you want to connect to.
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Enter the backend host and pairing code separately.
+ </p>
+ )}
+ <div className="space-y-3">
+ <label className="block">
+ <span className="mb-1.5 block text-xs font-medium text-foreground">
+ Label
+ </span>
+ <Input
+ value={savedBackendLabel}
+ onChange={(event) => setSavedBackendLabel(event.target.value)}
+ placeholder="My backend (optional)"
+ disabled={isAddingSavedBackend}
+ spellCheck={false}
+ />
+ </label>
+ {savedBackendMode === "pairing-url" ? (
+ <label className="block">
+ <span className="mb-1.5 block text-xs font-medium text-foreground">
+ Pairing URL
+ </span>
+ <Input
+ value={savedBackendPairingUrl}
+ onChange={(event) => setSavedBackendPairingUrl(event.target.value)}
+ placeholder="https://backend.example.com/pair#token=..."
+ disabled={isAddingSavedBackend}
+ spellCheck={false}
+ />
+ <span className="mt-1 block text-[11px] text-muted-foreground">
+ The full URL including the pairing token.
+ </span>
+ </label>
+ ) : (
+ <>
+ <label className="block">
+ <span className="mb-1.5 block text-xs font-medium text-foreground">
+ Host
+ </span>
+ <Input
+ value={savedBackendHost}
+ onChange={(event) => setSavedBackendHost(event.target.value)}
+ placeholder="https://backend.example.com"
+ disabled={isAddingSavedBackend}
+ spellCheck={false}
+ />
+ </label>
+ <label className="block">
+ <span className="mb-1.5 block text-xs font-medium text-foreground">
+ Pairing code
+ </span>
+ <Input
+ value={savedBackendPairingCode}
+ onChange={(event) => setSavedBackendPairingCode(event.target.value)}
+ placeholder="Pairing code"
+ disabled={isAddingSavedBackend}
+ spellCheck={false}
+ />
+ </label>
+ </>
+ )}
+ </div>
+ {savedBackendError ? (
+ <p className="text-xs text-destructive">{savedBackendError}</p>
+ ) : null}
+ <Button
+ variant="outline"
+ className="w-full"
+ disabled={isAddingSavedBackend}
+ onClick={() => void handleAddSavedBackend()}
+ >
+ <PlusIcon className="size-3.5" />
+ {isAddingSavedBackend ? "Adding…" : "Add Backend"}
+ </Button>
+ </div>
+ </DialogPanel>
+ </DialogPopup>
+ </Dialog>
+ }
+ >
+ {savedEnvironmentIds.map((environmentId) => (
+ <SavedBackendListRow
+ key={environmentId}
+ environmentId={environmentId}
+ reconnectingEnvironmentId={reconnectingSavedEnvironmentId}
+ removingEnvironmentId={removingSavedEnvironmentId}
+ onReconnect={handleReconnectSavedBackend}
+ onRemove={handleRemoveSavedBackend}
+ />
+ ))}
+
+ {savedEnvironmentIds.length === 0 ? (
+ <div className={ITEM_ROW_CLASSNAME}>
+ <p className="text-xs text-muted-foreground">
+ No remote environments yet. Click &ldquo;Add environment&rdquo; to pair another
+ environment.
+ </p>
+ </div>
+ ) : null}
+ </SettingsSection>
+ </SettingsPageContainer>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx
index ab2c8ab3f..e6a6759f8 100644
--- a/apps/web/src/components/settings/SettingsPanels.browser.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx
@@ -1,11 +1,17 @@
import "../../index.css";
import {
+ type AuthAccessStreamEvent,
+ type AuthAccessSnapshot,
+ AuthSessionId,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
+ type DesktopBridge,
+ type DesktopUpdateState,
type LocalApi,
type ServerConfig,
} from "@t3tools/contracts";
+import { DateTime } from "effect";
import { page } from "vitest/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
@@ -13,8 +19,155 @@ import { render } from "vitest-browser-react";
import { __resetLocalApiForTests } from "../../localApi";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
+import { ConnectionsSettings } from "./ConnectionsSettings";
import { GeneralSettingsPanel } from "./SettingsPanels";
+const authAccessHarness = vi.hoisted(() => {
+ type Snapshot = AuthAccessSnapshot;
+ let snapshot: Snapshot = {
+ pairingLinks: [],
+ clientSessions: [],
+ };
+ let revision = 1;
+ const listeners = new Set<(event: AuthAccessStreamEvent) => void>();
+
+ const emitEvent = (event: AuthAccessStreamEvent) => {
+ for (const listener of listeners) {
+ listener(event);
+ }
+ };
+
+ return {
+ reset() {
+ snapshot = {
+ pairingLinks: [],
+ clientSessions: [],
+ };
+ revision = 1;
+ listeners.clear();
+ },
+ setSnapshot(next: Snapshot) {
+ snapshot = next;
+ },
+ emitSnapshot() {
+ emitEvent({
+ version: 1 as const,
+ revision,
+ type: "snapshot" as const,
+ payload: snapshot,
+ });
+ revision += 1;
+ },
+ emitEvent,
+ emitPairingLinkUpserted(pairingLink: Snapshot["pairingLinks"][number]) {
+ emitEvent({
+ version: 1,
+ revision,
+ type: "pairingLinkUpserted",
+ payload: pairingLink,
+ });
+ revision += 1;
+ },
+ emitPairingLinkRemoved(id: string) {
+ emitEvent({
+ version: 1,
+ revision,
+ type: "pairingLinkRemoved",
+ payload: { id },
+ });
+ revision += 1;
+ },
+ emitClientUpserted(clientSession: Snapshot["clientSessions"][number]) {
+ emitEvent({
+ version: 1,
+ revision,
+ type: "clientUpserted",
+ payload: clientSession,
+ });
+ revision += 1;
+ },
+ emitClientRemoved(sessionId: string) {
+ emitEvent({
+ version: 1,
+ revision,
+ type: "clientRemoved",
+ payload: {
+ sessionId: AuthSessionId.makeUnsafe(sessionId),
+ },
+ });
+ revision += 1;
+ },
+ subscribe(listener: (event: AuthAccessStreamEvent) => void) {
+ listeners.add(listener);
+ listener({
+ version: 1,
+ revision: 1,
+ type: "snapshot",
+ payload: snapshot,
+ });
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ };
+});
+
+vi.mock("../../environments/runtime", () => {
+ const primaryConnection = {
+ kind: "primary" as const,
+ knownEnvironment: {
+ id: "environment-local",
+ label: "Local environment",
+ source: "manual" as const,
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ target: {
+ httpBaseUrl: "http://localhost:3000",
+ wsBaseUrl: "ws://localhost:3000",
+ },
+ },
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ client: {
+ server: {
+ subscribeAuthAccess: (listener: Parameters<typeof authAccessHarness.subscribe>[0]) =>
+ authAccessHarness.subscribe(listener),
+ },
+ },
+ ensureBootstrapped: async () => undefined,
+ reconnect: async () => undefined,
+ dispose: async () => undefined,
+ };
+
+ return {
+ getEnvironmentHttpBaseUrl: () => "http://localhost:3000",
+ getSavedEnvironmentRecord: () => null,
+ getSavedEnvironmentRuntimeState: () => null,
+ hasSavedEnvironmentRegistryHydrated: () => true,
+ listSavedEnvironmentRecords: () => [],
+ resetSavedEnvironmentRegistryStoreForTests: () => undefined,
+ resetSavedEnvironmentRuntimeStoreForTests: () => undefined,
+ resolveEnvironmentHttpUrl: (_environmentId: unknown, path: string) =>
+ new URL(path, "http://localhost:3000").toString(),
+ waitForSavedEnvironmentRegistryHydration: async () => undefined,
+ addSavedEnvironment: vi.fn(),
+ disconnectSavedEnvironment: vi.fn(),
+ ensureEnvironmentConnectionBootstrapped: async () => undefined,
+ getPrimaryEnvironmentConnection: () => primaryConnection,
+ readEnvironmentConnection: () => primaryConnection,
+ reconnectSavedEnvironment: vi.fn(),
+ removeSavedEnvironment: vi.fn(),
+ requireEnvironmentConnection: () => primaryConnection,
+ resetEnvironmentServiceForTests: () => undefined,
+ startEnvironmentConnectionService: () => undefined,
+ subscribeEnvironmentConnections: () => () => {},
+ useSavedEnvironmentRegistryStore: (
+ selector: (state: { byId: Record<string, never> }) => unknown,
+ ) => selector({ byId: {} }),
+ useSavedEnvironmentRuntimeStore: (
+ selector: (state: { byId: Record<string, never> }) => unknown,
+ ) => selector({ byId: {} }),
+ };
+});
+
function createBaseServerConfig(): ServerConfig {
return {
environment: {
@@ -24,6 +177,12 @@ function createBaseServerConfig(): ServerConfig {
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -41,24 +200,222 @@ function createBaseServerConfig(): ServerConfig {
};
}
+function makeUtc(value: string) {
+ return DateTime.makeUnsafe(Date.parse(value));
+}
+
+function makePairingLink(input: {
+ readonly id: string;
+ readonly credential: string;
+ readonly role: "owner" | "client";
+ readonly subject: string;
+ readonly label?: string;
+ readonly createdAt: string;
+ readonly expiresAt: string;
+}): AuthAccessSnapshot["pairingLinks"][number] {
+ return {
+ ...input,
+ createdAt: makeUtc(input.createdAt),
+ expiresAt: makeUtc(input.expiresAt),
+ };
+}
+
+function makeClientSession(input: {
+ readonly sessionId: string;
+ readonly subject: string;
+ readonly role: "owner" | "client";
+ readonly method: "browser-session-cookie";
+ readonly client?: {
+ readonly label?: string;
+ readonly ipAddress?: string;
+ readonly userAgent?: string;
+ readonly deviceType?: "desktop" | "mobile" | "tablet" | "bot" | "unknown";
+ readonly os?: string;
+ readonly browser?: string;
+ };
+ readonly issuedAt: string;
+ readonly expiresAt: string;
+ readonly lastConnectedAt?: string | null;
+ readonly connected: boolean;
+ readonly current: boolean;
+}): AuthAccessSnapshot["clientSessions"][number] {
+ return {
+ ...input,
+ client: {
+ deviceType: "unknown",
+ ...input.client,
+ },
+ sessionId: AuthSessionId.makeUnsafe(input.sessionId),
+ issuedAt: makeUtc(input.issuedAt),
+ expiresAt: makeUtc(input.expiresAt),
+ lastConnectedAt:
+ input.lastConnectedAt === undefined || input.lastConnectedAt === null
+ ? null
+ : makeUtc(input.lastConnectedAt),
+ };
+}
+
+const createDesktopBridgeStub = (overrides?: {
+ readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
+ readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
+}): DesktopBridge => {
+ const idleUpdateState: DesktopUpdateState = {
+ enabled: false,
+ status: "idle",
+ currentVersion: "0.0.0-test",
+ hostArch: "arm64",
+ appArch: "arm64",
+ runningUnderArm64Translation: false,
+ availableVersion: null,
+ downloadedVersion: null,
+ downloadPercent: null,
+ checkedAt: null,
+ message: null,
+ errorContext: null,
+ canRetry: false,
+ };
+
+ return {
+ getLocalEnvironmentBootstrap: () => ({
+ label: "Local environment",
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ bootstrapToken: "desktop-bootstrap-token",
+ }),
+ getServerExposureState: vi.fn().mockResolvedValue(
+ overrides?.serverExposureState ?? {
+ mode: "local-only",
+ endpointUrl: null,
+ advertisedHost: null,
+ },
+ ),
+ setServerExposureMode:
+ overrides?.setServerExposureMode ??
+ vi.fn().mockImplementation(async (mode) => ({
+ mode,
+ endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null,
+ advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null,
+ })),
+ pickFolder: vi.fn().mockResolvedValue(null),
+ confirm: vi.fn().mockResolvedValue(false),
+ setTheme: vi.fn().mockResolvedValue(undefined),
+ showContextMenu: vi.fn().mockResolvedValue(null),
+ openExternal: vi.fn().mockResolvedValue(true),
+ onMenuAction: () => () => {},
+ getUpdateState: vi.fn().mockResolvedValue(idleUpdateState),
+ checkForUpdate: vi.fn().mockResolvedValue({ checked: false, state: idleUpdateState }),
+ downloadUpdate: vi
+ .fn()
+ .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }),
+ installUpdate: vi
+ .fn()
+ .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }),
+ onUpdateState: () => () => {},
+ };
+};
+
describe("GeneralSettingsPanel observability", () => {
+ let mounted:
+ | (Awaited<ReturnType<typeof render>> & {
+ cleanup?: () => Promise<void>;
+ unmount?: () => Promise<void>;
+ })
+ | null = null;
+
beforeEach(async () => {
resetServerStateForTests();
await __resetLocalApiForTests();
localStorage.clear();
- document.body.innerHTML = "";
+ authAccessHarness.reset();
});
afterEach(async () => {
+ if (mounted) {
+ const teardown = mounted.cleanup ?? mounted.unmount;
+ await teardown?.call(mounted).catch(() => {});
+ }
+ mounted = null;
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(window, "desktopBridge");
+ Reflect.deleteProperty(window, "nativeApi");
+ document.body.innerHTML = "";
resetServerStateForTests();
await __resetLocalApiForTests();
- document.body.innerHTML = "";
+ authAccessHarness.reset();
+ });
+
+ it("hides owner pairing tools in browser-served loopback builds without remote exposure", async () => {
+ Reflect.deleteProperty(window, "desktopBridge");
+ authAccessHarness.setSnapshot({
+ pairingLinks: [],
+ clientSessions: [
+ makeClientSession({
+ sessionId: "session-owner",
+ subject: "browser-owner",
+ role: "owner",
+ method: "browser-session-cookie",
+ client: {
+ label: "Chrome on Mac",
+ deviceType: "desktop",
+ os: "macOS",
+ browser: "Chrome",
+ ipAddress: "127.0.0.1",
+ },
+ issuedAt: "2026-04-07T00:00:00.000Z",
+ expiresAt: "2026-05-07T00:00:00.000Z",
+ connected: true,
+ current: true,
+ }),
+ ],
+ });
+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input) => {
+ const url = String(input);
+ if (url.endsWith("/api/auth/session")) {
+ return new Response(
+ JSON.stringify({
+ authenticated: true,
+ auth: createBaseServerConfig().auth,
+ role: "owner",
+ sessionMethod: "browser-session-cookie",
+ expiresAt: "2026-05-07T00:00:00.000Z",
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ },
+ );
+ }
+
+ throw new Error(`Unhandled fetch GET ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ mounted = await render(
+ <AppAtomRegistryProvider>
+ <ConnectionsSettings />
+ </AppAtomRegistryProvider>,
+ );
+
+ await expect.element(page.getByText("Manage local backend")).toBeInTheDocument();
+ await expect.element(page.getByLabelText("Enable network access")).toBeDisabled();
+ await expect
+ .element(
+ page.getByText(
+ "This backend is only reachable on this machine. Restart it with a non-loopback host to enable remote pairing.",
+ ),
+ )
+ .toBeInTheDocument();
+ await expect.element(page.getByText("Authorized clients")).not.toBeInTheDocument();
+ await expect.element(page.getByText("Chrome on Mac")).not.toBeInTheDocument();
+ await expect
+ .element(page.getByRole("heading", { name: "Remote environments", exact: true }))
+ .toBeInTheDocument();
});
it("shows diagnostics inside About with a single logs-folder action", async () => {
setServerConfigSnapshot(createBaseServerConfig());
- await render(
+ mounted = await render(
<AppAtomRegistryProvider>
<GeneralSettingsPanel />
</AppAtomRegistryProvider>,
@@ -79,6 +436,233 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
+ it("creates and shows a pairing link when network access is enabled", async () => {
+ window.desktopBridge = createDesktopBridgeStub({
+ serverExposureState: {
+ mode: "network-accessible",
+ endpointUrl: "http://192.168.1.44:3773",
+ advertisedHost: "192.168.1.44",
+ },
+ });
+ let pairingLinks: Array<AuthAccessSnapshot["pairingLinks"][number]> = [];
+ let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
+ makeClientSession({
+ sessionId: "session-owner",
+ subject: "desktop-bootstrap",
+ role: "owner",
+ method: "browser-session-cookie",
+ client: {
+ label: "This Mac",
+ deviceType: "desktop",
+ os: "macOS",
+ browser: "Electron",
+ ipAddress: "127.0.0.1",
+ },
+ issuedAt: "2026-04-07T00:00:00.000Z",
+ expiresAt: "2026-05-07T00:00:00.000Z",
+ connected: true,
+ current: true,
+ }),
+ ];
+ authAccessHarness.setSnapshot({
+ pairingLinks,
+ clientSessions,
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ if (url.endsWith("/api/auth/pairing-token") && method === "POST") {
+ pairingLinks = [
+ makePairingLink({
+ id: "pairing-link-1",
+ credential: "pairing-token",
+ role: "client",
+ subject: "one-time-token",
+ label: "Julius iPhone",
+ createdAt: "2026-04-07T00:00:00.000Z",
+ expiresAt: "2026-04-10T00:05:00.000Z",
+ }),
+ ];
+ clientSessions = [
+ ...clientSessions,
+ makeClientSession({
+ sessionId: "session-client",
+ subject: "one-time-token",
+ role: "client",
+ method: "browser-session-cookie",
+ client: {
+ label: "Julius iPhone",
+ deviceType: "mobile",
+ os: "iOS",
+ browser: "Safari",
+ ipAddress: "192.168.1.88",
+ },
+ issuedAt: "2026-04-07T00:01:00.000Z",
+ expiresAt: "2026-05-07T00:01:00.000Z",
+ connected: false,
+ current: false,
+ }),
+ ];
+ authAccessHarness.setSnapshot({
+ pairingLinks,
+ clientSessions,
+ });
+ return new Response(
+ JSON.stringify({
+ id: "pairing-link-1",
+ credential: "pairing-token",
+ label: "Julius iPhone",
+ expiresAt: "2026-04-10T00:05:00.000Z",
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ },
+ );
+ }
+
+ throw new Error(`Unhandled fetch ${method} ${url}`);
+ }),
+ );
+
+ setServerConfigSnapshot(createBaseServerConfig());
+
+ mounted = await render(
+ <AppAtomRegistryProvider>
+ <ConnectionsSettings />
+ </AppAtomRegistryProvider>,
+ );
+
+ await expect.element(page.getByText("Authorized clients")).toBeInTheDocument();
+ await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
+ await expect.element(page.getByText("This Mac")).toBeInTheDocument();
+ await page.getByRole("button", { name: "Create link", exact: true }).click();
+ await expect.element(page.getByText("Create pairing link")).toBeInTheDocument();
+ await page.getByRole("button", { name: "Create link", exact: true }).click();
+ authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!);
+ authAccessHarness.emitClientUpserted(clientSessions[1]!);
+ await expect
+ .element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
+ .toBeInTheDocument();
+ await expect
+ .element(page.getByRole("button", { name: "Copy", exact: true }))
+ .toBeInTheDocument();
+ await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
+ });
+
+ it("revokes all other paired clients from settings", async () => {
+ window.desktopBridge = createDesktopBridgeStub({
+ serverExposureState: {
+ mode: "network-accessible",
+ endpointUrl: "http://192.168.1.44:3773",
+ advertisedHost: "192.168.1.44",
+ },
+ });
+ let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
+ makeClientSession({
+ sessionId: "session-owner",
+ subject: "desktop-bootstrap",
+ role: "owner",
+ method: "browser-session-cookie",
+ client: {
+ label: "This Mac",
+ deviceType: "desktop",
+ os: "macOS",
+ browser: "Electron",
+ },
+ issuedAt: "2026-04-05T00:00:00.000Z",
+ expiresAt: "2026-05-05T00:00:00.000Z",
+ connected: true,
+ current: true,
+ }),
+ makeClientSession({
+ sessionId: "session-client",
+ subject: "one-time-token",
+ role: "client",
+ method: "browser-session-cookie",
+ client: {
+ label: "Julius iPhone",
+ deviceType: "mobile",
+ os: "iOS",
+ browser: "Safari",
+ ipAddress: "192.168.1.88",
+ },
+ issuedAt: "2026-04-05T00:01:00.000Z",
+ expiresAt: "2026-05-05T00:01:00.000Z",
+ connected: false,
+ current: false,
+ }),
+ ];
+ authAccessHarness.setSnapshot({
+ pairingLinks: [],
+ clientSessions,
+ });
+
+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ if (url.endsWith("/api/auth/clients/revoke-others") && method === "POST") {
+ clientSessions = clientSessions.filter((session) => session.current);
+ authAccessHarness.setSnapshot({
+ pairingLinks: [],
+ clientSessions,
+ });
+ authAccessHarness.emitClientRemoved("session-client");
+ return new Response(JSON.stringify({ revokedCount: 1 }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+
+ throw new Error(`Unhandled fetch ${method} ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ setServerConfigSnapshot(createBaseServerConfig());
+
+ mounted = await render(
+ <AppAtomRegistryProvider>
+ <ConnectionsSettings />
+ </AppAtomRegistryProvider>,
+ );
+
+ await expect.element(page.getByText("Julius iPhone")).toBeInTheDocument();
+ await page.getByRole("button", { name: "Revoke others", exact: true }).click();
+ await expect.element(page.getByText("This Mac")).toBeInTheDocument();
+ await expect.element(page.getByText("Julius iPhone")).not.toBeInTheDocument();
+ expect(fetchMock).toHaveBeenCalled();
+ });
+
+ it("shows a disabled network access toggle with guidance in desktop builds", async () => {
+ const desktopBridge = createDesktopBridgeStub();
+ window.desktopBridge = desktopBridge;
+
+ setServerConfigSnapshot(createBaseServerConfig());
+
+ mounted = await render(
+ <AppAtomRegistryProvider>
+ <ConnectionsSettings />
+ </AppAtomRegistryProvider>,
+ );
+
+ const networkAccessToggle = page.getByLabelText("Enable network access");
+ await expect.element(networkAccessToggle).not.toBeDisabled();
+ await networkAccessToggle.click();
+ await expect.element(page.getByText("Enable network access?")).toBeInTheDocument();
+ await expect
+ .element(page.getByText("T3 Code will restart to expose this environment over the network."))
+ .toBeInTheDocument();
+ await page.getByRole("button", { name: "Restart and enable", exact: true }).click();
+ await vi.waitFor(() => {
+ expect(desktopBridge.setServerExposureMode).toHaveBeenCalledWith("network-accessible");
+ });
+ await expect
+ .element(page.getByText("Reachable at http://192.168.1.44:3773"))
+ .toBeInTheDocument();
+ });
+
it("opens the logs folder in the preferred editor", async () => {
const openInEditor = vi.fn<LocalApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
window.nativeApi = {
@@ -89,7 +673,7 @@ describe("GeneralSettingsPanel observability", () => {
setServerConfigSnapshot(createBaseServerConfig());
- await render(
+ mounted = await render(
<AppAtomRegistryProvider>
<GeneralSettingsPanel />
</AppAtomRegistryProvider>,
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 6251db7cd..c8766f264 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -6,11 +6,10 @@ import {
LoaderIcon,
PlusIcon,
RefreshCwIcon,
- Undo2Icon,
XIcon,
} from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
-import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
import {
PROVIDER_DISPLAY_NAMES,
type ScopedThreadRef,
@@ -47,9 +46,10 @@ import {
resolveAppModelSelectionState,
} from "../../modelSelection";
import { ensureLocalApi, readLocalApi } from "../../localApi";
+import { useShallow } from "zustand/react/shallow";
import {
selectProjectsAcrossEnvironments,
- selectThreadsAcrossEnvironments,
+ selectThreadShellsAcrossEnvironments,
useStore,
} from "../../store";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
@@ -62,6 +62,13 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../
import { Switch } from "../ui/switch";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import {
+ SettingResetButton,
+ SettingsPageContainer,
+ SettingsRow,
+ SettingsSection,
+ useRelativeTimeTick,
+} from "./settingsLayout";
import { ProjectFavicon } from "../ProjectFavicon";
import {
useServerAvailableEditors,
@@ -191,15 +198,6 @@ function getProviderVersionLabel(version: string | null | undefined) {
return version.startsWith("v") ? version : `v${version}`;
}
-function useRelativeTimeTick(intervalMs = 1_000) {
- const [tick, setTick] = useState(() => Date.now());
- useEffect(() => {
- const id = setInterval(() => setTick(Date.now()), intervalMs);
- return () => clearInterval(id);
- }, [intervalMs]);
- return tick;
-}
-
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
useRelativeTimeTick();
const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null;
@@ -222,104 +220,6 @@ function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }
);
}
-function SettingsSection({
- title,
- icon,
- headerAction,
- children,
-}: {
- title: string;
- icon?: ReactNode;
- headerAction?: ReactNode;
- children: ReactNode;
-}) {
- return (
- <section className="space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
- {icon}
- {title}
- </h2>
- {headerAction}
- </div>
- <div className="relative overflow-hidden rounded-2xl border bg-card text-card-foreground shadow-xs/5 not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
- {children}
- </div>
- </section>
- );
-}
-
-function SettingsRow({
- title,
- description,
- status,
- resetAction,
- control,
- children,
-}: {
- title: ReactNode;
- description: string;
- status?: ReactNode;
- resetAction?: ReactNode;
- control?: ReactNode;
- children?: ReactNode;
-}) {
- return (
- <div className="border-t border-border px-4 py-4 first:border-t-0 sm:px-5">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div className="min-w-0 flex-1 space-y-1">
- <div className="flex min-h-5 items-center gap-1.5">
- <h3 className="text-sm font-medium text-foreground">{title}</h3>
- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
- {resetAction}
- </span>
- </div>
- <p className="text-xs text-muted-foreground">{description}</p>
- {status ? <div className="pt-1 text-[11px] text-muted-foreground">{status}</div> : null}
- </div>
- {control ? (
- <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
- {control}
- </div>
- ) : null}
- </div>
- {children}
- </div>
- );
-}
-
-function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
- return (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon-xs"
- variant="ghost"
- aria-label={`Reset ${label} to default`}
- className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
- onClick={(event) => {
- event.stopPropagation();
- onClick();
- }}
- >
- <Undo2Icon className="size-3" />
- </Button>
- }
- />
- <TooltipPopup side="top">Reset to default</TooltipPopup>
- </Tooltip>
- );
-}
-
-function SettingsPageContainer({ children }: { children: ReactNode }) {
- return (
- <div className="flex-1 overflow-y-auto p-6">
- <div className="mx-auto flex w-full max-w-4xl flex-col gap-6">{children}</div>
- </div>
- );
-}
-
function AboutVersionTitle() {
return (
<span className="inline-flex items-center gap-2">
@@ -781,6 +681,7 @@ export function GeneralSettingsPanel() {
serverProviders[0]!.checkedAt,
)
: null;
+
return (
<SettingsPageContainer>
<SettingsSection title="General">
@@ -1484,8 +1385,8 @@ export function GeneralSettingsPanel() {
}
export function ArchivedThreadsPanel() {
- const projects = useStore(selectProjectsAcrossEnvironments);
- const threads = useStore(selectThreadsAcrossEnvironments);
+ const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
+ const threads = useStore(useShallow(selectThreadShellsAcrossEnvironments));
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const archivedGroups = useMemo(() => {
return projects
@@ -1553,7 +1454,7 @@ export function ArchivedThreadsPanel() {
<SettingsSection
key={project.id}
title={project.name}
- icon={<ProjectFavicon cwd={project.cwd} />}
+ icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
>
{projectThreads.map((thread) => (
<div
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index 6ba698c91..a150a7c75 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -1,5 +1,5 @@
import type { ComponentType } from "react";
-import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react";
+import { ArchiveIcon, ArrowLeftIcon, Link2Icon, Settings2Icon } from "lucide-react";
import { useNavigate } from "@tanstack/react-router";
import {
@@ -12,7 +12,10 @@ import {
SidebarSeparator,
} from "../ui/sidebar";
-export type SettingsSectionPath = "/settings/general" | "/settings/archived";
+export type SettingsSectionPath =
+ | "/settings/general"
+ | "/settings/connections"
+ | "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
@@ -20,6 +23,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
+ { label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -41,8 +45,8 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
isActive={isActive}
className={
isActive
- ? "gap-2 px-2 py-2 text-left text-xs text-foreground"
- : "gap-2 px-2 py-2 text-left text-xs text-muted-foreground hover:text-foreground/80"
+ ? "gap-2.5 px-2.5 py-2 text-left text-[13px] font-medium text-foreground"
+ : "gap-2.5 px-2.5 py-2 text-left text-[13px] text-muted-foreground/70 hover:text-foreground/80"
}
onClick={() => void navigate({ to: item.to, replace: true })}
>
@@ -50,7 +54,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
className={
isActive
? "size-4 shrink-0 text-foreground"
- : "size-4 shrink-0 text-muted-foreground"
+ : "size-4 shrink-0 text-muted-foreground/60"
}
/>
<span className="truncate">{item.label}</span>
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
new file mode 100644
index 000000000..f41e32f9e
--- /dev/null
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -0,0 +1,122 @@
+import { Undo2Icon } from "lucide-react";
+import { type ReactNode, useEffect, useState } from "react";
+
+import { cn } from "../../lib/utils";
+import { Button } from "../ui/button";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
+export function useRelativeTimeTick(intervalMs = 1_000) {
+ const [nowMs, setNowMs] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNowMs(Date.now()), intervalMs);
+ return () => clearInterval(id);
+ }, [intervalMs]);
+ return nowMs;
+}
+
+export function SettingsSection({
+ title,
+ icon,
+ headerAction,
+ children,
+}: {
+ title: string;
+ icon?: ReactNode;
+ headerAction?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <section className="space-y-2.5">
+ <div className="flex items-center justify-between px-1">
+ <h2 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/50">
+ <span className="inline-block h-px w-3 bg-border" aria-hidden />
+ {icon}
+ {title}
+ </h2>
+ {headerAction}
+ </div>
+ <div className="relative overflow-hidden rounded-2xl border bg-card text-card-foreground shadow-sm/4 not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:shadow-none dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
+ {children}
+ </div>
+ </section>
+ );
+}
+
+export function SettingsRow({
+ title,
+ description,
+ status,
+ resetAction,
+ control,
+ children,
+}: {
+ title: ReactNode;
+ description: string;
+ status?: ReactNode;
+ resetAction?: ReactNode;
+ control?: ReactNode;
+ children?: ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "border-t border-border/60 px-4 first:border-t-0 sm:px-5",
+ children ? "pt-4 pb-0" : "py-4",
+ )}
+ >
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex min-h-5 items-center gap-1.5">
+ <h3 className="text-[13px] font-semibold tracking-[-0.01em] text-foreground">
+ {title}
+ </h3>
+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
+ {resetAction}
+ </span>
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground/80">{description}</p>
+ {status ? <div className="pt-0.5 text-[11px] text-muted-foreground">{status}</div> : null}
+ </div>
+ {control ? (
+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
+ {control}
+ </div>
+ ) : null}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+export function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ aria-label={`Reset ${label} to default`}
+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ onClick();
+ }}
+ >
+ <Undo2Icon className="size-3" />
+ </Button>
+ }
+ />
+ <TooltipPopup side="top">Reset to default</TooltipPopup>
+ </Tooltip>
+ );
+}
+
+export function SettingsPageContainer({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex-1 overflow-y-auto p-6 sm:p-8">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-8">{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/ui/qr-code.test.tsx b/apps/web/src/components/ui/qr-code.test.tsx
new file mode 100644
index 000000000..118bd4295
--- /dev/null
+++ b/apps/web/src/components/ui/qr-code.test.tsx
@@ -0,0 +1,27 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+
+import { QRCodeSvg } from "./qr-code";
+
+describe("QRCodeSvg", () => {
+ it("renders with explicit high-contrast colors by default", () => {
+ const markup = renderToStaticMarkup(<QRCodeSvg value="https://example.com/pair" />);
+
+ expect(markup).toContain('fill="#fff"');
+ expect(markup).toContain('fill="#000"');
+ expect(markup).not.toContain('fill="currentColor"');
+ });
+
+ it("supports custom foreground and background colors", () => {
+ const markup = renderToStaticMarkup(
+ <QRCodeSvg
+ value="https://example.com/pair"
+ foregroundColor="#123456"
+ backgroundColor="#abcdef"
+ />,
+ );
+
+ expect(markup).toContain('fill="#abcdef"');
+ expect(markup).toContain('fill="#123456"');
+ });
+});
diff --git a/apps/web/src/components/ui/qr-code.tsx b/apps/web/src/components/ui/qr-code.tsx
new file mode 100644
index 000000000..9b474f76e
--- /dev/null
+++ b/apps/web/src/components/ui/qr-code.tsx
@@ -0,0 +1,81 @@
+import { memo } from "react";
+import { QrCode } from "../../lib/vendor/qrcodegen";
+
+type QRCodeSvgProps = {
+ value: string;
+ size?: number;
+ level?: "L" | "M" | "Q" | "H";
+ marginSize?: number;
+ title?: string;
+ className?: string;
+ foregroundColor?: string;
+ backgroundColor?: string;
+};
+
+const ERROR_CORRECTION_LEVELS = {
+ L: QrCode.Ecc.LOW,
+ M: QrCode.Ecc.MEDIUM,
+ Q: QrCode.Ecc.QUARTILE,
+ H: QrCode.Ecc.HIGH,
+} as const;
+
+function buildQrPathData(qrCode: ReturnType<typeof QrCode.encodeText>, marginSize: number): string {
+ const commands: Array<string> = [];
+
+ for (let y = 0; y < qrCode.size; y += 1) {
+ let runStart = -1;
+
+ for (let x = 0; x <= qrCode.size; x += 1) {
+ const isDark = x < qrCode.size && qrCode.getModule(x, y);
+
+ if (isDark) {
+ if (runStart === -1) {
+ runStart = x;
+ }
+ continue;
+ }
+
+ if (runStart === -1) {
+ continue;
+ }
+
+ commands.push(
+ `M${runStart + marginSize} ${y + marginSize}h${x - runStart}v1H${runStart + marginSize}z`,
+ );
+ runStart = -1;
+ }
+ }
+
+ return commands.join("");
+}
+
+export const QRCodeSvg = memo(function QRCodeSvg({
+ value,
+ size = 128,
+ level = "L",
+ marginSize = 0,
+ title,
+ className,
+ foregroundColor = "#000",
+ backgroundColor = "#fff",
+}: QRCodeSvgProps) {
+ const qrCode = QrCode.encodeText(value, ERROR_CORRECTION_LEVELS[level]);
+ const viewBoxSize = qrCode.size + marginSize * 2;
+
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox={`0 0 ${viewBoxSize} ${viewBoxSize}`}
+ width={size}
+ height={size}
+ shapeRendering="crispEdges"
+ role={title ? "img" : undefined}
+ aria-label={title}
+ className={className}
+ >
+ {title ? <title>{title}</title> : null}
+ <rect width={viewBoxSize} height={viewBoxSize} fill={backgroundColor} />
+ <path d={buildQrPathData(qrCode, marginSize)} fill={foregroundColor} />
+ </svg>
+ );
+});
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 8432680d4..fb56e691e 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -800,6 +800,50 @@ describe("composerDraftStore project draft thread mapping", () => {
envMode: "worktree",
});
});
+
+ it("clears branch and worktree context when remapping a draft to another environment", () => {
+ const store = useComposerDraftStore.getState();
+ store.setProjectDraftThreadId(projectRef, draftId, {
+ threadId,
+ branch: "feature/local-only",
+ worktreePath: "/tmp/local-worktree",
+ envMode: "worktree",
+ });
+
+ store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), remoteProjectRef, draftId, {
+ threadId,
+ });
+
+ expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({
+ environmentId: OTHER_TEST_ENVIRONMENT_ID,
+ projectId,
+ branch: null,
+ worktreePath: null,
+ envMode: "local",
+ });
+ });
+
+ it("clears branch and worktree context when changing a draft thread project ref", () => {
+ const store = useComposerDraftStore.getState();
+ store.setProjectDraftThreadId(projectRef, draftId, {
+ threadId,
+ branch: "feature/local-only",
+ worktreePath: "/tmp/local-worktree",
+ envMode: "worktree",
+ });
+
+ store.setDraftThreadContext(draftId, {
+ projectRef: remoteProjectRef,
+ });
+
+ expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({
+ environmentId: OTHER_TEST_ENVIRONMENT_ID,
+ projectId,
+ branch: null,
+ worktreePath: null,
+ envMode: "local",
+ });
+ });
});
describe("composerDraftStore modelSelection", () => {
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index 0df2332e0..fac23d847 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -1001,10 +1001,22 @@ function createDraftThreadState(
interactionMode?: ProviderInteractionMode;
},
): DraftThreadState {
+ const projectChanged =
+ existingThread !== undefined &&
+ (existingThread.environmentId !== projectRef.environmentId ||
+ existingThread.projectId !== projectRef.projectId);
const nextWorktreePath =
options?.worktreePath === undefined
- ? (existingThread?.worktreePath ?? null)
+ ? projectChanged
+ ? null
+ : (existingThread?.worktreePath ?? null)
: (options.worktreePath ?? null);
+ const nextBranch =
+ options?.branch === undefined
+ ? projectChanged
+ ? null
+ : (existingThread?.branch ?? null)
+ : (options.branch ?? null);
return {
threadId,
environmentId: projectRef.environmentId,
@@ -1014,11 +1026,15 @@ function createDraftThreadState(
runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
interactionMode:
options?.interactionMode ?? existingThread?.interactionMode ?? DEFAULT_INTERACTION_MODE,
- branch:
- options?.branch === undefined ? (existingThread?.branch ?? null) : (options.branch ?? null),
+ branch: nextBranch,
worktreePath: nextWorktreePath,
envMode:
- options?.envMode ?? (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")),
+ options?.envMode ??
+ (nextWorktreePath
+ ? "worktree"
+ : projectChanged
+ ? "local"
+ : (existingThread?.envMode ?? "local")),
promotedTo: null,
};
}
@@ -1908,10 +1924,21 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
) {
return state;
}
+ const projectChanged =
+ nextProjectRef.environmentId !== existing.environmentId ||
+ nextProjectRef.projectId !== existing.projectId;
const nextWorktreePath =
options.worktreePath === undefined
- ? existing.worktreePath
+ ? projectChanged
+ ? null
+ : existing.worktreePath
: (options.worktreePath ?? null);
+ const nextBranch =
+ options.branch === undefined
+ ? projectChanged
+ ? null
+ : existing.branch
+ : (options.branch ?? null);
const nextDraftThread: DraftThreadState = {
threadId: existing.threadId,
environmentId: nextProjectRef.environmentId,
@@ -1923,10 +1950,15 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
: options.createdAt || existing.createdAt,
runtimeMode: options.runtimeMode ?? existing.runtimeMode,
interactionMode: options.interactionMode ?? existing.interactionMode,
- branch: options.branch === undefined ? existing.branch : (options.branch ?? null),
+ branch: nextBranch,
worktreePath: nextWorktreePath,
envMode:
- options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
+ options.envMode ??
+ (nextWorktreePath
+ ? "worktree"
+ : projectChanged
+ ? "local"
+ : (existing.envMode ?? "local")),
promotedTo: existing.promotedTo ?? null,
};
const isUnchanged =
diff --git a/apps/web/src/environmentApi.ts b/apps/web/src/environmentApi.ts
index a56594068..5f23a53a7 100644
--- a/apps/web/src/environmentApi.ts
+++ b/apps/web/src/environmentApi.ts
@@ -1,6 +1,7 @@
import type { EnvironmentId, EnvironmentApi } from "@t3tools/contracts";
-import { readWsRpcClientEntryForEnvironment, WsRpcClient } from "./wsRpcClient";
+import type { WsRpcClient } from "./rpc/wsRpcClient";
+import { readEnvironmentConnection } from "./environments/runtime";
export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
return {
@@ -54,8 +55,8 @@ export function readEnvironmentApi(environmentId: EnvironmentId): EnvironmentApi
return undefined;
}
- const entry = readWsRpcClientEntryForEnvironment(environmentId);
- return entry ? createEnvironmentApi(entry.client) : undefined;
+ const connection = readEnvironmentConnection(environmentId);
+ return connection ? createEnvironmentApi(connection.client) : undefined;
}
export function ensureEnvironmentApi(environmentId: EnvironmentId): EnvironmentApi {
diff --git a/apps/web/src/environmentBootstrap.ts b/apps/web/src/environmentBootstrap.ts
deleted file mode 100644
index 860c459ed..000000000
--- a/apps/web/src/environmentBootstrap.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import {
- createKnownEnvironmentFromWsUrl,
- getKnownEnvironmentBaseUrl,
- type KnownEnvironment,
-} from "@t3tools/client-runtime";
-import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
-
-function createKnownEnvironmentFromDesktopBootstrap(
- bootstrap: DesktopEnvironmentBootstrap | null | undefined,
-): KnownEnvironment | null {
- if (!bootstrap?.wsUrl) {
- return null;
- }
-
- return createKnownEnvironmentFromWsUrl({
- id: `desktop:${bootstrap.label}`,
- label: bootstrap.label,
- source: "desktop-managed",
- wsUrl: bootstrap.wsUrl,
- });
-}
-
-export function getPrimaryKnownEnvironment(): KnownEnvironment | null {
- const desktopEnvironment = createKnownEnvironmentFromDesktopBootstrap(
- window.desktopBridge?.getLocalEnvironmentBootstrap(),
- );
- if (desktopEnvironment) {
- return desktopEnvironment;
- }
-
- const legacyDesktopWsUrl = window.desktopBridge?.getWsUrl();
- if (typeof legacyDesktopWsUrl === "string" && legacyDesktopWsUrl.length > 0) {
- return createKnownEnvironmentFromWsUrl({
- id: "desktop-legacy",
- label: "Local environment",
- source: "desktop-managed",
- wsUrl: legacyDesktopWsUrl,
- });
- }
-
- const configuredWsUrl = import.meta.env.VITE_WS_URL;
- if (typeof configuredWsUrl === "string" && configuredWsUrl.length > 0) {
- return createKnownEnvironmentFromWsUrl({
- id: "configured-primary",
- label: "Primary environment",
- source: "configured",
- wsUrl: configuredWsUrl,
- });
- }
-
- return createKnownEnvironmentFromWsUrl({
- id: "window-origin",
- label: "Primary environment",
- source: "window-origin",
- wsUrl: window.location.origin,
- });
-}
-
-export function resolvePrimaryEnvironmentBootstrapUrl(): string {
- const baseUrl = getKnownEnvironmentBaseUrl(getPrimaryKnownEnvironment());
- if (!baseUrl) {
- throw new Error("Unable to resolve a known environment bootstrap URL.");
- }
- return baseUrl;
-}
diff --git a/apps/web/src/environmentGrouping.test.ts b/apps/web/src/environmentGrouping.test.ts
new file mode 100644
index 000000000..7c28f1f89
--- /dev/null
+++ b/apps/web/src/environmentGrouping.test.ts
@@ -0,0 +1,453 @@
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
+import { scopeProjectRef } from "@t3tools/client-runtime";
+import { describe, expect, it } from "vitest";
+
+import {
+ selectProjectsAcrossEnvironments,
+ selectSidebarThreadsAcrossEnvironments,
+ selectSidebarThreadsForProjectRef,
+ selectSidebarThreadsForProjectRefs,
+ type AppState,
+ type EnvironmentState,
+} from "./store";
+import { deriveLogicalProjectKey } from "./logicalProject";
+import type { Project, SidebarThreadSummary } from "./types";
+import { DEFAULT_INTERACTION_MODE } from "./types";
+
+// ── Fixture Identifiers ──────────────────────────────────────────────
+
+const primaryEnvId = EnvironmentId.makeUnsafe("env-primary");
+const remoteEnvId = EnvironmentId.makeUnsafe("env-remote");
+
+const sharedProjectPrimaryId = ProjectId.makeUnsafe("shared-proj-primary");
+const sharedProjectRemoteId = ProjectId.makeUnsafe("shared-proj-remote");
+const localOnlyProjectId = ProjectId.makeUnsafe("local-only-proj");
+const remoteOnlyProjectId = ProjectId.makeUnsafe("remote-only-proj");
+
+const threadP1 = ThreadId.makeUnsafe("thread-shared-primary-1");
+const threadP2 = ThreadId.makeUnsafe("thread-shared-primary-2");
+const threadR1 = ThreadId.makeUnsafe("thread-shared-remote-1");
+const threadL1 = ThreadId.makeUnsafe("thread-local-only-1");
+const threadRO1 = ThreadId.makeUnsafe("thread-remote-only-1");
+
+const SHARED_REPO_CANONICAL_KEY = "github.com/example/shared-repo";
+
+// ── Factory Helpers ──────────────────────────────────────────────────
+
+function makeProject(
+ overrides: Partial<Project> & Pick<Project, "id" | "environmentId" | "name">,
+): Project {
+ return {
+ cwd: `/tmp/${overrides.name}`,
+ defaultModelSelection: { provider: "codex" as const, model: "gpt-5-codex" },
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ scripts: [],
+ ...overrides,
+ };
+}
+
+function makeSidebarThreadSummary(
+ overrides: Partial<SidebarThreadSummary> &
+ Pick<SidebarThreadSummary, "id" | "environmentId" | "projectId" | "title">,
+): SidebarThreadSummary {
+ return {
+ interactionMode: DEFAULT_INTERACTION_MODE,
+ session: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ archivedAt: null,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ latestTurn: null,
+ branch: null,
+ worktreePath: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+ ...overrides,
+ };
+}
+
+function makeEmptyEnvironmentState(): EnvironmentState {
+ return {
+ projectIds: [],
+ projectById: {},
+ threadIds: [],
+ threadIdsByProjectId: {},
+ threadShellById: {},
+ threadSessionById: {},
+ threadTurnStateById: {},
+ messageIdsByThreadId: {},
+ messageByThreadId: {},
+ activityIdsByThreadId: {},
+ activityByThreadId: {},
+ proposedPlanIdsByThreadId: {},
+ proposedPlanByThreadId: {},
+ turnDiffIdsByThreadId: {},
+ turnDiffSummaryByThreadId: {},
+ sidebarThreadSummaryById: {},
+ bootstrapComplete: true,
+ };
+}
+
+// ── Fixture: Two environments, shared + local-only + remote-only projects ──
+
+function makeFixtureState(): AppState {
+ // Shared project: same repo in both envs
+ const sharedProjectPrimary = makeProject({
+ id: sharedProjectPrimaryId,
+ environmentId: primaryEnvId,
+ name: "shared-repo",
+ repositoryIdentity: {
+ canonicalKey: SHARED_REPO_CANONICAL_KEY,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/example/shared-repo.git",
+ },
+ },
+ });
+ const sharedProjectRemote = makeProject({
+ id: sharedProjectRemoteId,
+ environmentId: remoteEnvId,
+ name: "shared-repo",
+ repositoryIdentity: {
+ canonicalKey: SHARED_REPO_CANONICAL_KEY,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/example/shared-repo.git",
+ },
+ },
+ });
+ // Local-only project
+ const localOnlyProject = makeProject({
+ id: localOnlyProjectId,
+ environmentId: primaryEnvId,
+ name: "local-only",
+ });
+ // Remote-only project
+ const remoteOnlyProject = makeProject({
+ id: remoteOnlyProjectId,
+ environmentId: remoteEnvId,
+ name: "remote-only",
+ });
+
+ // Threads
+ const summaryP1 = makeSidebarThreadSummary({
+ id: threadP1,
+ environmentId: primaryEnvId,
+ projectId: sharedProjectPrimaryId,
+ title: "Shared primary thread 1",
+ });
+ const summaryP2 = makeSidebarThreadSummary({
+ id: threadP2,
+ environmentId: primaryEnvId,
+ projectId: sharedProjectPrimaryId,
+ title: "Shared primary thread 2",
+ });
+ const summaryR1 = makeSidebarThreadSummary({
+ id: threadR1,
+ environmentId: remoteEnvId,
+ projectId: sharedProjectRemoteId,
+ title: "Shared remote thread 1",
+ });
+ const summaryL1 = makeSidebarThreadSummary({
+ id: threadL1,
+ environmentId: primaryEnvId,
+ projectId: localOnlyProjectId,
+ title: "Local only thread 1",
+ });
+ const summaryRO1 = makeSidebarThreadSummary({
+ id: threadRO1,
+ environmentId: remoteEnvId,
+ projectId: remoteOnlyProjectId,
+ title: "Remote only thread 1",
+ });
+
+ const primaryEnvState: EnvironmentState = {
+ ...makeEmptyEnvironmentState(),
+ projectIds: [sharedProjectPrimaryId, localOnlyProjectId],
+ projectById: {
+ [sharedProjectPrimaryId]: sharedProjectPrimary,
+ [localOnlyProjectId]: localOnlyProject,
+ },
+ threadIds: [threadP1, threadP2, threadL1],
+ threadIdsByProjectId: {
+ [sharedProjectPrimaryId]: [threadP1, threadP2],
+ [localOnlyProjectId]: [threadL1],
+ },
+ sidebarThreadSummaryById: {
+ [threadP1]: summaryP1,
+ [threadP2]: summaryP2,
+ [threadL1]: summaryL1,
+ },
+ };
+
+ const remoteEnvState: EnvironmentState = {
+ ...makeEmptyEnvironmentState(),
+ projectIds: [sharedProjectRemoteId, remoteOnlyProjectId],
+ projectById: {
+ [sharedProjectRemoteId]: sharedProjectRemote,
+ [remoteOnlyProjectId]: remoteOnlyProject,
+ },
+ threadIds: [threadR1, threadRO1],
+ threadIdsByProjectId: {
+ [sharedProjectRemoteId]: [threadR1],
+ [remoteOnlyProjectId]: [threadRO1],
+ },
+ sidebarThreadSummaryById: {
+ [threadR1]: summaryR1,
+ [threadRO1]: summaryRO1,
+ },
+ };
+
+ return {
+ activeEnvironmentId: primaryEnvId,
+ environmentStateById: {
+ [primaryEnvId]: primaryEnvState,
+ [remoteEnvId]: remoteEnvState,
+ },
+ };
+}
+
+// ── Tests ────────────────────────────────────────────────────────────
+
+describe("environment grouping", () => {
+ describe("deriveLogicalProjectKey", () => {
+ it("uses repositoryIdentity.canonicalKey when present", () => {
+ const project = makeProject({
+ id: sharedProjectPrimaryId,
+ environmentId: primaryEnvId,
+ name: "shared-repo",
+ repositoryIdentity: {
+ canonicalKey: SHARED_REPO_CANONICAL_KEY,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/example/shared-repo.git",
+ },
+ },
+ });
+ expect(deriveLogicalProjectKey(project)).toBe(SHARED_REPO_CANONICAL_KEY);
+ });
+
+ it("falls back to scoped project key when no repositoryIdentity", () => {
+ const project = makeProject({
+ id: localOnlyProjectId,
+ environmentId: primaryEnvId,
+ name: "local-only",
+ });
+ const key = deriveLogicalProjectKey(project);
+ expect(key).toContain(primaryEnvId);
+ expect(key).toContain(localOnlyProjectId);
+ });
+
+ it("groups projects from different environments that share the same canonical key", () => {
+ const primary = makeProject({
+ id: sharedProjectPrimaryId,
+ environmentId: primaryEnvId,
+ name: "shared-repo",
+ repositoryIdentity: {
+ canonicalKey: SHARED_REPO_CANONICAL_KEY,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/example/shared-repo.git",
+ },
+ },
+ });
+ const remote = makeProject({
+ id: sharedProjectRemoteId,
+ environmentId: remoteEnvId,
+ name: "shared-repo",
+ repositoryIdentity: {
+ canonicalKey: SHARED_REPO_CANONICAL_KEY,
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "https://github.com/example/shared-repo.git",
+ },
+ },
+ });
+ expect(deriveLogicalProjectKey(primary)).toBe(deriveLogicalProjectKey(remote));
+ });
+
+ it("does NOT group projects without shared canonical key", () => {
+ const local = makeProject({
+ id: localOnlyProjectId,
+ environmentId: primaryEnvId,
+ name: "local-only",
+ });
+ const remote = makeProject({
+ id: remoteOnlyProjectId,
+ environmentId: remoteEnvId,
+ name: "remote-only",
+ });
+ expect(deriveLogicalProjectKey(local)).not.toBe(deriveLogicalProjectKey(remote));
+ });
+ });
+
+ describe("selectProjectsAcrossEnvironments", () => {
+ it("returns all projects from all environments", () => {
+ const state = makeFixtureState();
+ const projects = selectProjectsAcrossEnvironments(state);
+ expect(projects).toHaveLength(4);
+ const names = projects.map((p) => p.name).toSorted();
+ expect(names).toEqual(["local-only", "remote-only", "shared-repo", "shared-repo"]);
+ });
+ });
+
+ describe("selectSidebarThreadsAcrossEnvironments", () => {
+ it("returns all sidebar thread summaries from all environments", () => {
+ const state = makeFixtureState();
+ const threads = selectSidebarThreadsAcrossEnvironments(state);
+ expect(threads).toHaveLength(5);
+ const ids = new Set(threads.map((t) => t.id));
+ expect(ids).toContain(threadP1);
+ expect(ids).toContain(threadP2);
+ expect(ids).toContain(threadR1);
+ expect(ids).toContain(threadL1);
+ expect(ids).toContain(threadRO1);
+ });
+ });
+
+ describe("selectSidebarThreadsForProjectRef", () => {
+ it("returns threads for a single project ref", () => {
+ const state = makeFixtureState();
+ const ref = scopeProjectRef(primaryEnvId, sharedProjectPrimaryId);
+ const threads = selectSidebarThreadsForProjectRef(state, ref);
+ expect(threads).toHaveLength(2);
+ expect(threads.map((t) => t.id)).toEqual([threadP1, threadP2]);
+ });
+
+ it("returns empty array for null ref", () => {
+ const state = makeFixtureState();
+ expect(selectSidebarThreadsForProjectRef(state, null)).toEqual([]);
+ });
+
+ it("returns empty array for nonexistent environment", () => {
+ const state = makeFixtureState();
+ const ref = scopeProjectRef(EnvironmentId.makeUnsafe("nonexistent"), sharedProjectPrimaryId);
+ expect(selectSidebarThreadsForProjectRef(state, ref)).toEqual([]);
+ });
+ });
+
+ describe("selectSidebarThreadsForProjectRefs", () => {
+ it("returns empty for empty refs", () => {
+ const state = makeFixtureState();
+ expect(selectSidebarThreadsForProjectRefs(state, [])).toEqual([]);
+ });
+
+ it("returns threads for a single ref", () => {
+ const state = makeFixtureState();
+ const refs = [scopeProjectRef(primaryEnvId, sharedProjectPrimaryId)];
+ const threads = selectSidebarThreadsForProjectRefs(state, refs);
+ expect(threads).toHaveLength(2);
+ expect(threads.map((t) => t.id)).toEqual([threadP1, threadP2]);
+ });
+
+ it("returns combined threads from multiple refs across environments", () => {
+ const state = makeFixtureState();
+ const refs = [
+ scopeProjectRef(primaryEnvId, sharedProjectPrimaryId),
+ scopeProjectRef(remoteEnvId, sharedProjectRemoteId),
+ ];
+ const threads = selectSidebarThreadsForProjectRefs(state, refs);
+ expect(threads).toHaveLength(3);
+ const ids = new Set(threads.map((t) => t.id));
+ expect(ids).toContain(threadP1);
+ expect(ids).toContain(threadP2);
+ expect(ids).toContain(threadR1);
+ });
+
+ it("returns threads from remote-only project", () => {
+ const state = makeFixtureState();
+ const refs = [scopeProjectRef(remoteEnvId, remoteOnlyProjectId)];
+ const threads = selectSidebarThreadsForProjectRefs(state, refs);
+ expect(threads).toHaveLength(1);
+ expect(threads[0]?.id).toBe(threadRO1);
+ });
+
+ it("returns threads from local-only project", () => {
+ const state = makeFixtureState();
+ const refs = [scopeProjectRef(primaryEnvId, localOnlyProjectId)];
+ const threads = selectSidebarThreadsForProjectRefs(state, refs);
+ expect(threads).toHaveLength(1);
+ expect(threads[0]?.id).toBe(threadL1);
+ });
+
+ it("handles refs with nonexistent environment gracefully", () => {
+ const state = makeFixtureState();
+ const refs = [
+ scopeProjectRef(primaryEnvId, sharedProjectPrimaryId),
+ scopeProjectRef(EnvironmentId.makeUnsafe("nonexistent"), ProjectId.makeUnsafe("nope")),
+ ];
+ const threads = selectSidebarThreadsForProjectRefs(state, refs);
+ // Only returns threads from the valid ref
+ expect(threads).toHaveLength(2);
+ expect(threads.map((t) => t.id)).toEqual([threadP1, threadP2]);
+ });
+ });
+
+ describe("logical project grouping for sidebar", () => {
+ it("computes correct logical key for grouped projects and aggregates threads", () => {
+ const state = makeFixtureState();
+ const allProjects = selectProjectsAcrossEnvironments(state);
+
+ // Group by logical key
+ const groups = new Map<string, Project[]>();
+ for (const project of allProjects) {
+ const key = deriveLogicalProjectKey(project);
+ const existing = groups.get(key) ?? [];
+ existing.push(project);
+ groups.set(key, existing);
+ }
+
+ // Shared project should be grouped
+ const sharedGroup = groups.get(SHARED_REPO_CANONICAL_KEY);
+ expect(sharedGroup).toBeDefined();
+ expect(sharedGroup).toHaveLength(2);
+ expect(sharedGroup!.map((p) => p.environmentId).toSorted()).toEqual(
+ [primaryEnvId, remoteEnvId].toSorted(),
+ );
+
+ // Build member refs for the grouped project and fetch threads
+ const memberRefs = sharedGroup!.map((p) => scopeProjectRef(p.environmentId, p.id));
+ const threads = selectSidebarThreadsForProjectRefs(state, memberRefs);
+ expect(threads).toHaveLength(3);
+ const threadIds = threads.map((t) => t.id);
+ expect(threadIds).toContain(threadP1);
+ expect(threadIds).toContain(threadP2);
+ expect(threadIds).toContain(threadR1);
+ });
+
+ it("local-only and remote-only projects remain ungrouped", () => {
+ const state = makeFixtureState();
+ const allProjects = selectProjectsAcrossEnvironments(state);
+
+ const groups = new Map<string, Project[]>();
+ for (const project of allProjects) {
+ const key = deriveLogicalProjectKey(project);
+ const existing = groups.get(key) ?? [];
+ existing.push(project);
+ groups.set(key, existing);
+ }
+
+ // Should have 3 groups total: shared, local-only, remote-only
+ expect(groups.size).toBe(3);
+
+ // Local-only group
+ const localKey = deriveLogicalProjectKey(
+ allProjects.find((p) => p.id === localOnlyProjectId)!,
+ );
+ expect(groups.get(localKey)).toHaveLength(1);
+
+ // Remote-only group
+ const remoteKey = deriveLogicalProjectKey(
+ allProjects.find((p) => p.id === remoteOnlyProjectId)!,
+ );
+ expect(groups.get(remoteKey)).toHaveLength(1);
+ });
+ });
+});
diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.ts
new file mode 100644
index 000000000..b2b330ce7
--- /dev/null
+++ b/apps/web/src/environments/primary/auth.ts
@@ -0,0 +1,361 @@
+import type {
+ AuthBootstrapInput,
+ AuthBootstrapResult,
+ AuthClientMetadata,
+ AuthCreatePairingCredentialInput,
+ AuthPairingCredentialResult,
+ AuthRevokeClientSessionInput,
+ AuthRevokePairingLinkInput,
+ AuthSessionId,
+ AuthSessionState,
+} from "@t3tools/contracts";
+
+import {
+ getPairingTokenFromUrl,
+ stripPairingTokenFromUrl as stripPairingTokenUrl,
+} from "../../pairingUrl";
+
+import { resolvePrimaryEnvironmentHttpUrl } from "./target";
+
+export interface ServerPairingLinkRecord {
+ readonly id: string;
+ readonly credential: string;
+ readonly role: "owner" | "client";
+ readonly subject: string;
+ readonly label?: string;
+ readonly createdAt: string;
+ readonly expiresAt: string;
+}
+
+export interface ServerClientSessionRecord {
+ readonly sessionId: AuthSessionId;
+ readonly subject: string;
+ readonly role: "owner" | "client";
+ readonly method: "browser-session-cookie" | "bearer-session-token";
+ readonly client: AuthClientMetadata;
+ readonly issuedAt: string;
+ readonly expiresAt: string;
+ readonly lastConnectedAt: string | null;
+ readonly connected: boolean;
+ readonly current: boolean;
+}
+
+type ServerAuthGateState =
+ | { status: "authenticated" }
+ | {
+ status: "requires-auth";
+ auth: AuthSessionState["auth"];
+ errorMessage?: string;
+ };
+
+let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
+const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
+const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
+
+export function peekPairingTokenFromUrl(): string | null {
+ return getPairingTokenFromUrl(new URL(window.location.href));
+}
+
+export function stripPairingTokenFromUrl() {
+ const url = new URL(window.location.href);
+ const next = stripPairingTokenUrl(url);
+ if (next.toString() === url.toString()) {
+ return;
+ }
+ window.history.replaceState({}, document.title, next.toString());
+}
+
+export function takePairingTokenFromUrl(): string | null {
+ const token = peekPairingTokenFromUrl();
+ if (!token) {
+ return null;
+ }
+ stripPairingTokenFromUrl();
+ return token;
+}
+
+function getDesktopBootstrapCredential(): string | null {
+ const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
+ return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
+ ? bootstrap.bootstrapToken
+ : null;
+}
+
+export async function fetchSessionState(): Promise<AuthSessionState> {
+ return retryTransientBootstrap(async () => {
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/session"), {
+ credentials: "include",
+ });
+ if (!response.ok) {
+ throw new BootstrapHttpError(
+ `Failed to load server auth session state (${response.status}).`,
+ response.status,
+ );
+ }
+ return (await response.json()) as AuthSessionState;
+ });
+}
+
+async function readErrorMessage(response: Response, fallbackMessage: string): Promise<string> {
+ const text = await response.text();
+ return text || fallbackMessage;
+}
+
+async function exchangeBootstrapCredential(credential: string): Promise<AuthBootstrapResult> {
+ return retryTransientBootstrap(async () => {
+ const payload: AuthBootstrapInput = { credential };
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/bootstrap"), {
+ body: JSON.stringify(payload),
+ credentials: "include",
+ headers: {
+ "content-type": "application/json",
+ },
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ const message = await response.text();
+ throw new BootstrapHttpError(
+ message || `Failed to bootstrap auth session (${response.status}).`,
+ response.status,
+ );
+ }
+
+ return (await response.json()) as AuthBootstrapResult;
+ });
+}
+
+async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
+ const startedAt = Date.now();
+
+ while (true) {
+ const session = await fetchSessionState();
+ if (session.authenticated) {
+ return session;
+ }
+
+ if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
+ throw new Error("Timed out waiting for authenticated session after bootstrap.");
+ }
+
+ await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
+ }
+}
+
+const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
+const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
+const BOOTSTRAP_RETRY_STEP_MS = 500;
+
+export class BootstrapHttpError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = "BootstrapHttpError";
+ this.status = status;
+ }
+}
+
+export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
+ const startedAt = Date.now();
+ while (true) {
+ try {
+ return await operation();
+ } catch (error) {
+ if (!isTransientBootstrapError(error)) {
+ throw error;
+ }
+
+ if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
+ throw error;
+ }
+
+ await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
+ }
+ }
+}
+
+function waitForBootstrapRetry(delayMs: number): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, delayMs);
+ });
+}
+
+function isTransientBootstrapError(error: unknown): boolean {
+ if (error instanceof BootstrapHttpError) {
+ return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
+ }
+
+ if (error instanceof TypeError) {
+ return true;
+ }
+
+ return error instanceof DOMException && error.name === "AbortError";
+}
+
+async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
+ const bootstrapCredential = getDesktopBootstrapCredential();
+ const currentSession = await fetchSessionState();
+ if (currentSession.authenticated) {
+ return { status: "authenticated" };
+ }
+
+ if (!bootstrapCredential) {
+ return {
+ status: "requires-auth",
+ auth: currentSession.auth,
+ };
+ }
+
+ try {
+ await exchangeBootstrapCredential(bootstrapCredential);
+ await waitForAuthenticatedSessionAfterBootstrap();
+ return { status: "authenticated" };
+ } catch (error) {
+ return {
+ status: "requires-auth",
+ auth: currentSession.auth,
+ errorMessage: error instanceof Error ? error.message : "Authentication failed.",
+ };
+ }
+}
+
+export async function submitServerAuthCredential(credential: string): Promise<void> {
+ const trimmedCredential = credential.trim();
+ if (!trimmedCredential) {
+ throw new Error("Enter a pairing token to continue.");
+ }
+
+ await exchangeBootstrapCredential(trimmedCredential);
+ bootstrapPromise = null;
+ stripPairingTokenFromUrl();
+}
+
+export async function createServerPairingCredential(
+ label?: string,
+): Promise<AuthPairingCredentialResult> {
+ const trimmedLabel = label?.trim();
+ const payload: AuthCreatePairingCredentialInput = trimmedLabel ? { label: trimmedLabel } : {};
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-token"), {
+ body: JSON.stringify(payload),
+ credentials: "include",
+ headers: {
+ "content-type": "application/json",
+ },
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(response, `Failed to create pairing credential (${response.status}).`),
+ );
+ }
+
+ return (await response.json()) as AuthPairingCredentialResult;
+}
+
+export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links"), {
+ credentials: "include",
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(response, `Failed to load pairing links (${response.status}).`),
+ );
+ }
+
+ return (await response.json()) as ReadonlyArray<ServerPairingLinkRecord>;
+}
+
+export async function revokeServerPairingLink(id: string): Promise<void> {
+ const payload: AuthRevokePairingLinkInput = { id };
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links/revoke"), {
+ body: JSON.stringify(payload),
+ credentials: "include",
+ headers: {
+ "content-type": "application/json",
+ },
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(response, `Failed to revoke pairing link (${response.status}).`),
+ );
+ }
+}
+
+export async function listServerClientSessions(): Promise<
+ ReadonlyArray<ServerClientSessionRecord>
+> {
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients"), {
+ credentials: "include",
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(response, `Failed to load paired clients (${response.status}).`),
+ );
+ }
+
+ return (await response.json()) as ReadonlyArray<ServerClientSessionRecord>;
+}
+
+export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
+ const payload: AuthRevokeClientSessionInput = { sessionId };
+ const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke"), {
+ body: JSON.stringify(payload),
+ credentials: "include",
+ headers: {
+ "content-type": "application/json",
+ },
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(response, `Failed to revoke client session (${response.status}).`),
+ );
+ }
+}
+
+export async function revokeOtherServerClientSessions(): Promise<number> {
+ const response = await fetch(
+ resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke-others"),
+ {
+ credentials: "include",
+ method: "POST",
+ },
+ );
+
+ if (!response.ok) {
+ throw new Error(
+ await readErrorMessage(
+ response,
+ `Failed to revoke other client sessions (${response.status}).`,
+ ),
+ );
+ }
+
+ const result = (await response.json()) as { revokedCount?: number };
+ return result.revokedCount ?? 0;
+}
+
+export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
+ if (bootstrapPromise) {
+ return bootstrapPromise;
+ }
+
+ const nextPromise = bootstrapServerAuth();
+ bootstrapPromise = nextPromise;
+ return nextPromise.finally(() => {
+ if (bootstrapPromise === nextPromise) {
+ bootstrapPromise = null;
+ }
+ });
+}
+
+export function __resetServerAuthBootstrapForTests() {
+ bootstrapPromise = null;
+}
diff --git a/apps/web/src/environments/primary/bootstrap.test.ts b/apps/web/src/environments/primary/bootstrap.test.ts
new file mode 100644
index 000000000..f27eebd91
--- /dev/null
+++ b/apps/web/src/environments/primary/bootstrap.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EnvironmentId } from "@t3tools/contracts";
+
+import {
+ getPrimaryKnownEnvironment,
+ resolveInitialPrimaryEnvironmentDescriptor,
+ resetPrimaryEnvironmentDescriptorForTests,
+ writePrimaryEnvironmentDescriptor,
+} from ".";
+
+function jsonResponse(body: unknown, init?: ResponseInit) {
+ return new Response(JSON.stringify(body), {
+ headers: {
+ "content-type": "application/json",
+ },
+ status: 200,
+ ...init,
+ });
+}
+
+const BASE_ENVIRONMENT = {
+ environmentId: "environment-local",
+ label: "Local environment",
+ platform: {
+ os: "darwin",
+ arch: "arm64",
+ },
+ serverVersion: "0.0.0-test",
+ capabilities: {
+ repositoryIdentity: true,
+ },
+};
+
+function installTestBrowser(url: string) {
+ vi.stubGlobal("window", {
+ location: new URL(url),
+ history: {
+ replaceState: vi.fn(),
+ },
+ });
+}
+
+describe("environmentBootstrap", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ installTestBrowser("http://localhost/");
+ });
+
+ afterEach(() => {
+ resetPrimaryEnvironmentDescriptorForTests();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("attaches the bootstrapped environment descriptor to the primary environment", () => {
+ vi.stubGlobal("window", {
+ location: {
+ origin: "http://localhost:3773",
+ },
+ desktopBridge: undefined,
+ });
+ writePrimaryEnvironmentDescriptor({
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ label: "Bootstrapped environment",
+ platform: {
+ os: "darwin",
+ arch: "arm64",
+ },
+ serverVersion: "0.0.0-test",
+ capabilities: {
+ repositoryIdentity: true,
+ },
+ });
+
+ expect(getPrimaryKnownEnvironment()).toEqual({
+ id: "environment-local",
+ label: "Bootstrapped environment",
+ source: "window-origin",
+ environmentId: "environment-local",
+ target: {
+ httpBaseUrl: "http://localhost:3773/",
+ wsBaseUrl: "ws://localhost:3773/",
+ },
+ });
+ });
+
+ it("reuses an in-flight descriptor bootstrap request", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await Promise.all([
+ resolveInitialPrimaryEnvironmentDescriptor(),
+ resolveInitialPrimaryEnvironmentDescriptor(),
+ ]);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledWith("http://localhost/.well-known/t3/environment");
+ });
+
+ it("uses https descriptor urls when the primary environment uses wss", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
+ vi.stubGlobal("fetch", fetchMock);
+ vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
+ vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
+
+ await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
+ expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
+ });
+
+ it("uses the current origin as the descriptor base for local dev environments", async () => {
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
+ vi.stubGlobal("fetch", fetchMock);
+ installTestBrowser("http://localhost:5735/");
+
+ await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
+ expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/.well-known/t3/environment");
+ });
+});
diff --git a/apps/web/src/environments/primary/context.ts b/apps/web/src/environments/primary/context.ts
new file mode 100644
index 000000000..df8c5d1db
--- /dev/null
+++ b/apps/web/src/environments/primary/context.ts
@@ -0,0 +1,120 @@
+import {
+ attachEnvironmentDescriptor,
+ createKnownEnvironment,
+ type KnownEnvironment,
+} from "@t3tools/client-runtime";
+import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
+import { create } from "zustand";
+
+import { BootstrapHttpError, retryTransientBootstrap } from "./auth";
+
+import { readPrimaryEnvironmentTarget, resolvePrimaryEnvironmentHttpUrl } from "./target";
+
+const SERVER_ENVIRONMENT_DESCRIPTOR_PATH = "/.well-known/t3/environment";
+
+interface PrimaryEnvironmentBootstrapState {
+ readonly descriptor: ExecutionEnvironmentDescriptor | null;
+ readonly setDescriptor: (descriptor: ExecutionEnvironmentDescriptor | null) => void;
+ readonly reset: () => void;
+}
+
+const usePrimaryEnvironmentBootstrapStore = create<PrimaryEnvironmentBootstrapState>()((set) => ({
+ descriptor: null,
+ setDescriptor: (descriptor) => set({ descriptor }),
+ reset: () => set({ descriptor: null }),
+}));
+
+let primaryEnvironmentDescriptorPromise: Promise<ExecutionEnvironmentDescriptor> | null = null;
+
+function createPrimaryKnownEnvironment(input: {
+ readonly source: KnownEnvironment["source"];
+ readonly target: KnownEnvironment["target"];
+}): KnownEnvironment | null {
+ const descriptor = readPrimaryEnvironmentDescriptor();
+ if (!descriptor) {
+ return null;
+ }
+
+ return attachEnvironmentDescriptor(
+ createKnownEnvironment({
+ id: descriptor.environmentId,
+ label: descriptor.label,
+ source: input.source,
+ target: input.target,
+ }),
+ descriptor,
+ );
+}
+
+async function fetchPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironmentDescriptor> {
+ return retryTransientBootstrap(async () => {
+ const response = await fetch(
+ resolvePrimaryEnvironmentHttpUrl(SERVER_ENVIRONMENT_DESCRIPTOR_PATH),
+ );
+ if (!response.ok) {
+ throw new BootstrapHttpError(
+ `Failed to load server environment descriptor (${response.status}).`,
+ response.status,
+ );
+ }
+
+ const descriptor = (await response.json()) as ExecutionEnvironmentDescriptor;
+ writePrimaryEnvironmentDescriptor(descriptor);
+ return descriptor;
+ });
+}
+
+export function readPrimaryEnvironmentDescriptor(): ExecutionEnvironmentDescriptor | null {
+ return usePrimaryEnvironmentBootstrapStore.getState().descriptor;
+}
+
+export function usePrimaryEnvironmentId(): EnvironmentId | null {
+ return usePrimaryEnvironmentBootstrapStore((state) => state.descriptor?.environmentId ?? null);
+}
+
+export function writePrimaryEnvironmentDescriptor(
+ descriptor: ExecutionEnvironmentDescriptor | null,
+): void {
+ usePrimaryEnvironmentBootstrapStore.getState().setDescriptor(descriptor);
+}
+
+export function getPrimaryKnownEnvironment(): KnownEnvironment | null {
+ const primaryTarget = readPrimaryEnvironmentTarget();
+ if (!primaryTarget) {
+ return null;
+ }
+
+ return createPrimaryKnownEnvironment({
+ source: primaryTarget.source,
+ target: primaryTarget.target,
+ });
+}
+
+export function resolveInitialPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironmentDescriptor> {
+ const descriptor = readPrimaryEnvironmentDescriptor();
+ if (descriptor) {
+ return Promise.resolve(descriptor);
+ }
+
+ if (primaryEnvironmentDescriptorPromise) {
+ return primaryEnvironmentDescriptorPromise;
+ }
+
+ const nextPromise = fetchPrimaryEnvironmentDescriptor();
+ primaryEnvironmentDescriptorPromise = nextPromise;
+ return nextPromise.finally(() => {
+ if (primaryEnvironmentDescriptorPromise === nextPromise) {
+ primaryEnvironmentDescriptorPromise = null;
+ }
+ });
+}
+
+export function __resetPrimaryEnvironmentBootstrapForTests(): void {
+ primaryEnvironmentDescriptorPromise = null;
+ usePrimaryEnvironmentBootstrapStore.getState().reset();
+}
+
+export const resetPrimaryEnvironmentDescriptorForTests = __resetPrimaryEnvironmentBootstrapForTests;
+
+export const __resetPrimaryEnvironmentDescriptorBootstrapForTests =
+ __resetPrimaryEnvironmentBootstrapForTests;
diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.ts
new file mode 100644
index 000000000..78e4b0660
--- /dev/null
+++ b/apps/web/src/environments/primary/index.ts
@@ -0,0 +1,35 @@
+export {
+ getPrimaryKnownEnvironment,
+ readPrimaryEnvironmentDescriptor,
+ resetPrimaryEnvironmentDescriptorForTests,
+ resolveInitialPrimaryEnvironmentDescriptor,
+ usePrimaryEnvironmentId,
+ writePrimaryEnvironmentDescriptor,
+ __resetPrimaryEnvironmentBootstrapForTests,
+ __resetPrimaryEnvironmentDescriptorBootstrapForTests,
+} from "./context";
+
+export {
+ resolveInitialPrimaryEnvironmentDescriptor as ensurePrimaryEnvironmentReady,
+ writePrimaryEnvironmentDescriptor as updatePrimaryEnvironmentDescriptor,
+} from "./context";
+
+export {
+ createServerPairingCredential,
+ fetchSessionState,
+ listServerClientSessions,
+ listServerPairingLinks,
+ peekPairingTokenFromUrl,
+ resolveInitialServerAuthGateState,
+ revokeOtherServerClientSessions,
+ revokeServerClientSession,
+ revokeServerPairingLink,
+ stripPairingTokenFromUrl,
+ submitServerAuthCredential,
+ takePairingTokenFromUrl,
+ type ServerClientSessionRecord,
+ type ServerPairingLinkRecord,
+ __resetServerAuthBootstrapForTests,
+} from "./auth";
+
+export { resolvePrimaryEnvironmentHttpUrl } from "./target";
diff --git a/apps/web/src/environments/primary/target.ts b/apps/web/src/environments/primary/target.ts
new file mode 100644
index 000000000..2e83fc388
--- /dev/null
+++ b/apps/web/src/environments/primary/target.ts
@@ -0,0 +1,103 @@
+import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
+import type { KnownEnvironment } from "@t3tools/client-runtime";
+
+export interface PrimaryEnvironmentTarget {
+ readonly source: KnownEnvironment["source"];
+ readonly target: KnownEnvironment["target"];
+}
+
+function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
+ return window.desktopBridge?.getLocalEnvironmentBootstrap() ?? null;
+}
+
+function normalizeBaseUrl(rawValue: string): string {
+ return new URL(rawValue, window.location.origin).toString();
+}
+
+function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
+ const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim();
+ const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim();
+
+ if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
+ return null;
+ }
+
+ if (!configuredHttpBaseUrl || !configuredWsBaseUrl) {
+ throw new Error("Configured primary environments require both VITE_HTTP_URL and VITE_WS_URL.");
+ }
+
+ return {
+ source: "configured",
+ target: {
+ httpBaseUrl: normalizeBaseUrl(configuredHttpBaseUrl),
+ wsBaseUrl: normalizeBaseUrl(configuredWsBaseUrl),
+ },
+ };
+}
+
+function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
+ const httpBaseUrl = normalizeBaseUrl(window.location.origin);
+ const url = new URL(httpBaseUrl);
+ if (url.protocol === "http:") {
+ url.protocol = "ws:";
+ } else if (url.protocol === "https:") {
+ url.protocol = "wss:";
+ } else {
+ throw new Error(`Unsupported HTTP base URL protocol: ${url.protocol}`);
+ }
+ return {
+ source: "window-origin",
+ target: {
+ httpBaseUrl,
+ wsBaseUrl: url.toString(),
+ },
+ };
+}
+
+function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
+ const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
+ if (!desktopBootstrap) {
+ return null;
+ }
+ if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
+ return null;
+ }
+ if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
+ throw new Error(
+ "Desktop bootstrap must provide both httpBaseUrl and wsBaseUrl for the local environment.",
+ );
+ }
+
+ return {
+ source: "desktop-managed",
+ target: {
+ httpBaseUrl: normalizeBaseUrl(desktopBootstrap.httpBaseUrl),
+ wsBaseUrl: normalizeBaseUrl(desktopBootstrap.wsBaseUrl),
+ },
+ };
+}
+
+export function resolvePrimaryEnvironmentHttpUrl(
+ pathname: string,
+ searchParams?: Record<string, string>,
+): string {
+ const primaryTarget = readPrimaryEnvironmentTarget();
+ if (!primaryTarget) {
+ throw new Error("Unable to resolve the primary environment HTTP base URL.");
+ }
+
+ const url = new URL(primaryTarget.target.httpBaseUrl);
+ url.pathname = pathname;
+ if (searchParams) {
+ url.search = new URLSearchParams(searchParams).toString();
+ }
+ return url.toString();
+}
+
+export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget | null {
+ return (
+ resolveDesktopPrimaryTarget() ??
+ resolveConfiguredPrimaryTarget() ??
+ resolveWindowOriginPrimaryTarget()
+ );
+}
diff --git a/apps/web/src/environments/remote/api.test.ts b/apps/web/src/environments/remote/api.test.ts
new file mode 100644
index 000000000..bbff76241
--- /dev/null
+++ b/apps/web/src/environments/remote/api.test.ts
@@ -0,0 +1,235 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ bootstrapRemoteBearerSession,
+ fetchRemoteEnvironmentDescriptor,
+ fetchRemoteSessionState,
+ issueRemoteWebSocketToken,
+ resolveRemoteWebSocketConnectionUrl,
+} from "./api";
+import { resolveRemotePairingTarget } from "./target";
+
+const originalFetch = globalThis.fetch;
+
+beforeEach(() => {
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ location: {
+ origin: "https://app.example.com",
+ },
+ },
+ });
+ vi.restoreAllMocks();
+});
+
+describe("remote environment api", () => {
+ it("derives backend urls and token from a pairing url", () => {
+ expect(
+ resolveRemotePairingTarget({
+ pairingUrl: "https://remote.example.com/pair#token=pairing-token",
+ }),
+ ).toEqual({
+ credential: "pairing-token",
+ httpBaseUrl: "https://remote.example.com/",
+ wsBaseUrl: "wss://remote.example.com/",
+ });
+ });
+
+ it("accepts pairing urls that still use a query token", () => {
+ expect(
+ resolveRemotePairingTarget({
+ pairingUrl: "https://remote.example.com/pair?token=pairing-token",
+ }),
+ ).toEqual({
+ credential: "pairing-token",
+ httpBaseUrl: "https://remote.example.com/",
+ wsBaseUrl: "wss://remote.example.com/",
+ });
+ });
+
+ it("derives backend urls from a host and pairing code", () => {
+ expect(
+ resolveRemotePairingTarget({
+ host: "https://remote.example.com",
+ pairingCode: "pairing-token",
+ }),
+ ).toEqual({
+ credential: "pairing-token",
+ httpBaseUrl: "https://remote.example.com/",
+ wsBaseUrl: "wss://remote.example.com/",
+ });
+ });
+
+ it("preserves host ports when normalizing a bare host input", () => {
+ expect(
+ resolveRemotePairingTarget({
+ host: "myserver.com:3000",
+ pairingCode: "pairing-token",
+ }),
+ ).toEqual({
+ credential: "pairing-token",
+ httpBaseUrl: "https://myserver.com:3000/",
+ wsBaseUrl: "wss://myserver.com:3000/",
+ });
+ });
+
+ it("bootstraps bearer auth against a remote backend", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ authenticated: true,
+ role: "client",
+ sessionMethod: "bearer-session-token",
+ expiresAt: "2026-05-01T12:00:00.000Z",
+ sessionToken: "bearer-token",
+ }),
+ { status: 200 },
+ ),
+ );
+ globalThis.fetch = fetchMock as typeof fetch;
+
+ await expect(
+ bootstrapRemoteBearerSession({
+ httpBaseUrl: "https://remote.example.com/",
+ credential: "pairing-token",
+ }),
+ ).resolves.toMatchObject({
+ sessionMethod: "bearer-session-token",
+ sessionToken: "bearer-token",
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/bootstrap/bearer", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ credential: "pairing-token",
+ }),
+ });
+ });
+
+ it("loads remote session state and websocket tokens over bearer auth", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ environmentId: "environment-remote",
+ label: "Remote environment",
+ platform: {
+ os: "linux",
+ arch: "x64",
+ },
+ serverVersion: "0.0.0-test",
+ capabilities: {
+ repositoryIdentity: true,
+ },
+ }),
+ { status: 200 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ authenticated: true,
+ auth: {
+ policy: "remote-reachable",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
+ role: "client",
+ sessionMethod: "bearer-session-token",
+ expiresAt: "2026-05-01T12:00:00.000Z",
+ }),
+ { status: 200 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ token: "ws-token",
+ expiresAt: "2026-05-01T12:05:00.000Z",
+ }),
+ { status: 200 },
+ ),
+ );
+ globalThis.fetch = fetchMock as typeof fetch;
+
+ await expect(
+ fetchRemoteEnvironmentDescriptor({
+ httpBaseUrl: "https://remote.example.com/",
+ }),
+ ).resolves.toMatchObject({
+ environmentId: "environment-remote",
+ label: "Remote environment",
+ });
+
+ await expect(
+ fetchRemoteSessionState({
+ httpBaseUrl: "https://remote.example.com/",
+ bearerToken: "bearer-token",
+ }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ role: "client",
+ });
+
+ await expect(
+ issueRemoteWebSocketToken({
+ httpBaseUrl: "https://remote.example.com/",
+ bearerToken: "bearer-token",
+ }),
+ ).resolves.toMatchObject({
+ token: "ws-token",
+ });
+
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 1,
+ "https://remote.example.com/.well-known/t3/environment",
+ {
+ method: "GET",
+ headers: {},
+ },
+ );
+ expect(fetchMock).toHaveBeenNthCalledWith(2, "https://remote.example.com/api/auth/session", {
+ method: "GET",
+ headers: {
+ authorization: "Bearer bearer-token",
+ },
+ });
+ expect(fetchMock).toHaveBeenNthCalledWith(3, "https://remote.example.com/api/auth/ws-token", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer bearer-token",
+ },
+ });
+ });
+
+ it("mints a websocket url with a short-lived ws token", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ token: "ws-token",
+ expiresAt: "2026-05-01T12:05:00.000Z",
+ }),
+ { status: 200 },
+ ),
+ );
+ globalThis.fetch = fetchMock as typeof fetch;
+
+ await expect(
+ resolveRemoteWebSocketConnectionUrl({
+ wsBaseUrl: "wss://remote.example.com/",
+ httpBaseUrl: "https://remote.example.com/",
+ bearerToken: "bearer-token",
+ }),
+ ).resolves.toBe("wss://remote.example.com/?wsToken=ws-token");
+ });
+});
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
diff --git a/apps/web/src/environments/remote/api.ts b/apps/web/src/environments/remote/api.ts
new file mode 100644
index 000000000..50b593975
--- /dev/null
+++ b/apps/web/src/environments/remote/api.ts
@@ -0,0 +1,143 @@
+import type {
+ AuthBearerBootstrapResult,
+ AuthSessionState,
+ AuthWebSocketTokenResult,
+ ExecutionEnvironmentDescriptor,
+} from "@t3tools/contracts";
+
+class RemoteEnvironmentAuthHttpError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = "RemoteEnvironmentAuthHttpError";
+ this.status = status;
+ }
+}
+
+function remoteEndpointUrl(httpBaseUrl: string, pathname: string): string {
+ const url = new URL(httpBaseUrl);
+ url.pathname = pathname;
+ url.search = "";
+ url.hash = "";
+ return url.toString();
+}
+
+async function readRemoteAuthErrorMessage(
+ response: Response,
+ fallbackMessage: string,
+): Promise<string> {
+ const text = await response.text();
+ if (!text) {
+ return fallbackMessage;
+ }
+
+ try {
+ const parsed = JSON.parse(text) as { readonly error?: string };
+ if (typeof parsed.error === "string" && parsed.error.length > 0) {
+ return parsed.error;
+ }
+ } catch {
+ // Fall back to raw text below.
+ }
+
+ return text;
+}
+
+async function fetchRemoteJson<T>(input: {
+ readonly httpBaseUrl: string;
+ readonly pathname: string;
+ readonly method?: "GET" | "POST";
+ readonly bearerToken?: string;
+ readonly body?: unknown;
+}): Promise<T> {
+ const requestUrl = remoteEndpointUrl(input.httpBaseUrl, input.pathname);
+ let response: Response;
+ try {
+ response = await fetch(requestUrl, {
+ method: input.method ?? "GET",
+ headers: {
+ ...(input.body !== undefined ? { "content-type": "application/json" } : {}),
+ ...(input.bearerToken ? { authorization: `Bearer ${input.bearerToken}` } : {}),
+ },
+ ...(input.body !== undefined ? { body: JSON.stringify(input.body) } : {}),
+ });
+ } catch (error) {
+ throw new Error(
+ `Failed to fetch remote auth endpoint ${requestUrl} (${(error as Error).message}).`,
+ { cause: error },
+ );
+ }
+
+ if (!response.ok) {
+ throw new RemoteEnvironmentAuthHttpError(
+ await readRemoteAuthErrorMessage(
+ response,
+ `Remote auth request failed (${response.status}).`,
+ ),
+ response.status,
+ );
+ }
+
+ return (await response.json()) as T;
+}
+
+export async function bootstrapRemoteBearerSession(input: {
+ readonly httpBaseUrl: string;
+ readonly credential: string;
+}): Promise<AuthBearerBootstrapResult> {
+ return fetchRemoteJson<AuthBearerBootstrapResult>({
+ httpBaseUrl: input.httpBaseUrl,
+ pathname: "/api/auth/bootstrap/bearer",
+ method: "POST",
+ body: {
+ credential: input.credential,
+ },
+ });
+}
+
+export async function fetchRemoteSessionState(input: {
+ readonly httpBaseUrl: string;
+ readonly bearerToken: string;
+}): Promise<AuthSessionState> {
+ return fetchRemoteJson<AuthSessionState>({
+ httpBaseUrl: input.httpBaseUrl,
+ pathname: "/api/auth/session",
+ bearerToken: input.bearerToken,
+ });
+}
+
+export async function fetchRemoteEnvironmentDescriptor(input: {
+ readonly httpBaseUrl: string;
+}): Promise<ExecutionEnvironmentDescriptor> {
+ return fetchRemoteJson<ExecutionEnvironmentDescriptor>({
+ httpBaseUrl: input.httpBaseUrl,
+ pathname: "/.well-known/t3/environment",
+ });
+}
+
+export async function issueRemoteWebSocketToken(input: {
+ readonly httpBaseUrl: string;
+ readonly bearerToken: string;
+}): Promise<AuthWebSocketTokenResult> {
+ return fetchRemoteJson<AuthWebSocketTokenResult>({
+ httpBaseUrl: input.httpBaseUrl,
+ pathname: "/api/auth/ws-token",
+ method: "POST",
+ bearerToken: input.bearerToken,
+ });
+}
+
+export async function resolveRemoteWebSocketConnectionUrl(input: {
+ readonly wsBaseUrl: string;
+ readonly httpBaseUrl: string;
+ readonly bearerToken: string;
+}): Promise<string> {
+ const issued = await issueRemoteWebSocketToken({
+ httpBaseUrl: input.httpBaseUrl,
+ bearerToken: input.bearerToken,
+ });
+ const url = new URL(input.wsBaseUrl, window.location.origin);
+ url.searchParams.set("wsToken", issued.token);
+ return url.toString();
+}
diff --git a/apps/web/src/environments/remote/target.ts b/apps/web/src/environments/remote/target.ts
new file mode 100644
index 000000000..311450d5f
--- /dev/null
+++ b/apps/web/src/environments/remote/target.ts
@@ -0,0 +1,86 @@
+import { getPairingTokenFromUrl } from "../../pairingUrl";
+
+export interface ResolvedRemotePairingTarget {
+ readonly credential: string;
+ readonly httpBaseUrl: string;
+ readonly wsBaseUrl: string;
+}
+
+function normalizeRemoteBaseUrl(rawValue: string): URL {
+ const trimmed = rawValue.trim();
+ if (!trimmed) {
+ throw new Error("Enter a backend URL.");
+ }
+
+ const normalizedInput =
+ /^[a-zA-Z][a-zA-Z\d+-]*:\/\//.test(trimmed) || trimmed.startsWith("//")
+ ? trimmed
+ : `https://${trimmed}`;
+ const url = new URL(normalizedInput, window.location.origin);
+ url.pathname = "/";
+ url.search = "";
+ url.hash = "";
+ return url;
+}
+
+function toHttpBaseUrl(url: URL): string {
+ const next = new URL(url.toString());
+ if (next.protocol === "ws:") {
+ next.protocol = "http:";
+ } else if (next.protocol === "wss:") {
+ next.protocol = "https:";
+ }
+ next.pathname = "/";
+ next.search = "";
+ next.hash = "";
+ return next.toString();
+}
+
+function toWsBaseUrl(url: URL): string {
+ const next = new URL(url.toString());
+ if (next.protocol === "http:") {
+ next.protocol = "ws:";
+ } else if (next.protocol === "https:") {
+ next.protocol = "wss:";
+ }
+ next.pathname = "/";
+ next.search = "";
+ next.hash = "";
+ return next.toString();
+}
+
+export function resolveRemotePairingTarget(input: {
+ readonly pairingUrl?: string;
+ readonly host?: string;
+ readonly pairingCode?: string;
+}): ResolvedRemotePairingTarget {
+ const pairingUrl = input.pairingUrl?.trim() ?? "";
+ if (pairingUrl.length > 0) {
+ const url = new URL(pairingUrl, window.location.origin);
+ const credential = getPairingTokenFromUrl(url) ?? "";
+ if (!credential) {
+ throw new Error("Pairing URL is missing its token.");
+ }
+ return {
+ credential,
+ httpBaseUrl: toHttpBaseUrl(url),
+ wsBaseUrl: toWsBaseUrl(url),
+ };
+ }
+
+ const host = input.host?.trim() ?? "";
+ const pairingCode = input.pairingCode?.trim() ?? "";
+ if (!host) {
+ throw new Error("Enter a backend URL.");
+ }
+ if (!pairingCode) {
+ throw new Error("Enter a pairing code.");
+ }
+
+ const normalizedHost = normalizeRemoteBaseUrl(host);
+ return {
+ credential: pairingCode,
+ httpBaseUrl: toHttpBaseUrl(normalizedHost),
+ wsBaseUrl: toWsBaseUrl(normalizedHost),
+ };
+}
diff --git a/apps/web/src/environments/runtime/catalog.test.ts b/apps/web/src/environments/runtime/catalog.test.ts
new file mode 100644
index 000000000..d0578946f
--- /dev/null
+++ b/apps/web/src/environments/runtime/catalog.test.ts
@@ -0,0 +1,51 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ resetSavedEnvironmentRegistryStoreForTests,
+ resetSavedEnvironmentRuntimeStoreForTests,
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+} from "./catalog";
+
+describe("environment runtime catalog stores", () => {
+ afterEach(() => {
+ resetSavedEnvironmentRegistryStoreForTests();
+ resetSavedEnvironmentRuntimeStoreForTests();
+ });
+
+ it("resets the saved environment registry store state", () => {
+ const environmentId = EnvironmentId.makeUnsafe("environment-1");
+
+ useSavedEnvironmentRegistryStore.getState().upsert({
+ environmentId,
+ label: "Remote environment",
+ httpBaseUrl: "https://remote.example.com/",
+ wsBaseUrl: "wss://remote.example.com/",
+ bearerToken: "token",
+ createdAt: "2026-04-09T00:00:00.000Z",
+ lastConnectedAt: null,
+ });
+
+ expect(useSavedEnvironmentRegistryStore.getState().byId[environmentId]).toBeDefined();
+
+ resetSavedEnvironmentRegistryStoreForTests();
+
+ expect(useSavedEnvironmentRegistryStore.getState().byId).toEqual({});
+ });
+
+ it("resets the saved environment runtime store state", () => {
+ const environmentId = EnvironmentId.makeUnsafe("environment-1");
+
+ useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
+ connectionState: "connected",
+ connectedAt: "2026-04-09T00:00:00.000Z",
+ });
+
+ expect(useSavedEnvironmentRuntimeStore.getState().byId[environmentId]).toBeDefined();
+
+ resetSavedEnvironmentRuntimeStoreForTests();
+
+ expect(useSavedEnvironmentRuntimeStore.getState().byId).toEqual({});
+ });
+});
diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.ts
new file mode 100644
index 000000000..11c11fdfa
--- /dev/null
+++ b/apps/web/src/environments/runtime/catalog.ts
@@ -0,0 +1,251 @@
+import { getKnownEnvironmentHttpBaseUrl } from "@t3tools/client-runtime";
+import type {
+ AuthSessionRole,
+ EnvironmentId,
+ ExecutionEnvironmentDescriptor,
+ ServerConfig,
+} from "@t3tools/contracts";
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+import { resolveStorage } from "../../lib/storage";
+import { getPrimaryKnownEnvironment } from "../primary";
+
+const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
+
+export interface SavedEnvironmentRecord {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly wsBaseUrl: string;
+ readonly httpBaseUrl: string;
+ readonly bearerToken: string;
+ readonly createdAt: string;
+ readonly lastConnectedAt: string | null;
+}
+
+interface SavedEnvironmentRegistryState {
+ readonly byId: Record<EnvironmentId, SavedEnvironmentRecord>;
+}
+
+interface SavedEnvironmentRegistryStore extends SavedEnvironmentRegistryState {
+ readonly upsert: (record: SavedEnvironmentRecord) => void;
+ readonly remove: (environmentId: EnvironmentId) => void;
+ readonly markConnected: (environmentId: EnvironmentId, connectedAt: string) => void;
+ readonly reset: () => void;
+}
+
+function createSavedEnvironmentRegistryStorage() {
+ return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
+}
+
+export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()(
+ persist(
+ (set) => ({
+ byId: {},
+ upsert: (record) =>
+ set((state) => ({
+ byId: {
+ ...state.byId,
+ [record.environmentId]: record,
+ },
+ })),
+ remove: (environmentId) =>
+ set((state) => {
+ const { [environmentId]: _removed, ...remaining } = state.byId;
+ return {
+ byId: remaining,
+ };
+ }),
+ markConnected: (environmentId, connectedAt) =>
+ set((state) => {
+ const existing = state.byId[environmentId];
+ if (!existing) {
+ return state;
+ }
+ return {
+ byId: {
+ ...state.byId,
+ [environmentId]: {
+ ...existing,
+ lastConnectedAt: connectedAt,
+ },
+ },
+ };
+ }),
+ reset: () =>
+ set({
+ byId: {},
+ }),
+ }),
+ {
+ name: SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
+ version: 1,
+ storage: createJSONStorage(createSavedEnvironmentRegistryStorage),
+ partialize: (state) => ({
+ byId: state.byId,
+ }),
+ },
+ ),
+);
+
+export function hasSavedEnvironmentRegistryHydrated(): boolean {
+ return useSavedEnvironmentRegistryStore.persist.hasHydrated();
+}
+
+export function waitForSavedEnvironmentRegistryHydration(): Promise<void> {
+ if (hasSavedEnvironmentRegistryHydrated()) {
+ return Promise.resolve();
+ }
+
+ return new Promise((resolve) => {
+ const unsubscribe = useSavedEnvironmentRegistryStore.persist.onFinishHydration(() => {
+ unsubscribe();
+ resolve();
+ });
+
+ if (hasSavedEnvironmentRegistryHydrated()) {
+ unsubscribe();
+ resolve();
+ }
+ });
+}
+
+export function listSavedEnvironmentRecords(): ReadonlyArray<SavedEnvironmentRecord> {
+ return Object.values(useSavedEnvironmentRegistryStore.getState().byId).toSorted((left, right) =>
+ left.label.localeCompare(right.label),
+ );
+}
+
+export function getSavedEnvironmentRecord(
+ environmentId: EnvironmentId,
+): SavedEnvironmentRecord | null {
+ return useSavedEnvironmentRegistryStore.getState().byId[environmentId] ?? null;
+}
+
+export function getEnvironmentHttpBaseUrl(environmentId: EnvironmentId): string | null {
+ const primaryEnvironment = getPrimaryKnownEnvironment();
+ if (primaryEnvironment?.environmentId === environmentId) {
+ return getKnownEnvironmentHttpBaseUrl(primaryEnvironment);
+ }
+
+ return getSavedEnvironmentRecord(environmentId)?.httpBaseUrl ?? null;
+}
+
+export function resolveEnvironmentHttpUrl(input: {
+ readonly environmentId: EnvironmentId;
+ readonly pathname: string;
+ readonly searchParams?: Record<string, string>;
+}): string {
+ const httpBaseUrl = getEnvironmentHttpBaseUrl(input.environmentId);
+ if (!httpBaseUrl) {
+ throw new Error(`Unable to resolve HTTP base URL for environment ${input.environmentId}.`);
+ }
+
+ const url = new URL(httpBaseUrl);
+ url.pathname = input.pathname;
+ if (input.searchParams) {
+ url.search = new URLSearchParams(input.searchParams).toString();
+ }
+ return url.toString();
+}
+
+export function resetSavedEnvironmentRegistryStoreForTests() {
+ useSavedEnvironmentRegistryStore.getState().reset();
+}
+
+export type SavedEnvironmentConnectionState = "connecting" | "connected" | "disconnected" | "error";
+
+export type SavedEnvironmentAuthState = "authenticated" | "requires-auth" | "unknown";
+
+export interface SavedEnvironmentRuntimeState {
+ readonly connectionState: SavedEnvironmentConnectionState;
+ readonly authState: SavedEnvironmentAuthState;
+ readonly lastError: string | null;
+ readonly lastErrorAt: string | null;
+ readonly role: AuthSessionRole | null;
+ readonly descriptor: ExecutionEnvironmentDescriptor | null;
+ readonly serverConfig: ServerConfig | null;
+ readonly connectedAt: string | null;
+ readonly disconnectedAt: string | null;
+}
+
+interface SavedEnvironmentRuntimeStoreState {
+ readonly byId: Record<EnvironmentId, SavedEnvironmentRuntimeState>;
+ readonly ensure: (environmentId: EnvironmentId) => void;
+ readonly patch: (
+ environmentId: EnvironmentId,
+ patch: Partial<SavedEnvironmentRuntimeState>,
+ ) => void;
+ readonly clear: (environmentId: EnvironmentId) => void;
+ readonly reset: () => void;
+}
+
+const DEFAULT_SAVED_ENVIRONMENT_RUNTIME_STATE: SavedEnvironmentRuntimeState = Object.freeze({
+ connectionState: "disconnected",
+ authState: "unknown",
+ lastError: null,
+ lastErrorAt: null,
+ role: null,
+ descriptor: null,
+ serverConfig: null,
+ connectedAt: null,
+ disconnectedAt: null,
+});
+
+function createDefaultSavedEnvironmentRuntimeState(): SavedEnvironmentRuntimeState {
+ return {
+ ...DEFAULT_SAVED_ENVIRONMENT_RUNTIME_STATE,
+ };
+}
+
+export const useSavedEnvironmentRuntimeStore = create<SavedEnvironmentRuntimeStoreState>()(
+ (set) => ({
+ byId: {},
+ ensure: (environmentId) =>
+ set((state) => {
+ if (state.byId[environmentId]) {
+ return state;
+ }
+ return {
+ byId: {
+ ...state.byId,
+ [environmentId]: createDefaultSavedEnvironmentRuntimeState(),
+ },
+ };
+ }),
+ patch: (environmentId, patch) =>
+ set((state) => ({
+ byId: {
+ ...state.byId,
+ [environmentId]: {
+ ...(state.byId[environmentId] ?? createDefaultSavedEnvironmentRuntimeState()),
+ ...patch,
+ },
+ },
+ })),
+ clear: (environmentId) =>
+ set((state) => {
+ const { [environmentId]: _removed, ...remaining } = state.byId;
+ return {
+ byId: remaining,
+ };
+ }),
+ reset: () =>
+ set({
+ byId: {},
+ }),
+ }),
+);
+
+export function getSavedEnvironmentRuntimeState(
+ environmentId: EnvironmentId,
+): SavedEnvironmentRuntimeState {
+ return (
+ useSavedEnvironmentRuntimeStore.getState().byId[environmentId] ??
+ DEFAULT_SAVED_ENVIRONMENT_RUNTIME_STATE
+ );
+}
+
+export function resetSavedEnvironmentRuntimeStoreForTests() {
+ useSavedEnvironmentRuntimeStore.getState().reset();
+}
diff --git a/apps/web/src/environments/runtime/connection.test.ts b/apps/web/src/environments/runtime/connection.test.ts
new file mode 100644
index 000000000..d42471b86
--- /dev/null
+++ b/apps/web/src/environments/runtime/connection.test.ts
@@ -0,0 +1,216 @@
+import { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vitest";
+
+import { createEnvironmentConnection } from "./connection";
+import type { WsRpcClient } from "~/rpc/wsRpcClient";
+
+function createTestClient(options?: {
+ readonly getSnapshot?: () => Promise<{ readonly snapshotSequence: number }>;
+}) {
+ const lifecycleListeners = new Set<(event: any) => void>();
+ const configListeners = new Set<(event: any) => void>();
+ const terminalListeners = new Set<(event: any) => void>();
+
+ const getSnapshot = vi.fn(
+ options?.getSnapshot ??
+ (async () =>
+ ({
+ snapshotSequence: 1,
+ projects: [],
+ threads: [],
+ }) as any),
+ );
+
+ const client = {
+ dispose: vi.fn(async () => undefined),
+ reconnect: vi.fn(async () => undefined),
+ server: {
+ getConfig: vi.fn(async () => ({
+ environment: {
+ environmentId: EnvironmentId.makeUnsafe("env-1"),
+ },
+ })),
+ subscribeConfig: (listener: (event: any) => void) => {
+ configListeners.add(listener);
+ return () => configListeners.delete(listener);
+ },
+ subscribeLifecycle: (listener: (event: any) => void) => {
+ lifecycleListeners.add(listener);
+ return () => lifecycleListeners.delete(listener);
+ },
+ subscribeAuthAccess: () => () => undefined,
+ refreshProviders: vi.fn(async () => undefined),
+ upsertKeybinding: vi.fn(async () => undefined),
+ getSettings: vi.fn(async () => undefined),
+ updateSettings: vi.fn(async () => undefined),
+ },
+ orchestration: {
+ getSnapshot,
+ dispatchCommand: vi.fn(async () => undefined),
+ getTurnDiff: vi.fn(async () => undefined),
+ getFullThreadDiff: vi.fn(async () => undefined),
+ replayEvents: vi.fn(async () => []),
+ onDomainEvent: () => () => undefined,
+ },
+ terminal: {
+ open: vi.fn(async () => undefined),
+ write: vi.fn(async () => undefined),
+ resize: vi.fn(async () => undefined),
+ clear: vi.fn(async () => undefined),
+ restart: vi.fn(async () => undefined),
+ close: vi.fn(async () => undefined),
+ onEvent: (listener: (event: any) => void) => {
+ terminalListeners.add(listener);
+ return () => terminalListeners.delete(listener);
+ },
+ },
+ projects: {
+ searchEntries: vi.fn(async () => []),
+ writeFile: vi.fn(async () => undefined),
+ },
+ shell: {
+ openInEditor: vi.fn(async () => undefined),
+ },
+ git: {
+ pull: vi.fn(async () => undefined),
+ refreshStatus: vi.fn(async () => undefined),
+ onStatus: vi.fn(() => () => undefined),
+ runStackedAction: vi.fn(async () => ({}) as any),
+ listBranches: vi.fn(async () => []),
+ createWorktree: vi.fn(async () => undefined),
+ removeWorktree: vi.fn(async () => undefined),
+ createBranch: vi.fn(async () => undefined),
+ checkout: vi.fn(async () => undefined),
+ init: vi.fn(async () => undefined),
+ resolvePullRequest: vi.fn(async () => undefined),
+ preparePullRequestThread: vi.fn(async () => undefined),
+ },
+ } as unknown as WsRpcClient;
+
+ return {
+ client,
+ getSnapshot,
+ emitWelcome: (environmentId: EnvironmentId) => {
+ for (const listener of lifecycleListeners) {
+ listener({
+ type: "welcome",
+ payload: {
+ environment: {
+ environmentId,
+ },
+ },
+ });
+ }
+ },
+ emitConfigSnapshot: (environmentId: EnvironmentId) => {
+ for (const listener of configListeners) {
+ listener({
+ type: "snapshot",
+ config: {
+ environment: {
+ environmentId,
+ },
+ },
+ });
+ }
+ },
+ };
+}
+
+describe("createEnvironmentConnection", () => {
+ it("bootstraps a snapshot immediately for a new connection", async () => {
+ const environmentId = EnvironmentId.makeUnsafe("env-1");
+ const { client, getSnapshot } = createTestClient();
+ const syncSnapshot = vi.fn();
+
+ const connection = createEnvironmentConnection({
+ kind: "saved",
+ knownEnvironment: {
+ id: "env-1",
+ label: "Remote env",
+ source: "manual",
+ target: {
+ httpBaseUrl: "http://example.test",
+ wsBaseUrl: "ws://example.test",
+ },
+ environmentId,
+ },
+ client,
+ applyEventBatch: vi.fn(),
+ syncSnapshot,
+ applyTerminalEvent: vi.fn(),
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(getSnapshot).toHaveBeenCalledTimes(1);
+ expect(syncSnapshot).toHaveBeenCalledWith(
+ expect.objectContaining({ snapshotSequence: 1 }),
+ environmentId,
+ );
+
+ await connection.dispose();
+ });
+
+ it("rejects welcome/config identity drift", async () => {
+ const environmentId = EnvironmentId.makeUnsafe("env-1");
+ const { client, emitWelcome } = createTestClient();
+
+ const connection = createEnvironmentConnection({
+ kind: "saved",
+ knownEnvironment: {
+ id: "env-1",
+ label: "Remote env",
+ source: "manual",
+ target: {
+ httpBaseUrl: "http://example.test",
+ wsBaseUrl: "ws://example.test",
+ },
+ environmentId,
+ },
+ client,
+ applyEventBatch: vi.fn(),
+ syncSnapshot: vi.fn(),
+ applyTerminalEvent: vi.fn(),
+ });
+
+ expect(() => emitWelcome(EnvironmentId.makeUnsafe("env-2"))).toThrow(
+ "Environment connection env-1 changed identity to env-2 via server lifecycle welcome.",
+ );
+
+ await connection.dispose();
+ });
+
+ it("rejects ensureBootstrapped when snapshot recovery fails", async () => {
+ const environmentId = EnvironmentId.makeUnsafe("env-1");
+ const snapshotError = new Error("snapshot failed");
+ const { client } = createTestClient({
+ getSnapshot: async () => {
+ throw snapshotError;
+ },
+ });
+
+ const connection = createEnvironmentConnection({
+ kind: "saved",
+ knownEnvironment: {
+ id: "env-1",
+ label: "Remote env",
+ source: "manual",
+ target: {
+ httpBaseUrl: "http://example.test",
+ wsBaseUrl: "ws://example.test",
+ },
+ environmentId,
+ },
+ client,
+ applyEventBatch: vi.fn(),
+ syncSnapshot: vi.fn(),
+ applyTerminalEvent: vi.fn(),
+ });
+
+ await expect(connection.ensureBootstrapped()).rejects.toThrow("snapshot failed");
+
+ await connection.dispose();
+ });
+});
diff --git a/apps/web/src/environments/runtime/connection.ts b/apps/web/src/environments/runtime/connection.ts
new file mode 100644
index 000000000..692092527
--- /dev/null
+++ b/apps/web/src/environments/runtime/connection.ts
@@ -0,0 +1,296 @@
+import type {
+ EnvironmentId,
+ OrchestrationEvent,
+ OrchestrationReadModel,
+ ServerConfig,
+ ServerLifecycleWelcomePayload,
+ TerminalEvent,
+} from "@t3tools/contracts";
+import type { KnownEnvironment } from "@t3tools/client-runtime";
+
+import {
+ deriveReplayRetryDecision,
+ type OrchestrationRecoveryReason,
+} from "../../orchestrationRecovery";
+import {
+ createOrchestrationRecoveryCoordinator,
+ type ReplayRetryTracker,
+} from "../../orchestrationRecovery";
+import type { WsRpcClient } from "~/rpc/wsRpcClient";
+
+const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
+const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
+
+export interface EnvironmentConnection {
+ readonly kind: "primary" | "saved";
+ readonly environmentId: EnvironmentId;
+ readonly knownEnvironment: KnownEnvironment;
+ readonly client: WsRpcClient;
+ readonly ensureBootstrapped: () => Promise<void>;
+ readonly reconnect: () => Promise<void>;
+ readonly dispose: () => Promise<void>;
+}
+
+interface OrchestrationHandlers {
+ readonly applyEventBatch: (
+ events: ReadonlyArray<OrchestrationEvent>,
+ environmentId: EnvironmentId,
+ ) => void;
+ readonly syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => void;
+ readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
+}
+
+interface EnvironmentConnectionInput extends OrchestrationHandlers {
+ readonly kind: "primary" | "saved";
+ readonly knownEnvironment: KnownEnvironment;
+ readonly client: WsRpcClient;
+ readonly refreshMetadata?: () => Promise<void>;
+ readonly onConfigSnapshot?: (config: ServerConfig) => void;
+ readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
+}
+
+function createSnapshotBootstrapController(input: {
+ readonly isBootstrapped: () => boolean;
+ readonly runSnapshotRecovery: (
+ reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
+ ) => Promise<void>;
+}) {
+ let inFlight: Promise<void> | null = null;
+
+ return {
+ ensureSnapshotRecovery(
+ reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
+ ): Promise<void> {
+ if (input.isBootstrapped()) {
+ return Promise.resolve();
+ }
+
+ if (inFlight !== null) {
+ return inFlight;
+ }
+
+ const nextInFlight = input.runSnapshotRecovery(reason).finally(() => {
+ if (inFlight === nextInFlight) {
+ inFlight = null;
+ }
+ });
+ inFlight = nextInFlight;
+ return inFlight;
+ },
+ };
+}
+
+export function createEnvironmentConnection(
+ input: EnvironmentConnectionInput,
+): EnvironmentConnection {
+ const recovery = createOrchestrationRecoveryCoordinator();
+ let replayRetryTracker: ReplayRetryTracker | null = null;
+ const pendingDomainEvents: OrchestrationEvent[] = [];
+ let flushPendingDomainEventsScheduled = false;
+ const environmentId = input.knownEnvironment.environmentId;
+
+ if (!environmentId) {
+ throw new Error(
+ `Known environment ${input.knownEnvironment.label} is missing its environmentId.`,
+ );
+ }
+
+ let disposed = false;
+
+ const observeEnvironmentIdentity = (nextEnvironmentId: EnvironmentId, source: string) => {
+ if (environmentId !== nextEnvironmentId) {
+ throw new Error(
+ `Environment connection ${environmentId} changed identity to ${nextEnvironmentId} via ${source}.`,
+ );
+ }
+ };
+
+ const flushPendingDomainEvents = () => {
+ flushPendingDomainEventsScheduled = false;
+ if (disposed || pendingDomainEvents.length === 0) {
+ return;
+ }
+
+ const events = pendingDomainEvents.splice(0, pendingDomainEvents.length);
+ const nextEvents = recovery.markEventBatchApplied(events);
+ if (nextEvents.length === 0) {
+ return;
+ }
+ input.applyEventBatch(nextEvents, environmentId);
+ };
+
+ const schedulePendingDomainEventFlush = () => {
+ if (flushPendingDomainEventsScheduled) {
+ return;
+ }
+
+ flushPendingDomainEventsScheduled = true;
+ queueMicrotask(flushPendingDomainEvents);
+ };
+
+ const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
+ if (!recovery.beginReplayRecovery(reason)) {
+ return;
+ }
+
+ const fromSequenceExclusive = recovery.getState().latestSequence;
+ try {
+ const events = await input.client.orchestration.replayEvents({ fromSequenceExclusive });
+ if (!disposed) {
+ const nextEvents = recovery.markEventBatchApplied(events);
+ if (nextEvents.length > 0) {
+ input.applyEventBatch(nextEvents, environmentId);
+ }
+ }
+ } catch {
+ replayRetryTracker = null;
+ recovery.failReplayRecovery();
+ await snapshotBootstrap.ensureSnapshotRecovery("replay-failed");
+ return;
+ }
+
+ if (disposed) {
+ return;
+ }
+
+ const replayCompletion = recovery.completeReplayRecovery();
+ const retryDecision = deriveReplayRetryDecision({
+ previousTracker: replayRetryTracker,
+ completion: replayCompletion,
+ recoveryState: recovery.getState(),
+ baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
+ maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
+ });
+ replayRetryTracker = retryDecision.tracker;
+
+ if (retryDecision.shouldRetry) {
+ if (retryDecision.delayMs > 0) {
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, retryDecision.delayMs);
+ });
+ if (disposed) {
+ return;
+ }
+ }
+ void runReplayRecovery(reason);
+ } else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
+ console.warn(
+ "[orchestration-recovery]",
+ "Stopping replay recovery after no-progress retries.",
+ {
+ environmentId,
+ state: recovery.getState(),
+ },
+ );
+ }
+ };
+
+ const runSnapshotRecovery = async (
+ reason: Extract<OrchestrationRecoveryReason, "bootstrap" | "replay-failed">,
+ ): Promise<void> => {
+ const started = recovery.beginSnapshotRecovery(reason);
+ if (!started) {
+ return;
+ }
+
+ try {
+ const snapshot = await input.client.orchestration.getSnapshot();
+ if (!disposed) {
+ input.syncSnapshot(snapshot, environmentId);
+ if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
+ void runReplayRecovery("sequence-gap");
+ }
+ }
+ } catch (error) {
+ recovery.failSnapshotRecovery();
+ throw error;
+ }
+ };
+
+ const snapshotBootstrap = createSnapshotBootstrapController({
+ isBootstrapped: () => recovery.getState().bootstrapped,
+ runSnapshotRecovery,
+ });
+
+ const unsubLifecycle = input.client.server.subscribeLifecycle(
+ (event: Parameters<Parameters<WsRpcClient["server"]["subscribeLifecycle"]>[0]>[0]) => {
+ if (event.type !== "welcome") {
+ return;
+ }
+ observeEnvironmentIdentity(
+ event.payload.environment.environmentId,
+ "server lifecycle welcome",
+ );
+ input.onWelcome?.(event.payload);
+ },
+ );
+
+ const unsubConfig = input.client.server.subscribeConfig(
+ (event: Parameters<Parameters<WsRpcClient["server"]["subscribeConfig"]>[0]>[0]) => {
+ if (event.type !== "snapshot") {
+ return;
+ }
+ observeEnvironmentIdentity(event.config.environment.environmentId, "server config snapshot");
+ input.onConfigSnapshot?.(event.config);
+ },
+ );
+
+ const unsubDomainEvent = input.client.orchestration.onDomainEvent(
+ (event: Parameters<Parameters<WsRpcClient["orchestration"]["onDomainEvent"]>[0]>[0]) => {
+ const action = recovery.classifyDomainEvent(event.sequence);
+ if (action === "apply") {
+ pendingDomainEvents.push(event);
+ schedulePendingDomainEventFlush();
+ return;
+ }
+ if (action === "recover") {
+ flushPendingDomainEvents();
+ void runReplayRecovery("sequence-gap");
+ }
+ },
+ {
+ onResubscribe: () => {
+ if (disposed) {
+ return;
+ }
+ flushPendingDomainEvents();
+ void runReplayRecovery("resubscribe");
+ },
+ },
+ );
+
+ const unsubTerminalEvent = input.client.terminal.onEvent(
+ (event: Parameters<Parameters<WsRpcClient["terminal"]["onEvent"]>[0]>[0]) => {
+ input.applyTerminalEvent(event, environmentId);
+ },
+ );
+
+ void snapshotBootstrap.ensureSnapshotRecovery("bootstrap").catch(() => undefined);
+
+ const cleanup = () => {
+ disposed = true;
+ flushPendingDomainEventsScheduled = false;
+ pendingDomainEvents.length = 0;
+ unsubDomainEvent();
+ unsubTerminalEvent();
+ unsubLifecycle();
+ unsubConfig();
+ };
+
+ return {
+ kind: input.kind,
+ environmentId,
+ knownEnvironment: input.knownEnvironment,
+ client: input.client,
+ ensureBootstrapped: () => snapshotBootstrap.ensureSnapshotRecovery("bootstrap"),
+ reconnect: async () => {
+ await input.client.reconnect();
+ await input.refreshMetadata?.();
+ await snapshotBootstrap.ensureSnapshotRecovery("bootstrap");
+ },
+ dispose: async () => {
+ cleanup();
+ await input.client.dispose();
+ },
+ };
+}
diff --git a/apps/web/src/environments/runtime/index.ts b/apps/web/src/environments/runtime/index.ts
new file mode 100644
index 000000000..8c813f108
--- /dev/null
+++ b/apps/web/src/environments/runtime/index.ts
@@ -0,0 +1,29 @@
+export {
+ getEnvironmentHttpBaseUrl,
+ getSavedEnvironmentRecord,
+ getSavedEnvironmentRuntimeState,
+ hasSavedEnvironmentRegistryHydrated,
+ listSavedEnvironmentRecords,
+ resetSavedEnvironmentRegistryStoreForTests,
+ resetSavedEnvironmentRuntimeStoreForTests,
+ resolveEnvironmentHttpUrl,
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+ waitForSavedEnvironmentRegistryHydration,
+ type SavedEnvironmentRecord,
+ type SavedEnvironmentRuntimeState,
+} from "./catalog";
+
+export {
+ addSavedEnvironment,
+ disconnectSavedEnvironment,
+ ensureEnvironmentConnectionBootstrapped,
+ getPrimaryEnvironmentConnection,
+ readEnvironmentConnection,
+ reconnectSavedEnvironment,
+ removeSavedEnvironment,
+ requireEnvironmentConnection,
+ resetEnvironmentServiceForTests,
+ startEnvironmentConnectionService,
+ subscribeEnvironmentConnections,
+} from "./service";
diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts
new file mode 100644
index 000000000..a7083a2d7
--- /dev/null
+++ b/apps/web/src/environments/runtime/service.ts
@@ -0,0 +1,659 @@
+import {
+ type AuthSessionRole,
+ type EnvironmentId,
+ type OrchestrationEvent,
+ type OrchestrationReadModel,
+ type ServerConfig,
+ type TerminalEvent,
+ ThreadId,
+} from "@t3tools/contracts";
+import { type QueryClient } from "@tanstack/react-query";
+import { Throttler } from "@tanstack/react-pacer";
+import {
+ createKnownEnvironment,
+ getKnownEnvironmentWsBaseUrl,
+ scopedProjectKey,
+ scopedThreadKey,
+ scopeProjectRef,
+ scopeThreadRef,
+} from "@t3tools/client-runtime";
+
+import {
+ markPromotedDraftThreadByRef,
+ markPromotedDraftThreadsByRef,
+ useComposerDraftStore,
+} from "~/composerDraftStore";
+import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
+import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
+import { projectQueryKeys } from "~/lib/projectReactQuery";
+import { providerQueryKeys } from "~/lib/providerReactQuery";
+import { getPrimaryKnownEnvironment } from "../primary";
+import {
+ bootstrapRemoteBearerSession,
+ fetchRemoteEnvironmentDescriptor,
+ fetchRemoteSessionState,
+ resolveRemoteWebSocketConnectionUrl,
+} from "../remote/api";
+import { resolveRemotePairingTarget } from "../remote/target";
+import {
+ getSavedEnvironmentRecord,
+ hasSavedEnvironmentRegistryHydrated,
+ listSavedEnvironmentRecords,
+ type SavedEnvironmentRecord,
+ useSavedEnvironmentRegistryStore,
+ useSavedEnvironmentRuntimeStore,
+ waitForSavedEnvironmentRegistryHydration,
+} from "./catalog";
+import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
+import {
+ useStore,
+ selectProjectsAcrossEnvironments,
+ selectThreadByRef,
+ selectThreadsAcrossEnvironments,
+} from "~/store";
+import { useTerminalStateStore } from "~/terminalStateStore";
+import { useUiStateStore } from "~/uiStateStore";
+import { WsTransport } from "../../rpc/wsTransport";
+import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
+
+type EnvironmentServiceState = {
+ readonly queryClient: QueryClient;
+ readonly queryInvalidationThrottler: Throttler<() => void>;
+ refCount: number;
+ stop: () => void;
+};
+
+const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
+const environmentConnectionListeners = new Set<() => void>();
+
+let activeService: EnvironmentServiceState | null = null;
+let needsProviderInvalidation = false;
+
+function emitEnvironmentConnectionRegistryChange() {
+ for (const listener of environmentConnectionListeners) {
+ listener();
+ }
+}
+
+function getRuntimeErrorFields(error: unknown) {
+ return {
+ lastError: error instanceof Error ? error.message : String(error),
+ lastErrorAt: new Date().toISOString(),
+ } as const;
+}
+
+function isoNow(): string {
+ return new Date().toISOString();
+}
+
+function setRuntimeConnecting(environmentId: EnvironmentId) {
+ useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
+ connectionState: "connecting",
+ lastError: null,
+ lastErrorAt: null,
+ });
+}
+
+function setRuntimeConnected(environmentId: EnvironmentId) {
+ const connectedAt = isoNow();
+ useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
+ connectionState: "connected",
+ authState: "authenticated",
+ connectedAt,
+ disconnectedAt: null,
+ lastError: null,
+ lastErrorAt: null,
+ });
+ useSavedEnvironmentRegistryStore.getState().markConnected(environmentId, connectedAt);
+}
+
+function setRuntimeDisconnected(environmentId: EnvironmentId, reason?: string | null) {
+ useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
+ connectionState: "disconnected",
+ disconnectedAt: isoNow(),
+ ...(reason && reason.trim().length > 0
+ ? {
+ lastError: reason,
+ lastErrorAt: isoNow(),
+ }
+ : {}),
+ });
+}
+
+function setRuntimeError(environmentId: EnvironmentId, error: unknown) {
+ useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
+ connectionState: "error",
+ ...getRuntimeErrorFields(error),
+ });
+}
+
+function coalesceOrchestrationUiEvents(
+ events: ReadonlyArray<OrchestrationEvent>,
+): OrchestrationEvent[] {
+ if (events.length < 2) {
+ return [...events];
+ }
+
+ const coalesced: OrchestrationEvent[] = [];
+ for (const event of events) {
+ const previous = coalesced.at(-1);
+ if (
+ previous?.type === "thread.message-sent" &&
+ event.type === "thread.message-sent" &&
+ previous.payload.threadId === event.payload.threadId &&
+ previous.payload.messageId === event.payload.messageId
+ ) {
+ coalesced[coalesced.length - 1] = {
+ ...event,
+ payload: {
+ ...event.payload,
+ attachments: event.payload.attachments ?? previous.payload.attachments,
+ createdAt: previous.payload.createdAt,
+ text:
+ !event.payload.streaming && event.payload.text.length > 0
+ ? event.payload.text
+ : previous.payload.text + event.payload.text,
+ },
+ };
+ continue;
+ }
+
+ coalesced.push(event);
+ }
+
+ return coalesced;
+}
+
+function reconcileSnapshotDerivedState() {
+ const storeState = useStore.getState();
+ const threads = selectThreadsAcrossEnvironments(storeState);
+ const projects = selectProjectsAcrossEnvironments(storeState);
+
+ useUiStateStore.getState().syncProjects(
+ projects.map((project) => ({
+ key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
+ cwd: project.cwd,
+ })),
+ );
+ useUiStateStore.getState().syncThreads(
+ threads.map((thread) => ({
+ key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ seedVisitedAt: thread.updatedAt ?? thread.createdAt,
+ })),
+ );
+ markPromotedDraftThreadsByRef(
+ threads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
+ );
+
+ const activeThreadKeys = collectActiveTerminalThreadIds({
+ snapshotThreads: threads.map((thread) => ({
+ key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ deletedAt: null,
+ archivedAt: thread.archivedAt,
+ })),
+ draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(),
+ });
+ useTerminalStateStore.getState().removeOrphanedTerminalStates(activeThreadKeys);
+}
+
+function applyRecoveredEventBatch(
+ events: ReadonlyArray<OrchestrationEvent>,
+ environmentId: EnvironmentId,
+) {
+ if (events.length === 0) {
+ return;
+ }
+
+ const batchEffects = deriveOrchestrationBatchEffects(events);
+ const uiEvents = coalesceOrchestrationUiEvents(events);
+ const needsProjectUiSync = events.some(
+ (event) =>
+ event.type === "project.created" ||
+ event.type === "project.meta-updated" ||
+ event.type === "project.deleted",
+ );
+
+ if (batchEffects.needsProviderInvalidation) {
+ needsProviderInvalidation = true;
+ void activeService?.queryInvalidationThrottler.maybeExecute();
+ }
+
+ useStore.getState().applyOrchestrationEvents(uiEvents, environmentId);
+ if (needsProjectUiSync) {
+ const projects = selectProjectsAcrossEnvironments(useStore.getState());
+ useUiStateStore.getState().syncProjects(
+ projects.map((project) => ({
+ key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
+ cwd: project.cwd,
+ })),
+ );
+ }
+
+ const needsThreadUiSync = events.some(
+ (event) => event.type === "thread.created" || event.type === "thread.deleted",
+ );
+ if (needsThreadUiSync) {
+ const threads = selectThreadsAcrossEnvironments(useStore.getState());
+ useUiStateStore.getState().syncThreads(
+ threads.map((thread) => ({
+ key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
+ seedVisitedAt: thread.updatedAt ?? thread.createdAt,
+ })),
+ );
+ }
+
+ const draftStore = useComposerDraftStore.getState();
+ for (const threadId of batchEffects.promoteDraftThreadIds) {
+ markPromotedDraftThreadByRef(scopeThreadRef(environmentId, threadId));
+ }
+ for (const threadId of batchEffects.clearDeletedThreadIds) {
+ draftStore.clearDraftThread(scopeThreadRef(environmentId, threadId));
+ useUiStateStore
+ .getState()
+ .clearThreadUi(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
+ }
+ for (const threadId of batchEffects.removeTerminalStateThreadIds) {
+ useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId));
+ }
+}
+
+function createEnvironmentConnectionHandlers() {
+ return {
+ applyEventBatch: applyRecoveredEventBatch,
+ syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => {
+ useStore.getState().syncServerReadModel(snapshot, environmentId);
+ reconcileSnapshotDerivedState();
+ },
+ applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => {
+ const threadRef = scopeThreadRef(environmentId, ThreadId.makeUnsafe(event.threadId));
+ const thread = selectThreadByRef(useStore.getState(), threadRef);
+ if (!thread || thread.archivedAt !== null) {
+ return;
+ }
+ useTerminalStateStore.getState().applyTerminalEvent(threadRef, event);
+ },
+ };
+}
+
+function createPrimaryEnvironmentClient(
+ knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
+) {
+ const wsBaseUrl = getKnownEnvironmentWsBaseUrl(knownEnvironment);
+ if (!wsBaseUrl) {
+ throw new Error(
+ `Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
+ );
+ }
+
+ return createWsRpcClient(new WsTransport(wsBaseUrl));
+}
+
+function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClient {
+ useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
+
+ return createWsRpcClient(
+ new WsTransport(
+ () =>
+ resolveRemoteWebSocketConnectionUrl({
+ wsBaseUrl: record.wsBaseUrl,
+ httpBaseUrl: record.httpBaseUrl,
+ bearerToken: record.bearerToken,
+ }),
+ {
+ onAttempt: () => {
+ setRuntimeConnecting(record.environmentId);
+ },
+ onOpen: () => {
+ setRuntimeConnected(record.environmentId);
+ },
+ onError: (message: string) => {
+ useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
+ connectionState: "error",
+ lastError: message,
+ lastErrorAt: isoNow(),
+ });
+ },
+ onClose: (details: { readonly code: number; readonly reason: string }) => {
+ setRuntimeDisconnected(record.environmentId, details.reason);
+ },
+ },
+ ),
+ );
+}
+
+async function refreshSavedEnvironmentMetadata(
+ record: SavedEnvironmentRecord,
+ client: WsRpcClient,
+ roleHint?: AuthSessionRole | null,
+ configHint?: ServerConfig | null,
+): Promise<void> {
+ const [serverConfig, sessionState] = await Promise.all([
+ configHint ? Promise.resolve(configHint) : client.server.getConfig(),
+ fetchRemoteSessionState({
+ httpBaseUrl: record.httpBaseUrl,
+ bearerToken: record.bearerToken,
+ }),
+ ]);
+
+ useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
+ authState: sessionState.authenticated ? "authenticated" : "requires-auth",
+ descriptor: serverConfig.environment,
+ serverConfig,
+ role: sessionState.authenticated ? (sessionState.role ?? roleHint ?? null) : null,
+ });
+}
+
+function registerConnection(connection: EnvironmentConnection): EnvironmentConnection {
+ const existing = environmentConnections.get(connection.environmentId);
+ if (existing && existing !== connection) {
+ throw new Error(`Environment ${connection.environmentId} already has an active connection.`);
+ }
+ environmentConnections.set(connection.environmentId, connection);
+ emitEnvironmentConnectionRegistryChange();
+ return connection;
+}
+
+async function removeConnection(environmentId: EnvironmentId): Promise<boolean> {
+ const connection = environmentConnections.get(environmentId);
+ if (!connection) {
+ return false;
+ }
+
+ environmentConnections.delete(environmentId);
+ emitEnvironmentConnectionRegistryChange();
+ await connection.dispose();
+ return true;
+}
+
+function createPrimaryEnvironmentConnection(): EnvironmentConnection {
+ const knownEnvironment = getPrimaryKnownEnvironment();
+ if (!knownEnvironment?.environmentId) {
+ throw new Error("Unable to resolve the primary environment.");
+ }
+
+ const existing = environmentConnections.get(knownEnvironment.environmentId);
+ if (existing) {
+ return existing;
+ }
+
+ return registerConnection(
+ createEnvironmentConnection({
+ kind: "primary",
+ knownEnvironment,
+ client: createPrimaryEnvironmentClient(knownEnvironment),
+ ...createEnvironmentConnectionHandlers(),
+ }),
+ );
+}
+
+async function ensureSavedEnvironmentConnection(
+ record: SavedEnvironmentRecord,
+ options?: {
+ readonly client?: WsRpcClient;
+ readonly role?: AuthSessionRole | null;
+ readonly serverConfig?: ServerConfig | null;
+ },
+): Promise<EnvironmentConnection> {
+ const existing = environmentConnections.get(record.environmentId);
+ if (existing) {
+ return existing;
+ }
+
+ const client = options?.client ?? createSavedEnvironmentClient(record);
+ const knownEnvironment = createKnownEnvironment({
+ id: record.environmentId,
+ label: record.label,
+ source: "manual",
+ target: {
+ httpBaseUrl: record.httpBaseUrl,
+ wsBaseUrl: record.wsBaseUrl,
+ },
+ });
+ const connection = createEnvironmentConnection({
+ kind: "saved",
+ knownEnvironment: {
+ ...knownEnvironment,
+ environmentId: record.environmentId,
+ },
+ client,
+ refreshMetadata: async () => {
+ await refreshSavedEnvironmentMetadata(record, client);
+ },
+ onConfigSnapshot: (config) => {
+ useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
+ descriptor: config.environment,
+ serverConfig: config,
+ });
+ },
+ onWelcome: (payload) => {
+ useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
+ descriptor: payload.environment,
+ });
+ },
+ ...createEnvironmentConnectionHandlers(),
+ });
+
+ registerConnection(connection);
+
+ try {
+ await refreshSavedEnvironmentMetadata(
+ record,
+ client,
+ options?.role ?? null,
+ options?.serverConfig ?? null,
+ );
+ return connection;
+ } catch (error) {
+ setRuntimeError(record.environmentId, error);
+ await removeConnection(record.environmentId).catch(() => false);
+ throw error;
+ }
+}
+
+async function syncSavedEnvironmentConnections(
+ records: ReadonlyArray<SavedEnvironmentRecord>,
+): Promise<void> {
+ const expectedEnvironmentIds = new Set(records.map((record) => record.environmentId));
+ const staleEnvironmentIds = [...environmentConnections.values()]
+ .filter((connection) => connection.kind === "saved")
+ .map((connection) => connection.environmentId)
+ .filter((environmentId) => !expectedEnvironmentIds.has(environmentId));
+
+ await Promise.all(
+ staleEnvironmentIds.map((environmentId) => disconnectSavedEnvironment(environmentId)),
+ );
+ await Promise.all(
+ records.map((record) => ensureSavedEnvironmentConnection(record).catch(() => undefined)),
+ );
+}
+
+function stopActiveService() {
+ activeService?.stop();
+ activeService = null;
+}
+
+export function subscribeEnvironmentConnections(listener: () => void): () => void {
+ environmentConnectionListeners.add(listener);
+ return () => {
+ environmentConnectionListeners.delete(listener);
+ };
+}
+
+export function listEnvironmentConnections(): ReadonlyArray<EnvironmentConnection> {
+ return [...environmentConnections.values()];
+}
+
+export function readEnvironmentConnection(
+ environmentId: EnvironmentId,
+): EnvironmentConnection | null {
+ return environmentConnections.get(environmentId) ?? null;
+}
+
+export function requireEnvironmentConnection(environmentId: EnvironmentId): EnvironmentConnection {
+ const connection = readEnvironmentConnection(environmentId);
+ if (!connection) {
+ throw new Error(`No websocket client registered for environment ${environmentId}.`);
+ }
+ return connection;
+}
+
+export function getPrimaryEnvironmentConnection(): EnvironmentConnection {
+ return createPrimaryEnvironmentConnection();
+}
+
+export async function disconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
+ const connection = environmentConnections.get(environmentId);
+ if (connection?.kind !== "saved") {
+ return;
+ }
+
+ useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
+ await removeConnection(environmentId).catch(() => false);
+}
+
+export async function reconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
+ const record = getSavedEnvironmentRecord(environmentId);
+ if (!record) {
+ throw new Error("Saved environment not found.");
+ }
+
+ const connection = environmentConnections.get(environmentId);
+ if (!connection) {
+ await ensureSavedEnvironmentConnection(record);
+ return;
+ }
+
+ setRuntimeConnecting(environmentId);
+ try {
+ await connection.reconnect();
+ } catch (error) {
+ setRuntimeError(environmentId, error);
+ throw error;
+ }
+}
+
+export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
+ useSavedEnvironmentRegistryStore.getState().remove(environmentId);
+ await disconnectSavedEnvironment(environmentId);
+}
+
+export async function addSavedEnvironment(input: {
+ readonly label: string;
+ readonly pairingUrl?: string;
+ readonly host?: string;
+ readonly pairingCode?: string;
+}): Promise<SavedEnvironmentRecord> {
+ const resolvedTarget = resolveRemotePairingTarget({
+ ...(input.pairingUrl !== undefined ? { pairingUrl: input.pairingUrl } : {}),
+ ...(input.host !== undefined ? { host: input.host } : {}),
+ ...(input.pairingCode !== undefined ? { pairingCode: input.pairingCode } : {}),
+ });
+ const descriptor = await fetchRemoteEnvironmentDescriptor({
+ httpBaseUrl: resolvedTarget.httpBaseUrl,
+ });
+ const environmentId = descriptor.environmentId;
+
+ if (environmentConnections.has(environmentId)) {
+ throw new Error("This environment is already connected.");
+ }
+
+ const bearerSession = await bootstrapRemoteBearerSession({
+ httpBaseUrl: resolvedTarget.httpBaseUrl,
+ credential: resolvedTarget.credential,
+ });
+
+ const record: SavedEnvironmentRecord = {
+ environmentId,
+ label: input.label.trim() || descriptor.label,
+ wsBaseUrl: resolvedTarget.wsBaseUrl,
+ httpBaseUrl: resolvedTarget.httpBaseUrl,
+ bearerToken: bearerSession.sessionToken,
+ createdAt: isoNow(),
+ lastConnectedAt: isoNow(),
+ };
+
+ await ensureSavedEnvironmentConnection(record, {
+ role: bearerSession.role,
+ });
+ useSavedEnvironmentRegistryStore.getState().upsert(record);
+ return record;
+}
+
+export async function ensureEnvironmentConnectionBootstrapped(
+ environmentId: EnvironmentId,
+): Promise<void> {
+ await environmentConnections.get(environmentId)?.ensureBootstrapped();
+}
+
+export function startEnvironmentConnectionService(queryClient: QueryClient): () => void {
+ if (activeService?.queryClient === queryClient) {
+ activeService.refCount += 1;
+ return () => {
+ if (!activeService || activeService.queryClient !== queryClient) {
+ return;
+ }
+ activeService.refCount -= 1;
+ if (activeService.refCount === 0) {
+ stopActiveService();
+ }
+ };
+ }
+
+ stopActiveService();
+ needsProviderInvalidation = false;
+ const queryInvalidationThrottler = new Throttler(
+ () => {
+ if (!needsProviderInvalidation) {
+ return;
+ }
+ needsProviderInvalidation = false;
+ void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
+ void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
+ },
+ {
+ wait: 100,
+ leading: false,
+ trailing: true,
+ },
+ );
+
+ createPrimaryEnvironmentConnection();
+
+ const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => {
+ if (!hasSavedEnvironmentRegistryHydrated()) {
+ return;
+ }
+ void syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
+ });
+
+ void waitForSavedEnvironmentRegistryHydration()
+ .then(() => syncSavedEnvironmentConnections(listSavedEnvironmentRecords()))
+ .catch(() => undefined);
+
+ activeService = {
+ queryClient,
+ queryInvalidationThrottler,
+ refCount: 1,
+ stop: () => {
+ unsubscribeSavedEnvironments();
+ queryInvalidationThrottler.cancel();
+ },
+ };
+
+ return () => {
+ if (!activeService || activeService.queryClient !== queryClient) {
+ return;
+ }
+ activeService.refCount -= 1;
+ if (activeService.refCount === 0) {
+ stopActiveService();
+ }
+ };
+}
+
+export async function resetEnvironmentServiceForTests(): Promise<void> {
+ stopActiveService();
+ await Promise.all(
+ [...environmentConnections.keys()].map((environmentId) => removeConnection(environmentId)),
+ );
+}
diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts
index 6afe83dfe..d903151e8 100644
--- a/apps/web/src/hooks/useTheme.ts
+++ b/apps/web/src/hooks/useTheme.ts
@@ -8,6 +8,8 @@ type ThemeSnapshot = {
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
+const THEME_COLOR_META_NAME = "theme-color";
+const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
@@ -26,12 +28,63 @@ function getStored(): Theme {
return "system";
}
+function ensureThemeColorMetaTag(): HTMLMetaElement {
+ let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
+ if (element) {
+ return element;
+ }
+
+ element = document.createElement("meta");
+ element.name = THEME_COLOR_META_NAME;
+ element.setAttribute("data-dynamic-theme-color", "true");
+ document.head.append(element);
+ return element;
+}
+
+function normalizeThemeColor(value: string | null | undefined): string | null {
+ const normalizedValue = value?.trim().toLowerCase();
+ if (
+ !normalizedValue ||
+ normalizedValue === "transparent" ||
+ normalizedValue === "rgba(0, 0, 0, 0)" ||
+ normalizedValue === "rgba(0 0 0 / 0)"
+ ) {
+ return null;
+ }
+
+ return value?.trim() ?? null;
+}
+
+function resolveBrowserChromeSurface(): HTMLElement {
+ return (
+ document.querySelector<HTMLElement>("main[data-slot='sidebar-inset']") ??
+ document.querySelector<HTMLElement>("[data-slot='sidebar-inner']") ??
+ document.body
+ );
+}
+
+export function syncBrowserChromeTheme() {
+ if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
+ const surfaceColor = normalizeThemeColor(
+ getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
+ );
+ const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
+ const backgroundColor = surfaceColor ?? fallbackColor;
+ if (!backgroundColor) return;
+
+ document.documentElement.style.backgroundColor = backgroundColor;
+ document.body.style.backgroundColor = backgroundColor;
+ ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
+}
+
function applyTheme(theme: Theme, suppressTransitions = false) {
+ if (typeof document === "undefined") return;
if (suppressTransitions) {
document.documentElement.classList.add("no-transitions");
}
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
document.documentElement.classList.toggle("dark", isDark);
+ syncBrowserChromeTheme();
syncDesktopTheme(theme);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index ea76f24fa..120a3ea5e 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -47,8 +47,12 @@
* {
@apply border-border outline-ring/50;
}
+ html {
+ background-color: var(--app-chrome-background);
+ }
body {
- @apply bg-background text-foreground relative;
+ @apply text-foreground relative;
+ background-color: var(--app-chrome-background);
}
}
@@ -65,6 +69,7 @@
color-scheme: light;
--radius: 0.625rem;
--background: var(--color-white);
+ --app-chrome-background: var(--background);
--foreground: var(--color-neutral-800);
--card: var(--color-white);
--card-foreground: var(--color-neutral-800);
@@ -93,6 +98,7 @@
@variant dark {
color-scheme: dark;
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
+ --app-chrome-background: var(--background);
--foreground: var(--color-neutral-100);
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
--card-foreground: var(--color-neutral-100);
@@ -157,9 +163,7 @@ body::after {
}
pre,
-code,
-textarea,
-input {
+code {
font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}
diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.ts
index 5651a19b0..68d2b5bf5 100644
--- a/apps/web/src/lib/gitReactQuery.ts
+++ b/apps/web/src/lib/gitReactQuery.ts
@@ -11,7 +11,7 @@ import {
type QueryClient,
} from "@tanstack/react-query";
import { ensureEnvironmentApi } from "../environmentApi";
-import { getWsRpcClientForEnvironment } from "../wsRpcClient";
+import { requireEnvironmentConnection } from "../environments/runtime";
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
@@ -180,7 +180,7 @@ export function gitRunStackedActionMutationOptions(input: {
onProgress?: (event: GitActionProgressEvent) => void;
}) => {
if (!input.cwd || !input.environmentId) throw new Error("Git action is unavailable.");
- return getWsRpcClientForEnvironment(input.environmentId).git.runStackedAction(
+ return requireEnvironmentConnection(input.environmentId).client.git.runStackedAction(
{
action,
actionId,
diff --git a/apps/web/src/lib/gitStatusState.test.ts b/apps/web/src/lib/gitStatusState.test.ts
index 5ffed921b..ef61e4e94 100644
--- a/apps/web/src/lib/gitStatusState.test.ts
+++ b/apps/web/src/lib/gitStatusState.test.ts
@@ -1,6 +1,8 @@
import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
+import type { WsRpcClient } from "../rpc/wsRpcClient";
+import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
import {
getGitStatusSnapshot,
resetGitStatusStateForTests,
@@ -8,6 +10,22 @@ import {
watchGitStatus,
} from "./gitStatusState";
+const serviceHarness = vi.hoisted(() => ({
+ connections: new Map<string, any>(),
+ listeners: new Set<() => void>(),
+}));
+
+vi.mock("../environments/runtime/service", () => ({
+ readEnvironmentConnection: (environmentId: string) =>
+ serviceHarness.connections.get(environmentId) ?? null,
+ subscribeEnvironmentConnections: (listener: () => void) => {
+ serviceHarness.listeners.add(listener);
+ return () => {
+ serviceHarness.listeners.delete(listener);
+ };
+ },
+}));
+
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
@@ -50,11 +68,110 @@ function emitGitStatus(event: GitStatusResult) {
}
}
-afterEach(() => {
+function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
+ const listeners = new Set<(event: GitStatusResult) => void>();
+ const client = {
+ dispose: vi.fn(async () => undefined),
+ reconnect: vi.fn(async () => undefined),
+ terminal: {
+ open: vi.fn(async () => undefined),
+ write: vi.fn(async () => undefined),
+ resize: vi.fn(async () => undefined),
+ clear: vi.fn(async () => undefined),
+ restart: vi.fn(async () => undefined),
+ close: vi.fn(async () => undefined),
+ onEvent: vi.fn(() => () => undefined),
+ },
+ projects: {
+ searchEntries: vi.fn(async () => []),
+ writeFile: vi.fn(async () => undefined),
+ },
+ shell: {
+ openInEditor: vi.fn(async () => undefined),
+ },
+ git: {
+ pull: vi.fn(async () => undefined),
+ refreshStatus: vi.fn(async (input: { cwd: string }) => ({
+ ...BASE_STATUS,
+ branch: `${input.cwd}-refreshed`,
+ })),
+ onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
+ registerListener(listeners, listener),
+ ),
+ runStackedAction: vi.fn(async () => ({}) as any),
+ listBranches: vi.fn(async () => []),
+ createWorktree: vi.fn(async () => undefined),
+ removeWorktree: vi.fn(async () => undefined),
+ createBranch: vi.fn(async () => undefined),
+ checkout: vi.fn(async () => undefined),
+ init: vi.fn(async () => undefined),
+ resolvePullRequest: vi.fn(async () => undefined),
+ preparePullRequestThread: vi.fn(async () => undefined),
+ },
+ server: {
+ getConfig: vi.fn(async () => ({
+ environment: {
+ environmentId,
+ },
+ })),
+ refreshProviders: vi.fn(async () => undefined),
+ upsertKeybinding: vi.fn(async () => undefined),
+ getSettings: vi.fn(async () => undefined),
+ updateSettings: vi.fn(async () => undefined),
+ subscribeConfig: vi.fn(() => () => undefined),
+ subscribeLifecycle: vi.fn(() => () => undefined),
+ subscribeAuthAccess: vi.fn(() => () => undefined),
+ },
+ orchestration: {
+ getSnapshot: vi.fn(async () => ({ snapshotSequence: 1, projects: [], threads: [] }) as any),
+ dispatchCommand: vi.fn(async () => undefined),
+ getTurnDiff: vi.fn(async () => undefined),
+ getFullThreadDiff: vi.fn(async () => undefined),
+ replayEvents: vi.fn(async () => []),
+ onDomainEvent: vi.fn(() => () => undefined),
+ },
+ } as unknown as WsRpcClient;
+
+ serviceHarness.connections.set(environmentId, {
+ kind: "saved" as const,
+ knownEnvironment: {
+ id: environmentId,
+ label: `Environment ${environmentId}`,
+ source: "manual" as const,
+ environmentId,
+ target: {
+ httpBaseUrl: "http://example.test",
+ wsBaseUrl: "ws://example.test",
+ },
+ },
+ client,
+ environmentId,
+ ensureBootstrapped: async () => undefined,
+ reconnect: async () => undefined,
+ dispose: async () => undefined,
+ });
+ for (const listener of serviceHarness.listeners) {
+ listener();
+ }
+
+ return {
+ client,
+ emit: (event: GitStatusResult) => {
+ for (const listener of listeners) {
+ listener(event);
+ }
+ },
+ };
+}
+
+afterEach(async () => {
gitStatusListeners.clear();
+ serviceHarness.connections.clear();
+ serviceHarness.listeners.clear();
gitClient.onStatus.mockClear();
gitClient.refreshStatus.mockClear();
resetGitStatusStateForTests();
+ resetAppAtomRegistryForTests();
});
describe("gitStatusState", () => {
@@ -147,4 +264,63 @@ describe("gitStatusState", () => {
releaseLocal();
releaseRemote();
});
+
+ it("waits for a delayed environment client registration instead of throwing", () => {
+ const release = watchGitStatus(TARGET);
+
+ expect(getGitStatusSnapshot(TARGET)).toEqual({
+ data: null,
+ error: null,
+ cause: null,
+ isPending: true,
+ });
+
+ const registered = createRegisteredGitStatusClient(ENVIRONMENT_ID);
+ registered.emit(BASE_STATUS);
+
+ expect(getGitStatusSnapshot(TARGET)).toEqual({
+ data: BASE_STATUS,
+ error: null,
+ cause: null,
+ isPending: false,
+ });
+
+ release();
+ });
+
+ it("resubscribes after the environment client is removed and re-registered", async () => {
+ const firstClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
+ const release = watchGitStatus(TARGET);
+
+ firstClient.emit(BASE_STATUS);
+ expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
+
+ serviceHarness.connections.delete(ENVIRONMENT_ID);
+ for (const listener of serviceHarness.listeners) {
+ listener();
+ }
+
+ expect(getGitStatusSnapshot(TARGET)).toEqual({
+ data: BASE_STATUS,
+ error: null,
+ cause: null,
+ isPending: true,
+ });
+
+ const secondClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
+ secondClient.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
+
+ expect(getGitStatusSnapshot(TARGET)).toEqual({
+ data: { ...BASE_STATUS, branch: "reconnected-branch" },
+ error: null,
+ cause: null,
+ isPending: false,
+ });
+
+ release();
+ });
+
+ it("returns the cached snapshot when refresh is requested before the client is registered", async () => {
+ await expect(refreshGitStatus(TARGET)).resolves.toBeNull();
+ });
});
diff --git a/apps/web/src/lib/gitStatusState.ts b/apps/web/src/lib/gitStatusState.ts
index cabd2d9b9..2c23ae5b8 100644
--- a/apps/web/src/lib/gitStatusState.ts
+++ b/apps/web/src/lib/gitStatusState.ts
@@ -9,25 +9,31 @@ import { Atom } from "effect/unstable/reactivity";
import { useEffect } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
-import { getWsRpcClient, getWsRpcClientForEnvironment, type WsRpcClient } from "../wsRpcClient";
-
-export type GitStatusStreamError = GitManagerServiceError;
+import {
+ readEnvironmentConnection,
+ subscribeEnvironmentConnections,
+} from "../environments/runtime";
+import type { WsRpcClient } from "~/rpc/wsRpcClient";
-export interface GitStatusState {
+interface GitStatusState {
readonly data: GitStatusResult | null;
- readonly error: GitStatusStreamError | null;
- readonly cause: Cause.Cause<GitStatusStreamError> | null;
+ readonly error: GitManagerServiceError | null;
+ readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
+interface ResolvedGitStatusClient {
+ readonly clientIdentity: string;
+ readonly client: GitStatusClient;
+}
interface WatchedGitStatus {
refCount: number;
unsubscribe: () => void;
}
-export interface GitStatusTarget {
+interface GitStatusTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
}
@@ -64,18 +70,21 @@ const gitStatusStateAtom = Atom.family((key: string) => {
});
function getGitStatusTargetKey(target: GitStatusTarget): string | null {
- if (target.cwd === null) {
+ if (target.environmentId === null || target.cwd === null) {
return null;
}
- return `${target.environmentId ?? "__default__"}:${target.cwd}`;
+ return `${target.environmentId}:${target.cwd}`;
}
-function resolveGitStatusClient(target: GitStatusTarget): GitStatusClient {
- if (target.environmentId) {
- return getWsRpcClientForEnvironment(target.environmentId).git;
+function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatusClient | null {
+ if (target.environmentId === null) {
+ return null;
}
- return getWsRpcClient().git;
+ const connection = readEnvironmentConnection(target.environmentId);
+ return connection
+ ? { clientIdentity: connection.environmentId, client: connection.client.git }
+ : null;
}
export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
@@ -87,10 +96,7 @@ export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
return appAtomRegistry.get(gitStatusStateAtom(targetKey));
}
-export function watchGitStatus(
- target: GitStatusTarget,
- client: GitStatusClient = resolveGitStatusClient(target),
-): () => void {
+export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) {
return NOOP;
@@ -104,7 +110,7 @@ export function watchGitStatus(
watchedGitStatuses.set(targetKey, {
refCount: 1,
- unsubscribe: subscribeToGitStatus(targetKey, target.cwd!, client),
+ unsubscribe: subscribeToGitStatusTarget(targetKey, target, client),
});
return () => unwatchGitStatus(targetKey);
@@ -112,13 +118,18 @@ export function watchGitStatus(
export function refreshGitStatus(
target: GitStatusTarget,
- client: GitStatusClient = resolveGitStatusClient(target),
+ client?: GitStatusClient,
): Promise<GitStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
+ const resolvedClient = client ?? readResolvedGitStatusClient(target)?.client;
+ if (!resolvedClient) {
+ return Promise.resolve(getGitStatusSnapshot(target).data);
+ }
+
const currentInFlight = gitStatusRefreshInFlight.get(targetKey);
if (currentInFlight) {
return currentInFlight;
@@ -130,7 +141,7 @@ export function refreshGitStatus(
}
gitStatusLastRefreshAtByKey.set(targetKey, Date.now());
- const refreshPromise = client.refreshStatus({ cwd: target.cwd }).finally(() => {
+ const refreshPromise = resolvedClient.refreshStatus({ cwd: target.cwd }).finally(() => {
gitStatusRefreshInFlight.delete(targetKey);
});
gitStatusRefreshInFlight.set(targetKey, refreshPromise);
@@ -179,11 +190,62 @@ function unwatchGitStatus(targetKey: string): void {
watchedGitStatuses.delete(targetKey);
}
+function subscribeToGitStatusTarget(
+ targetKey: string,
+ target: GitStatusTarget,
+ providedClient?: GitStatusClient,
+): () => void {
+ if (target.cwd === null) {
+ return NOOP;
+ }
+
+ const cwd = target.cwd;
+ let currentClientIdentity: string | null = null;
+ let currentUnsubscribe = NOOP;
+
+ const syncClientSubscription = () => {
+ const resolved = providedClient
+ ? {
+ clientIdentity: `provided:${targetKey}`,
+ client: providedClient,
+ }
+ : readResolvedGitStatusClient(target);
+
+ if (!resolved) {
+ if (currentClientIdentity !== null) {
+ currentUnsubscribe();
+ currentUnsubscribe = NOOP;
+ currentClientIdentity = null;
+ }
+ markGitStatusPending(targetKey);
+ return;
+ }
+
+ if (currentClientIdentity === resolved.clientIdentity) {
+ return;
+ }
+
+ currentUnsubscribe();
+ currentClientIdentity = resolved.clientIdentity;
+ currentUnsubscribe = subscribeToGitStatus(targetKey, cwd, resolved.client);
+ };
+
+ const unsubscribeRegistry = providedClient
+ ? NOOP
+ : subscribeEnvironmentConnections(syncClientSubscription);
+ syncClientSubscription();
+
+ return () => {
+ unsubscribeRegistry();
+ currentUnsubscribe();
+ };
+}
+
function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusClient): () => void {
markGitStatusPending(targetKey);
return client.onStatus(
{ cwd },
- (status) => {
+ (status: GitStatusResult) => {
appAtomRegistry.set(gitStatusStateAtom(targetKey), {
data: status,
error: null,
diff --git a/apps/web/src/lib/utils.test.ts b/apps/web/src/lib/utils.test.ts
index 317933d67..35785f426 100644
--- a/apps/web/src/lib/utils.test.ts
+++ b/apps/web/src/lib/utils.test.ts
@@ -1,15 +1,5 @@
-import { assert, describe, expect, it, vi } from "vitest";
-
-const { resolvePrimaryEnvironmentBootstrapUrlMock } = vi.hoisted(() => ({
- resolvePrimaryEnvironmentBootstrapUrlMock: vi.fn(() => "http://bootstrap.test:4321"),
-}));
-
-vi.mock("../environmentBootstrap", () => ({
- resolvePrimaryEnvironmentBootstrapUrl: resolvePrimaryEnvironmentBootstrapUrlMock,
-}));
-
+import { describe, assert, it } from "vitest";
import { isWindowsPlatform } from "./utils";
-import { resolveServerUrl } from "./utils";
describe("isWindowsPlatform", () => {
it("matches Windows platform identifiers", () => {
@@ -22,34 +12,3 @@ describe("isWindowsPlatform", () => {
assert.isFalse(isWindowsPlatform("darwin"));
});
});
-
-describe("resolveServerUrl", () => {
- it("falls back to the bootstrap environment URL when the explicit URL is empty", () => {
- expect(resolveServerUrl({ url: "" })).toBe("http://bootstrap.test:4321/");
- });
-
- it("uses the bootstrap environment URL when no explicit URL is provided", () => {
- expect(resolveServerUrl()).toBe("http://bootstrap.test:4321/");
- });
-
- it("prefers an explicit URL override", () => {
- expect(
- resolveServerUrl({
- url: "https://override.test:9999",
- protocol: "wss",
- pathname: "/rpc",
- searchParams: { hello: "world" },
- }),
- ).toBe("wss://override.test:9999/rpc?hello=world");
- });
-
- it("does not evaluate the bootstrap resolver when an explicit URL is provided", () => {
- resolvePrimaryEnvironmentBootstrapUrlMock.mockImplementationOnce(() => {
- throw new Error("bootstrap unavailable");
- });
-
- expect(resolveServerUrl({ url: "https://override.test:9999" })).toBe(
- "https://override.test:9999/",
- );
- });
-});
diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts
index 27800b3a6..541693619 100644
--- a/apps/web/src/lib/utils.ts
+++ b/apps/web/src/lib/utils.ts
@@ -1,10 +1,8 @@
import { CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
-import { String, Predicate } from "effect";
import { type CxOptions, cx } from "class-variance-authority";
import { twMerge } from "tailwind-merge";
import * as Random from "effect/Random";
import * as Effect from "effect/Effect";
-import { resolvePrimaryEnvironmentBootstrapUrl } from "../environmentBootstrap";
import { DraftId } from "../composerDraftStore";
export function cn(...inputs: CxOptions) {
@@ -39,30 +37,3 @@ export const newThreadId = (): ThreadId => ThreadId.makeUnsafe(randomUUID());
export const newDraftId = (): DraftId => DraftId.makeUnsafe(randomUUID());
export const newMessageId = (): MessageId => MessageId.makeUnsafe(randomUUID());
-
-const isNonEmptyString = Predicate.compose(Predicate.isString, String.isNonEmpty);
-
-export const resolveServerUrl = (options?: {
- url?: string | undefined;
- protocol?: "http" | "https" | "ws" | "wss" | undefined;
- pathname?: string | undefined;
- searchParams?: Record<string, string> | undefined;
-}): string => {
- const rawUrl = isNonEmptyString(options?.url)
- ? options.url
- : resolvePrimaryEnvironmentBootstrapUrl();
-
- const parsedUrl = new URL(rawUrl);
- if (options?.protocol) {
- parsedUrl.protocol = options.protocol;
- }
- if (options?.pathname) {
- parsedUrl.pathname = options.pathname;
- } else {
- parsedUrl.pathname = "/";
- }
- if (options?.searchParams) {
- parsedUrl.search = new URLSearchParams(options.searchParams).toString();
- }
- return parsedUrl.toString();
-};
diff --git a/apps/web/src/lib/vendor/qrcodegen.ts b/apps/web/src/lib/vendor/qrcodegen.ts
new file mode 100644
index 000000000..5a5532f0d
--- /dev/null
+++ b/apps/web/src/lib/vendor/qrcodegen.ts
@@ -0,0 +1,996 @@
+// @ts-nocheck
+/* oxlint-disable eslint/no-useless-escape */
+/*
+ * QR Code generator library (TypeScript)
+ *
+ * Copyright (c) Project Nayuki. (MIT License)
+ * https://www.nayuki.io/page/qr-code-generator-library
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ * the Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ * - The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * - The Software is provided "as is", without warranty of any kind, express or
+ * implied, including but not limited to the warranties of merchantability,
+ * fitness for a particular purpose and noninfringement. In no event shall the
+ * authors or copyright holders be liable for any claim, damages or other
+ * liability, whether in an action of contract, tort or otherwise, arising from,
+ * out of or in connection with the Software or the use or other dealings in the
+ * Software.
+ */
+
+"use strict";
+
+
+namespace qrcodegen {
+
+ type bit = number;
+ type byte = number;
+ type int = number;
+
+
+ /*---- QR Code symbol class ----*/
+
+ /*
+ * A QR Code symbol, which is a type of two-dimension barcode.
+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
+ * Instances of this class represent an immutable square grid of dark and light cells.
+ * The class provides static factory functions to create a QR Code from text or binary data.
+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
+ *
+ * Ways to create a QR Code object:
+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
+ * - Low level: Custom-make the array of data codeword bytes (including
+ * segment headers and final padding, excluding error correction codewords),
+ * supply the appropriate version number, and call the QrCode() constructor.
+ * (Note that all ways require supplying the desired error correction level.)
+ */
+ export class QrCode {
+
+ /*-- Static factory functions (high level) --*/
+
+ // Returns a QR Code representing the given Unicode text string at the given error correction level.
+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
+ // ecl argument if it can be done without increasing the version.
+ public static encodeText(text: string, ecl: QrCode.Ecc): QrCode {
+ const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text);
+ return QrCode.encodeSegments(segs, ecl);
+ }
+
+
+ // Returns a QR Code representing the given binary data at the given error correction level.
+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of
+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
+ public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode {
+ const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data);
+ return QrCode.encodeSegments([seg], ecl);
+ }
+
+
+ /*-- Static factory functions (mid level) --*/
+
+ // Returns a QR Code representing the given segments with the given encoding parameters.
+ // The smallest possible QR Code version within the given range is automatically
+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result
+ // may be higher than the ecl argument if it can be done without increasing the
+ // version. The mask number is either between 0 to 7 (inclusive) to force that
+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).
+ // This function allows the user to create a custom sequence of segments that switches
+ // between modes (such as alphanumeric and byte) to encode text in less space.
+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
+ public static encodeSegments(segs: Readonly<Array<QrSegment>>, ecl: QrCode.Ecc,
+ minVersion: int = 1, maxVersion: int = 40,
+ mask: int = -1, boostEcl: boolean = true): QrCode {
+
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
+ || mask < -1 || mask > 7)
+ throw new RangeError("Invalid value");
+
+ // Find the minimal version number to use
+ let version: int;
+ let dataUsedBits: int;
+ for (version = minVersion; ; version++) {
+ const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
+ const usedBits: number = QrSegment.getTotalBits(segs, version);
+ if (usedBits <= dataCapacityBits) {
+ dataUsedBits = usedBits;
+ break; // This version number is found to be suitable
+ }
+ if (version >= maxVersion) // All versions in the range could not fit the given data
+ throw new RangeError("Data too long");
+ }
+
+ // Increase the error correction level while the data still fits in the current version number
+ for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high
+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
+ ecl = newEcl;
+ }
+
+ // Concatenate all segments to create the data bit string
+ let bb: Array<bit> = []
+ for (const seg of segs) {
+ appendBits(seg.mode.modeBits, 4, bb);
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
+ for (const b of seg.getData())
+ bb.push(b);
+ }
+ assert(bb.length == dataUsedBits);
+
+ // Add terminator and pad up to a byte if applicable
+ const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;
+ assert(bb.length <= dataCapacityBits);
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
+ appendBits(0, (8 - bb.length % 8) % 8, bb);
+ assert(bb.length % 8 == 0);
+
+ // Pad with alternating bytes until data capacity is reached
+ for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
+ appendBits(padByte, 8, bb);
+
+ // Pack bits into bytes in big endian
+ let dataCodewords: Array<byte> = [];
+ while (dataCodewords.length * 8 < bb.length)
+ dataCodewords.push(0);
+ bb.forEach((b: bit, i: int) =>
+ dataCodewords[i >>> 3] |= b << (7 - (i & 7)));
+
+ // Create the QR Code object
+ return new QrCode(version, ecl, dataCodewords, mask);
+ }
+
+
+ /*-- Fields --*/
+
+ // The width and height of this QR Code, measured in modules, between
+ // 21 and 177 (inclusive). This is equal to version * 4 + 17.
+ public readonly size: int;
+
+ // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
+ // Even if a QR Code is created with automatic masking requested (mask = -1),
+ // the resulting object still has a mask value between 0 and 7.
+ public readonly mask: int;
+
+ // The modules of this QR Code (false = light, true = dark).
+ // Immutable after constructor finishes. Accessed through getModule().
+ private readonly modules : Array<Array<boolean>> = [];
+
+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
+ private readonly isFunction: Array<Array<boolean>> = [];
+
+
+ /*-- Constructor (low level) and fields --*/
+
+ // Creates a new QR Code with the given version number,
+ // error correction level, data codeword bytes, and mask number.
+ // This is a low-level API that most users should not use directly.
+ // A mid-level API is the encodeSegments() function.
+ public constructor(
+ // The version number of this QR Code, which is between 1 and 40 (inclusive).
+ // This determines the size of this barcode.
+ public readonly version: int,
+
+ // The error correction level used in this QR Code.
+ public readonly errorCorrectionLevel: QrCode.Ecc,
+
+ dataCodewords: Readonly<Array<byte>>,
+
+ msk: int) {
+
+ // Check scalar arguments
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
+ throw new RangeError("Version value out of range");
+ if (msk < -1 || msk > 7)
+ throw new RangeError("Mask value out of range");
+ this.size = version * 4 + 17;
+
+ // Initialize both grids to be size*size arrays of Boolean false
+ let row: Array<boolean> = [];
+ for (let i = 0; i < this.size; i++)
+ row.push(false);
+ for (let i = 0; i < this.size; i++) {
+ this.modules .push(row.slice()); // Initially all light
+ this.isFunction.push(row.slice());
+ }
+
+ // Compute ECC, draw modules
+ this.drawFunctionPatterns();
+ const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);
+ this.drawCodewords(allCodewords);
+
+ // Do masking
+ if (msk == -1) { // Automatically choose best mask
+ let minPenalty: int = 1000000000;
+ for (let i = 0; i < 8; i++) {
+ this.applyMask(i);
+ this.drawFormatBits(i);
+ const penalty: int = this.getPenaltyScore();
+ if (penalty < minPenalty) {
+ msk = i;
+ minPenalty = penalty;
+ }
+ this.applyMask(i); // Undoes the mask due to XOR
+ }
+ }
+ assert(0 <= msk && msk <= 7);
+ this.mask = msk;
+ this.applyMask(msk); // Apply the final choice of mask
+ this.drawFormatBits(msk); // Overwrite old format bits
+
+ this.isFunction = [];
+ }
+
+
+ /*-- Accessor methods --*/
+
+ // Returns the color of the module (pixel) at the given coordinates, which is false
+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
+ // If the given coordinates are out of bounds, then false (light) is returned.
+ public getModule(x: int, y: int): boolean {
+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
+ }
+
+
+ /*-- Private helper methods for constructor: Drawing function modules --*/
+
+ // Reads this object's version field, and draws and marks all function modules.
+ private drawFunctionPatterns(): void {
+ // Draw horizontal and vertical timing patterns
+ for (let i = 0; i < this.size; i++) {
+ this.setFunctionModule(6, i, i % 2 == 0);
+ this.setFunctionModule(i, 6, i % 2 == 0);
+ }
+
+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
+ this.drawFinderPattern(3, 3);
+ this.drawFinderPattern(this.size - 4, 3);
+ this.drawFinderPattern(3, this.size - 4);
+
+ // Draw numerous alignment patterns
+ const alignPatPos: Array<int> = this.getAlignmentPatternPositions();
+ const numAlign: int = alignPatPos.length;
+ for (let i = 0; i < numAlign; i++) {
+ for (let j = 0; j < numAlign; j++) {
+ // Don't draw on the three finder corners
+ if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
+ }
+ }
+
+ // Draw configuration data
+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
+ this.drawVersion();
+ }
+
+
+ // Draws two copies of the format bits (with its own error correction code)
+ // based on the given mask and this object's error correction level field.
+ private drawFormatBits(mask: int): void {
+ // Calculate error correction code and pack bits
+ const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
+ let rem: int = data;
+ for (let i = 0; i < 10; i++)
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
+ const bits = (data << 10 | rem) ^ 0x5412; // uint15
+ assert(bits >>> 15 == 0);
+
+ // Draw first copy
+ for (let i = 0; i <= 5; i++)
+ this.setFunctionModule(8, i, getBit(bits, i));
+ this.setFunctionModule(8, 7, getBit(bits, 6));
+ this.setFunctionModule(8, 8, getBit(bits, 7));
+ this.setFunctionModule(7, 8, getBit(bits, 8));
+ for (let i = 9; i < 15; i++)
+ this.setFunctionModule(14 - i, 8, getBit(bits, i));
+
+ // Draw second copy
+ for (let i = 0; i < 8; i++)
+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
+ for (let i = 8; i < 15; i++)
+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
+ this.setFunctionModule(8, this.size - 8, true); // Always dark
+ }
+
+
+ // Draws two copies of the version bits (with its own error correction code),
+ // based on this object's version field, iff 7 <= version <= 40.
+ private drawVersion(): void {
+ if (this.version < 7)
+ return;
+
+ // Calculate error correction code and pack bits
+ let rem: int = this.version; // version is uint6, in the range [7, 40]
+ for (let i = 0; i < 12; i++)
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
+ const bits: int = this.version << 12 | rem; // uint18
+ assert(bits >>> 18 == 0);
+
+ // Draw two copies
+ for (let i = 0; i < 18; i++) {
+ const color: boolean = getBit(bits, i);
+ const a: int = this.size - 11 + i % 3;
+ const b: int = Math.floor(i / 3);
+ this.setFunctionModule(a, b, color);
+ this.setFunctionModule(b, a, color);
+ }
+ }
+
+
+ // Draws a 9*9 finder pattern including the border separator,
+ // with the center module at (x, y). Modules can be out of bounds.
+ private drawFinderPattern(x: int, y: int): void {
+ for (let dy = -4; dy <= 4; dy++) {
+ for (let dx = -4; dx <= 4; dx++) {
+ const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
+ const xx: int = x + dx;
+ const yy: int = y + dy;
+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
+ }
+ }
+ }
+
+
+ // Draws a 5*5 alignment pattern, with the center module
+ // at (x, y). All modules must be in bounds.
+ private drawAlignmentPattern(x: int, y: int): void {
+ for (let dy = -2; dy <= 2; dy++) {
+ for (let dx = -2; dx <= 2; dx++)
+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
+ }
+ }
+
+
+ // Sets the color of a module and marks it as a function module.
+ // Only used by the constructor. Coordinates must be in bounds.
+ private setFunctionModule(x: int, y: int, isDark: boolean): void {
+ this.modules[y][x] = isDark;
+ this.isFunction[y][x] = true;
+ }
+
+
+ /*-- Private helper methods for constructor: Codewords and masking --*/
+
+ // Returns a new byte string representing the given data with the appropriate error correction
+ // codewords appended to it, based on this object's version and error correction level.
+ private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {
+ const ver: int = this.version;
+ const ecl: QrCode.Ecc = this.errorCorrectionLevel;
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))
+ throw new RangeError("Invalid argument");
+
+ // Calculate parameter numbers
+ const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
+ const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver];
+ const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
+ const numShortBlocks: int = numBlocks - rawCodewords % numBlocks;
+ const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);
+
+ // Split data into blocks and append ECC to each block
+ let blocks: Array<Array<byte>> = [];
+ const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);
+ for (let i = 0, k = 0; i < numBlocks; i++) {
+ let dat: Array<byte> = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
+ k += dat.length;
+ const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
+ if (i < numShortBlocks)
+ dat.push(0);
+ blocks.push(dat.concat(ecc));
+ }
+
+ // Interleave (not concatenate) the bytes from every block into a single sequence
+ let result: Array<byte> = [];
+ for (let i = 0; i < blocks[0].length; i++) {
+ blocks.forEach((block, j) => {
+ // Skip the padding byte in short blocks
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
+ result.push(block[i]);
+ });
+ }
+ assert(result.length == rawCodewords);
+ return result;
+ }
+
+
+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
+ // data area of this QR Code. Function modules need to be marked off before this is called.
+ private drawCodewords(data: Readonly<Array<byte>>): void {
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
+ throw new RangeError("Invalid argument");
+ let i: int = 0; // Bit index into the data
+ // Do the funny zigzag scan
+ for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
+ if (right == 6)
+ right = 5;
+ for (let vert = 0; vert < this.size; vert++) { // Vertical counter
+ for (let j = 0; j < 2; j++) {
+ const x: int = right - j; // Actual x coordinate
+ const upward: boolean = ((right + 1) & 2) == 0;
+ const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate
+ if (!this.isFunction[y][x] && i < data.length * 8) {
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
+ i++;
+ }
+ // If this QR Code has any remainder bits (0 to 7), they were assigned as
+ // 0/false/light by the constructor and are left unchanged by this method
+ }
+ }
+ }
+ assert(i == data.length * 8);
+ }
+
+
+ // XORs the codeword modules in this QR Code with the given mask pattern.
+ // The function modules must be marked and the codeword bits must be drawn
+ // before masking. Due to the arithmetic of XOR, calling applyMask() with
+ // the same mask value a second time will undo the mask. A final well-formed
+ // QR Code needs exactly one (not zero, two, etc.) mask applied.
+ private applyMask(mask: int): void {
+ if (mask < 0 || mask > 7)
+ throw new RangeError("Mask value out of range");
+ for (let y = 0; y < this.size; y++) {
+ for (let x = 0; x < this.size; x++) {
+ let invert: boolean;
+ switch (mask) {
+ case 0: invert = (x + y) % 2 == 0; break;
+ case 1: invert = y % 2 == 0; break;
+ case 2: invert = x % 3 == 0; break;
+ case 3: invert = (x + y) % 3 == 0; break;
+ case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0; break;
+ case 5: invert = x * y % 2 + x * y % 3 == 0; break;
+ case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
+ case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
+ default: throw new Error("Unreachable");
+ }
+ if (!this.isFunction[y][x] && invert)
+ this.modules[y][x] = !this.modules[y][x];
+ }
+ }
+ }
+
+
+ // Calculates and returns the penalty score based on state of this QR Code's current modules.
+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
+ private getPenaltyScore(): int {
+ let result: int = 0;
+
+ // Adjacent modules in row having same color, and finder-like patterns
+ for (let y = 0; y < this.size; y++) {
+ let runColor = false;
+ let runX = 0;
+ let runHistory = [0,0,0,0,0,0,0];
+ for (let x = 0; x < this.size; x++) {
+ if (this.modules[y][x] == runColor) {
+ runX++;
+ if (runX == 5)
+ result += QrCode.PENALTY_N1;
+ else if (runX > 5)
+ result++;
+ } else {
+ this.finderPenaltyAddHistory(runX, runHistory);
+ if (!runColor)
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
+ runColor = this.modules[y][x];
+ runX = 1;
+ }
+ }
+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
+ }
+ // Adjacent modules in column having same color, and finder-like patterns
+ for (let x = 0; x < this.size; x++) {
+ let runColor = false;
+ let runY = 0;
+ let runHistory = [0,0,0,0,0,0,0];
+ for (let y = 0; y < this.size; y++) {
+ if (this.modules[y][x] == runColor) {
+ runY++;
+ if (runY == 5)
+ result += QrCode.PENALTY_N1;
+ else if (runY > 5)
+ result++;
+ } else {
+ this.finderPenaltyAddHistory(runY, runHistory);
+ if (!runColor)
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
+ runColor = this.modules[y][x];
+ runY = 1;
+ }
+ }
+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
+ }
+
+ // 2*2 blocks of modules having same color
+ for (let y = 0; y < this.size - 1; y++) {
+ for (let x = 0; x < this.size - 1; x++) {
+ const color: boolean = this.modules[y][x];
+ if ( color == this.modules[y][x + 1] &&
+ color == this.modules[y + 1][x] &&
+ color == this.modules[y + 1][x + 1])
+ result += QrCode.PENALTY_N2;
+ }
+ }
+
+ // Balance of dark and light modules
+ let dark: int = 0;
+ for (const row of this.modules)
+ dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
+ const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2
+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
+ const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
+ assert(0 <= k && k <= 9);
+ result += k * QrCode.PENALTY_N4;
+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
+ return result;
+ }
+
+
+ /*-- Private helper functions --*/
+
+ // Returns an ascending list of positions of alignment patterns for this version number.
+ // Each position is in the range [0,177), and are used on both the x and y axes.
+ // This could be implemented as lookup table of 40 variable-length lists of integers.
+ private getAlignmentPatternPositions(): Array<int> {
+ if (this.version == 1)
+ return [];
+ else {
+ const numAlign: int = Math.floor(this.version / 7) + 2;
+ const step: int = (this.version == 32) ? 26 :
+ Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
+ let result: Array<int> = [6];
+ for (let pos = this.size - 7; result.length < numAlign; pos -= step)
+ result.splice(1, 0, pos);
+ return result;
+ }
+ }
+
+
+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after
+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
+ private static getNumRawDataModules(ver: int): int {
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
+ throw new RangeError("Version number out of range");
+ let result: int = (16 * ver + 128) * ver + 64;
+ if (ver >= 2) {
+ const numAlign: int = Math.floor(ver / 7) + 2;
+ result -= (25 * numAlign - 10) * numAlign - 55;
+ if (ver >= 7)
+ result -= 36;
+ }
+ assert(208 <= result && result <= 29648);
+ return result;
+ }
+
+
+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
+ // QR Code of the given version number and error correction level, with remainder bits discarded.
+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.
+ private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int {
+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
+ QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] *
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
+ }
+
+
+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
+ private static reedSolomonComputeDivisor(degree: int): Array<byte> {
+ if (degree < 1 || degree > 255)
+ throw new RangeError("Degree out of range");
+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
+ let result: Array<byte> = [];
+ for (let i = 0; i < degree - 1; i++)
+ result.push(0);
+ result.push(1); // Start off with the monomial x^0
+
+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
+ // and drop the highest monomial term which is always 1x^degree.
+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
+ let root = 1;
+ for (let i = 0; i < degree; i++) {
+ // Multiply the current product by (x - r^i)
+ for (let j = 0; j < result.length; j++) {
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
+ if (j + 1 < result.length)
+ result[j] ^= result[j + 1];
+ }
+ root = QrCode.reedSolomonMultiply(root, 0x02);
+ }
+ return result;
+ }
+
+
+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
+ private static reedSolomonComputeRemainder(data: Readonly<Array<byte>>, divisor: Readonly<Array<byte>>): Array<byte> {
+ let result: Array<byte> = divisor.map(_ => 0);
+ for (const b of data) { // Polynomial division
+ const factor: byte = b ^ (result.shift() as byte);
+ result.push(0);
+ divisor.forEach((coef, i) =>
+ result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
+ }
+ return result;
+ }
+
+
+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
+ private static reedSolomonMultiply(x: byte, y: byte): byte {
+ if (x >>> 8 != 0 || y >>> 8 != 0)
+ throw new RangeError("Byte out of range");
+ // Russian peasant multiplication
+ let z: int = 0;
+ for (let i = 7; i >= 0; i--) {
+ z = (z << 1) ^ ((z >>> 7) * 0x11D);
+ z ^= ((y >>> i) & 1) * x;
+ }
+ assert(z >>> 8 == 0);
+ return z as byte;
+ }
+
+
+ // Can only be called immediately after a light run is added, and
+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().
+ private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {
+ const n: int = runHistory[1];
+ assert(n <= this.size * 3);
+ const core: boolean = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
+ return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
+ + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
+ }
+
+
+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
+ private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array<int>): int {
+ if (currentRunColor) { // Terminate dark run
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
+ currentRunLength = 0;
+ }
+ currentRunLength += this.size; // Add light border to final run
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
+ return this.finderPenaltyCountPatterns(runHistory);
+ }
+
+
+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
+ private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {
+ if (runHistory[0] == 0)
+ currentRunLength += this.size; // Add light border to initial run
+ runHistory.pop();
+ runHistory.unshift(currentRunLength);
+ }
+
+
+ /*-- Constants and tables --*/
+
+ // The minimum version number supported in the QR Code Model 2 standard.
+ public static readonly MIN_VERSION: int = 1;
+ // The maximum version number supported in the QR Code Model 2 standard.
+ public static readonly MAX_VERSION: int = 40;
+
+ // For use in getPenaltyScore(), when evaluating which mask is best.
+ private static readonly PENALTY_N1: int = 3;
+ private static readonly PENALTY_N2: int = 3;
+ private static readonly PENALTY_N3: int = 40;
+ private static readonly PENALTY_N4: int = 10;
+
+ private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
+ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
+ [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
+ [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
+ [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
+ ];
+
+ private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
+ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
+ [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
+ [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
+ [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
+ ];
+
+ }
+
+
+ // Appends the given number of low-order bits of the given value
+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
+ function appendBits(val: int, len: int, bb: Array<bit>): void {
+ if (len < 0 || len > 31 || val >>> len != 0)
+ throw new RangeError("Value out of range");
+ for (let i = len - 1; i >= 0; i--) // Append bit by bit
+ bb.push((val >>> i) & 1);
+ }
+
+
+ // Returns true iff the i'th bit of x is set to 1.
+ function getBit(x: int, i: int): boolean {
+ return ((x >>> i) & 1) != 0;
+ }
+
+
+ // Throws an exception if the given condition is false.
+ function assert(cond: boolean): void {
+ if (!cond)
+ throw new Error("Assertion error");
+ }
+
+
+
+ /*---- Data segment class ----*/
+
+ /*
+ * A segment of character/binary/control data in a QR Code symbol.
+ * Instances of this class are immutable.
+ * The mid-level way to create a segment is to take the payload data
+ * and call a static factory function such as QrSegment.makeNumeric().
+ * The low-level way to create a segment is to custom-make the bit buffer
+ * and call the QrSegment() constructor with appropriate values.
+ * This segment class imposes no length restrictions, but QR Codes have restrictions.
+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.
+ */
+ export class QrSegment {
+
+ /*-- Static factory functions (mid level) --*/
+
+ // Returns a segment representing the given binary data encoded in
+ // byte mode. All input byte arrays are acceptable. Any text string
+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.
+ public static makeBytes(data: Readonly<Array<byte>>): QrSegment {
+ let bb: Array<bit> = []
+ for (const b of data)
+ appendBits(b, 8, bb);
+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
+ }
+
+
+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.
+ public static makeNumeric(digits: string): QrSegment {
+ if (!QrSegment.isNumeric(digits))
+ throw new RangeError("String contains non-numeric characters");
+ let bb: Array<bit> = []
+ for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration
+ const n: int = Math.min(digits.length - i, 3);
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
+ i += n;
+ }
+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
+ }
+
+
+ // Returns a segment representing the given text string encoded in alphanumeric mode.
+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
+ public static makeAlphanumeric(text: string): QrSegment {
+ if (!QrSegment.isAlphanumeric(text))
+ throw new RangeError("String contains unencodable characters in alphanumeric mode");
+ let bb: Array<bit> = []
+ let i: int;
+ for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
+ let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
+ appendBits(temp, 11, bb);
+ }
+ if (i < text.length) // 1 character remaining
+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
+ }
+
+
+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.
+ public static makeSegments(text: string): Array<QrSegment> {
+ // Select the most efficient segment encoding automatically
+ if (text == "")
+ return [];
+ else if (QrSegment.isNumeric(text))
+ return [QrSegment.makeNumeric(text)];
+ else if (QrSegment.isAlphanumeric(text))
+ return [QrSegment.makeAlphanumeric(text)];
+ else
+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
+ }
+
+
+ // Returns a segment representing an Extended Channel Interpretation
+ // (ECI) designator with the given assignment value.
+ public static makeEci(assignVal: int): QrSegment {
+ let bb: Array<bit> = []
+ if (assignVal < 0)
+ throw new RangeError("ECI assignment value out of range");
+ else if (assignVal < (1 << 7))
+ appendBits(assignVal, 8, bb);
+ else if (assignVal < (1 << 14)) {
+ appendBits(0b10, 2, bb);
+ appendBits(assignVal, 14, bb);
+ } else if (assignVal < 1000000) {
+ appendBits(0b110, 3, bb);
+ appendBits(assignVal, 21, bb);
+ } else
+ throw new RangeError("ECI assignment value out of range");
+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);
+ }
+
+
+ // Tests whether the given string can be encoded as a segment in numeric mode.
+ // A string is encodable iff each character is in the range 0 to 9.
+ public static isNumeric(text: string): boolean {
+ return QrSegment.NUMERIC_REGEX.test(text);
+ }
+
+
+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.
+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z
+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
+ public static isAlphanumeric(text: string): boolean {
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
+ }
+
+
+ /*-- Constructor (low level) and fields --*/
+
+ // Creates a new QR Code segment with the given attributes and data.
+ // The character count (numChars) must agree with the mode and the bit buffer length,
+ // but the constraint isn't checked. The given bit buffer is cloned and stored.
+ public constructor(
+ // The mode indicator of this segment.
+ public readonly mode: QrSegment.Mode,
+
+ // The length of this segment's unencoded data. Measured in characters for
+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
+ // Always zero or positive. Not the same as the data's bit length.
+ public readonly numChars: int,
+
+ // The data bits of this segment. Accessed through getData().
+ private readonly bitData: Array<bit>) {
+
+ if (numChars < 0)
+ throw new RangeError("Invalid argument");
+ this.bitData = bitData.slice(); // Make defensive copy
+ }
+
+
+ /*-- Methods --*/
+
+ // Returns a new copy of the data bits of this segment.
+ public getData(): Array<bit> {
+ return this.bitData.slice(); // Make defensive copy
+ }
+
+
+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
+ // the given version. The result is infinity if a segment has too many characters to fit its length field.
+ public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {
+ let result: number = 0;
+ for (const seg of segs) {
+ const ccbits: int = seg.mode.numCharCountBits(version);
+ if (seg.numChars >= (1 << ccbits))
+ return Infinity; // The segment's length doesn't fit the field's bit width
+ result += 4 + ccbits + seg.bitData.length;
+ }
+ return result;
+ }
+
+
+ // Returns a new array of bytes representing the given string encoded in UTF-8.
+ private static toUtf8ByteArray(str: string): Array<byte> {
+ str = encodeURI(str);
+ let result: Array<byte> = [];
+ for (let i = 0; i < str.length; i++) {
+ if (str.charAt(i) != "%")
+ result.push(str.charCodeAt(i));
+ else {
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
+ i += 2;
+ }
+ }
+ return result;
+ }
+
+
+ /*-- Constants --*/
+
+ // Describes precisely all strings that are encodable in numeric mode.
+ private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;
+
+ // Describes precisely all strings that are encodable in alphanumeric mode.
+ private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;
+
+ // The set of all legal characters in alphanumeric mode,
+ // where each character value maps to the index in the string.
+ private static readonly ALPHANUMERIC_CHARSET: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
+
+ }
+
+}
+
+
+
+/*---- Public helper enumeration ----*/
+
+namespace qrcodegen.QrCode {
+
+ type int = number;
+
+
+ /*
+ * The error correction level in a QR Code symbol. Immutable.
+ */
+ export class Ecc {
+
+ /*-- Constants --*/
+
+ public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
+ public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
+ public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
+ public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
+
+
+ /*-- Constructor and fields --*/
+
+ private constructor(
+ // In the range 0 to 3 (unsigned 2-bit integer).
+ public readonly ordinal: int,
+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
+ public readonly formatBits: int) {}
+
+ }
+}
+
+
+
+/*---- Public helper enumeration ----*/
+
+namespace qrcodegen.QrSegment {
+
+ type int = number;
+
+
+ /*
+ * Describes how a segment's data bits are interpreted. Immutable.
+ */
+ export class Mode {
+
+ /*-- Constants --*/
+
+ public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]);
+ public static readonly ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]);
+ public static readonly BYTE = new Mode(0x4, [ 8, 16, 16]);
+ public static readonly KANJI = new Mode(0x8, [ 8, 10, 12]);
+ public static readonly ECI = new Mode(0x7, [ 0, 0, 0]);
+
+
+ /*-- Constructor and fields --*/
+
+ private constructor(
+ // The mode indicator bits, which is a uint4 value (range 0 to 15).
+ public readonly modeBits: int,
+ // Number of character count bits for three different version ranges.
+ private readonly numBitsCharCount: [int,int,int]) {}
+
+
+ /*-- Method --*/
+
+ // (Package-private) Returns the bit width of the character count field for a segment in
+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].
+ public numCharCountBits(ver: int): int {
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
+ }
+
+ }
+}
+
+export const QrCode = qrcodegen.QrCode;
+export const QrSegment = qrcodegen.QrSegment;
diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts
index f8d5e531f..911bce322 100644
--- a/apps/web/src/localApi.test.ts
+++ b/apps/web/src/localApi.test.ts
@@ -79,6 +79,7 @@ const rpcClientMock = {
updateSettings: vi.fn(),
subscribeConfig: vi.fn(),
subscribeLifecycle: vi.fn(),
+ subscribeAuthAccess: vi.fn(),
},
orchestration: {
getSnapshot: vi.fn(),
@@ -92,23 +93,29 @@ const rpcClientMock = {
},
};
-vi.mock("./wsRpcClient", () => {
- return {
- getWsRpcClient: () => rpcClientMock,
- getPrimaryWsRpcClientEntry: () => ({
- key: "primary",
- knownEnvironment: {
- id: "primary",
- label: "Primary",
- source: "manual",
- target: { type: "ws", wsUrl: "ws://localhost:3000" },
+vi.mock("./environments/runtime", () => ({
+ getPrimaryEnvironmentConnection: () => ({
+ kind: "primary" as const,
+ knownEnvironment: {
+ id: "environment-local",
+ label: "Primary",
+ source: "manual" as const,
+ target: {
+ httpBaseUrl: "http://localhost:3000",
+ wsBaseUrl: "ws://localhost:3000",
},
- client: rpcClientMock,
- environmentId: null,
- }),
- __resetWsRpcClientForTests: vi.fn(),
- };
-});
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ },
+ client: rpcClientMock,
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ ensureBootstrapped: async () => undefined,
+ reconnect: async () => undefined,
+ dispose: async () => undefined,
+ }),
+ resetEnvironmentServiceForTests: vi.fn(),
+ resetSavedEnvironmentRegistryStoreForTests: vi.fn(),
+ resetSavedEnvironmentRuntimeStoreForTests: vi.fn(),
+}));
vi.mock("./contextMenuFallback", () => ({
showContextMenuFallback: showContextMenuFallbackMock,
@@ -132,8 +139,17 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
return {
- getWsUrl: () => null,
getLocalEnvironmentBootstrap: () => null,
+ getServerExposureState: async () => ({
+ mode: "local-only",
+ endpointUrl: null,
+ advertisedHost: null,
+ }),
+ setServerExposureMode: async () => ({
+ mode: "local-only",
+ endpointUrl: null,
+ advertisedHost: null,
+ }),
pickFolder: async () => null,
confirm: async () => true,
setTheme: async () => undefined,
@@ -185,6 +201,12 @@ const baseEnvironment = {
const baseServerConfig: ServerConfig = {
environment: baseEnvironment,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
cwd: "/tmp/workspace",
keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
keybindings: [],
@@ -232,7 +254,7 @@ describe("wsApi", () => {
rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
const { createLocalApi } = await import("./localApi");
- const api = createLocalApi();
+ const api = createLocalApi(rpcClientMock as never);
await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
@@ -395,7 +417,7 @@ describe("wsApi", () => {
rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
const { createLocalApi } = await import("./localApi");
- const api = createLocalApi();
+ const api = createLocalApi(rpcClientMock as never);
await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
@@ -409,7 +431,7 @@ describe("wsApi", () => {
rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
const { createLocalApi } = await import("./localApi");
- const api = createLocalApi();
+ const api = createLocalApi(rpcClientMock as never);
await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
nextSettings,
@@ -424,7 +446,7 @@ describe("wsApi", () => {
getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
const { createLocalApi } = await import("./localApi");
- const api = createLocalApi();
+ const api = createLocalApi(rpcClientMock as never);
const items = [{ id: "delete", label: "Delete" }] as const;
await expect(api.contextMenu.show(items)).resolves.toBe("delete");
@@ -435,7 +457,7 @@ describe("wsApi", () => {
showContextMenuFallbackMock.mockResolvedValue("rename");
const { createLocalApi } = await import("./localApi");
- const api = createLocalApi();
+ const api = createLocalApi(rpcClientMock as never);
const items = [{ id: "rename", label: "Rename" }] as const;
await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts
index 3705c9f74..2a51f1029 100644
--- a/apps/web/src/localApi.ts
+++ b/apps/web/src/localApi.ts
@@ -1,19 +1,23 @@
import type { ContextMenuItem, LocalApi } from "@t3tools/contracts";
import { resetGitStatusStateForTests } from "./lib/gitStatusState";
-
-import { __resetWsRpcAtomClientForTests } from "./rpc/client";
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
import { resetServerStateForTests } from "./rpc/serverState";
import { resetWsConnectionStateForTests } from "./rpc/wsConnectionState";
-import { getPrimaryWsRpcClientEntry, WsRpcClient, __resetWsRpcClientForTests } from "./wsRpcClient";
+import {
+ resetSavedEnvironmentRegistryStoreForTests,
+ resetSavedEnvironmentRuntimeStoreForTests,
+} from "./environments/runtime";
+import {
+ getPrimaryEnvironmentConnection,
+ resetEnvironmentServiceForTests,
+} from "./environments/runtime";
+import { type WsRpcClient } from "./rpc/wsRpcClient";
import { showContextMenuFallback } from "./contextMenuFallback";
let cachedApi: LocalApi | undefined;
-export function createLocalApi(
- rpcClient: WsRpcClient = getPrimaryWsRpcClientEntry().client,
-): LocalApi {
+export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
return {
dialogs: {
pickFolder: async () => {
@@ -71,7 +75,7 @@ export function readLocalApi(): LocalApi | undefined {
return cachedApi;
}
- cachedApi = createLocalApi();
+ cachedApi = createLocalApi(getPrimaryEnvironmentConnection().client);
return cachedApi;
}
@@ -85,10 +89,11 @@ export function ensureLocalApi(): LocalApi {
export async function __resetLocalApiForTests() {
cachedApi = undefined;
- await __resetWsRpcAtomClientForTests();
- await __resetWsRpcClientForTests();
+ await resetEnvironmentServiceForTests();
resetGitStatusStateForTests();
resetRequestLatencyStateForTests();
+ resetSavedEnvironmentRegistryStoreForTests();
+ resetSavedEnvironmentRuntimeStoreForTests();
resetServerStateForTests();
resetWsConnectionStateForTests();
}
diff --git a/apps/web/src/observability/clientTracing.ts b/apps/web/src/observability/clientTracing.ts
index aa9d50c11..f9eae4b5a 100644
--- a/apps/web/src/observability/clientTracing.ts
+++ b/apps/web/src/observability/clientTracing.ts
@@ -2,8 +2,8 @@ import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
+import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
import { isElectron } from "../env";
-import { resolveServerUrl } from "../lib/utils";
import { APP_VERSION } from "~/branding";
const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
@@ -51,10 +51,7 @@ export function configureClientTracing(config: ClientTracingConfig = {}): Promis
}
async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
- const otlpTracesUrl = resolveServerUrl({
- protocol: window.location.protocol === "https:" ? "https" : "http",
- pathname: "/api/observability/v1/traces",
- });
+ const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
diff --git a/apps/web/src/pairingUrl.ts b/apps/web/src/pairingUrl.ts
new file mode 100644
index 000000000..bd6be221f
--- /dev/null
+++ b/apps/web/src/pairingUrl.ts
@@ -0,0 +1,33 @@
+const PAIRING_TOKEN_PARAM = "token";
+
+function readHashParams(url: URL): URLSearchParams {
+ return new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
+}
+
+export function getPairingTokenFromUrl(url: URL): string | null {
+ const hashToken = readHashParams(url).get(PAIRING_TOKEN_PARAM)?.trim() ?? "";
+ if (hashToken.length > 0) {
+ return hashToken;
+ }
+
+ const searchToken = url.searchParams.get(PAIRING_TOKEN_PARAM)?.trim() ?? "";
+ return searchToken.length > 0 ? searchToken : null;
+}
+
+export function stripPairingTokenFromUrl(url: URL): URL {
+ const next = new URL(url.toString());
+ const hashParams = readHashParams(next);
+ if (hashParams.has(PAIRING_TOKEN_PARAM)) {
+ hashParams.delete(PAIRING_TOKEN_PARAM);
+ next.hash = hashParams.toString();
+ }
+ next.searchParams.delete(PAIRING_TOKEN_PARAM);
+ return next;
+}
+
+export function setPairingTokenOnUrl(url: URL, credential: string): URL {
+ const next = new URL(url.toString());
+ next.searchParams.delete(PAIRING_TOKEN_PARAM);
+ next.hash = new URLSearchParams([[PAIRING_TOKEN_PARAM, credential]]).toString();
+ return next;
+}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index dd69738de..6494ecdb2 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -10,9 +10,11 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as SettingsRouteImport } from './routes/settings'
+import { Route as PairRouteImport } from './routes/pair'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
+import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -22,6 +24,11 @@ const SettingsRoute = SettingsRouteImport.update({
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
+const PairRoute = PairRouteImport.update({
+ id: '/pair',
+ path: '/pair',
+ getParentRoute: () => rootRouteImport,
+} as any)
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
getParentRoute: () => rootRouteImport,
@@ -36,6 +43,11 @@ const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
path: '/general',
getParentRoute: () => SettingsRoute,
} as any)
+const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
+ id: '/connections',
+ path: '/connections',
+ getParentRoute: () => SettingsRoute,
+} as any)
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
id: '/archived',
path: '/archived',
@@ -55,15 +67,19 @@ const ChatEnvironmentIdThreadIdRoute =
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
+ '/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
+ '/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
export interface FileRoutesByTo {
+ '/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
+ '/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
@@ -72,8 +88,10 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
+ '/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
+ '/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
@@ -83,15 +101,19 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
+ | '/pair'
| '/settings'
| '/settings/archived'
+ | '/settings/connections'
| '/settings/general'
| '/$environmentId/$threadId'
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
to:
+ | '/pair'
| '/settings'
| '/settings/archived'
+ | '/settings/connections'
| '/settings/general'
| '/'
| '/$environmentId/$threadId'
@@ -99,8 +121,10 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/_chat'
+ | '/pair'
| '/settings'
| '/settings/archived'
+ | '/settings/connections'
| '/settings/general'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
@@ -109,6 +133,7 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
+ PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
}
@@ -121,6 +146,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
+ '/pair': {
+ id: '/pair'
+ path: '/pair'
+ fullPath: '/pair'
+ preLoaderRoute: typeof PairRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/_chat': {
id: '/_chat'
path: ''
@@ -142,6 +174,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsGeneralRouteImport
parentRoute: typeof SettingsRoute
}
+ '/settings/connections': {
+ id: '/settings/connections'
+ path: '/connections'
+ fullPath: '/settings/connections'
+ preLoaderRoute: typeof SettingsConnectionsRouteImport
+ parentRoute: typeof SettingsRoute
+ }
'/settings/archived': {
id: '/settings/archived'
path: '/archived'
@@ -182,11 +221,13 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsArchivedRoute: typeof SettingsArchivedRoute
+ SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsArchivedRoute: SettingsArchivedRoute,
+ SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
}
@@ -196,6 +237,7 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
+ PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
}
export const routeTree = rootRouteImport
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 8b2419852..7259fd3b2 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -1,25 +1,14 @@
-import {
- type EnvironmentId,
- OrchestrationEvent,
- type ServerLifecycleWelcomePayload,
- ThreadId,
-} from "@t3tools/contracts";
-import {
- scopedProjectKey,
- scopedThreadKey,
- scopeProjectRef,
- scopeThreadRef,
-} from "@t3tools/client-runtime";
+import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
+import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
- useNavigate,
useLocation,
+ useNavigate,
} from "@tanstack/react-router";
-import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
-import { Throttler } from "@tanstack/react-pacer";
import { APP_DISPLAY_NAME } from "../branding";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
@@ -40,38 +29,34 @@ import {
useServerConfigUpdatedSubscription,
useServerWelcomeSubscription,
} from "../rpc/serverState";
-import {
- markPromotedDraftThreadByRef,
- markPromotedDraftThreadsByRef,
- useComposerDraftStore,
-} from "../composerDraftStore";
-import {
- selectProjectsAcrossEnvironments,
- selectThreadsAcrossEnvironments,
- useStore,
-} from "../store";
+import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
-import { useTerminalStateStore } from "../terminalStateStore";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
-import { providerQueryKeys } from "../lib/providerReactQuery";
-import { projectQueryKeys } from "../lib/projectReactQuery";
-import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
-import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
-import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
-import { deriveReplayRetryDecision } from "../orchestrationRecovery";
-import { selectThreadByRef } from "../store";
+import { syncBrowserChromeTheme } from "../hooks/useTheme";
+import {
+ ensureEnvironmentConnectionBootstrapped,
+ getPrimaryEnvironmentConnection,
+ startEnvironmentConnectionService,
+} from "../environments/runtime";
+import { configureClientTracing } from "../observability/clientTracing";
import {
- bindPrimaryWsRpcClientEnvironment,
- bindWsRpcClientEntryEnvironment,
- getPrimaryWsRpcClientEntry,
- listWsRpcClientEntries,
- subscribeWsRpcClientRegistry,
- type WsRpcClientEntry,
-} from "~/wsRpcClient";
+ ensurePrimaryEnvironmentReady,
+ resolveInitialServerAuthGateState,
+ updatePrimaryEnvironmentDescriptor,
+} from "../environments/primary";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
}>()({
+ beforeLoad: async () => {
+ const [, authGateState] = await Promise.all([
+ ensurePrimaryEnvironmentReady(),
+ resolveInitialServerAuthGateState(),
+ ]);
+ return {
+ authGateState,
+ };
+ },
component: RootRouteView,
errorComponent: RootRouteErrorView,
head: () => ({
@@ -80,22 +65,31 @@ export const Route = createRootRouteWithContext<{
});
function RootRouteView() {
- if (!readLocalApi()) {
- return (
- <div className="flex h-screen flex-col bg-background text-foreground">
- <div className="flex flex-1 items-center justify-center">
- <p className="text-sm text-muted-foreground">
- Connecting to {APP_DISPLAY_NAME} server...
- </p>
- </div>
- </div>
- );
+ const pathname = useLocation({ select: (location) => location.pathname });
+ const { authGateState } = Route.useRouteContext();
+
+ useEffect(() => {
+ const frame = window.requestAnimationFrame(() => {
+ syncBrowserChromeTheme();
+ });
+ return () => {
+ window.cancelAnimationFrame(frame);
+ };
+ }, [pathname]);
+
+ if (pathname === "/pair") {
+ return <Outlet />;
}
+ if (authGateState.status !== "authenticated") {
+ return <Outlet />;
+ }
return (
<ToastProvider>
<AnchoredToastProvider>
+ <AuthenticatedTracingBootstrap />
<ServerStateBootstrap />
+ <EnvironmentConnectionManagerBootstrap />
<EventRouter />
<WebSocketConnectionCoordinator />
<SlowRpcAckToastCoordinator />
@@ -180,97 +174,48 @@ function errorDetails(error: unknown): string {
}
}
-function coalesceOrchestrationUiEvents(
- events: ReadonlyArray<OrchestrationEvent>,
-): OrchestrationEvent[] {
- if (events.length < 2) {
- return [...events];
- }
-
- const coalesced: OrchestrationEvent[] = [];
- for (const event of events) {
- const previous = coalesced.at(-1);
- if (
- previous?.type === "thread.message-sent" &&
- event.type === "thread.message-sent" &&
- previous.payload.threadId === event.payload.threadId &&
- previous.payload.messageId === event.payload.messageId
- ) {
- coalesced[coalesced.length - 1] = {
- ...event,
- payload: {
- ...event.payload,
- attachments: event.payload.attachments ?? previous.payload.attachments,
- createdAt: previous.payload.createdAt,
- text:
- !event.payload.streaming && event.payload.text.length > 0
- ? event.payload.text
- : previous.payload.text + event.payload.text,
- },
- };
- continue;
- }
-
- coalesced.push(event);
- }
+function ServerStateBootstrap() {
+ useEffect(() => startServerStateSync(getPrimaryEnvironmentConnection().client.server), []);
- return coalesced;
+ return null;
}
-const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
-const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
-
-function useRegisteredWsRpcClientEntries(): ReadonlyArray<WsRpcClientEntry> {
- const [, setRevision] = useState(0);
-
- useEffect(() => subscribeWsRpcClientRegistry(() => setRevision((value) => value + 1)), []);
+function AuthenticatedTracingBootstrap() {
+ useEffect(() => {
+ void configureClientTracing();
+ }, []);
- const entries = listWsRpcClientEntries();
- return entries.length > 0 ? entries : [getPrimaryWsRpcClientEntry()];
+ return null;
}
-function ServerStateBootstrap() {
- useEffect(() => startServerStateSync(getPrimaryWsRpcClientEntry().client.server), []);
+function EnvironmentConnectionManagerBootstrap() {
+ const queryClient = useQueryClient();
+
+ useEffect(() => {
+ return startEnvironmentConnectionService(queryClient);
+ }, [queryClient]);
return null;
}
function EventRouter() {
- const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
- const syncServerReadModel = useStore((store) => store.syncServerReadModel);
- const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
- const syncProjects = useUiStateStore((store) => store.syncProjects);
- const syncThreads = useUiStateStore((store) => store.syncThreads);
- const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
- const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
- const removeOrphanedTerminalStates = useTerminalStateStore(
- (store) => store.removeOrphanedTerminalStates,
- );
- const applyTerminalEvent = useTerminalStateStore((store) => store.applyTerminalEvent);
- const queryClient = useQueryClient();
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
const disposedRef = useRef(false);
- const bootstrapFromSnapshotRef = useRef<(environmentId: EnvironmentId) => Promise<void>>(
- async () => undefined,
- );
- const schedulePendingDomainEventFlushRef = useRef<() => void>(() => undefined);
const serverConfig = useServerConfig();
- const clientEntries = useRegisteredWsRpcClientEntries();
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
if (!payload) return;
- bindPrimaryWsRpcClientEnvironment(payload.environment.environmentId);
+ updatePrimaryEnvironmentDescriptor(payload.environment);
setActiveEnvironmentId(payload.environment.environmentId);
- schedulePendingDomainEventFlushRef.current();
migrateLocalSettingsToServer();
void (async () => {
- await bootstrapFromSnapshotRef.current(payload.environment.environmentId);
+ await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
if (disposedRef.current) {
return;
}
@@ -278,12 +223,14 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
- setProjectExpanded(
- scopedProjectKey(
- scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
- ),
- true,
- );
+ useUiStateStore
+ .getState()
+ .setProjectExpanded(
+ scopedProjectKey(
+ scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
+ ),
+ true,
+ );
if (readPathname() !== "/") {
return;
@@ -365,379 +312,16 @@ function EventRouter() {
return;
}
- bindPrimaryWsRpcClientEnvironment(serverConfig.environment.environmentId);
+ updatePrimaryEnvironmentDescriptor(serverConfig.environment);
setActiveEnvironmentId(serverConfig.environment.environmentId);
- schedulePendingDomainEventFlushRef.current();
}, [serverConfig, setActiveEnvironmentId]);
useEffect(() => {
- let disposed = false;
disposedRef.current = false;
- let needsProviderInvalidation = false;
- const primaryClientKey = getPrimaryWsRpcClientEntry().key;
-
- const reconcileSnapshotDerivedState = () => {
- const storeState = useStore.getState();
- const threads = selectThreadsAcrossEnvironments(storeState);
- const projects = selectProjectsAcrossEnvironments(storeState);
- syncProjects(
- projects.map((project) => ({
- key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
- cwd: project.cwd,
- })),
- );
- syncThreads(
- threads.map((thread) => ({
- key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- seedVisitedAt: thread.updatedAt ?? thread.createdAt,
- })),
- );
- markPromotedDraftThreadsByRef(
- threads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
- );
- const activeThreadKeys = collectActiveTerminalThreadIds({
- snapshotThreads: threads.map((thread) => ({
- key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- deletedAt: null,
- archivedAt: thread.archivedAt,
- })),
- draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(),
- });
- removeOrphanedTerminalStates(activeThreadKeys);
- };
-
- const queryInvalidationThrottler = new Throttler(
- () => {
- if (!needsProviderInvalidation) {
- return;
- }
- needsProviderInvalidation = false;
- void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
- // Invalidate workspace entry queries so the @-mention file picker
- // reflects files created, deleted, or restored during this turn.
- void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
- },
- {
- wait: 100,
- leading: false,
- trailing: true,
- },
- );
-
- const applyEventBatch = (
- events: ReadonlyArray<OrchestrationEvent>,
- environmentId: EnvironmentId,
- recovery: ReturnType<typeof createOrchestrationRecoveryCoordinator>,
- ) => {
- const nextEvents = recovery.markEventBatchApplied(events);
- if (nextEvents.length === 0) {
- return;
- }
-
- const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
- const uiEvents = coalesceOrchestrationUiEvents(nextEvents);
- const needsProjectUiSync = nextEvents.some(
- (event) =>
- event.type === "project.created" ||
- event.type === "project.meta-updated" ||
- event.type === "project.deleted",
- );
-
- if (batchEffects.needsProviderInvalidation) {
- needsProviderInvalidation = true;
- void queryInvalidationThrottler.maybeExecute();
- }
-
- applyOrchestrationEvents(uiEvents, environmentId);
- if (needsProjectUiSync) {
- const projects = selectProjectsAcrossEnvironments(useStore.getState());
- syncProjects(
- projects.map((project) => ({
- key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
- cwd: project.cwd,
- })),
- );
- }
- const needsThreadUiSync = nextEvents.some(
- (event) => event.type === "thread.created" || event.type === "thread.deleted",
- );
- if (needsThreadUiSync) {
- const threads = selectThreadsAcrossEnvironments(useStore.getState());
- syncThreads(
- threads.map((thread) => ({
- key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
- seedVisitedAt: thread.updatedAt ?? thread.createdAt,
- })),
- );
- }
- const draftStore = useComposerDraftStore.getState();
- for (const threadId of batchEffects.promoteDraftThreadIds) {
- markPromotedDraftThreadByRef(scopeThreadRef(environmentId, threadId));
- }
- for (const threadId of batchEffects.clearDeletedThreadIds) {
- draftStore.clearDraftThread(scopeThreadRef(environmentId, threadId));
- clearThreadUi(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
- }
- for (const threadId of batchEffects.removeTerminalStateThreadIds) {
- removeTerminalState(scopeThreadRef(environmentId, threadId));
- }
- };
- const clientContexts = clientEntries.map((entry) => {
- const recovery = createOrchestrationRecoveryCoordinator();
- let replayRetryTracker: import("../orchestrationRecovery").ReplayRetryTracker | null = null;
- const pendingDomainEvents: OrchestrationEvent[] = [];
- let flushPendingDomainEventsScheduled = false;
- let boundEnvironmentId = entry.environmentId;
-
- const bindEnvironmentId = (environmentId: EnvironmentId) => {
- if (boundEnvironmentId === environmentId) {
- return;
- }
- boundEnvironmentId = environmentId;
- bindWsRpcClientEntryEnvironment(entry.key, environmentId);
- schedulePendingDomainEventFlush();
- };
-
- const flushPendingDomainEvents = () => {
- flushPendingDomainEventsScheduled = false;
- if (disposed || pendingDomainEvents.length === 0 || boundEnvironmentId === null) {
- return;
- }
-
- const events = pendingDomainEvents.splice(0, pendingDomainEvents.length);
- applyEventBatch(events, boundEnvironmentId, recovery);
- };
-
- const schedulePendingDomainEventFlush = () => {
- if (flushPendingDomainEventsScheduled) {
- return;
- }
-
- flushPendingDomainEventsScheduled = true;
- queueMicrotask(flushPendingDomainEvents);
- };
-
- const runSnapshotRecovery = async (
- reason: "bootstrap" | "replay-failed",
- environmentId: EnvironmentId,
- ): Promise<void> => {
- const started = recovery.beginSnapshotRecovery(reason);
- if (import.meta.env.MODE !== "test") {
- const state = recovery.getState();
- console.info("[orchestration-recovery]", "Snapshot recovery requested.", {
- reason,
- clientKey: entry.key,
- environmentId,
- skipped: !started,
- ...(started
- ? {}
- : {
- blockedBy: state.inFlight?.kind ?? null,
- blockedByReason: state.inFlight?.reason ?? null,
- }),
- state,
- });
- }
- if (!started) {
- return;
- }
-
- try {
- const snapshot = await entry.client.orchestration.getSnapshot();
- if (!disposed) {
- bindEnvironmentId(environmentId);
- syncServerReadModel(snapshot, environmentId);
- reconcileSnapshotDerivedState();
- if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
- void runReplayRecovery("sequence-gap");
- }
- }
- } catch {
- recovery.failSnapshotRecovery();
- }
- };
-
- const fallbackToSnapshotRecovery = async (): Promise<void> => {
- if (boundEnvironmentId === null) {
- return;
- }
- await runSnapshotRecovery("replay-failed", boundEnvironmentId);
- };
-
- const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
- if (!recovery.beginReplayRecovery(reason)) {
- return;
- }
-
- const fromSequenceExclusive = recovery.getState().latestSequence;
- try {
- const events = await entry.client.orchestration.replayEvents({ fromSequenceExclusive });
- if (!disposed) {
- if (boundEnvironmentId === null) {
- replayRetryTracker = null;
- recovery.failReplayRecovery();
- return;
- }
- applyEventBatch(events, boundEnvironmentId, recovery);
- }
- } catch {
- replayRetryTracker = null;
- recovery.failReplayRecovery();
- void fallbackToSnapshotRecovery();
- return;
- }
-
- if (!disposed) {
- const replayCompletion = recovery.completeReplayRecovery();
- const retryDecision = deriveReplayRetryDecision({
- previousTracker: replayRetryTracker,
- completion: replayCompletion,
- recoveryState: recovery.getState(),
- baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
- maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
- });
- replayRetryTracker = retryDecision.tracker;
-
- if (retryDecision.shouldRetry) {
- if (retryDecision.delayMs > 0) {
- await new Promise<void>((resolve) => {
- setTimeout(resolve, retryDecision.delayMs);
- });
- if (disposed) {
- return;
- }
- }
- void runReplayRecovery(reason);
- } else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
- console.warn(
- "[orchestration-recovery]",
- "Stopping replay recovery after no-progress retries.",
- {
- clientKey: entry.key,
- environmentId: boundEnvironmentId,
- state: recovery.getState(),
- },
- );
- }
- }
- };
-
- const unsubLifecycle = entry.client.server.subscribeLifecycle((event) => {
- if (event.type === "welcome") {
- bindEnvironmentId(event.payload.environment.environmentId);
- }
- });
- const unsubConfig = entry.client.server.subscribeConfig((event) => {
- if (event.type === "snapshot") {
- bindEnvironmentId(event.config.environment.environmentId);
- }
- });
- if (boundEnvironmentId === null) {
- void entry.client.server
- .getConfig()
- .then((config) => {
- if (!disposed) {
- bindEnvironmentId(config.environment.environmentId);
- }
- })
- .catch(() => undefined);
- }
- const unsubDomainEvent = entry.client.orchestration.onDomainEvent(
- (event) => {
- const action = recovery.classifyDomainEvent(event.sequence);
- if (action === "apply") {
- pendingDomainEvents.push(event);
- schedulePendingDomainEventFlush();
- return;
- }
- if (action === "recover") {
- flushPendingDomainEvents();
- void runReplayRecovery("sequence-gap");
- }
- },
- {
- onResubscribe: () => {
- if (disposed) {
- return;
- }
- flushPendingDomainEvents();
- void runReplayRecovery("resubscribe");
- },
- },
- );
- const unsubTerminalEvent = entry.client.terminal.onEvent((event) => {
- if (boundEnvironmentId === null) {
- return;
- }
-
- const threadRef = scopeThreadRef(boundEnvironmentId, ThreadId.makeUnsafe(event.threadId));
- const thread = selectThreadByRef(useStore.getState(), threadRef);
- if (!thread || thread.archivedAt !== null) {
- return;
- }
- applyTerminalEvent(threadRef, event);
- });
-
- return {
- key: entry.key,
- bindEnvironmentId,
- flushPendingDomainEvents,
- schedulePendingDomainEventFlush,
- runSnapshotRecovery,
- cleanup: () => {
- flushPendingDomainEventsScheduled = false;
- pendingDomainEvents.length = 0;
- unsubDomainEvent();
- unsubTerminalEvent();
- unsubLifecycle();
- unsubConfig();
- },
- };
- });
-
- schedulePendingDomainEventFlushRef.current = () => {
- for (const context of clientContexts) {
- context.schedulePendingDomainEventFlush();
- }
- };
-
- const primaryClientContext =
- clientContexts.find((context) => context.key === primaryClientKey) ??
- clientContexts[0] ??
- null;
- bootstrapFromSnapshotRef.current = async (environmentId: EnvironmentId) => {
- if (!primaryClientContext) {
- return;
- }
- primaryClientContext.bindEnvironmentId(environmentId);
- await primaryClientContext.runSnapshotRecovery("bootstrap", environmentId);
- };
-
return () => {
- disposed = true;
disposedRef.current = true;
- needsProviderInvalidation = false;
- schedulePendingDomainEventFlushRef.current = () => undefined;
- queryInvalidationThrottler.cancel();
- for (const context of clientContexts) {
- context.cleanup();
- }
};
- }, [
- applyOrchestrationEvents,
- clientEntries,
- navigate,
- queryClient,
- removeTerminalState,
- removeOrphanedTerminalStates,
- applyTerminalEvent,
- clearThreadUi,
- setProjectExpanded,
- setActiveEnvironmentId,
- syncProjects,
- syncServerReadModel,
- syncThreads,
- ]);
+ }, []);
useServerWelcomeSubscription(handleWelcome);
useServerConfigUpdatedSubscription(handleServerConfigUpdated);
diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx
index 888e6ee74..43f06177a 100644
--- a/apps/web/src/routes/_chat.index.tsx
+++ b/apps/web/src/routes/_chat.index.tsx
@@ -1,33 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
-import { isElectron } from "../env";
-import { SidebarTrigger } from "../components/ui/sidebar";
+import { NoActiveThreadState } from "../components/NoActiveThreadState";
function ChatIndexRouteView() {
- return (
- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
- {!isElectron && (
- <header className="border-b border-border px-3 py-2 md:hidden">
- <div className="flex items-center gap-2">
- <SidebarTrigger className="size-7 shrink-0" />
- <span className="text-sm font-medium text-foreground">Threads</span>
- </div>
- </header>
- )}
-
- {isElectron && (
- <div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
- <span className="text-xs text-muted-foreground/50">No active thread</span>
- </div>
- )}
-
- <div className="flex flex-1 items-center justify-center">
- <div className="text-center">
- <p className="text-sm">Select a thread or create a new one to get started.</p>
- </div>
- </div>
- </div>
- );
+ return <NoActiveThreadState />;
}
export const Route = createFileRoute("/_chat/")({
diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx
index 7491fce00..51d6d3eee 100644
--- a/apps/web/src/routes/_chat.tsx
+++ b/apps/web/src/routes/_chat.tsx
@@ -1,7 +1,11 @@
import { scopeProjectRef } from "@t3tools/client-runtime";
-import { Outlet, createFileRoute } from "@tanstack/react-router";
+import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useEffect } from "react";
+import {
+ ensurePrimaryEnvironmentReady,
+ resolveInitialServerAuthGateState,
+} from "../environments/primary";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
@@ -102,5 +106,14 @@ function ChatRouteLayout() {
}
export const Route = createFileRoute("/_chat")({
+ beforeLoad: async () => {
+ const [, authGateState] = await Promise.all([
+ ensurePrimaryEnvironmentReady(),
+ resolveInitialServerAuthGateState(),
+ ]);
+ if (authGateState.status !== "authenticated") {
+ throw redirect({ to: "/pair", replace: true });
+ }
+ },
component: ChatRouteLayout,
});
diff --git a/apps/web/src/routes/pair.tsx b/apps/web/src/routes/pair.tsx
new file mode 100644
index 000000000..053816bd7
--- /dev/null
+++ b/apps/web/src/routes/pair.tsx
@@ -0,0 +1,47 @@
+import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
+
+import { PairingPendingSurface, PairingRouteSurface } from "../components/auth/PairingRouteSurface";
+import {
+ ensurePrimaryEnvironmentReady,
+ resolveInitialServerAuthGateState,
+} from "../environments/primary";
+
+export const Route = createFileRoute("/pair")({
+ beforeLoad: async () => {
+ const [, authGateState] = await Promise.all([
+ ensurePrimaryEnvironmentReady(),
+ resolveInitialServerAuthGateState(),
+ ]);
+ if (authGateState.status === "authenticated") {
+ throw redirect({ to: "/", replace: true });
+ }
+ return {
+ authGateState,
+ };
+ },
+ component: PairRouteView,
+ pendingComponent: PairRoutePendingView,
+});
+
+function PairRouteView() {
+ const { authGateState } = Route.useRouteContext();
+ const navigate = useNavigate();
+
+ if (!authGateState) {
+ return null;
+ }
+
+ return (
+ <PairingRouteSurface
+ auth={authGateState.auth}
+ onAuthenticated={() => {
+ void navigate({ to: "/", replace: true });
+ }}
+ {...(authGateState.errorMessage ? { initialErrorMessage: authGateState.errorMessage } : {})}
+ />
+ );
+}
+
+function PairRoutePendingView() {
+ return <PairingPendingSurface />;
+}
diff --git a/apps/web/src/routes/settings.connections.tsx b/apps/web/src/routes/settings.connections.tsx
new file mode 100644
index 000000000..275eda6c5
--- /dev/null
+++ b/apps/web/src/routes/settings.connections.tsx
@@ -0,0 +1,7 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { ConnectionsSettings } from "../components/settings/ConnectionsSettings";
+
+export const Route = createFileRoute("/settings/connections")({
+ component: ConnectionsSettings,
+});
diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx
index 45096fd6d..543b182c3 100644
--- a/apps/web/src/routes/settings.tsx
+++ b/apps/web/src/routes/settings.tsx
@@ -2,6 +2,10 @@ import { RotateCcwIcon } from "lucide-react";
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useEffect, useState } from "react";
+import {
+ ensurePrimaryEnvironmentReady,
+ resolveInitialServerAuthGateState,
+} from "../environments/primary";
import { useSettingsRestore } from "../components/settings/SettingsPanels";
import { Button } from "../components/ui/button";
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
@@ -83,7 +87,15 @@ function SettingsRouteLayout() {
}
export const Route = createFileRoute("/settings")({
- beforeLoad: ({ location }) => {
+ beforeLoad: async ({ location }) => {
+ const [, authGateState] = await Promise.all([
+ ensurePrimaryEnvironmentReady(),
+ resolveInitialServerAuthGateState(),
+ ]);
+ if (authGateState.status !== "authenticated") {
+ throw redirect({ to: "/pair", replace: true });
+ }
+
if (location.pathname === "/settings") {
throw redirect({ to: "/settings/general", replace: true });
}
diff --git a/apps/web/src/rpc/client.test.ts b/apps/web/src/rpc/client.test.ts
deleted file mode 100644
index 8e3e1a281..000000000
--- a/apps/web/src/rpc/client.test.ts
+++ /dev/null
@@ -1,279 +0,0 @@
-import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
-
-import {
- configureClientTracing,
- __resetClientTracingForTests,
-} from "../observability/clientTracing";
-import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
-
-type WsEventType = "open" | "message" | "close" | "error";
-type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
-type WsListener = (event?: WsEvent) => void;
-
-const sockets: MockWebSocket[] = [];
-
-class MockWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
-
- readyState = MockWebSocket.CONNECTING;
- readonly sent: string[] = [];
- readonly url: string;
- private readonly listeners = new Map<WsEventType, Set<WsListener>>();
-
- constructor(url: string) {
- this.url = url;
- sockets.push(this);
- }
-
- addEventListener(type: WsEventType, listener: WsListener) {
- const listeners = this.listeners.get(type) ?? new Set<WsListener>();
- listeners.add(listener);
- this.listeners.set(type, listeners);
- }
-
- removeEventListener(type: WsEventType, listener: WsListener) {
- this.listeners.get(type)?.delete(listener);
- }
-
- send(data: string) {
- this.sent.push(data);
- }
-
- close(code = 1000, reason = "") {
- this.readyState = MockWebSocket.CLOSED;
- this.emit("close", { code, reason, type: "close" });
- }
-
- open() {
- this.readyState = MockWebSocket.OPEN;
- this.emit("open", { type: "open" });
- }
-
- serverMessage(data: unknown) {
- this.emit("message", { data, type: "message" });
- }
-
- private emit(type: WsEventType, event?: WsEvent) {
- const listeners = this.listeners.get(type);
- if (!listeners) {
- return;
- }
- for (const listener of listeners) {
- listener(event);
- }
- }
-}
-
-const originalWebSocket = globalThis.WebSocket;
-const originalFetch = globalThis.fetch;
-
-function getSocket(): MockWebSocket {
- const socket = sockets.at(-1);
- if (!socket) {
- throw new Error("Expected a websocket instance");
- }
- return socket;
-}
-
-async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void> {
- const startedAt = Date.now();
- for (;;) {
- try {
- assertion();
- return;
- } catch (error) {
- if (Date.now() - startedAt >= timeoutMs) {
- throw error;
- }
- await new Promise((resolve) => setTimeout(resolve, 10));
- }
- }
-}
-
-beforeEach(() => {
- sockets.length = 0;
-
- Object.defineProperty(globalThis, "window", {
- configurable: true,
- value: {
- location: {
- hostname: "localhost",
- origin: "http://localhost:3020",
- port: "3020",
- protocol: "ws:",
- },
- desktopBridge: undefined,
- },
- });
-
- globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket;
-});
-
-afterEach(() => {
- __resetWsRpcAtomClientForTests();
- globalThis.WebSocket = originalWebSocket;
- globalThis.fetch = originalFetch;
- vi.restoreAllMocks();
-});
-
-describe("WsRpcAtomClient", () => {
- it("runs unary requests through the AtomRpc service", async () => {
- const expectedSettings = {
- ...DEFAULT_SERVER_SETTINGS,
- enableAssistantStreaming: true,
- defaultThreadEnvMode: "worktree" as const,
- textGenerationModelSelection: {
- provider: "codex" as const,
- model: "gpt-5.4",
- },
- providers: {
- codex: {
- ...DEFAULT_SERVER_SETTINGS.providers.codex,
- homePath: "/tmp/codex-home",
- },
- claudeAgent: {
- ...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
- enabled: false,
- },
- },
- };
- const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
-
- await waitFor(() => {
- expect(sockets).toHaveLength(1);
- });
-
- const socket = getSocket();
- socket.open();
-
- await waitFor(() => {
- expect(socket.sent).toHaveLength(1);
- });
-
- const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
- expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
-
- socket.serverMessage(
- JSON.stringify({
- _tag: "Exit",
- requestId: requestMessage.id,
- exit: {
- _tag: "Success",
- value: expectedSettings,
- },
- }),
- );
-
- await expect(requestPromise).resolves.toEqual(expectedSettings);
- });
-
- it("exposes atom-backed query state for unary RPC methods", async () => {
- const expectedSettings = {
- ...DEFAULT_SERVER_SETTINGS,
- enableAssistantStreaming: true,
- defaultThreadEnvMode: "worktree" as const,
- textGenerationModelSelection: {
- provider: "codex" as const,
- model: "gpt-5.4",
- },
- providers: {
- codex: {
- ...DEFAULT_SERVER_SETTINGS.providers.codex,
- homePath: "/tmp/codex-home",
- },
- claudeAgent: {
- ...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
- enabled: false,
- },
- },
- };
- const registry = AtomRegistry.make();
- const query = WsRpcAtomClient.query(WS_METHODS.serverGetSettings, {});
- const release = registry.mount(query);
-
- await waitFor(() => {
- expect(sockets).toHaveLength(1);
- });
-
- const socket = getSocket();
- socket.open();
-
- await waitFor(() => {
- expect(socket.sent).toHaveLength(1);
- });
-
- const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
- expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
- expect(registry.get(query)._tag).toBe("Initial");
-
- socket.serverMessage(
- JSON.stringify({
- _tag: "Exit",
- requestId: requestMessage.id,
- exit: {
- _tag: "Success",
- value: expectedSettings,
- },
- }),
- );
-
- await waitFor(() => {
- const result = registry.get(query);
- expect(AsyncResult.isSuccess(result)).toBe(true);
- if (!AsyncResult.isSuccess(result)) {
- return;
- }
- expect(result.value).toEqual(expectedSettings);
- });
-
- release();
- registry.dispose();
- });
-
- it("attaches distributed trace ids when client OTLP tracing is enabled", async () => {
- await configureClientTracing({
- exportIntervalMs: 10,
- });
-
- const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
-
- await waitFor(() => {
- expect(sockets).toHaveLength(1);
- });
-
- const socket = getSocket();
- socket.open();
-
- await waitFor(() => {
- expect(socket.sent).toHaveLength(1);
- });
-
- const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as {
- id: string;
- spanId?: string;
- tag: string;
- traceId?: string;
- };
- expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
- expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/);
- expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/);
-
- socket.serverMessage(
- JSON.stringify({
- _tag: "Exit",
- requestId: requestMessage.id,
- exit: {
- _tag: "Success",
- value: DEFAULT_SERVER_SETTINGS,
- },
- }),
- );
-
- await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS);
- });
-});
diff --git a/apps/web/src/rpc/client.ts b/apps/web/src/rpc/client.ts
deleted file mode 100644
index e4f9a6bbd..000000000
--- a/apps/web/src/rpc/client.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { WsRpcGroup } from "@t3tools/contracts";
-import { Effect, Layer, ManagedRuntime } from "effect";
-import { AtomRpc } from "effect/unstable/reactivity";
-
-import {
- __resetClientTracingForTests,
- ClientTracingLive,
- configureClientTracing,
-} from "../observability/clientTracing";
-import { createWsRpcProtocolLayer } from "./protocol";
-
-export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
- group: WsRpcGroup,
- protocol: Layer.suspend(() => createWsRpcProtocolLayer()),
-}) {}
-
-let sharedRuntime: ManagedRuntime.ManagedRuntime<WsRpcAtomClient, never> | null = null;
-
-function getRuntime() {
- if (sharedRuntime !== null) {
- return sharedRuntime;
- }
-
- sharedRuntime = ManagedRuntime.make(Layer.mergeAll(WsRpcAtomClient.layer, ClientTracingLive));
- return sharedRuntime;
-}
-
-export function runRpc<TSuccess, TError = never>(
- execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
-): Promise<TSuccess> {
- return configureClientTracing().then(() => {
- const runtime = getRuntime();
- return runtime.runPromise(WsRpcAtomClient.use(execute));
- });
-}
-
-export async function __resetWsRpcAtomClientForTests() {
- const runtime = sharedRuntime;
- sharedRuntime = null;
- await runtime?.dispose();
- await __resetClientTracingForTests();
-}
diff --git a/apps/web/src/rpc/protocol.ts b/apps/web/src/rpc/protocol.ts
index fc5ab9097..9dc769623 100644
--- a/apps/web/src/rpc/protocol.ts
+++ b/apps/web/src/rpc/protocol.ts
@@ -3,7 +3,6 @@ import { Duration, Effect, Layer, Schedule } from "effect";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
-import { resolveServerUrl } from "../lib/utils";
import {
acknowledgeRpcRequest,
clearAllTrackedRpcRequests,
@@ -18,44 +17,96 @@ import {
WS_RECONNECT_MAX_RETRIES,
} from "./wsConnectionState";
-export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
+export interface WsProtocolLifecycleHandlers {
+ readonly onAttempt?: (socketUrl: string) => void;
+ readonly onOpen?: () => void;
+ readonly onError?: (message: string) => void;
+ readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
+}
+export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
type RpcClientFactory = typeof makeWsRpcProtocolClient;
export type WsRpcProtocolClient =
RpcClientFactory extends Effect.Effect<infer Client, any, any> ? Client : never;
+export type WsRpcProtocolSocketUrlProvider = string | (() => Promise<string>);
+
+function formatSocketErrorMessage(error: unknown): string {
+ if (error instanceof Error && error.message.trim().length > 0) {
+ return error.message;
+ }
+ return String(error);
+}
+
+function resolveWsRpcSocketUrl(rawUrl: string): string {
+ const resolved = new URL(rawUrl);
+ if (resolved.protocol !== "ws:" && resolved.protocol !== "wss:") {
+ throw new Error(`Unsupported websocket transport URL protocol: ${resolved.protocol}`);
+ }
+
+ resolved.pathname = "/ws";
+ return resolved.toString();
+}
+
+function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
+ return {
+ onAttempt: recordWsConnectionAttempt,
+ onOpen: recordWsConnectionOpened,
+ onError: (message) => {
+ clearAllTrackedRpcRequests();
+ recordWsConnectionErrored(message);
+ },
+ onClose: (details) => {
+ clearAllTrackedRpcRequests();
+ recordWsConnectionClosed(details);
+ },
+ };
+}
+
+export function createWsRpcProtocolLayer(
+ url: WsRpcProtocolSocketUrlProvider,
+ handlers?: WsProtocolLifecycleHandlers,
+) {
+ const lifecycle = {
+ ...defaultLifecycleHandlers(),
+ ...handlers,
+ };
+ const resolvedUrl =
+ typeof url === "function"
+ ? Effect.promise(() => url()).pipe(
+ Effect.map((rawUrl) => resolveWsRpcSocketUrl(rawUrl)),
+ Effect.tapError((error) =>
+ Effect.sync(() => {
+ lifecycle.onError(formatSocketErrorMessage(error));
+ }),
+ ),
+ Effect.orDie,
+ )
+ : resolveWsRpcSocketUrl(url);
-export function createWsRpcProtocolLayer(url?: string) {
- const resolvedUrl = resolveServerUrl({
- url,
- protocol: window.location.protocol === "https:" ? "wss" : "ws",
- pathname: "/ws",
- });
const trackingWebSocketConstructorLayer = Layer.succeed(
Socket.WebSocketConstructor,
(socketUrl, protocols) => {
- recordWsConnectionAttempt(socketUrl);
+ lifecycle.onAttempt(socketUrl);
const socket = new globalThis.WebSocket(socketUrl, protocols);
socket.addEventListener(
"open",
() => {
- recordWsConnectionOpened();
+ lifecycle.onOpen();
},
{ once: true },
);
socket.addEventListener(
"error",
() => {
- clearAllTrackedRpcRequests();
- recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
+ lifecycle.onError("Unable to connect to the T3 server WebSocket.");
},
{ once: true },
);
socket.addEventListener(
"close",
(event) => {
- clearAllTrackedRpcRequests();
- recordWsConnectionClosed({
+ lifecycle.onClose({
code: event.code,
reason: event.reason,
});
diff --git a/apps/web/src/rpc/serverState.test.ts b/apps/web/src/rpc/serverState.test.ts
index 4eb198324..5ee6d6807 100644
--- a/apps/web/src/rpc/serverState.test.ts
+++ b/apps/web/src/rpc/serverState.test.ts
@@ -66,6 +66,12 @@ const baseEnvironment = {
const baseServerConfig: ServerConfig = {
environment: baseEnvironment,
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie", "bearer-session-token"],
+ sessionCookieName: "t3_session",
+ },
cwd: "/tmp/workspace",
keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
keybindings: [],
diff --git a/apps/web/src/rpc/serverState.ts b/apps/web/src/rpc/serverState.ts
index 3e8dbab28..35472a96e 100644
--- a/apps/web/src/rpc/serverState.ts
+++ b/apps/web/src/rpc/serverState.ts
@@ -13,7 +13,7 @@ import {
import { Atom } from "effect/unstable/reactivity";
import { useCallback, useRef } from "react";
-import type { WsRpcClient } from "../wsRpcClient";
+import type { WsRpcClient } from "./wsRpcClient";
import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
diff --git a/apps/web/src/wsRpcClient.test.ts b/apps/web/src/rpc/wsRpcClient.test.ts
similarity index 75%
rename from apps/web/src/wsRpcClient.test.ts
rename to apps/web/src/rpc/wsRpcClient.test.ts
index 8d1cf6849..56f39b1bd 100644
--- a/apps/web/src/wsRpcClient.test.ts
+++ b/apps/web/src/rpc/wsRpcClient.test.ts
@@ -3,8 +3,7 @@ import type {
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
-import { EnvironmentId } from "@t3tools/contracts";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { describe, expect, it, vi } from "vitest";
vi.mock("./wsTransport", () => ({
WsTransport: class WsTransport {
@@ -16,12 +15,7 @@ vi.mock("./wsTransport", () => ({
},
}));
-import {
- __resetWsRpcClientForTests,
- createWsRpcClient,
- ensureWsRpcClientEntryForKnownEnvironment,
- readWsRpcClientEntryForEnvironment,
-} from "./wsRpcClient";
+import { createWsRpcClient } from "./wsRpcClient";
import { type WsTransport } from "./wsTransport";
const baseLocalStatus: GitStatusLocalResult = {
@@ -41,10 +35,6 @@ const baseRemoteStatus: GitStatusRemoteResult = {
};
describe("wsRpcClient", () => {
- afterEach(async () => {
- await __resetWsRpcClientForTests();
- });
-
it("reduces git status stream events into flat status snapshots", () => {
const subscribe = vi.fn(<TValue>(_connect: unknown, listener: (value: TValue) => void) => {
for (const event of [
@@ -111,20 +101,4 @@ describe("wsRpcClient", () => {
],
]);
});
-
- it("does not fall back to the only registered client for an unbound environment", () => {
- ensureWsRpcClientEntryForKnownEnvironment({
- id: "known-env-a",
- label: "Environment A",
- source: "manual",
- target: {
- type: "ws",
- wsUrl: "ws://localhost:3000",
- },
- });
-
- expect(
- readWsRpcClientEntryForEnvironment(EnvironmentId.makeUnsafe("environment-b")),
- ).toBeNull();
- });
});
diff --git a/apps/web/src/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts
similarity index 66%
rename from apps/web/src/wsRpcClient.ts
rename to apps/web/src/rpc/wsRpcClient.ts
index 7251b91fa..b714889b7 100644
--- a/apps/web/src/wsRpcClient.ts
+++ b/apps/web/src/rpc/wsRpcClient.ts
@@ -6,20 +6,14 @@ import {
type GitStatusStreamEvent,
type LocalApi,
ORCHESTRATION_WS_METHODS,
- type EnvironmentId,
type ServerSettingsPatch,
WS_METHODS,
} from "@t3tools/contracts";
-import { getKnownEnvironmentBaseUrl, type KnownEnvironment } from "@t3tools/client-runtime";
import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
import { Effect, Stream } from "effect";
-import {
- getPrimaryKnownEnvironment,
- resolvePrimaryEnvironmentBootstrapUrl,
-} from "./environmentBootstrap";
-import { type WsRpcProtocolClient } from "./rpc/protocol";
-import { resetWsReconnectBackoff } from "./rpc/wsConnectionState";
+import { type WsRpcProtocolClient } from "./protocol";
+import { resetWsReconnectBackoff } from "./wsConnectionState";
import { WsTransport } from "./wsTransport";
type RpcTag = keyof WsRpcProtocolClient & string;
@@ -104,6 +98,7 @@ export interface WsRpcClient {
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverUpdateSettings>>;
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
+ readonly subscribeAuthAccess: RpcStreamMethod<typeof WS_METHODS.subscribeAuthAccess>;
};
readonly orchestration: {
readonly getSnapshot: RpcUnaryNoArgMethod<typeof ORCHESTRATION_WS_METHODS.getSnapshot>;
@@ -115,157 +110,7 @@ export interface WsRpcClient {
};
}
-export interface WsRpcClientEntry {
- readonly key: string;
- readonly knownEnvironment: KnownEnvironment;
- readonly client: WsRpcClient;
- readonly environmentId: EnvironmentId | null;
-}
-
-type MutableWsRpcClientEntry = {
- key: string;
- knownEnvironment: KnownEnvironment;
- client: WsRpcClient;
- environmentId: EnvironmentId | null;
-};
-
-const wsRpcClientEntriesByKey = new Map<string, MutableWsRpcClientEntry>();
-const wsRpcClientKeyByEnvironmentId = new Map<EnvironmentId, string>();
-const wsRpcClientRegistryListeners = new Set<() => void>();
-
-function emitWsRpcClientRegistryChange() {
- for (const listener of wsRpcClientRegistryListeners) {
- listener();
- }
-}
-
-function toReadonlyEntry(entry: MutableWsRpcClientEntry): WsRpcClientEntry {
- return entry;
-}
-
-function createWsRpcClientEntry(knownEnvironment: KnownEnvironment): MutableWsRpcClientEntry {
- const baseUrl = getKnownEnvironmentBaseUrl(knownEnvironment);
- if (!baseUrl) {
- throw new Error(`Unable to resolve websocket bootstrap URL for ${knownEnvironment.label}.`);
- }
-
- return {
- key: knownEnvironment.id,
- knownEnvironment,
- client: createWsRpcClient(new WsTransport(baseUrl)),
- environmentId: knownEnvironment.environmentId ?? null,
- };
-}
-
-export function subscribeWsRpcClientRegistry(listener: () => void): () => void {
- wsRpcClientRegistryListeners.add(listener);
- return () => {
- wsRpcClientRegistryListeners.delete(listener);
- };
-}
-
-export function listWsRpcClientEntries(): ReadonlyArray<WsRpcClientEntry> {
- return [...wsRpcClientEntriesByKey.values()].map(toReadonlyEntry);
-}
-
-export function ensureWsRpcClientEntryForKnownEnvironment(
- knownEnvironment: KnownEnvironment,
-): WsRpcClientEntry {
- const existingEntry = wsRpcClientEntriesByKey.get(knownEnvironment.id);
- if (existingEntry) {
- return toReadonlyEntry(existingEntry);
- }
-
- const entry = createWsRpcClientEntry(knownEnvironment);
- wsRpcClientEntriesByKey.set(entry.key, entry);
- if (entry.environmentId) {
- wsRpcClientKeyByEnvironmentId.set(entry.environmentId, entry.key);
- }
- emitWsRpcClientRegistryChange();
- return toReadonlyEntry(entry);
-}
-
-export function getPrimaryWsRpcClientEntry(): WsRpcClientEntry {
- const primaryKnownEnvironment = getPrimaryKnownEnvironment();
- if (!primaryKnownEnvironment) {
- throw new Error("Unable to resolve the primary websocket environment.");
- }
-
- return ensureWsRpcClientEntryForKnownEnvironment(primaryKnownEnvironment);
-}
-
-export function getWsRpcClient(): WsRpcClient {
- return getPrimaryWsRpcClientEntry().client;
-}
-
-export function bindWsRpcClientEntryEnvironment(
- clientKey: string,
- environmentId: EnvironmentId,
-): void {
- const entry = wsRpcClientEntriesByKey.get(clientKey);
- if (!entry) {
- throw new Error(`No websocket client registered for key ${clientKey}.`);
- }
-
- const previousBoundEnvironmentId = entry.environmentId;
- const previousKeyForEnvironment = wsRpcClientKeyByEnvironmentId.get(environmentId);
-
- if (previousBoundEnvironmentId === environmentId && previousKeyForEnvironment === clientKey) {
- return;
- }
-
- if (previousBoundEnvironmentId) {
- wsRpcClientKeyByEnvironmentId.delete(previousBoundEnvironmentId);
- }
-
- if (previousKeyForEnvironment && previousKeyForEnvironment !== clientKey) {
- const previousEntry = wsRpcClientEntriesByKey.get(previousKeyForEnvironment);
- if (previousEntry) {
- previousEntry.environmentId = null;
- }
- }
-
- entry.environmentId = environmentId;
- wsRpcClientKeyByEnvironmentId.set(environmentId, clientKey);
- emitWsRpcClientRegistryChange();
-}
-
-export function bindPrimaryWsRpcClientEnvironment(environmentId: EnvironmentId): void {
- bindWsRpcClientEntryEnvironment(getPrimaryWsRpcClientEntry().key, environmentId);
-}
-
-export function readWsRpcClientEntryForEnvironment(
- environmentId: EnvironmentId,
-): WsRpcClientEntry | null {
- const clientKey = wsRpcClientKeyByEnvironmentId.get(environmentId);
- if (clientKey) {
- const entry = wsRpcClientEntriesByKey.get(clientKey);
- return entry ? toReadonlyEntry(entry) : null;
- }
-
- return null;
-}
-
-export function getWsRpcClientForEnvironment(environmentId: EnvironmentId): WsRpcClient {
- const entry = readWsRpcClientEntryForEnvironment(environmentId);
- if (!entry) {
- throw new Error(`No websocket client registered for environment ${environmentId}.`);
- }
- return entry.client;
-}
-
-export async function __resetWsRpcClientForTests() {
- for (const entry of wsRpcClientEntriesByKey.values()) {
- await entry.client.dispose();
- }
- wsRpcClientEntriesByKey.clear();
- wsRpcClientKeyByEnvironmentId.clear();
- wsRpcClientRegistryListeners.clear();
-}
-
-export function createWsRpcClient(
- transport = new WsTransport(resolvePrimaryEnvironmentBootstrapUrl()),
-): WsRpcClient {
+export function createWsRpcClient(transport: WsTransport): WsRpcClient {
return {
dispose: () => transport.dispose(),
reconnect: async () => {
@@ -366,6 +211,12 @@ export function createWsRpcClient(
listener,
options,
),
+ subscribeAuthAccess: (listener, options) =>
+ transport.subscribe(
+ (client) => client[WS_METHODS.subscribeAuthAccess]({}),
+ listener,
+ options,
+ ),
},
orchestration: {
getSnapshot: () =>
diff --git a/apps/web/src/wsTransport.test.ts b/apps/web/src/rpc/wsTransport.test.ts
similarity index 87%
rename from apps/web/src/wsTransport.test.ts
rename to apps/web/src/rpc/wsTransport.test.ts
index 58453d991..e8948d8a2 100644
--- a/apps/web/src/wsTransport.test.ts
+++ b/apps/web/src/rpc/wsTransport.test.ts
@@ -1,20 +1,21 @@
import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
+import { Stream } from "effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
__resetClientTracingForTests,
configureClientTracing,
-} from "./observability/clientTracing";
+} from "../observability/clientTracing";
import {
getSlowRpcAckRequests,
resetRequestLatencyStateForTests,
setSlowRpcAckThresholdMsForTests,
-} from "./rpc/requestLatencyState";
+} from "../rpc/requestLatencyState";
import {
getWsConnectionStatus,
getWsConnectionUiState,
resetWsConnectionStateForTests,
-} from "./rpc/wsConnectionState";
+} from "../rpc/wsConnectionState";
import { WsTransport } from "./wsTransport";
type WsEventType = "open" | "message" | "close" | "error";
@@ -153,21 +154,36 @@ describe("WsTransport", () => {
await transport.dispose();
});
- it("uses wss when falling back to an https page origin", async () => {
- Object.assign(window.location, {
- origin: "https://app.example.com",
- hostname: "app.example.com",
- port: "",
- protocol: "https:",
+ it("uses an explicit secure websocket base url", async () => {
+ const transport = new WsTransport("wss://app.example.com");
+
+ await waitFor(() => {
+ expect(sockets).toHaveLength(1);
});
- const transport = new WsTransport();
+ expect(getSocket().url).toBe("wss://app.example.com/ws");
+ await transport.dispose();
+ });
+
+ it("uses an explicit insecure websocket base url for remote backends", async () => {
+ const transport = new WsTransport("ws://192.168.1.44:3773");
await waitFor(() => {
expect(sockets).toHaveLength(1);
});
- expect(getSocket().url).toBe("wss://app.example.com/ws");
+ expect(getSocket().url).toBe("ws://192.168.1.44:3773/ws");
+ await transport.dispose();
+ });
+
+ it("supports async websocket url providers", async () => {
+ const transport = new WsTransport(async () => "wss://remote.example.com/?wsToken=dynamic");
+
+ await waitFor(() => {
+ expect(sockets).toHaveLength(1);
+ });
+
+ expect(getSocket().url).toBe("wss://remote.example.com/ws?wsToken=dynamic");
await transport.dispose();
});
@@ -619,6 +635,78 @@ describe("WsTransport", () => {
await transport.dispose();
});
+ it("does not retry stream subscriptions after application-level failures", async () => {
+ const transport = new WsTransport("ws://localhost:3020");
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ let attempts = 0;
+
+ const unsubscribe = transport.subscribe(
+ () =>
+ Stream.suspend(() => {
+ attempts += 1;
+ return Stream.fail(new Error("Git command failed in GitCore.statusDetails"));
+ }),
+ vi.fn(),
+ { retryDelay: 10 },
+ );
+
+ await waitFor(() => {
+ expect(sockets).toHaveLength(1);
+ });
+
+ getSocket().open();
+
+ await waitFor(() => {
+ expect(attempts).toBe(1);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ expect(attempts).toBe(1);
+ expect(warnSpy).toHaveBeenCalledWith("WebSocket RPC subscription failed", {
+ error: "Git command failed in GitCore.statusDetails",
+ });
+ expect(warnSpy).not.toHaveBeenCalledWith(
+ "WebSocket RPC subscription disconnected",
+ expect.anything(),
+ );
+
+ unsubscribe();
+ await transport.dispose();
+ });
+
+ it("keeps retrying stream subscriptions after transport failures", async () => {
+ const transport = new WsTransport("ws://localhost:3020");
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ let attempts = 0;
+
+ const unsubscribe = transport.subscribe(
+ () =>
+ Stream.suspend(() => {
+ attempts += 1;
+ return Stream.fail(new Error("SocketCloseError: WebSocket closed"));
+ }),
+ vi.fn(),
+ { retryDelay: 10 },
+ );
+
+ await waitFor(() => {
+ expect(sockets).toHaveLength(1);
+ });
+
+ getSocket().open();
+
+ await waitFor(() => {
+ expect(attempts).toBeGreaterThanOrEqual(2);
+ });
+
+ expect(warnSpy).toHaveBeenCalledWith("WebSocket RPC subscription disconnected", {
+ error: "SocketCloseError: WebSocket closed",
+ });
+
+ unsubscribe();
+ await transport.dispose();
+ });
+
it("streams finite request events without re-subscribing", async () => {
const transport = new WsTransport("ws://localhost:3020");
const listener = vi.fn();
diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/rpc/wsTransport.ts
similarity index 86%
rename from apps/web/src/wsTransport.ts
rename to apps/web/src/rpc/wsTransport.ts
index 3e435ee16..0bcc8a8a5 100644
--- a/apps/web/src/wsTransport.ts
+++ b/apps/web/src/rpc/wsTransport.ts
@@ -11,12 +11,15 @@ import {
} from "effect";
import { RpcClient } from "effect/unstable/rpc";
-import { ClientTracingLive, configureClientTracing } from "./observability/clientTracing";
+import { ClientTracingLive } from "../observability/clientTracing";
import {
createWsRpcProtocolLayer,
makeWsRpcProtocolClient,
+ type WsProtocolLifecycleHandlers,
type WsRpcProtocolClient,
-} from "./rpc/protocol";
+ type WsRpcProtocolSocketUrlProvider,
+} from "./protocol";
+import { isTransportConnectionErrorMessage } from "./transportError";
interface SubscribeOptions {
readonly retryDelay?: Duration.Input;
@@ -44,15 +47,18 @@ function formatErrorMessage(error: unknown): string {
}
export class WsTransport {
- private readonly tracingReady: Promise<void>;
- private readonly url: string | undefined;
+ private readonly url: WsRpcProtocolSocketUrlProvider;
+ private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
private disposed = false;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
- constructor(url?: string) {
+ constructor(
+ url: WsRpcProtocolSocketUrlProvider,
+ lifecycleHandlers?: WsProtocolLifecycleHandlers,
+ ) {
this.url = url;
- this.tracingReady = configureClientTracing();
+ this.lifecycleHandlers = lifecycleHandlers;
this.session = this.createSession();
}
@@ -64,7 +70,6 @@ export class WsTransport {
throw new Error("Transport disposed");
}
- await this.tracingReady;
const session = this.session;
const client = await session.clientPromise;
return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
@@ -78,7 +83,6 @@ export class WsTransport {
throw new Error("Transport disposed");
}
- await this.tracingReady;
const session = this.session;
const client = await session.clientPromise;
await session.runtime.runPromise(
@@ -144,8 +148,16 @@ export class WsTransport {
return;
}
+ const formattedError = formatErrorMessage(error);
+ if (!isTransportConnectionErrorMessage(formattedError)) {
+ console.warn("WebSocket RPC subscription failed", {
+ error: formattedError,
+ });
+ return;
+ }
+
console.warn("WebSocket RPC subscription disconnected", {
- error: formatErrorMessage(error),
+ error: formattedError,
});
await sleep(retryDelayMs);
}
@@ -193,7 +205,7 @@ export class WsTransport {
private createSession(): TransportSession {
const runtime = ManagedRuntime.make(
- Layer.mergeAll(createWsRpcProtocolLayer(this.url), ClientTracingLive),
+ Layer.mergeAll(createWsRpcProtocolLayer(this.url, this.lifecycleHandlers), ClientTracingLive),
);
const clientScope = runtime.runSync(Scope.make());
return {
@@ -220,8 +232,7 @@ export class WsTransport {
rejectCompleted = reject;
});
const cancel = session.runtime.runCallback(
- Effect.promise(() => this.tracingReady).pipe(
- Effect.flatMap(() => Effect.promise(() => session.clientPromise)),
+ Effect.promise(() => session.clientPromise).pipe(
Effect.flatMap((client) =>
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
index d5d7d436d..1fbb722a0 100644
--- a/apps/web/src/store.ts
+++ b/apps/web/src/store.ts
@@ -1,21 +1,21 @@
-import {
- type EnvironmentId,
- type MessageId,
- type OrchestrationCheckpointSummary,
- type OrchestrationEvent,
- type OrchestrationMessage,
- type OrchestrationProposedPlan,
- type OrchestrationReadModel,
- type OrchestrationSession,
- type OrchestrationSessionStatus,
- type OrchestrationThread,
- type OrchestrationThreadActivity,
- type ProjectId,
- type ProviderKind,
- type ScopedProjectRef,
- type ScopedThreadRef,
+import type {
+ EnvironmentId,
+ MessageId,
+ OrchestrationCheckpointSummary,
+ OrchestrationEvent,
+ OrchestrationMessage,
+ OrchestrationProposedPlan,
+ OrchestrationReadModel,
+ OrchestrationSession,
+ OrchestrationSessionStatus,
+ OrchestrationThread,
+ OrchestrationThreadActivity,
+ ProjectId,
+ ProviderKind,
+ ScopedProjectRef,
+ ScopedThreadRef,
ThreadId,
- type TurnId,
+ TurnId,
} from "@t3tools/contracts";
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
import { create } from "zustand";
@@ -36,6 +36,7 @@ import {
type ThreadTurnState,
type TurnDiffSummary,
} from "./types";
+import { resolveEnvironmentHttpUrl } from "./environments/runtime";
import { sanitizeThreadErrorMessage } from "./rpc/transportError";
export interface EnvironmentState {
@@ -136,14 +137,17 @@ function mapSession(session: OrchestrationSession): ThreadSession {
};
}
-function mapMessage(message: OrchestrationMessage): ChatMessage {
+function mapMessage(environmentId: EnvironmentId, message: OrchestrationMessage): ChatMessage {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
- previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
+ previewUrl: resolveEnvironmentHttpUrl({
+ environmentId,
+ pathname: attachmentPreviewRoutePath(attachment.id),
+ }),
}));
return {
@@ -212,7 +216,7 @@ function mapThread(thread: OrchestrationThread, environmentId: EnvironmentId): T
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
session: thread.session ? mapSession(thread.session) : null,
- messages: thread.messages.map(mapMessage),
+ messages: thread.messages.map((message) => mapMessage(environmentId, message)),
proposedPlans: thread.proposedPlans.map(mapProposedPlan),
error: sanitizeThreadErrorMessage(thread.session?.lastError),
createdAt: thread.createdAt,
@@ -883,34 +887,6 @@ function toLegacyProvider(providerName: string | null): ProviderKind {
return "codex";
}
-function resolveWsHttpOrigin(): string {
- if (typeof window === "undefined") return "";
- const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
- const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
- const wsCandidate =
- typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
- ? bridgeWsUrl
- : typeof envWsUrl === "string" && envWsUrl.length > 0
- ? envWsUrl
- : null;
- if (!wsCandidate) return window.location.origin;
- try {
- const wsUrl = new URL(wsCandidate);
- const protocol =
- wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
- return `${protocol}//${wsUrl.host}`;
- } catch {
- return window.location.origin;
- }
-}
-
-function toAttachmentPreviewUrl(rawUrl: string): string {
- if (rawUrl.startsWith("/")) {
- return `${resolveWsHttpOrigin()}${rawUrl}`;
- }
- return rawUrl;
-}
-
function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
@@ -1298,7 +1274,7 @@ function applyEnvironmentOrchestrationEvent(
case "thread.message-sent":
return updateThreadState(state, event.payload.threadId, (thread) => {
- const message = mapMessage({
+ const message = mapMessage(thread.environmentId, {
id: event.payload.messageId,
role: event.payload.role,
text: event.payload.text,
@@ -1631,6 +1607,16 @@ export function selectThreadsAcrossEnvironments(state: AppState): Thread[] {
);
}
+/** Like `selectThreadsAcrossEnvironments` but returns stable `ThreadShell` references from the store (no derived data). */
+export function selectThreadShellsAcrossEnvironments(state: AppState): ThreadShell[] {
+ return getEnvironmentEntries(state).flatMap(([, environmentState]) =>
+ environmentState.threadIds.flatMap((threadId) => {
+ const shell = environmentState.threadShellById[threadId];
+ return shell ? [shell] : [];
+ }),
+ );
+}
+
export function selectSidebarThreadsAcrossEnvironments(state: AppState): SidebarThreadSummary[] {
return getEnvironmentEntries(state).flatMap(([environmentId, environmentState]) =>
environmentState.threadIds.flatMap((threadId) => {
@@ -1656,6 +1642,15 @@ export function selectSidebarThreadsForProjectRef(
});
}
+export function selectSidebarThreadsForProjectRefs(
+ state: AppState,
+ refs: readonly ScopedProjectRef[],
+): SidebarThreadSummary[] {
+ if (refs.length === 0) return [];
+ if (refs.length === 1) return selectSidebarThreadsForProjectRef(state, refs[0]);
+ return refs.flatMap((ref) => selectSidebarThreadsForProjectRef(state, ref));
+}
+
export function selectBootstrapCompleteForActiveEnvironment(state: AppState): boolean {
return selectEnvironmentState(state, state.activeEnvironmentId).bootstrapComplete;
}
diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts
index f45ada734..c716af922 100644
--- a/apps/web/src/timestampFormat.test.ts
+++ b/apps/web/src/timestampFormat.test.ts
@@ -1,6 +1,11 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { getTimestampFormatOptions } from "./timestampFormat";
+import {
+ formatElapsedDurationLabel,
+ formatExpiresInLabel,
+ formatRelativeTimeUntilLabel,
+ getTimestampFormatOptions,
+} from "./timestampFormat";
describe("getTimestampFormatOptions", () => {
it("omits hour12 when locale formatting is requested", () => {
@@ -28,3 +33,82 @@ describe("getTimestampFormatOptions", () => {
});
});
});
+
+describe("formatRelativeTimeUntilLabel", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("returns Expired when the instant is in the past", () => {
+ expect(formatRelativeTimeUntilLabel("2026-04-07T11:59:00.000Z")).toBe("Expired");
+ });
+
+ it("formats seconds remaining", () => {
+ expect(formatRelativeTimeUntilLabel("2026-04-07T12:00:45.000Z")).toBe("45s left");
+ });
+
+ it("formats minutes remaining", () => {
+ expect(formatRelativeTimeUntilLabel("2026-04-07T12:15:00.000Z")).toBe("15m left");
+ });
+
+ it("formats hours remaining", () => {
+ expect(formatRelativeTimeUntilLabel("2026-04-07T18:00:00.000Z")).toBe("6h left");
+ });
+});
+
+describe("formatExpiresInLabel", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("returns Expired when the instant is in the past", () => {
+ expect(formatExpiresInLabel("2026-04-07T11:59:00.000Z")).toBe("Expired");
+ });
+
+ it("uses sub-minute second count", () => {
+ expect(formatExpiresInLabel("2026-04-07T12:00:45.000Z")).toBe("Expires in 45s");
+ });
+
+ it("uses minutes and seconds under one hour", () => {
+ expect(formatExpiresInLabel("2026-04-07T12:04:12.000Z")).toBe("Expires in 4m 12s");
+ expect(formatExpiresInLabel("2026-04-07T12:15:00.000Z")).toBe("Expires in 15m");
+ });
+
+ it("uses hours with minute and second remainder", () => {
+ expect(formatExpiresInLabel("2026-04-07T14:02:03.000Z")).toBe("Expires in 2h 2m 3s");
+ expect(formatExpiresInLabel("2026-04-07T18:00:00.000Z")).toBe("Expires in 6h");
+ });
+});
+
+describe("formatElapsedDurationLabel", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("returns just now when the instant is current or in the future", () => {
+ expect(formatElapsedDurationLabel("2026-04-07T12:00:00.000Z")).toBe("just now");
+ expect(formatElapsedDurationLabel("2026-04-07T12:01:00.000Z")).toBe("just now");
+ });
+
+ it("formats seconds, minutes, hours, and days", () => {
+ expect(formatElapsedDurationLabel("2026-04-07T11:59:45.000Z")).toBe("15s");
+ expect(formatElapsedDurationLabel("2026-04-07T11:45:00.000Z")).toBe("15m");
+ expect(formatElapsedDurationLabel("2026-04-07T06:00:00.000Z")).toBe("6h");
+ expect(formatElapsedDurationLabel("2026-04-03T12:00:00.000Z")).toBe("4d");
+ });
+});
diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts
index 453c07016..c39e4a6c7 100644
--- a/apps/web/src/timestampFormat.ts
+++ b/apps/web/src/timestampFormat.ts
@@ -71,3 +71,90 @@ export function formatRelativeTimeLabel(isoDate: string) {
const relative = formatRelativeTime(isoDate);
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
}
+
+/**
+ * Relative elapsed duration since an ISO instant, without an "ago" suffix.
+ * Useful for labels like "Connected for 3m".
+ */
+export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
+ const diffMs = nowMs - new Date(isoDate).getTime();
+ if (diffMs <= 0) return "just now";
+
+ const seconds = Math.floor(diffMs / 1000);
+ if (seconds < 5) return "just now";
+ if (seconds < 60) return `${seconds}s`;
+
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h`;
+
+ const days = Math.floor(hours / 24);
+ return `${days}d`;
+}
+
+/**
+ * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
+ */
+export function formatRelativeTimeUntil(isoDate: string): { value: string; suffix: string | null } {
+ const diffMs = new Date(isoDate).getTime() - Date.now();
+ if (diffMs <= 0) return { value: "Expired", suffix: null };
+ const seconds = Math.floor(diffMs / 1000);
+ if (seconds < 5) return { value: "Soon", suffix: null };
+ if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return { value: `${hours}h`, suffix: "left" };
+ const days = Math.floor(hours / 24);
+ return { value: `${days}d`, suffix: "left" };
+}
+
+export function formatRelativeTimeUntilLabel(isoDate: string): string {
+ const relative = formatRelativeTimeUntil(isoDate);
+ return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
+}
+
+/**
+ * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
+ * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
+ */
+export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
+ const diffMs = new Date(isoDate).getTime() - nowMs;
+ if (diffMs <= 0) return "Expired";
+
+ const totalSeconds = Math.floor(diffMs / 1000);
+ if (totalSeconds < 5) return "Expires in a moment";
+ if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
+
+ if (totalSeconds < 3600) {
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
+ }
+
+ if (totalSeconds < 86_400) {
+ const hours = Math.floor(totalSeconds / 3600);
+ const rem = totalSeconds % 3600;
+ const minutes = Math.floor(rem / 60);
+ const seconds = rem % 60;
+ const parts = [`${hours}h`];
+ if (minutes > 0) parts.push(`${minutes}m`);
+ if (seconds > 0) parts.push(`${seconds}s`);
+ return `Expires in ${parts.join(" ")}`;
+ }
+
+ const days = Math.floor(totalSeconds / 86_400);
+ const remAfterDays = totalSeconds % 86_400;
+ if (remAfterDays === 0) return `Expires in ${days}d`;
+ const hours = Math.floor(remAfterDays / 3600);
+ const rem = remAfterDays % 3600;
+ const minutes = Math.floor(rem / 60);
+ const seconds = rem % 60;
+ const tail: string[] = [];
+ if (hours > 0) tail.push(`${hours}h`);
+ if (minutes > 0) tail.push(`${minutes}m`);
+ if (seconds > 0) tail.push(`${seconds}s`);
+ return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
+}
diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts
index 936afc42f..5a7d53a02 100644
--- a/apps/web/src/uiStateStore.ts
+++ b/apps/web/src/uiStateStore.ts
@@ -405,7 +405,7 @@ export const useUiStateStore = create<UiStateStore>((set) => ({
useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
-if (typeof window !== "undefined") {
+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
diff --git a/apps/web/test/authHttpHandlers.ts b/apps/web/test/authHttpHandlers.ts
new file mode 100644
index 000000000..8b9e00516
--- /dev/null
+++ b/apps/web/test/authHttpHandlers.ts
@@ -0,0 +1,41 @@
+import {
+ EnvironmentId,
+ type ExecutionEnvironmentDescriptor,
+ type ServerAuthDescriptor,
+} from "@t3tools/contracts";
+import { HttpResponse, http } from "msw";
+
+const TEST_SESSION_EXPIRES_AT = "2026-05-01T12:00:00.000Z";
+const TEST_ENVIRONMENT_DESCRIPTOR: ExecutionEnvironmentDescriptor = {
+ environmentId: EnvironmentId.makeUnsafe("environment-local"),
+ label: "Local environment",
+ platform: {
+ os: "darwin",
+ arch: "arm64",
+ },
+ serverVersion: "0.0.0-test",
+ capabilities: {
+ repositoryIdentity: true,
+ },
+};
+
+export function createAuthenticatedSessionHandlers(getAuthDescriptor: () => ServerAuthDescriptor) {
+ return [
+ http.get("*/.well-known/t3/environment", () => HttpResponse.json(TEST_ENVIRONMENT_DESCRIPTOR)),
+ http.get("*/api/auth/session", () =>
+ HttpResponse.json({
+ authenticated: true,
+ auth: getAuthDescriptor(),
+ sessionMethod: "browser-session-cookie",
+ expiresAt: TEST_SESSION_EXPIRES_AT,
+ }),
+ ),
+ http.post("*/api/auth/bootstrap", () =>
+ HttpResponse.json({
+ authenticated: true,
+ sessionMethod: "browser-session-cookie",
+ expiresAt: TEST_SESSION_EXPIRES_AT,
+ }),
+ ),
+ ] as const;
+}
diff --git a/apps/web/test/wsRpcHarness.ts b/apps/web/test/wsRpcHarness.ts
index aeae92d10..f5d86a501 100644
--- a/apps/web/test/wsRpcHarness.ts
+++ b/apps/web/test/wsRpcHarness.ts
@@ -1,6 +1,6 @@
import { Effect, Exit, PubSub, Scope, Stream } from "effect";
import { WS_METHODS, WsRpcGroup } from "@t3tools/contracts";
-import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
+import { RpcMessage, RpcSerialization, RpcServer } from "effect/unstable/rpc";
type RpcServerInstance = RpcServer.RpcServer<any>;
@@ -113,6 +113,13 @@ export class BrowserWsRpcHarness {
}
const messages = this.parser.decode(rawData);
for (const message of messages) {
+ if (message && typeof message === "object" && "_tag" in message && message._tag === "Ping") {
+ const encoded = this.parser.encode(RpcMessage.constPong);
+ if (typeof encoded === "string") {
+ this.client?.send(encoded);
+ }
+ continue;
+ }
await Effect.runPromise(server.write(0, message as never));
}
}
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 56b138d33..a9d47df60 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -6,6 +6,8 @@ import { defineConfig } from "vite";
import pkg from "./package.json" with { type: "json" };
const port = Number(process.env.PORT ?? 5733);
+const host = process.env.HOST?.trim() || "localhost";
+const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
const buildSourcemap =
@@ -15,6 +17,29 @@ const buildSourcemap =
? "hidden"
: true;
+function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
+ if (!wsUrl) {
+ return undefined;
+ }
+
+ try {
+ const url = new URL(wsUrl);
+ if (url.protocol === "ws:") {
+ url.protocol = "http:";
+ } else if (url.protocol === "wss:") {
+ url.protocol = "https:";
+ }
+ url.pathname = "";
+ url.search = "";
+ url.hash = "";
+ return url.toString();
+ } catch {
+ return undefined;
+ }
+}
+
+const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
+
export default defineConfig({
plugins: [
tanstackRouter(),
@@ -34,21 +59,36 @@ export default defineConfig({
},
define: {
// In dev mode, tell the web app where the WebSocket server lives
- "import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
+ "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
},
resolve: {
tsconfigPaths: true,
},
server: {
+ host,
port,
strictPort: true,
+ ...(devProxyTarget
+ ? {
+ proxy: {
+ "/api": {
+ target: devProxyTarget,
+ changeOrigin: true,
+ },
+ "/attachments": {
+ target: devProxyTarget,
+ changeOrigin: true,
+ },
+ },
+ }
+ : {}),
hmr: {
// Explicit config so Vite's HMR WebSocket connects reliably
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
- host: "localhost",
+ host,
},
},
build: {
diff --git a/packages/client-runtime/src/knownEnvironment.test.ts b/packages/client-runtime/src/knownEnvironment.test.ts
index 0856a253a..a09954a05 100644
--- a/packages/client-runtime/src/knownEnvironment.test.ts
+++ b/packages/client-runtime/src/knownEnvironment.test.ts
@@ -1,7 +1,7 @@
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
-import { createKnownEnvironmentFromWsUrl } from "./knownEnvironment";
+import { createKnownEnvironment, getKnownEnvironmentHttpBaseUrl } from "./knownEnvironment";
import {
parseScopedProjectKey,
parseScopedThreadKey,
@@ -13,22 +13,51 @@ import {
} from "./scoped";
describe("known environment bootstrap helpers", () => {
- it("creates known environments from explicit ws urls", () => {
+ it("creates known environments from explicit server base urls", () => {
expect(
- createKnownEnvironmentFromWsUrl({
+ createKnownEnvironment({
label: "Remote environment",
- wsUrl: "wss://remote.example.com/ws",
+ target: {
+ httpBaseUrl: "https://remote.example.com",
+ wsBaseUrl: "wss://remote.example.com",
+ },
}),
).toEqual({
id: "ws:Remote environment",
label: "Remote environment",
source: "manual",
target: {
- type: "ws",
- wsUrl: "wss://remote.example.com/ws",
+ httpBaseUrl: "https://remote.example.com",
+ wsBaseUrl: "wss://remote.example.com",
},
});
});
+
+ it("returns the explicit fetchable http origin", () => {
+ expect(
+ getKnownEnvironmentHttpBaseUrl(
+ createKnownEnvironment({
+ label: "Local environment",
+ target: {
+ httpBaseUrl: "http://localhost:3773",
+ wsBaseUrl: "ws://localhost:3773",
+ },
+ }),
+ ),
+ ).toBe("http://localhost:3773");
+
+ expect(
+ getKnownEnvironmentHttpBaseUrl(
+ createKnownEnvironment({
+ label: "Remote environment",
+ target: {
+ httpBaseUrl: "https://remote.example.com/api",
+ wsBaseUrl: "wss://remote.example.com/api",
+ },
+ }),
+ ),
+ ).toBe("https://remote.example.com/api");
+ });
});
describe("scoped refs", () => {
diff --git a/packages/client-runtime/src/knownEnvironment.ts b/packages/client-runtime/src/knownEnvironment.ts
index 3a5e0d0e7..495a6ddc9 100644
--- a/packages/client-runtime/src/knownEnvironment.ts
+++ b/packages/client-runtime/src/knownEnvironment.ts
@@ -1,8 +1,8 @@
-import type { EnvironmentId } from "@t3tools/contracts";
+import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
export interface KnownEnvironmentConnectionTarget {
- readonly type: "ws";
- readonly wsUrl: string;
+ readonly httpBaseUrl: string;
+ readonly wsBaseUrl: string;
}
export type KnownEnvironmentSource = "configured" | "desktop-managed" | "manual" | "window-origin";
@@ -15,25 +15,39 @@ export interface KnownEnvironment {
readonly target: KnownEnvironmentConnectionTarget;
}
-export function createKnownEnvironmentFromWsUrl(input: {
+export function createKnownEnvironment(input: {
readonly id?: string;
readonly label: string;
readonly source?: KnownEnvironmentSource;
- readonly wsUrl: string;
+ readonly target: KnownEnvironmentConnectionTarget;
}): KnownEnvironment {
return {
id: input.id ?? `ws:${input.label}`,
label: input.label,
source: input.source ?? "manual",
- target: {
- type: "ws",
- wsUrl: input.wsUrl,
- },
+ target: input.target,
};
}
-export function getKnownEnvironmentBaseUrl(
+export function getKnownEnvironmentWsBaseUrl(
+ environment: KnownEnvironment | null | undefined,
+): string | null {
+ return environment?.target.wsBaseUrl ?? null;
+}
+
+export function getKnownEnvironmentHttpBaseUrl(
environment: KnownEnvironment | null | undefined,
): string | null {
- return environment?.target.wsUrl ?? null;
+ return environment?.target.httpBaseUrl ?? null;
+}
+
+export function attachEnvironmentDescriptor(
+ environment: KnownEnvironment,
+ descriptor: ExecutionEnvironmentDescriptor,
+): KnownEnvironment {
+ return {
+ ...environment,
+ environmentId: descriptor.environmentId,
+ label: descriptor.label,
+ };
}
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
new file mode 100644
index 000000000..73327a45a
--- /dev/null
+++ b/packages/contracts/src/auth.ts
@@ -0,0 +1,266 @@
+import { Schema } from "effect";
+
+import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas";
+
+/**
+ * Declares the server's overall authentication posture.
+ *
+ * This is a high-level policy label that tells clients how the environment is
+ * expected to be accessed, not a transport detail and not an exhaustive list
+ * of every accepted credential.
+ *
+ * Typical usage:
+ * - rendered in auth/pairing UI so the user understands what kind of
+ * environment they are connecting to
+ * - used by clients to decide whether silent desktop bootstrap is expected or
+ * whether an explicit pairing flow should be shown
+ *
+ * Meanings:
+ * - `desktop-managed-local`: local desktop-managed environment with narrow
+ * trusted bootstrap, intended to avoid login prompts on the same machine
+ * - `loopback-browser`: standalone local server intended for browser pairing on
+ * the same machine
+ * - `remote-reachable`: environment intended to be reached from other devices
+ * or networks, where explicit pairing/auth is expected
+ * - `unsafe-no-auth`: intentionally unauthenticated mode; this is an explicit
+ * unsafe escape hatch, not a normal deployment mode
+ */
+export const ServerAuthPolicy = Schema.Literals([
+ "desktop-managed-local",
+ "loopback-browser",
+ "remote-reachable",
+ "unsafe-no-auth",
+]);
+export type ServerAuthPolicy = typeof ServerAuthPolicy.Type;
+
+/**
+ * A credential type that can be exchanged for a real authenticated session.
+ *
+ * Bootstrap methods are for establishing trust at the start of a connection or
+ * pairing flow. They are not the long-lived credential used for ordinary
+ * authenticated HTTP / WebSocket traffic after pairing succeeds.
+ *
+ * Current methods:
+ * - `desktop-bootstrap`: a trusted local desktop handoff, used so the desktop
+ * shell can pair the renderer without a login screen
+ * - `one-time-token`: a short-lived pairing token, suitable for manual pairing
+ * flows such as `/pair?token=...`
+ */
+export const ServerAuthBootstrapMethod = Schema.Literals(["desktop-bootstrap", "one-time-token"]);
+export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;
+
+/**
+ * A credential type accepted for steady-state authenticated requests after a
+ * client has already paired.
+ *
+ * These methods are used by the server-wide auth layer for privileged HTTP and
+ * WebSocket access. They are distinct from bootstrap methods so clients can
+ * reason clearly about "pair first, then use session auth".
+ *
+ * Current methods:
+ * - `browser-session-cookie`: cookie-backed browser session, used by the web
+ * app after bootstrap/pairing
+ * - `bearer-session-token`: token-based session suitable for non-cookie or
+ * non-browser clients
+ */
+export const ServerAuthSessionMethod = Schema.Literals([
+ "browser-session-cookie",
+ "bearer-session-token",
+]);
+export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;
+
+export const AuthSessionRole = Schema.Literals(["owner", "client"]);
+export type AuthSessionRole = typeof AuthSessionRole.Type;
+
+/**
+ * Server-advertised auth capabilities for a specific execution environment.
+ *
+ * Clients should treat this as the authoritative description of how that
+ * environment expects to be paired and how authenticated requests should be
+ * made afterward.
+ *
+ * Field meanings:
+ * - `policy`: high-level auth posture for the environment
+ * - `bootstrapMethods`: pairing/bootstrap methods the server is currently
+ * willing to accept
+ * - `sessionMethods`: authenticated request/session methods the server supports
+ * once pairing is complete
+ * - `sessionCookieName`: cookie name clients should expect when
+ * `browser-session-cookie` is in use
+ *
+ * This descriptor is intentionally capability-oriented. It lets clients choose
+ * the right UX without embedding server-specific auth logic or assuming a
+ * single access method.
+ */
+export const ServerAuthDescriptor = Schema.Struct({
+ policy: ServerAuthPolicy,
+ bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),
+ sessionMethods: Schema.Array(ServerAuthSessionMethod),
+ sessionCookieName: TrimmedNonEmptyString,
+});
+export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;
+
+export const AuthBootstrapInput = Schema.Struct({
+ credential: TrimmedNonEmptyString,
+});
+export type AuthBootstrapInput = typeof AuthBootstrapInput.Type;
+
+export const AuthBootstrapResult = Schema.Struct({
+ authenticated: Schema.Literal(true),
+ role: AuthSessionRole,
+ sessionMethod: ServerAuthSessionMethod,
+ expiresAt: Schema.DateTimeUtc,
+});
+export type AuthBootstrapResult = typeof AuthBootstrapResult.Type;
+
+export const AuthBearerBootstrapResult = Schema.Struct({
+ authenticated: Schema.Literal(true),
+ role: AuthSessionRole,
+ sessionMethod: Schema.Literal("bearer-session-token"),
+ expiresAt: Schema.DateTimeUtc,
+ sessionToken: TrimmedNonEmptyString,
+});
+export type AuthBearerBootstrapResult = typeof AuthBearerBootstrapResult.Type;
+
+export const AuthWebSocketTokenResult = Schema.Struct({
+ token: TrimmedNonEmptyString,
+ expiresAt: Schema.DateTimeUtc,
+});
+export type AuthWebSocketTokenResult = typeof AuthWebSocketTokenResult.Type;
+
+export const AuthPairingCredentialResult = Schema.Struct({
+ id: TrimmedNonEmptyString,
+ credential: TrimmedNonEmptyString,
+ label: Schema.optionalKey(TrimmedNonEmptyString),
+ expiresAt: Schema.DateTimeUtc,
+});
+export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
+
+export const AuthPairingLink = Schema.Struct({
+ id: TrimmedNonEmptyString,
+ credential: TrimmedNonEmptyString,
+ role: AuthSessionRole,
+ subject: TrimmedNonEmptyString,
+ label: Schema.optionalKey(TrimmedNonEmptyString),
+ createdAt: Schema.DateTimeUtc,
+ expiresAt: Schema.DateTimeUtc,
+});
+export type AuthPairingLink = typeof AuthPairingLink.Type;
+
+export const AuthClientMetadataDeviceType = Schema.Literals([
+ "desktop",
+ "mobile",
+ "tablet",
+ "bot",
+ "unknown",
+]);
+export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;
+
+export const AuthClientMetadata = Schema.Struct({
+ label: Schema.optionalKey(TrimmedNonEmptyString),
+ ipAddress: Schema.optionalKey(TrimmedNonEmptyString),
+ userAgent: Schema.optionalKey(TrimmedNonEmptyString),
+ deviceType: AuthClientMetadataDeviceType,
+ os: Schema.optionalKey(TrimmedNonEmptyString),
+ browser: Schema.optionalKey(TrimmedNonEmptyString),
+});
+export type AuthClientMetadata = typeof AuthClientMetadata.Type;
+
+export const AuthClientSession = Schema.Struct({
+ sessionId: AuthSessionId,
+ subject: TrimmedNonEmptyString,
+ role: AuthSessionRole,
+ method: ServerAuthSessionMethod,
+ client: AuthClientMetadata,
+ issuedAt: Schema.DateTimeUtc,
+ expiresAt: Schema.DateTimeUtc,
+ lastConnectedAt: Schema.NullOr(Schema.DateTimeUtc),
+ connected: Schema.Boolean,
+ current: Schema.Boolean,
+});
+export type AuthClientSession = typeof AuthClientSession.Type;
+
+export const AuthAccessSnapshot = Schema.Struct({
+ pairingLinks: Schema.Array(AuthPairingLink),
+ clientSessions: Schema.Array(AuthClientSession),
+});
+export type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;
+
+export const AuthAccessStreamSnapshotEvent = Schema.Struct({
+ version: Schema.Literal(1),
+ revision: Schema.Number,
+ type: Schema.Literal("snapshot"),
+ payload: AuthAccessSnapshot,
+});
+export type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;
+
+export const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({
+ version: Schema.Literal(1),
+ revision: Schema.Number,
+ type: Schema.Literal("pairingLinkUpserted"),
+ payload: AuthPairingLink,
+});
+export type AuthAccessStreamPairingLinkUpsertedEvent =
+ typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;
+
+export const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({
+ version: Schema.Literal(1),
+ revision: Schema.Number,
+ type: Schema.Literal("pairingLinkRemoved"),
+ payload: Schema.Struct({
+ id: TrimmedNonEmptyString,
+ }),
+});
+export type AuthAccessStreamPairingLinkRemovedEvent =
+ typeof AuthAccessStreamPairingLinkRemovedEvent.Type;
+
+export const AuthAccessStreamClientUpsertedEvent = Schema.Struct({
+ version: Schema.Literal(1),
+ revision: Schema.Number,
+ type: Schema.Literal("clientUpserted"),
+ payload: AuthClientSession,
+});
+export type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;
+
+export const AuthAccessStreamClientRemovedEvent = Schema.Struct({
+ version: Schema.Literal(1),
+ revision: Schema.Number,
+ type: Schema.Literal("clientRemoved"),
+ payload: Schema.Struct({
+ sessionId: AuthSessionId,
+ }),
+});
+export type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;
+
+export const AuthAccessStreamEvent = Schema.Union([
+ AuthAccessStreamSnapshotEvent,
+ AuthAccessStreamPairingLinkUpsertedEvent,
+ AuthAccessStreamPairingLinkRemovedEvent,
+ AuthAccessStreamClientUpsertedEvent,
+ AuthAccessStreamClientRemovedEvent,
+]);
+export type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;
+
+export const AuthRevokePairingLinkInput = Schema.Struct({
+ id: TrimmedNonEmptyString,
+});
+export type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;
+
+export const AuthRevokeClientSessionInput = Schema.Struct({
+ sessionId: AuthSessionId,
+});
+export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;
+
+export const AuthCreatePairingCredentialInput = Schema.Struct({
+ label: Schema.optionalKey(TrimmedNonEmptyString),
+});
+export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
+
+export const AuthSessionState = Schema.Struct({
+ authenticated: Schema.Boolean,
+ auth: ServerAuthDescriptor,
+ role: Schema.optionalKey(AuthSessionRole),
+ sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),
+ expiresAt: Schema.optionalKey(Schema.DateTimeUtc),
+});
+export type AuthSessionState = typeof AuthSessionState.Type;
diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts
index 5a199e9a6..9178ef8da 100644
--- a/packages/contracts/src/baseSchemas.ts
+++ b/packages/contracts/src/baseSchemas.ts
@@ -29,6 +29,8 @@ export const MessageId = makeEntityId("MessageId");
export type MessageId = typeof MessageId.Type;
export const TurnId = makeEntityId("TurnId");
export type TurnId = typeof TurnId.Type;
+export const AuthSessionId = makeEntityId("AuthSessionId");
+export type AuthSessionId = typeof AuthSessionId.Type;
export const ProviderItemId = makeEntityId("ProviderItemId");
export type ProviderItemId = typeof ProviderItemId.Type;
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index d2f84eda9..f12cf80d5 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -1,4 +1,5 @@
export * from "./baseSchemas";
+export * from "./auth";
export * from "./environment";
export * from "./ipc";
export * from "./terminal";
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 1a08d5208..462c6862c 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -107,12 +107,23 @@ export interface DesktopUpdateCheckResult {
export interface DesktopEnvironmentBootstrap {
label: string;
- wsUrl: string | null;
+ httpBaseUrl: string | null;
+ wsBaseUrl: string | null;
+ bootstrapToken?: string;
+}
+
+export type DesktopServerExposureMode = "local-only" | "network-accessible";
+
+export interface DesktopServerExposureState {
+ mode: DesktopServerExposureMode;
+ endpointUrl: string | null;
+ advertisedHost: string | null;
}
export interface DesktopBridge {
- getWsUrl: () => string | null;
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
+ getServerExposureState: () => Promise<DesktopServerExposureState>;
+ setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
setTheme: (theme: DesktopTheme) => Promise<void>;
diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts
index e62a957e0..7d87d882d 100644
--- a/packages/contracts/src/model.ts
+++ b/packages/contracts/src/model.ts
@@ -66,6 +66,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind,
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, string>> = {
codex: {
+ "gpt-5-codex": "gpt-5.4",
"5.4": "gpt-5.4",
"5.3": "gpt-5.3-codex",
"gpt-5.3": "gpt-5.3-codex",
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index a3d10299d..f47b427bc 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -3,6 +3,7 @@ import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import { OpenError, OpenInEditorInput } from "./editor";
+import { AuthAccessStreamEvent } from "./auth";
import {
GitActionProgressEvent,
GitCheckoutInput,
@@ -118,6 +119,7 @@ export const WS_METHODS = {
subscribeTerminalEvents: "subscribeTerminalEvents",
subscribeServerConfig: "subscribeServerConfig",
subscribeServerLifecycle: "subscribeServerLifecycle",
+ subscribeAuthAccess: "subscribeAuthAccess",
} as const;
export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {
@@ -334,6 +336,12 @@ export const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServer
stream: true,
});
+export const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess, {
+ payload: Schema.Struct({}),
+ success: AuthAccessStreamEvent,
+ stream: true,
+});
+
export const WsRpcGroup = RpcGroup.make(
WsServerGetConfigRpc,
WsServerRefreshProvidersRpc,
@@ -365,6 +373,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeTerminalEventsRpc,
WsSubscribeServerConfigRpc,
WsSubscribeServerLifecycleRpc,
+ WsSubscribeAuthAccessRpc,
WsOrchestrationGetSnapshotRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index 9227f4d8c..a4e33c990 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -1,5 +1,6 @@
import { Schema } from "effect";
import { ExecutionEnvironmentDescriptor } from "./environment";
+import { ServerAuthDescriptor } from "./auth";
import {
IsoDateTime,
NonNegativeInt,
@@ -85,6 +86,7 @@ export type ServerObservability = typeof ServerObservability.Type;
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
+ auth: ServerAuthDescriptor,
cwd: TrimmedNonEmptyString,
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts
index 232fa7118..62313f360 100644
--- a/packages/shared/src/model.test.ts
+++ b/packages/shared/src/model.test.ts
@@ -48,6 +48,7 @@ const claudeCaps: ModelCapabilities = {
describe("normalizeModelSlug", () => {
it("maps known aliases to canonical slugs", () => {
+ expect(normalizeModelSlug("gpt-5-codex")).toBe("gpt-5.4");
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("sonnet", "claudeAgent")).toBe("claude-sonnet-4-6");
});
diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts
index d3e19e55c..fc4a7b573 100644
--- a/scripts/dev-runner.test.ts
+++ b/scripts/dev-runner.test.ts
@@ -54,7 +54,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
- authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
@@ -75,7 +74,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/custom-t3",
- authToken: "secret",
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
@@ -105,7 +103,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
- authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
@@ -127,7 +124,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
- authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: false,
@@ -148,7 +144,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/my-t3",
- authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
@@ -161,13 +156,12 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
}),
);
- it.effect("does not export backend bootstrap env for dev:desktop", () =>
+ it.effect("pins desktop dev to a stable backend port and websocket url", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: {
T3CODE_PORT: "3773",
- T3CODE_AUTH_TOKEN: "stale-token",
T3CODE_MODE: "web",
T3CODE_NO_BROWSER: "0",
T3CODE_HOST: "0.0.0.0",
@@ -176,7 +170,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/my-t3",
- authToken: "fresh-token",
noBrowser: true,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
@@ -187,14 +180,13 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
assert.equal(env.PORT, "5733");
- assert.equal(env.ELECTRON_RENDERER_PORT, "5733");
- assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:5733");
- assert.equal(env.T3CODE_PORT, undefined);
- assert.equal(env.T3CODE_AUTH_TOKEN, undefined);
+ assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733");
+ assert.equal(env.HOST, "127.0.0.1");
+ assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.T3CODE_MODE, undefined);
assert.equal(env.T3CODE_NO_BROWSER, undefined);
assert.equal(env.T3CODE_HOST, undefined);
- assert.equal(env.VITE_WS_URL, undefined);
+ assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:4222");
}),
);
});
diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts
index 852f21ad0..b50c8237f 100644
--- a/scripts/dev-runner.ts
+++ b/scripts/dev-runner.ts
@@ -13,6 +13,7 @@ const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
+const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
path.join(homedir(), ".t3"),
@@ -120,7 +121,6 @@ interface CreateDevRunnerEnvInput {
readonly serverOffset: number;
readonly webOffset: number;
readonly t3Home: string | undefined;
- readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
@@ -135,7 +135,6 @@ export function createDevRunnerEnv({
serverOffset,
webOffset,
t3Home,
- authToken,
noBrowser,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
@@ -152,8 +151,9 @@ export function createDevRunnerEnv({
const output: NodeJS.ProcessEnv = {
...baseEnv,
PORT: String(webPort),
- ELECTRON_RENDERER_PORT: String(webPort),
- VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
+ VITE_DEV_SERVER_URL:
+ devUrl?.toString() ??
+ `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
T3CODE_HOME: resolvedBaseDir,
};
@@ -161,9 +161,8 @@ export function createDevRunnerEnv({
output.T3CODE_PORT = String(serverPort);
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
} else {
- delete output.T3CODE_PORT;
- delete output.VITE_WS_URL;
- delete output.T3CODE_AUTH_TOKEN;
+ output.T3CODE_PORT = String(serverPort);
+ output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;
delete output.T3CODE_HOST;
@@ -173,12 +172,6 @@ export function createDevRunnerEnv({
output.T3CODE_HOST = host;
}
- if (!isDesktopMode && authToken !== undefined) {
- output.T3CODE_AUTH_TOKEN = authToken;
- } else if (!isDesktopMode) {
- delete output.T3CODE_AUTH_TOKEN;
- }
-
if (!isDesktopMode && noBrowser !== undefined) {
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
} else if (!isDesktopMode) {
@@ -208,6 +201,7 @@ export function createDevRunnerEnv({
}
if (isDesktopMode) {
+ output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
delete output.T3CODE_DESKTOP_WS_URL;
}
@@ -350,7 +344,6 @@ export function resolveModePortOffsets<R = NetService>({
interface DevRunnerCliInput {
readonly mode: DevMode;
readonly t3Home: string | undefined;
- readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
@@ -430,7 +423,6 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
serverOffset,
webOffset,
t3Home: input.t3Home,
- authToken: input.authToken,
noBrowser: resolveOptionalBooleanOverride(input.noBrowser, envOverrides.noBrowser),
autoBootstrapProjectFromCwd: resolveOptionalBooleanOverride(
input.autoBootstrapProjectFromCwd,
@@ -503,11 +495,6 @@ const devRunnerCli = Command.make("dev-runner", {
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
),
- authToken: Flag.string("auth-token").pipe(
- Flag.withDescription("Auth token (forwards to T3CODE_AUTH_TOKEN)."),
- Flag.withAlias("token"),
- Flag.withFallbackConfig(optionalStringConfig("T3CODE_AUTH_TOKEN")),
- ),
noBrowser: Flag.boolean("no-browser").pipe(
Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
diff --git a/turbo.json b/turbo.json
index 47d709138..d4d58c15e 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,10 +1,10 @@
{
"$schema": "https://turbo.build/schema.json",
"globalEnv": [
+ "HOST",
"PORT",
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
- "ELECTRON_RENDERER_PORT",
"T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE",
"T3CODE_PORT",