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
44### Known environments and connection targets
45
46A saved client-side entry for an environment the client knows how to reach. It is not
47server-authored; it is local to a device or client profile. In the hosted web app these entries are
48browser-local. A hosted pairing URL can create one, but it does not give the hosted app a server-side
49control plane or a copy of session state.
50
51[`connection/model.ts`][model] defines four target tags, which are the real access taxonomy:
52
53| Target | Used for |
54| ------------------------- | ------------------------------------------------------------------------ |
55| `PrimaryConnectionTarget` | The platform-managed local server (desktop backend, CLI-served web app). |
56| `BearerConnectionTarget` | Any manually paired endpoint reached over direct HTTP/WebSocket. |
57| `RelayConnectionTarget` | Managed T3 Connect relay tunnels. |
58| `SshConnectionTarget` | Desktop-managed SSH environments. |
59
60Bearer, relay, and SSH are persisted; primary is platform-managed. Note that Tailscale is not a
61separate target kind. A Tailscale URL is paired through the ordinary bearer path in
62[`onboarding.ts`][onboarding] (`preparePairingRegistration`), which accepts either a pairing URL or a
63host plus pairing code. Tailscale is an endpoint provider and transport, not a distinct runtime
64concept.
65
66### AdvertisedEndpoint
67
68A server- or desktop-authored candidate endpoint for an environment: a concrete HTTP and WebSocket
69base URL pair, a default/available/unavailable marker, reachability hints (loopback, LAN, private,
70public, tunnel), and compatibility hints such as whether the hosted HTTPS app can use it.
71
72Clients treat advertised endpoints as hints, not proof that a route works from the current device.
73The connection attempt decides.
74
75The UI shows one default endpoint in the network-access summary and keeps the rest behind an advanced
76list. `selectPairingEndpoint` in
77[`ConnectionsSettings.tsx`](../../apps/web/src/components/settings/ConnectionsSettings.tsx) excludes
78unavailable endpoints and then picks, in order:
79
801. the saved `defaultEndpointKey` override;
812. the first endpoint marked `isDefault`;
823. the first endpoint whose reachability is not `loopback`;
834. the first endpoint compatible with the hosted HTTPS app;
845. otherwise nothing.
85
86There is no unconditional loopback fallback. A loopback endpoint only wins through an explicit saved
87override or `isDefault`. Persist the override by stable endpoint kind rather than raw URL where
88possible, since LAN addresses change with networks; Tailscale endpoints use provider-specific stable
89keys (`tailscale-ip:`, `tailscale-magicdns:`).
90
91### Endpoint providers
92
93Endpoint providers contribute advertised endpoints without becoming part of the core environment
94model: core owns environments, pairing, and connection lifecycle, and providers return normalized
95`AdvertisedEndpoint` records.
96
97Tailscale is the first provider, and T3 manages more than discovery. When `tailscaleServeEnabled` is
98set, the server acquires a Tailscale serve mapping for its actual listening port at startup with
99`ensureTailscaleServe` and releases it with `disableTailscaleServe` on scope close
100(`apps/server/src/server.ts`, using [`@t3tools/tailscale`](../../packages/tailscale/src/tailscale.ts)).
101Endpoint identifiers are synthesized in `apps/desktop/src/backend/tailscaleEndpointProvider.ts` with
102`private-network` reachability.
103
104### Hosted pairing request
105
106A hosted pairing request is a bootstrap URL for the static web app, not a transport:
107
108```text
109https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
110```
111
112The hosted app reads `host`, takes the token from the URL hash, exchanges it directly with that
113backend, strips the token from browser history, and saves the environment record locally. Helpers
114live in [`shared/remote.ts`](../../packages/shared/src/remote.ts) (`setPairingTokenOnUrl`,
115`getPairingTokenFromUrl`, `stripPairingTokenFromUrl`) and `apps/web/src/hostedPairing.ts`.
116
117Constraints:
118
119- the hosted app does not proxy HTTP or WebSocket traffic;
120- the backend must be directly reachable from the browser;
121- HTTPS pages can only reach HTTPS/WSS backends;
122- HTTP LAN endpoints keep using direct desktop or CLI pairing URLs;
123- the token belongs in the hash so it is never sent to the hosted app origin.
124
125### RepositoryIdentity and Project
126
127`RepositoryIdentity` is a best-effort logical repo grouping across environments, used for UI grouping
128and correlation only, never for routing. `Project` remains environment-local: a local clone and a
129remote clone are different projects that may share a `RepositoryIdentity`, and threads bind to one
130project in one environment.
131
132## Access methods
133
134Access answers one question: how does the client speak WebSocket to a T3 server? It does not answer
135how the server got started or who manages the process.
136
137### Direct WebSocket access
138
139`wss://t3.example.com` or `ws://10.0.0.15:3773`, paired as a bearer target. This is the base model.
140It works for desktop, mobile, and web with no client-side process management. Browser security rules
141are part of it: a hosted HTTPS client cannot connect to plain `ws://` or `http://` LAN backends.
142
143### Relay-tunneled access
144
145Managed T3 Connect relay tunnels use `RelayConnectionTarget` and are the answer when the host is
146behind NAT, inbound ports are unavailable, or mobile must reach a desktop-hosted environment. From
147the client's perspective this is still an ordinary WebSocket connection; the route is mediated. The
148relay Worker only brokers credentials and a managed endpoint; application traffic then flows over
149the provisioned Cloudflare tunnel hostname for the life of the connection, not through the relay
150Worker itself. See [t3-connect.md](./t3-connect.md).
151
152### Tailscale access
153
154A T3-managed `tailscale serve` mapping exposes the server on the tailnet over HTTPS, and the
155resulting private-network endpoints are advertised for pairing. Connection then follows the ordinary
156bearer path.
157
158### Desktop-managed SSH access
159
160SSH is an access and launch helper, not a separate environment type. `DesktopSshEnvironment`
161([apps/desktop/src/ssh/DesktopSshEnvironment.ts][sshenv]) exposes `discoverHosts`,
162`ensureEnvironment`, and `disconnectEnvironment`. It discovers targets from SSH config and known
163hosts, owns password/askpass prompts, and delegates lifecycle to `SshEnvironmentManager` in
164[packages/ssh/src/tunnel.ts][sshtunnel], which resolves the target, launches or reuses the remote T3
165server, opens a local tunnel, checks HTTP readiness, optionally issues a remote pairing token, and
166returns local HTTP/WS endpoints. Disconnect closes the tunnel and stops the remote server if the
167launcher started it; a server that was already running (marked `external`) is left running.
168
169The desktop main process owns this because it can spawn SSH, manage prompts, write launch scripts,
170and clean up forwards. The renderer connects through the forwarded URL like any other environment and
171needs no SSH-specific RPC path.
172
173Failure handling is explicit: SSH auth failure surfaces before an environment is saved, remote launch
174failure includes launcher output where available, forwarded-port failure leaves the environment
175disconnected rather than falling back to an unrelated endpoint, and reconnect restores the SSH bridge
176before reconnecting the WebSocket client.
177
178## Launch methods
179
180Launch answers a different question: how does a T3 server come to exist on the target machine? Keep
181it separate from access.
182
183- **Pre-existing server.** The operator already runs T3 and the client connects directly or through a
184 tunnel.
185- **Desktop-managed remote launch over SSH.** Desktop probes the machine, launches or reuses a remote
186 server, forwards a port, and the renderer connects normally. The saved environment records that it
187 came from SSH launch for reconnect and lifecycle UX only; that metadata never changes the protocol
188 or the identity model.
189- **Client-managed local publish.** A local server is published through the relay with
190 `t3 connect link`, exposing a desktop-hosted environment to mobile without router or firewall
191 changes.
192
193The same `ExecutionEnvironment` can be reached several of these ways. Only the launch and access
194paths differ.
195
196## Security model
197
198Some environments are reachable over untrusted networks, so remote-capable environments require
199explicit authentication, tunnel exposure never relies on obscurity, and saved endpoints carry enough
200auth metadata to reconnect safely.
201
202WebSocket authentication is a dedicated short-lived ticket, not a token in a query string. The client
203presents its long-lived bearer or DPoP credential in HTTP headers to
204`POST /api/auth/websocket-ticket` ([authorization/remote.ts][authremote]), and appends only the
205returned ticket as `wsTicket` on the socket URL. The server issues it through
206`EnvironmentAuth.issueWebSocketTicket`; tickets are tagged `kind: "websocket"` and default to a
207five-minute TTL (`DEFAULT_WEBSOCKET_TOKEN_TTL` in `apps/server/src/auth/SessionStore.ts`). The
208handshake verifies the ticket, and each RPC method still enforces its own scope. See
209[environment-auth.md](./environment-auth.md).
210
211Hosted pairing is a client-side convenience only. The hosted app must not receive pairing tokens
212through query parameters, must not store pairing state server-side, and must not imply that an HTTP
213backend is reachable from an HTTPS browser context.
214
215## Version coordination
216
217Remote environments stay online while clients move to newer releases. The environment descriptor
218carries the running server version and may advertise a safe replacement path, so the UI can show the
219right action without making the transport responsible for process management. The connection
220supervisor owns the resulting disconnect and reconnect like any other involuntary close. See
221[server-updates.md](./server-updates.md).
222
223## Future work
224
225These remain unbuilt and are listed to keep the model honest:
226
227- third-party tunnel products as additional endpoint providers;
228- a relay-hosted OAuth callback broker (see [t3-connect.md](./t3-connect.md));
229- richer multi-environment UI beyond the current connections list.
230
231[model]: ../../packages/client-runtime/src/connection/model.ts
232[onboarding]: ../../packages/client-runtime/src/connection/onboarding.ts
233[authremote]: ../../packages/client-runtime/src/authorization/remote.ts
234[sshenv]: ../../apps/desktop/src/ssh/DesktopSshEnvironment.ts
235[sshtunnel]: ../../packages/ssh/src/tunnel.ts