Open History to see the last commit
1# Connection Runtime
2
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4
5The connection runtime is shared by web and mobile. It owns connectivity,
6authentication, retries, transport lifetime, cached environment data, and
7environment-scoped operations.
8
9Web and mobile mount this runtime once at the application root and compose it
10identically: `apps/web/src/connection/runtime.ts` and
11`apps/mobile/src/connection/runtime.ts` differ only in the platform layer they
12supply. There is no legacy connection owner or supported mixed mode.
13
14## Composition
15
16[`connection/layer.ts`][layer] assembles the runtime:
17
18- `ConnectionResolver` ([resolver.ts][resolver]) resolves a catalog entry into a
19 prepared, authenticated endpoint for primary, bearer, relay, or SSH targets.
20- `ConnectionDriver` ([driver.ts][driver]) prepares through the resolver, opens
21 one RPC session, and reports `preparing`, `opening`, and `synchronizing`.
22- `RpcSessionFactory` ([rpc/session.ts][session]) performs one transport
23 attempt. It does not retry. `RpcSession` is the interface it returns,
24 exposing `client`, `initialConfig`, `ready`, `probe`, and `closed`.
25- `EnvironmentRegistry` ([registry.ts][registry]) owns the catalog and the
26 per-environment scopes.
27- `ConnectionOnboarding` and `RelayEnvironmentDiscovery` sit alongside the
28 registry. Startup calls `EnvironmentRegistry.start` and streams platform
29 registrations into `reconcilePlatform`.
30
31The registry creates one environment-scoped supervisor per environment.
32`acquireSupervisor` serializes access per environment, reuses an existing
33supervisor when the catalog entry is unchanged, and closes and recreates the
34scope when it changed. `createServiceScope` builds an `EnvironmentSupervisor`
35bound to a closeable scope and connects it; `run` and `runStream` execute caller
36effects with that supervisor provided.
37
38`EnvironmentSupervisor` owns desired state, retry scheduling, and the active
39session scope. React components do not create connections, transports, retry
40loops, or RPC clients.
41
42## Connection State
43
44The supervisor is the only retry owner.
45
461. A persisted or platform registration marks an environment as desired.
472. If the device is offline, the supervisor releases the active session and
48 waits for a signal without consuming retry attempts or running a timer.
493. When online, it asks the driver for one prepared connection and one RPC
50 session.
514. Transient failures retry forever with exponential backoff capped at 16
52 seconds (`RETRY_DELAYS_MS`). A connection stable for 30 seconds resets
53 accumulated backoff.
545. Authentication or configuration failures remain blocked until an external
55 wakeup changes the relevant input.
566. An involuntary session close keeps the registration and cache, then retries.
577. Explicit removal closes the session and deletes the registration,
58 credentials, shell cache, and thread cache.
59
60### Wakeups
61
62Wakeup handling differs by phase, in [supervisor.ts][supervisor]:
63
64- During establishment, `waitForEstablishmentInterrupt` consumes and **ignores**
65 plain application activation. Restarting an in-flight attempt because the app
66 came to the foreground would only delay it. The exception is
67 `application-active-reconnect`, which mobile emits after a meaningful
68 background suspension; it interrupts establishment and resets the retry
69 ladder, because the OS may have silently killed the socket underneath the
70 attempt.
71- Credential changes interrupt establishment only for relay targets, where a new
72 credential changes what is being established.
73- Explicit disconnect, explicit retry, and going offline interrupt establishment
74 in every case.
75- While waiting out backoff, application activation resets the retry ladder so a
76 foregrounded app reconnects immediately instead of serving the remaining
77 delay.
78- Once connected, `monitorConnectedLease` handles plain activation by probing
79 the existing session (`lease.session.probe`, with a shorter timeout for
80 mobile's `application-active-probe`) rather than reconnecting; a healthy
81 session survives foregrounding. `application-active-reconnect` skips the probe
82 and replaces the lease outright.
83
84The UI derives `available`, `offline`, `connecting`, `reconnecting`,
85`connected`, and `error` from supervisor state plus explicit data-sync state.
86It does not infer connection health from cached data or the existence of a
87transport object. An environment becomes `connected` after the socket opens and
88the initial config RPC succeeds, proving that the server is responsive. Shell
89and thread synchronization are independent data states. A healthy RPC transport
90with a failed shell subscription is shown as connected with a synchronization
91error, not as a reconnect that is not actually scheduled.
92
93## Data Boundary
94
95Finite requests, durable subscriptions, and commands are separate APIs:
96
97- Query atoms revalidate when the RPC generation changes.
98- Subscription atoms switch to replacement sessions.
99- Subscription failure handling in [rpc/client.ts][client] distinguishes two
100 cases. A transport failure (`isTransportFailure`: every failure is an RPC
101 client error) ends the inner subscription without resubscribing, so the outer
102 stream waits for the supervisor to supply a replacement session. A handled
103 domain failure runs `onExpectedFailure` and, when
104 `retryExpectedFailureAfter` is set, sleeps and resubscribes on the **same**
105 session. A healthy transport is never torn down for a domain failure.
106- Mutations resolve the current environment runtime at execution time.
107- Shell and thread snapshots are available while offline.
108- Sync status is explicit and independent per domain. Shell status is `empty`,
109 `cached`, `synchronizing`, or `live`, with a separate `error` field; there is
110 no `failed` status. Thread status adds `deleted`.
111- Cached shell and thread projections are never allowed to overwrite newer live
112 data during a fast reconnect.
113- Domain atom factories route effects through the environment registry and
114 resolve the current scoped service at execution time. Project and thread
115 commands are Atom factories under `src/state`
116 (`createProjectEnvironmentAtoms`, `createThreadEnvironmentAtoms`), as are the
117 shell and thread state factories (`createEnvironmentShellAtoms`,
118 `createEnvironmentThreadStateAtoms`).
119- Web and mobile own their Atom runtimes, React hooks, and feature composition.
120
121The Promise bridge exists only at the React/Atom boundary. Runtime and business
122logic remain Effect-native.
123
124## Platform Layers
125
126Web and mobile provide:
127
128- network status and network-change streams;
129- application lifecycle wakeups;
130- cloud session credentials;
131- device identity;
132- platform registrations;
133- persistent catalog, credential, shell, and thread stores;
134- HTTP, crypto, and telemetry layers.
135
136Platform layers adapt operating-system capabilities. They do not implement
137connection policy. `EnvironmentOwnedDataCleanup` is part of this contract: on
138removal the registry clears its cache and calls the platform implementation, so
139web clears composer drafts and mobile clears drafts plus the thread outbox.
140
141## Source Boundaries
142
143Applications must import explicit package subpaths; the package intentionally
144has no root export. The subpaths are documented in
145[packages/client-runtime/README.md](../../packages/client-runtime/README.md),
146with the `exports` map in that package's `package.json` as the authoritative
147list. Files that are not exported are implementation details.
148
149## Application Boundary
150
151The application root mounts the shared connection layer, creates its own Atom
152runtime, and selects the domain atom factories required by that platform. Web
153and mobile may expose different hooks and features without changing connection
154ownership.
155
156Application code must not construct RPC clients, retry loops, or raw
157orchestration commands. Persistence paths belong to the platform registration
158and cache stores, with explicit migration or invalidation policy.
159
160## Verification
161
162Core state-machine tests use `@effect/vitest` and deterministic service layers.
163Required coverage includes:
164
165- offline startup and online wakeup;
166- forever retry with the 16-second cap;
167- explicit retry interrupting backoff;
168- authentication wakeups;
169- involuntary close and reconnect;
170- explicit removal clearing all owned state;
171- relay token reuse and refresh;
172- progressive relay discovery;
173- shell and thread cache hydration;
174- durable subscriptions switching sessions;
175- command metadata and idempotent queued-command metadata.
176
177[layer]: ../../packages/client-runtime/src/connection/layer.ts
178[resolver]: ../../packages/client-runtime/src/connection/resolver.ts
179[driver]: ../../packages/client-runtime/src/connection/driver.ts
180[registry]: ../../packages/client-runtime/src/connection/registry.ts
181[supervisor]: ../../packages/client-runtime/src/connection/supervisor.ts
182[session]: ../../packages/client-runtime/src/rpc/session.ts
183[client]: ../../packages/client-runtime/src/rpc/client.ts