feat(web): support hosted pairing links

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-04-26 19:31:35 -07:00
1 parent 5cf83ffe8f
commit 814c206bde
12 files changed
+700 -24

No files matched your search

+350
View File
@@ -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=<encoded endpoint httpBaseUrl>#token=<one-time 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`
@@ -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 (
<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">
{status === "paired"
? "Backend paired"
: status === "error"
? "Pairing failed"
: "Pairing backend"}
</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
{request ? (
<div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
Host: <span className="font-mono text-foreground/80">{request.host}</span>
</div>
) : null}
{status === "error" ? (
<div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
Verify the backend is reachable from this browser, supports CORS for hosted clients, and
is served over HTTPS when opening this page from HTTPS.
</div>
) : null}
<div className="mt-6 flex flex-wrap gap-2">
<Button
disabled={status === "pairing"}
size="sm"
onClick={() => void submitHostedPairingRequest()}
>
{status === "pairing" ? "Pairing..." : "Try again"}
</Button>
{status === "paired" ? (
<Button size="sm" variant="outline" onClick={() => (window.location.href = "/")}>
Open app
</Button>
) : null}
</div>
</section>
</div>
);
}
function errorMessageFromUnknown(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
@@ -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;
+5 -1
View File
@@ -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()) {
+52
View File
@@ -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,
);
});
});
+49
View File
@@ -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();
}
+34 -8
View File
@@ -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;
}
+69 -10
View File
@@ -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 <Outlet />;
}
if (authGateState.status !== "authenticated") {
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
return <Outlet />;
}
return (
@@ -100,6 +126,7 @@ function RootRouteView() {
<AuthenticatedTracingBootstrap />
<ServerStateBootstrap />
<EnvironmentConnectionManagerBootstrap />
<HostedStaticEnvironmentBootstrap />
<EventRouter />
<WebSocketConnectionCoordinator />
<SlowRpcAckToastCoordinator />
@@ -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;
}
+4 -1
View File
@@ -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 });
}
},
+16 -2
View File
@@ -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 <HostedPairingRouteSurface />;
}
return (
<PairingRouteSurface
auth={authGateState.auth}
+4 -1
View File
@@ -88,7 +88,10 @@ function SettingsRouteLayout() {
export const Route = createFileRoute("/settings")({
beforeLoad: async ({ context, location }) => {
if (context.authGateState.status !== "authenticated") {
if (
context.authGateState.status !== "authenticated" &&
context.authGateState.status !== "hosted-static"
) {
throw redirect({ to: "/pair", replace: true });
}
+2
View File
@@ -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: {