From 814c206bde225c338af2851d9ea7b72da7fcf4a9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 26 Apr 2026 19:06:52 -0700 Subject: [PATCH] feat(web): support hosted pairing links Co-authored-by: codex --- .plans/19-remote-endpoints-hosted-static.md | 350 ++++++++++++++++++ .../components/auth/PairingRouteSurface.tsx | 99 +++++ .../settings/ConnectionsSettings.tsx | 17 +- apps/web/src/environments/runtime/service.ts | 6 +- apps/web/src/hostedPairing.test.ts | 52 +++ apps/web/src/hostedPairing.ts | 49 +++ apps/web/src/localApi.ts | 42 ++- apps/web/src/routes/__root.tsx | 79 +++- apps/web/src/routes/_chat.tsx | 5 +- apps/web/src/routes/pair.tsx | 18 +- apps/web/src/routes/settings.tsx | 5 +- apps/web/vite.config.ts | 2 + 12 files changed, 700 insertions(+), 24 deletions(-) create mode 100644 .plans/19-remote-endpoints-hosted-static.md create mode 100644 apps/web/src/hostedPairing.test.ts create mode 100644 apps/web/src/hostedPairing.ts diff --git a/.plans/19-remote-endpoints-hosted-static.md b/.plans/19-remote-endpoints-hosted-static.md new file mode 100644 index 0000000000..2fa0bc7021 --- /dev/null +++ b/.plans/19-remote-endpoints-hosted-static.md @@ -0,0 +1,350 @@ +# Remote Endpoints and Hosted Static App Plan + +## Purpose + +Make remote access feel first-class while keeping the free DIY path open. + +The immediate product goal is: + +- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel +- users can generate a hosted pairing link for `app.t3.codes` +- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin +- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX + +This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into. + +## Current State + +Already present or in progress: + +- Server auth distinguishes bootstrap credentials from session credentials. +- One-time pairing credentials can be exchanged for browser sessions or bearer sessions. +- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token. +- Remote environment WebSocket connections use a short-lived WebSocket token. +- Pairing URLs can carry tokens in the URL fragment. +- Hosted `/pair?host=...#token=...` can add a saved environment. +- Hosted static startup can avoid assuming the page origin is the backend. + +Main gaps: + +- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs. +- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model. +- Tailscale/MagicDNS endpoints are not detected or surfaced. +- Hosted-static empty/offline states are still thin. +- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure. + +## Core Decision: Add `AdvertisedEndpoint` + +Add a new first-class contract instead of extending the environment descriptor. + +### Why not extend `ExecutionEnvironmentDescriptor` + +`ExecutionEnvironmentDescriptor` answers: "What environment is this?" + +Examples: + +- environment id +- label +- platform +- server version +- capabilities + +`AdvertisedEndpoint` answers: "How can a client reach this environment right now?" + +Examples: + +- loopback URL +- LAN URL +- Tailscale IP URL +- MagicDNS/Serve URL +- manual URL +- future T3 Tunnel URL +- browser compatibility and exposure level + +Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about. + +### Target Contract + +Add a schema in `packages/contracts`, likely `remoteAccess.ts`: + +```ts +type AdvertisedEndpointProvider = + | "loopback" + | "lan" + | "tailscale-ip" + | "tailscale-magicdns" + | "manual" + | "t3-tunnel"; + +type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public"; + +type AdvertisedEndpointCompatibility = { + hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown"; + desktopApp: "compatible" | "unknown"; +}; + +type AdvertisedEndpoint = { + id: string; + provider: AdvertisedEndpointProvider; + label: string; + httpBaseUrl: string; + wsBaseUrl: string; + visibility: AdvertisedEndpointVisibility; + compatibility: AdvertisedEndpointCompatibility; + source: "server" | "desktop" | "user"; + status: "available" | "unavailable" | "unknown"; + isDefault?: boolean; +}; +``` + +Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`. + +## HTTP/WS and HTTPS/WSS Readiness + +The codebase is partially ready, but the UX and compatibility model are not explicit enough. + +What is ready: + +- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`. +- Saved environments store both HTTP and WebSocket base URLs. +- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable. +- WebSocket connections can use a dynamically issued `wsToken`. +- Server CORS support exists for browser remote auth endpoints. + +What is not solved by code alone: + +- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content. +- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust. +- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app. +- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible. + +Policy: + +- Support both HTTP/WS and HTTPS/WSS at the runtime layer. +- Mark endpoint compatibility at the product layer. +- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback. + +## Architecture + +### Endpoint Sources + +Endpoint records can come from several providers: + +1. **Server runtime** + - headless bind host and port + - server-known explicit advertised host config + +2. **Desktop shell** + - loopback backend URL + - LAN exposure state + - network interface discovery + - Tailscale CLI/status discovery + +3. **User configuration** + - manually added hostnames + - preferred endpoint labels + - hidden/disabled endpoints + +4. **Future cloud provider** + - T3 Tunnel endpoint + - billing/account status + - tunnel lifecycle state + +### Endpoint Registry + +Create a central runtime registry: + +- `packages/contracts/src/remoteAccess.ts` +- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification +- `apps/server/src/remoteAccess/*` for server/headless endpoints +- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints +- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection + +The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel. + +### Pairing Link Generation + +Move hosted pairing link generation to endpoint-driven input: + +```ts +buildHostedPairingUrl({ + endpoint: AdvertisedEndpoint, + token, +}); +``` + +Generated URL: + +```text +https://app.t3.codes/pair?host=#token= +``` + +Use fragment tokens by default. Continue accepting `?token=` for compatibility. + +## Phase 1: Endpoint Abstraction + +### Goals + +- Centralize URL normalization, protocol derivation, and compatibility checks. +- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection. +- Preserve all current remote behavior. + +### Tasks + +1. Add `AdvertisedEndpoint` schemas to `packages/contracts`. +2. Add shared helpers: + - normalize HTTP base URL + - derive WebSocket base URL + - classify loopback/private/LAN/Tailscale/public host + - classify hosted HTTPS compatibility +3. Add server endpoint discovery: + - loopback endpoint + - configured non-loopback endpoint + - explicit advertised host override +4. Add desktop endpoint discovery: + - local loopback + - LAN exposure endpoint + - endpoint status labels +5. Add WebSocket/API method or existing config field for endpoint snapshots. +6. Refactor settings connections UI: + - render endpoint rows + - endpoint picker for pairing link copy + - show compatibility warnings +7. Refactor hosted link builder to accept endpoint records. +8. Add tests for URL normalization and compatibility classification. + +### Acceptance Criteria + +- Existing LAN/network access UI still works. +- Pairing links are generated from endpoint records. +- Loopback endpoints never produce hosted pairing links silently. +- HTTP private-network endpoints are marked incompatible with `app.t3.codes`. +- No remote environment runtime changes are required for existing saved environments. + +## Phase 2: BYO Tailscale/MagicDNS + +### Goals + +- Detect free DIY Tailscale reachability. +- Surface Tailscale endpoints as normal advertised endpoints. +- Keep users in control of their own tailnet. + +### Tasks + +1. Detect Tailscale IPs from network interfaces: + - IPv4 `100.64.0.0/10` + - mark as `provider: "tailscale-ip"` +2. Add optional desktop-side `tailscale status --json` discovery: + - MagicDNS hostname + - Tailscale Serve/Funnel HTTPS endpoint if discoverable + - graceful failure if CLI is missing +3. Add manual Tailscale endpoint override: + - hostname + - label + - preferred/default flag +4. Show Tailscale endpoint rows in settings: + - raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked + - HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS +5. Generate pairing links using selected Tailscale endpoint. +6. Document DIY setup: + - local desktop-to-desktop over Tailscale + - hosted app requirements + - why HTTPS matters + +### Acceptance Criteria + +- A machine on Tailscale shows a Tailscale endpoint without paid features. +- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible. +- Users can still copy token-only/manual values when endpoint compatibility is unknown. +- Tailscale is optional and never required for regular LAN/loopback use. + +## Phase 3: Hosted Static App Completion + +### Goals + +- `app.t3.codes` works as a real client shell. +- It can pair, persist, reconnect, and clearly explain offline/incompatible states. + +### Tasks + +1. Finish hosted-static root behavior: + - no primary backend required + - saved environment hydration before initial routing decisions + - first saved environment selected as active +2. Add hosted empty state: + - no saved environments + - paste pairing URL + - add host + token +3. Add offline saved environment UI: + - last connected + - reconnect + - remove + - copy/add alternate endpoint +4. Audit primary-backend assumptions: + - command palette + - settings pages + - server config atom defaults + - keybindings + - provider/model lists + - update/desktop-only affordances +5. Add route tests for: + - hosted `/pair?host=...#token=...` + - hosted root with no saved environments + - hosted root with saved environment + - primary backend unavailable but saved environment present +6. Add deployment hardening: + - SPA fallback + - strict CSP + - no third-party scripts + - no query token logging + - disable or hide source maps in production if needed +7. Add browser error messages: + - mixed content + - unreachable backend + - CORS failure + - certificate failure + +### Acceptance Criteria + +- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload. +- A saved environment can be used without any backend at `app.t3.codes`. +- Offline machines show a useful state instead of a generic boot error. +- HTTP endpoints are still supported in desktop/native/local contexts. +- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints. + +## Phase 4: Future T3 Tunnel Provider + +Not part of the current implementation, but the endpoint abstraction should make it straightforward. + +Future tunnel provider responsibilities: + +- create endpoint with `provider: "t3-tunnel"` +- surface tunnel status +- provide stable HTTPS URL +- use existing backend pairing/session auth +- never bypass server auth + +The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`. + +## Security Checklist + +- Pairing tokens are short-lived and one-time. +- Generated hosted pairing links put tokens in the fragment. +- The backend remains the authorization boundary. +- Endpoint discovery never disables backend auth. +- Hosted app does not silently downgrade to HTTP. +- Tunnel/public endpoints require explicit user action. +- Client sessions remain revocable. +- Endpoint URLs and request logs must avoid recording pairing tokens. +- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing. + +## Verification + +Each implementation PR should run: + +- `bun fmt` +- `bun lint` +- `bun typecheck` +- focused tests for changed backend/web behavior +- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test` + diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index f583af72ec..46349ca1fa 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -2,11 +2,13 @@ import type { AuthSessionState } from "@t3tools/contracts"; import React, { startTransition, useEffect, useRef, useState, useCallback } from "react"; import { APP_DISPLAY_NAME } from "../../branding"; +import { addSavedEnvironment } from "../../environments/runtime"; import { peekPairingTokenFromUrl, stripPairingTokenFromUrl, submitServerAuthCredential, } from "../../environments/primary"; +import { readHostedPairingRequest } from "../../hostedPairing"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -159,6 +161,103 @@ export function PairingRouteSurface({ ); } +export function HostedPairingRouteSurface() { + const hostedPairingRequestRef = useRef(readHostedPairingRequest()); + const [status, setStatus] = useState<"pairing" | "paired" | "error">("pairing"); + const [message, setMessage] = useState("Connecting to this backend."); + const submitAttemptedRef = useRef(false); + + const submitHostedPairingRequest = useCallback(async () => { + const request = hostedPairingRequestRef.current; + + if (!request) { + setStatus("error"); + setMessage("This pairing link is missing its backend host or token."); + return; + } + + setStatus("pairing"); + setMessage("Connecting to this backend."); + + try { + const record = await addSavedEnvironment({ + label: request.label, + host: request.host, + pairingCode: request.token, + }); + setStatus("paired"); + setMessage(`${record.label} is saved in this browser.`); + } catch (error) { + setStatus("error"); + setMessage(errorMessageFromUnknown(error)); + } + }, []); + + useEffect(() => { + if (submitAttemptedRef.current) { + return; + } + submitAttemptedRef.current = true; + + stripPairingTokenFromUrl(); + void submitHostedPairingRequest(); + }, [submitHostedPairingRequest]); + + const request = hostedPairingRequestRef.current; + + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ {status === "paired" + ? "Backend paired" + : status === "error" + ? "Pairing failed" + : "Pairing backend"} +

+

{message}

+ + {request ? ( +
+ Host: {request.host} +
+ ) : null} + + {status === "error" ? ( +
+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and + is served over HTTPS when opening this page from HTTPS. +
+ ) : null} + +
+ + {status === "paired" ? ( + + ) : null} +
+
+
+ ); +} + function errorMessageFromUnknown(error: unknown): string { if (error instanceof Error && error.message.trim().length > 0) { return error.message; diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 880c4376e2..50af9f8859 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -9,6 +9,7 @@ import { import { DateTime } from "effect"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; +import { buildHostedPairingUrl } from "../../hostedPairing"; import { cn } from "../../lib/utils"; import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat"; import { @@ -249,6 +250,13 @@ function resolveDesktopPairingUrl(endpointUrl: string, credential: string): stri return setPairingTokenOnUrl(url, credential).toString(); } +function resolveHostedPairingUrl(endpointUrl: string, credential: string): string { + return buildHostedPairingUrl({ + host: endpointUrl, + token: credential, + }); +} + function resolveCurrentOriginPairingUrl(credential: string): string { const url = new URL("/pair", window.location.href); return setPairingTokenOnUrl(url, credential).toString(); @@ -278,9 +286,16 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ () => resolveCurrentOriginPairingUrl(pairingLink.credential), [pairingLink.credential], ); + const hostedPairingUrl = useMemo( + () => + endpointUrl != null && endpointUrl !== "" + ? resolveHostedPairingUrl(endpointUrl, pairingLink.credential) + : null, + [endpointUrl, pairingLink.credential], + ); const shareablePairingUrl = endpointUrl != null && endpointUrl !== "" - ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential) + ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)) : isLoopbackHostname(window.location.hostname) ? null : currentOriginPairingUrl; diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index d724eeff33..ec920e9a7b 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -905,6 +905,10 @@ function createPrimaryEnvironmentConnection(): EnvironmentConnection { ); } +function maybeCreatePrimaryEnvironmentConnection(): EnvironmentConnection | null { + return getPrimaryKnownEnvironment() ? createPrimaryEnvironmentConnection() : null; +} + async function ensureSavedEnvironmentConnection( record: SavedEnvironmentRecord, options?: { @@ -1170,7 +1174,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): () }, ); - createPrimaryEnvironmentConnection(); + maybeCreatePrimaryEnvironmentConnection(); const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => { if (!hasSavedEnvironmentRegistryHydrated()) { diff --git a/apps/web/src/hostedPairing.test.ts b/apps/web/src/hostedPairing.test.ts new file mode 100644 index 0000000000..f347ca46ab --- /dev/null +++ b/apps/web/src/hostedPairing.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + buildHostedPairingUrl, + hasHostedPairingRequest, + readHostedPairingRequest, +} from "./hostedPairing"; + +describe("hostedPairing", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("reads hosted pairing host and query token parameters", () => { + const url = new URL("https://app.t3.codes/pair?host=100.64.1.2:3773&token=ABCD1234"); + + expect(readHostedPairingRequest(url)).toEqual({ + host: "100.64.1.2:3773", + token: "ABCD1234", + label: "", + }); + expect(hasHostedPairingRequest(url)).toBe(true); + }); + + it("prefers hash tokens so generated hosted links do not put credentials in search params", () => { + vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes"); + + const url = new URL( + buildHostedPairingUrl({ + host: "https://backend.example.com:3773", + token: "pairing-token", + label: "Workstation", + }), + ); + + expect(url.origin).toBe("https://preview.t3.codes"); + expect(url.pathname).toBe("/pair"); + expect(url.searchParams.get("host")).toBe("https://backend.example.com:3773"); + expect(url.searchParams.get("label")).toBe("Workstation"); + expect(url.searchParams.has("token")).toBe(false); + expect(url.hash).toBe("#token=pairing-token"); + }); + + it("ignores incomplete hosted pairing requests", () => { + expect( + hasHostedPairingRequest(new URL("https://app.t3.codes/pair?host=backend.example.com")), + ).toBe(false); + expect(hasHostedPairingRequest(new URL("https://app.t3.codes/pair?token=ABCD1234"))).toBe( + false, + ); + }); +}); diff --git a/apps/web/src/hostedPairing.ts b/apps/web/src/hostedPairing.ts new file mode 100644 index 0000000000..9855c01be2 --- /dev/null +++ b/apps/web/src/hostedPairing.ts @@ -0,0 +1,49 @@ +import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl"; + +const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes"; + +export interface HostedPairingRequest { + readonly host: string; + readonly token: string; + readonly label: string; +} + +function configuredHostedAppUrl(): string { + return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL; +} + +export function readHostedPairingRequest(url: URL = new URL(window.location.href)) { + const host = url.searchParams.get("host")?.trim() ?? ""; + const token = getPairingTokenFromUrl(url)?.trim() ?? ""; + const label = url.searchParams.get("label")?.trim() ?? ""; + + if (!host || !token) { + return null; + } + + return { + host, + token, + label, + } satisfies HostedPairingRequest; +} + +export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean { + return readHostedPairingRequest(url) !== null; +} + +export function buildHostedPairingUrl(input: { + readonly host: string; + readonly token: string; + readonly label?: string | null; +}): string { + const url = new URL("/pair", configuredHostedAppUrl()); + url.searchParams.set("host", input.host); + + const label = input.label?.trim(); + if (label) { + url.searchParams.set("label", label); + } + + return setPairingTokenOnUrl(url, input.token).toString(); +} diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 4401b5b778..b01870f979 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -12,6 +12,7 @@ import { getPrimaryEnvironmentConnection, resetEnvironmentServiceForTests, } from "./environments/runtime"; +import { getPrimaryKnownEnvironment } from "./environments/primary"; import { type WsRpcClient } from "./rpc/wsRpcClient"; import { showContextMenuFallback } from "./contextMenuFallback"; import { @@ -26,7 +27,11 @@ import { let cachedApi: LocalApi | undefined; -export function createLocalApi(rpcClient: WsRpcClient): LocalApi { +function unavailableLocalBackendError(): Error { + return new Error("Local backend API is unavailable before a backend is paired."); +} + +function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi { return { dialogs: { pickFolder: async (options) => { @@ -41,7 +46,10 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi { }, }, shell: { - openInEditor: (cwd, editor) => rpcClient.shell.openInEditor({ cwd, editor }), + openInEditor: (cwd, editor) => + rpcClient + ? rpcClient.shell.openInEditor({ cwd, editor }) + : Promise.reject(unavailableLocalBackendError()), openExternal: async (url) => { if (window.desktopBridge) { const opened = await window.desktopBridge.openExternal(url); @@ -110,15 +118,30 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi { }, }, server: { - getConfig: rpcClient.server.getConfig, - refreshProviders: rpcClient.server.refreshProviders, - upsertKeybinding: rpcClient.server.upsertKeybinding, - getSettings: rpcClient.server.getSettings, - updateSettings: rpcClient.server.updateSettings, + getConfig: () => + rpcClient ? rpcClient.server.getConfig() : Promise.reject(unavailableLocalBackendError()), + refreshProviders: () => + rpcClient + ? rpcClient.server.refreshProviders() + : Promise.reject(unavailableLocalBackendError()), + upsertKeybinding: (input) => + rpcClient + ? rpcClient.server.upsertKeybinding(input) + : Promise.reject(unavailableLocalBackendError()), + getSettings: () => + rpcClient ? rpcClient.server.getSettings() : Promise.reject(unavailableLocalBackendError()), + updateSettings: (patch) => + rpcClient + ? rpcClient.server.updateSettings(patch) + : Promise.reject(unavailableLocalBackendError()), }, }; } +export function createLocalApi(rpcClient: WsRpcClient): LocalApi { + return createBrowserLocalApi(rpcClient); +} + export function readLocalApi(): LocalApi | undefined { if (typeof window === "undefined") return undefined; if (cachedApi) return cachedApi; @@ -128,7 +151,10 @@ export function readLocalApi(): LocalApi | undefined { return cachedApi; } - cachedApi = createLocalApi(getPrimaryEnvironmentConnection().client); + const primaryEnvironment = getPrimaryKnownEnvironment(); + cachedApi = primaryEnvironment + ? createLocalApi(getPrimaryEnvironmentConnection().client) + : createBrowserLocalApi(); return cachedApi; } diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 87e8667901..fb33c6ae23 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -46,26 +46,52 @@ import { syncBrowserChromeTheme } from "../hooks/useTheme"; import { ensureEnvironmentConnectionBootstrapped, getPrimaryEnvironmentConnection, + listSavedEnvironmentRecords, + waitForSavedEnvironmentRegistryHydration, startEnvironmentConnectionService, + useSavedEnvironmentRegistryStore, } from "../environments/runtime"; import { configureClientTracing } from "../observability/clientTracing"; import { ensurePrimaryEnvironmentReady, + getPrimaryKnownEnvironment, resolveInitialServerAuthGateState, updatePrimaryEnvironmentDescriptor, } from "../environments/primary"; +import { hasHostedPairingRequest } from "../hostedPairing"; export const Route = createRootRouteWithContext<{ queryClient: QueryClient; }>()({ - beforeLoad: async () => { - const [, authGateState] = await Promise.all([ - ensurePrimaryEnvironmentReady(), - resolveInitialServerAuthGateState(), - ]); - return { - authGateState, - }; + beforeLoad: async ({ location }) => { + if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) { + return { + authGateState: { + status: "hosted-pairing", + } as const, + }; + } + + try { + const [, authGateState] = await Promise.all([ + ensurePrimaryEnvironmentReady(), + resolveInitialServerAuthGateState(), + ]); + return { + authGateState, + }; + } catch (error) { + if (location.pathname === "/pair") { + throw error; + } + + await waitForSavedEnvironmentRegistryHydration(); + return { + authGateState: { + status: "hosted-static", + } as const, + }; + } }, component: RootRouteView, errorComponent: RootRouteErrorView, @@ -91,7 +117,7 @@ function RootRouteView() { return ; } - if (authGateState.status !== "authenticated") { + if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") { return ; } return ( @@ -100,6 +126,7 @@ function RootRouteView() { + @@ -115,6 +142,32 @@ function RootRouteView() { ); } +function HostedStaticEnvironmentBootstrap() { + const savedEnvironmentCount = useSavedEnvironmentRegistryStore( + (state) => Object.keys(state.byId).length, + ); + + useEffect(() => { + if (getPrimaryKnownEnvironment()) { + return; + } + + const currentActiveEnvironmentId = useStore.getState().activeEnvironmentId; + if (currentActiveEnvironmentId) { + return; + } + + const firstSavedEnvironment = listSavedEnvironmentRecords()[0]; + if (!firstSavedEnvironment) { + return; + } + + useStore.getState().setActiveEnvironmentId(firstSavedEnvironment.environmentId); + }, [savedEnvironmentCount]); + + return null; +} + function RootRouteErrorView({ error, reset }: ErrorComponentProps) { const message = errorMessage(error); const details = errorDetails(error); @@ -187,7 +240,13 @@ function errorDetails(error: unknown): string { } function ServerStateBootstrap() { - useEffect(() => startServerStateSync(getPrimaryEnvironmentConnection().client.server), []); + useEffect(() => { + if (!getPrimaryKnownEnvironment()) { + return; + } + + return startServerStateSync(getPrimaryEnvironmentConnection().client.server); + }, []); return null; } diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index fb8191f448..da22d7e602 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -108,7 +108,10 @@ function ChatRouteLayout() { export const Route = createFileRoute("/_chat")({ beforeLoad: async ({ context }) => { - if (context.authGateState.status !== "authenticated") { + if ( + context.authGateState.status !== "authenticated" && + context.authGateState.status !== "hosted-static" + ) { throw redirect({ to: "/pair", replace: true }); } }, diff --git a/apps/web/src/routes/pair.tsx b/apps/web/src/routes/pair.tsx index 6925dac69c..6575cd1baf 100644 --- a/apps/web/src/routes/pair.tsx +++ b/apps/web/src/routes/pair.tsx @@ -1,11 +1,21 @@ import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router"; -import { PairingPendingSurface, PairingRouteSurface } from "../components/auth/PairingRouteSurface"; +import { + HostedPairingRouteSurface, + PairingPendingSurface, + PairingRouteSurface, +} from "../components/auth/PairingRouteSurface"; export const Route = createFileRoute("/pair")({ beforeLoad: async ({ context }) => { const { authGateState } = context; - if (authGateState.status === "authenticated") { + if (authGateState.status === "hosted-pairing") { + return { + authGateState, + }; + } + + if (authGateState.status === "authenticated" || authGateState.status === "hosted-static") { throw redirect({ to: "/", replace: true }); } return { @@ -24,6 +34,10 @@ function PairRouteView() { return null; } + if (authGateState.status === "hosted-pairing") { + return ; + } + return ( { - if (context.authGateState.status !== "authenticated") { + if ( + context.authGateState.status !== "authenticated" && + context.authGateState.status !== "hosted-static" + ) { throw redirect({ to: "/pair", replace: true }); } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 01b5076695..091cb454b1 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -9,6 +9,7 @@ const port = Number(process.env.PORT ?? 5733); const host = process.env.HOST?.trim() || "localhost"; const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim(); const configuredWsUrl = process.env.VITE_WS_URL?.trim(); +const configuredHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim(); const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase(); const buildSourcemap = @@ -62,6 +63,7 @@ export default defineConfig({ "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""), // In dev mode, tell the web app where the WebSocket server lives "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""), + "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""), "import.meta.env.APP_VERSION": JSON.stringify(pkg.version), }, resolve: {