Skip to content

Commit fc761f3

Browse files
feat(clients): reach one environment over several routes
A saved environment held exactly one connection route, so pairing a machine over the LAN replaced its T3 Connect route and vice versa. Users who want LAN at home and T3 Connect or Tailscale away had to pick one. An environment now keeps an ordered list of routes (LAN, Tailscale, public URL, SSH, T3 Connect). The driver checks every direct route's public descriptor in parallel, skips the silent ones, and connects over the first that works; a blocked route (signed out, revoked) moves on instead of stopping. While on a fallback, the supervisor preflights better routes on network changes, app foregrounding, and every minute, and replaces the session when one would connect, with a cooldown for routes that answer but fail. Mobile and web report a network path change (Wi-Fi to cellular) so a dead LAN socket is dropped promptly. Pairing another address or adding T3 Connect to a saved machine adds a route; signing out of T3 Connect only drops that route. Settings lists the routes with reorder and remove on web, desktop, and mobile. GitHub routing trust covers the whole route list. The catalog stays schema version 1: routes are consecutive targets with the same environment id. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 8fb068c commit fc761f3

41 files changed

Lines changed: 2122 additions & 332 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 51 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -82,29 +82,58 @@ const connectivityLayer = Connectivity.layer({
8282
),
8383
});
8484

85+
/**
86+
* Wakes connections when the device moves between networks while staying
87+
* online, such as Wi-Fi to cellular. Connectivity only reports online or
88+
* offline, so leaving home on cellular would otherwise go unnoticed until the
89+
* LAN socket times out.
90+
*/
91+
const networkPathChanges = Stream.callback<"network-changed">((queue) =>
92+
Effect.acquireRelease(
93+
Effect.sync(() => {
94+
let previous: Network.NetworkStateType | undefined;
95+
return Network.addNetworkStateListener((state) => {
96+
const type = state.isConnected === true ? state.type : undefined;
97+
if (previous !== undefined && type !== undefined && type !== previous) {
98+
Queue.offerUnsafe(queue, "network-changed");
99+
}
100+
previous = type ?? previous;
101+
});
102+
}),
103+
(subscription) => Effect.sync(() => subscription.remove()),
104+
).pipe(Effect.asVoid),
105+
);
106+
85107
const wakeupsLayer = Wakeups.layer({
86-
changes: Stream.merge(
87-
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
88-
Effect.acquireRelease(
89-
Effect.sync(() => {
90-
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
91-
return AppState.addEventListener("change", (state) => {
92-
if (state === "background") {
93-
backgroundedAtMs = Date.now();
94-
return;
95-
}
96-
if (state === "active") {
97-
Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
98-
backgroundedAtMs = null;
99-
}
100-
});
101-
}),
102-
(subscription) => Effect.sync(() => subscription.remove()),
103-
).pipe(Effect.asVoid),
104-
),
105-
managedRelayAccountChanges(appAtomRegistry).pipe(
106-
Stream.map(() => "credentials-changed" as const),
107-
),
108+
changes: Stream.mergeAll(
109+
[
110+
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
111+
Effect.acquireRelease(
112+
Effect.sync(() => {
113+
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
114+
return AppState.addEventListener("change", (state) => {
115+
if (state === "background") {
116+
backgroundedAtMs = Date.now();
117+
return;
118+
}
119+
if (state === "active") {
120+
Queue.offerUnsafe(
121+
queue,
122+
mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()),
123+
);
124+
backgroundedAtMs = null;
125+
}
126+
});
127+
}),
128+
(subscription) => Effect.sync(() => subscription.remove()),
129+
).pipe(Effect.asVoid),
130+
),
131+
managedRelayAccountChanges(appAtomRegistry).pipe(
132+
Stream.map(() => "credentials-changed" as const),
133+
),
134+
networkPathChanges,
135+
],
136+
{ concurrency: "unbounded" },
108137
),
109138
});
110139

‎apps/mobile/src/connection/storage.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
registerConnectionInCatalog,
44
removeConnectionFromCatalog,
55
setConnectionEnabledInCatalog,
6+
setRoutesInCatalog,
67
removeCatalogValue,
78
replaceCatalogValue,
89
Persistence,
@@ -27,6 +28,7 @@ function targetPersistenceError(
2728
| "list-targets"
2829
| "list-disabled-targets"
2930
| "register-connection"
31+
| "set-connection-routes"
3032
| "remove-connection"
3133
| "set-connection-enabled",
3234
error: ConnectionTransientError,
@@ -57,13 +59,17 @@ export const connectionStorageLayer = Layer.effectContext(
5759
),
5860
});
5961
const registrationStore = Persistence.ConnectionRegistrationStore.of({
60-
register: (registration) =>
62+
register: (registration, routes) =>
6163
catalog
62-
.update((document) => registerConnectionInCatalog(document, registration))
64+
.update((document) => registerConnectionInCatalog(document, registration, routes))
6365
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
64-
remove: (target) =>
66+
setRoutes: (environmentId, routes) =>
6567
catalog
66-
.update((document) => removeConnectionFromCatalog(document, target))
68+
.update((document) => setRoutesInCatalog(document, environmentId, routes))
69+
.pipe(Effect.mapError((error) => targetPersistenceError("set-connection-routes", error))),
70+
remove: (environmentId) =>
71+
catalog
72+
.update((document) => removeConnectionFromCatalog(document, environmentId))
6773
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
6874
setEnabled: (environmentId, enabled) =>
6975
catalog

‎apps/mobile/src/features/cloud/cloud-drafts.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
1+
import { EnvironmentRegistry, connectionRoutes } from "@t3tools/client-runtime/connection";
22
import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime";
33
import * as Effect from "effect/Effect";
44
import * as Schema from "effect/Schema";
@@ -27,7 +27,10 @@ export const removeCloudEnvironments = createRuntimeCommand(connectionAtomRuntim
2727
const entries = yield* SubscriptionRef.get(registry.entries);
2828
const environmentIds = new Set(
2929
[...entries.values()]
30-
.filter((entry) => entry.target._tag === "RelayConnectionTarget")
30+
// Only environments that sign-out removes entirely lose their drafts.
31+
.filter((entry) =>
32+
connectionRoutes(entry).every((route) => route.target._tag === "RelayConnectionTarget"),
33+
)
3134
.map((entry) => entry.target.environmentId),
3235
);
3336
// Credentials are already revoked. A failed backup must leave the local

‎apps/mobile/src/features/connection/environmentSections.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,21 @@ describe("mobile environment settings sections", () => {
157157
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
158158
expect(sections.availableCloudEnvironments).toEqual([]);
159159
});
160+
161+
it("offers T3 Connect for a machine saved only over the LAN, as an added route", () => {
162+
const local = connectedEnvironment({
163+
environmentId: "environment-desk",
164+
isRelayManaged: false,
165+
});
166+
167+
const sections = splitEnvironmentSections({
168+
connectedEnvironments: [local],
169+
cloudEnvironments: [cloudEnvironment("environment-desk")],
170+
});
171+
172+
expect(sections.localEnvironments).toEqual([local]);
173+
expect(
174+
sections.availableCloudEnvironments.map((environment) => environment.environmentId),
175+
).toEqual([EnvironmentId.make("environment-desk")]);
176+
});
160177
});
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import {
3+
connectionRouteAddress,
4+
connectionRouteId,
5+
connectionRouteLabel,
6+
connectionRoutes,
7+
} from "@t3tools/client-runtime/connection";
8+
import type { EnvironmentId } from "@t3tools/contracts";
9+
import * as Option from "effect/Option";
10+
import { Alert, Pressable, View } from "react-native";
11+
12+
import { SymbolView } from "../../components/AppSymbol";
13+
import { AppText as Text } from "../../components/AppText";
14+
import { environmentCatalog } from "../../connection/catalog";
15+
import { environmentSession } from "../../state/session";
16+
import { useAtomCommand } from "../../state/use-atom-command";
17+
import { SettingsSection } from "./components/SettingsSection";
18+
19+
/**
20+
* The ways this device can reach an environment, preferred first. The first
21+
* route that answers is used, and the connection moves back up the list when
22+
* a better route becomes reachable again. Hidden for a single route.
23+
*/
24+
export function EnvironmentRoutesSection({
25+
environmentId,
26+
connected,
27+
}: {
28+
readonly environmentId: EnvironmentId;
29+
readonly connected: boolean;
30+
}) {
31+
const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
32+
const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
33+
const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
34+
const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
35+
if (entry === undefined) return null;
36+
const routes = connectionRoutes(entry);
37+
if (routes.length < 2) return null;
38+
const activeRouteId =
39+
connected && Option.isSome(prepared) ? connectionRouteId(prepared.value.target) : null;
40+
const ids = routes.map((route) => connectionRouteId(route.target));
41+
42+
const openActions = (index: number) => {
43+
const route = routes[index]!;
44+
const label = connectionRouteLabel(route);
45+
Alert.alert(label, connectionRouteAddress(route) ?? undefined, [
46+
...(index > 0
47+
? [
48+
{
49+
text: "Prefer this route",
50+
onPress: () => {
51+
const next = [...ids];
52+
next.splice(index, 1);
53+
next.unshift(ids[index]!);
54+
void reorder({ environmentId, routeIds: next });
55+
},
56+
},
57+
]
58+
: []),
59+
{
60+
text: "Remove route",
61+
style: "destructive",
62+
onPress: () => void removeRoute({ environmentId, routeId: ids[index]! }),
63+
},
64+
{ text: "Cancel", style: "cancel" },
65+
]);
66+
};
67+
68+
return (
69+
<SettingsSection title="Routes">
70+
{routes.map((route, index) => {
71+
const id = ids[index]!;
72+
const address = connectionRouteAddress(route);
73+
return (
74+
<Pressable
75+
key={id}
76+
accessibilityRole="button"
77+
accessibilityHint="Shows options for this route"
78+
onPress={() => openActions(index)}
79+
className="flex-row items-center gap-3 p-4 active:opacity-70"
80+
>
81+
<View className="w-5 items-center">
82+
{id === activeRouteId ? (
83+
<SymbolView
84+
name="checkmark"
85+
size={16}
86+
tintColorClassName="accent-icon"
87+
type="monochrome"
88+
/>
89+
) : null}
90+
</View>
91+
<View className="min-w-0 flex-1 gap-0.5">
92+
<Text className="text-base text-foreground">{connectionRouteLabel(route)}</Text>
93+
{address !== null ? (
94+
<Text numberOfLines={1} className="text-sm text-foreground-muted">
95+
{address}
96+
</Text>
97+
) : null}
98+
</View>
99+
<Text className="text-sm tabular-nums text-foreground-muted">{index + 1}</Text>
100+
</Pressable>
101+
);
102+
})}
103+
<Text className="px-4 pb-4 text-sm text-foreground-muted">
104+
The first route that answers is used. Pair this machine again over another address, or add
105+
it from T3 Connect, to add a route.
106+
</Text>
107+
</SettingsSection>
108+
);
109+
}

‎apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { environmentSession } from "../../state/session";
1515
import { useAtomCommand } from "../../state/use-atom-command";
1616
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
1717
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
18+
import { EnvironmentRoutesSection } from "./EnvironmentRoutesSection";
1819
import { SettingsActionRow } from "./components/SettingsActionRow";
1920
import { SettingsScreen } from "./components/SettingsScreen";
2021
import { SettingsSection } from "./components/SettingsSection";
@@ -167,6 +168,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
167168
onUpdate={connections.onUpdateEnvironment}
168169
/>
169170
</SettingsSection>
171+
<EnvironmentRoutesSection environmentId={environmentId} connected={connected} />
170172
{!connected ? (
171173
<Text className="px-2 text-sm text-foreground-muted">
172174
Connect this environment to manage it.

‎apps/mobile/src/state/environments.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import {
33
connectionCatalogDisplayUrl,
4+
hasRelayRoute,
45
type EnvironmentPresentation as BaseEnvironmentPresentation,
56
} from "@t3tools/client-runtime/connection";
67
import type { EnvironmentId } from "@t3tools/contracts";
@@ -26,7 +27,7 @@ export function projectEnvironmentPresentation(
2627
environmentId,
2728
label: presentation.entry.target.label,
2829
displayUrl: connectionCatalogDisplayUrl(presentation.entry),
29-
relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",
30+
relayManaged: hasRelayRoute(presentation.entry),
3031
};
3132
}
3233

‎apps/mobile/src/state/remote-environment-projections.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,10 @@ export function createRemoteEnvironmentProjectionAtoms(input: {
5252
: displayUrl.replace(/^http:/, "ws:")
5353
: new URL(socketUrl).origin;
5454
const authorization = prepared?.httpAuthorization ?? null;
55-
const relayManaged = presentation.entry.target._tag === "RelayConnectionTarget";
55+
// Credentials follow the route in use, which may not be the preferred one.
56+
const relayManaged = prepared
57+
? prepared.target._tag === "RelayConnectionTarget"
58+
: presentation.entry.target._tag === "RelayConnectionTarget";
5659

5760
previousEntry = presentation.entry;
5861
previousPrepared = prepared;

‎apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ describe("cloud onboarding discovery", () => {
327327
{
328328
environmentId: newMachineId,
329329
connection: { phase: "connected", error: null, traceId: null },
330+
relayManaged: true,
330331
},
331332
]}
332333
showSavedEnvironments

0 commit comments

Comments
 (0)