Open History to see the last commit
1# Remote Architecture
2
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4
5Remote environments are shipped, not planned. Direct, bearer-paired, relay-tunneled, Tailscale, and
6desktop-managed SSH access all exist today. This document describes the model they share and where
7each piece lives. For the user-facing setup guide see
8[remote access](../user/remote-access.md).
9
10## The model
11
12T3 has one runtime boundary: a client talks to a T3 server over HTTP and WebSocket, and the server
13owns orchestration, providers, terminals, git, and filesystem operations. Remoteness is expressed at
14the connection layer, never by splitting the runtime.
15
16```text
17┌──────────────────────────────────────────────┐
18│ Client (desktop / mobile / web) │
19│ known environments, connection supervisor │
20└───────────────┬──────────────────────────────┘
21 │ resolves one access endpoint
22┌───────────────▼──────────────────────────────┐
23│ Access method │
24│ direct ws/wss, relay tunnel, │
25│ Tailscale serve, desktop-managed ssh │
26└───────────────┬──────────────────────────────┘
27 │ connects to one T3 server
28┌───────────────▼──────────────────────────────┐
29│ Execution environment = one T3 server │
30│ identity, providers, projects/threads, │
31│ terminals, git, filesystem │
32└──────────────────────────────────────────────┘
33```
34
35### ExecutionEnvironment
36
37One running T3 server instance. It owns provider availability and auth, model availability, projects
38and threads, terminal processes, filesystem access, git operations, and server settings.
39
40It is identified by a stable `environmentId`, persisted by the server at `<stateDir>/environment-id`
41and generated on first start (`apps/server/src/environment/ServerEnvironment.ts`). Desktop, mobile,
42and web all reason about the same concept.
43
44Initialization publishes a complete ID atomically. Empty or whitespace-only ID files are repaired
45using a retained `<stateDir>/environment-id.recovery` file so concurrent and delayed repairs choose
46the same ID. Existing nonempty ID files remain authoritative.
47
48### Known environments and connection targets
49
50A saved client-side entry for an environment the client knows how to reach. It is not
51server-authored; it is local to a device or client profile. In the hosted web app these entries are
52browser-local. A hosted pairing URL can create one, but it does not give the hosted app a server-side
53control plane or a copy of session state.
54
55[`connection/model.ts`][model] defines four target tags, which are the real access taxonomy:
56
57| Target | Used for |
58| ------------------------- | ------------------------------------------------------------------------ |
59| `PrimaryConnectionTarget` | The platform-managed local server (desktop backend, CLI-served web app). |
60| `BearerConnectionTarget` | Any manually paired endpoint reached over direct HTTP/WebSocket. |
61| `RelayConnectionTarget` | Managed T3 Connect relay tunnels. |
62| `SshConnectionTarget` | Desktop-managed SSH environments. |
63
64Bearer, relay, and SSH are persisted; primary is platform-managed. Note that Tailscale is not a
65separate target kind. A Tailscale URL is paired through the ordinary bearer path in
66[`onboarding.ts`][onboarding] (`preparePairingRegistration`), which accepts either a pairing URL or a
67host plus pairing code. Tailscale is an endpoint provider and transport, not a distinct runtime
68concept.
69
70### AdvertisedEndpoint
71
72A server- or desktop-authored candidate endpoint for an environment: a concrete HTTP and WebSocket
73base URL pair, a default/available/unavailable marker, reachability hints (loopback, LAN, private,
74public, tunnel), and compatibility hints such as whether the hosted HTTPS app can use it.
75
76Clients treat advertised endpoints as hints, not proof that a route works from the current device.
77The connection attempt decides.
78
79The UI shows one default endpoint in the network-access summary and keeps the rest behind an advanced
80list. `selectPairingEndpoint` in
81[`ConnectionsSettings.tsx`](../../apps/web/src/components/settings/ConnectionsSettings.tsx) excludes
82unavailable endpoints and then picks, in order:
83
841. the saved `defaultEndpointKey` override;
852. the first endpoint marked `isDefault`;
863. the first endpoint whose reachability is not `loopback`;
874. the first endpoint compatible with the hosted HTTPS app;
885. otherwise nothing.
89
90There is no unconditional loopback fallback. A loopback endpoint only wins through an explicit saved
91override or `isDefault`. Persist the override by stable endpoint kind rather than raw URL where
92possible, since LAN addresses change with networks; Tailscale endpoints use provider-specific stable
93keys (`tailscale-ip:`, `tailscale-magicdns:`).
94
95### Endpoint providers
96
97Endpoint providers contribute advertised endpoints without becoming part of the core environment
98model: core owns environments, pairing, and connection lifecycle, and providers return normalized
99`AdvertisedEndpoint` records.
100
101Tailscale is the first provider, and T3 manages more than discovery. When `tailscaleServeEnabled` is
102set, the server acquires a Tailscale serve mapping for its actual listening port at startup with
103`ensureTailscaleServe` and releases it with `disableTailscaleServe` on scope close
104(`apps/server/src/server.ts`, using [`@t3tools/tailscale`](../../packages/tailscale/src/tailscale.ts)).
105Endpoint identifiers are synthesized in `apps/desktop/src/backend/tailscaleEndpointProvider.ts` with
106`private-network` reachability.
107
108### Hosted pairing request
109
110A hosted pairing request is a bootstrap URL for the static web app, not a transport:
111
112```text
113https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
114```
115
116The hosted app reads `host`, takes the token from the URL hash, exchanges it directly with that
117backend, strips the token from browser history, and saves the environment record locally. Helpers
118live in [`shared/remote.ts`](../../packages/shared/src/remote.ts) (`setPairingTokenOnUrl`,
119`getPairingTokenFromUrl`, `stripPairingTokenFromUrl`) and `apps/web/src/hostedPairing.ts`.
120
121Constraints:
122
123- the hosted app does not proxy HTTP or WebSocket traffic;
124- the backend must be directly reachable from the browser;
125- HTTPS pages can only reach HTTPS/WSS backends;
126- HTTP LAN endpoints keep using direct desktop or CLI pairing URLs;
127- the token belongs in the hash so it is never sent to the hosted app origin.
128
129### RepositoryIdentity and Project
130
131`RepositoryIdentity` is a best-effort logical repo grouping across environments, used for UI grouping
132and correlation only, never for routing. `Project` remains environment-local: a local clone and a
133remote clone are different projects that may share a `RepositoryIdentity`, and threads bind to one
134project in one environment.
135
136## Access methods
137
138Access answers one question: how does the client speak WebSocket to a T3 server? It does not answer
139how the server got started or who manages the process.
140
141### Direct WebSocket access
142
143`wss://t3.example.com` or `ws://10.0.0.15:3773`, paired as a bearer target. This is the base model.
144It works for desktop, mobile, and web with no client-side process management. Browser security rules
145are part of it: a hosted HTTPS client cannot connect to plain `ws://` or `http://` LAN backends.
146
147### Relay-tunneled access
148
149Managed T3 Connect relay tunnels use `RelayConnectionTarget` and are the answer when the host is
150behind NAT, inbound ports are unavailable, or mobile must reach a desktop-hosted environment. From
151the client's perspective this is still an ordinary WebSocket connection; the route is mediated. The
152relay Worker only brokers credentials and a managed endpoint; application traffic then flows over
153the provisioned Cloudflare tunnel hostname for the life of the connection, not through the relay
154Worker itself. See [t3-connect.md](./t3-connect.md).
155
156### Tailscale access
157
158A T3-managed `tailscale serve` mapping exposes the server on the tailnet over HTTPS, and the
159resulting private-network endpoints are advertised for pairing. Connection then follows the ordinary
160bearer path.
161
162### Desktop-managed SSH access
163
164SSH is an access and launch helper, not a separate environment type. `DesktopSshEnvironment`
165([apps/desktop/src/ssh/DesktopSshEnvironment.ts][sshenv]) exposes `discoverHosts`,
166`ensureEnvironment`, and `disconnectEnvironment`. It discovers targets from SSH config and known
167hosts, owns password/askpass prompts, and delegates lifecycle to `SshEnvironmentManager` in
168[packages/ssh/src/tunnel.ts][sshtunnel], which resolves the target, launches or reuses the remote T3
169server, opens a local tunnel, checks HTTP readiness, optionally issues a remote pairing token, and
170returns local HTTP/WS endpoints. Disconnect closes the tunnel and stops the remote server if the
171launcher started it; a server that was already running (marked `external`) is left running.
172
173The desktop main process owns this because it can spawn SSH, manage prompts, write launch scripts,
174and clean up forwards. The renderer connects through the forwarded URL like any other environment and
175needs no SSH-specific RPC path.
176
177Failure handling is explicit: SSH auth failure surfaces before an environment is saved, remote launch
178failure includes launcher output where available, forwarded-port failure leaves the environment
179disconnected rather than falling back to an unrelated endpoint, and reconnect restores the SSH bridge
180before reconnecting the WebSocket client.
181
182## Launch methods
183
184Launch answers a different question: how does a T3 server come to exist on the target machine? Keep
185it separate from access.
186
187- **Pre-existing server.** The operator already runs T3 and the client connects directly or through a
188 tunnel.
189- **Desktop-managed remote launch over SSH.** Desktop probes the machine, launches or reuses a remote
190 server, forwards a port, and the renderer connects normally. The saved environment records that it
191 came from SSH launch for reconnect and lifecycle UX only; that metadata never changes the protocol
192 or the identity model.
193- **Client-managed local publish.** A local server is published through the relay with
194 `t3 connect link`, exposing a desktop-hosted environment to mobile without router or firewall
195 changes.
196
197The same `ExecutionEnvironment` can be reached several of these ways. Only the launch and access
198paths differ.
199
200## Security model
201
202Some environments are reachable over untrusted networks, so remote-capable environments require
203explicit authentication, tunnel exposure never relies on obscurity, and saved endpoints carry enough
204auth metadata to reconnect safely.
205
206WebSocket authentication is a dedicated short-lived ticket, not a token in a query string. The client
207presents its long-lived bearer or DPoP credential in HTTP headers to
208`POST /api/auth/websocket-ticket` ([authorization/remote.ts][authremote]), and appends only the
209returned ticket as `wsTicket` on the socket URL. The server issues it through
210`EnvironmentAuth.issueWebSocketTicket`; tickets are tagged `kind: "websocket"` and default to a
211five-minute TTL (`DEFAULT_WEBSOCKET_TOKEN_TTL` in `apps/server/src/auth/SessionStore.ts`). The
212handshake verifies the ticket, and each RPC method still enforces its own scope. See
213[environment-auth.md](./environment-auth.md).
214
215Hosted pairing is a client-side convenience only. The hosted app must not receive pairing tokens
216through query parameters, must not store pairing state server-side, and must not imply that an HTTP
217backend is reachable from an HTTPS browser context.
218
219## Version coordination
220
221Remote environments stay online while clients move to newer releases. The environment descriptor
222carries the running server version and may advertise a safe replacement path, so the UI can show the
223right action without making the transport responsible for process management. The connection
224supervisor owns the resulting disconnect and reconnect like any other involuntary close. See
225[server-updates.md](./server-updates.md).
226
227## Machine identity
228
229Every environment is drawn with one of a fixed set of machine glyphs (`EnvironmentMachineKind` in
230contracts: server, cloud, desktop, laptop, mac-mini, mac-studio). Two inputs feed it, and the
231precedence lives in one helper, `resolveEnvironmentMachineKind`, so web and mobile cannot drift:
232
2331. `settings.environmentIcon`, a nullable server setting the user picks in Settings → Connections.
234 It is server state rather than client state so every device connecting to that server agrees.
2352. `environment.platform.machine`, detected once at startup by [ServerEnvironmentMachine.ts][machine]
236 (IOKit product name / `hw.model` on macOS, `/sys/class/dmi/id` on Linux with virtualization
237 markers mapped to "cloud"). Absent when there is no signal, so older servers, Windows hosts, and
238 containers decode without it.
2393. A generic server otherwise.
240
241Clients treat the field like any other capability: absent means "use the fallback", never "wait".
242
243## Future work
244
245These remain unbuilt and are listed to keep the model honest:
246
247- third-party tunnel products as additional endpoint providers;
248- a relay-hosted OAuth callback broker (see [t3-connect.md](./t3-connect.md));
249- richer multi-environment UI beyond the current connections list.
250
251[model]: ../../packages/client-runtime/src/connection/model.ts
252[onboarding]: ../../packages/client-runtime/src/connection/onboarding.ts
253[authremote]: ../../packages/client-runtime/src/authorization/remote.ts
254[sshenv]: ../../apps/desktop/src/ssh/DesktopSshEnvironment.ts
255[sshtunnel]: ../../packages/ssh/src/tunnel.ts
256[machine]: ../../apps/server/src/environment/ServerEnvironmentMachine.ts