feat(clients): reach one environment over several routes #15467
Mergedjuliusmarmingemerged 11 commits into
main fromrefs/pull/15467/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge removed labelssize:XXL
juliusmarminge added labelsmacroscope-review
- apps/mobile/src/connection/platform.ts line 95Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -82,3 +82,13 @@8282 ),8383 });848485+/**86+ * Wakes connections when the device moves between networks while staying87+ * online, such as Wi-Fi to cellular. Connectivity only reports online or88+ * offline, so leaving home on cellular would otherwise go unnoticed until the89+ * 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;packages/client-runtime/src/connection/outdatedHostUpdate.ts line 70Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -63,4 +64,7 @@6364 if (entry === undefined) {6465 return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });6566 }66- const { prepared, descriptor } = yield* resolver.prepareForUpdate(entry);67+ // An outdated server cannot connect normally, so the routes are tried in68+ // order here. The first that authorizes carries the update.69+ const { prepared, descriptor } = yield* Effect.firstSuccessOf(70+ connectionRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx line 127Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -121,4 +123,5 @@121123 ReadonlySet<EnvironmentId>122124 >(new Set());123125 const savedById = new Map(124- savedEnvironments.map((environment) => [environment.environmentId, environment]),126+ savedEnvironments127+ .filter((environment) => environment.relayManaged)packages/shared/src/hostClassification.ts line 89OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -81,3 +81,9 @@8181 return parseIpv4Address(normalized)?.[0] === 127;8282 };838384+/** A Tailscale address: a MagicDNS name or the 100.64.0.0/10 range Tailscale assigns. */85+export const isTailnetHost = (host: string): boolean => {86+ const normalized = normalizeHostname(host);87+ if (normalized.endsWith(".ts.net")) return true;88+ const parts = parseIpv4Address(normalized);89+ return parts !== null && parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127;packages/client-runtime/src/connection/onboarding.ts lines 94 to 94OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -84,3 +85,10 @@8485 },8586 );868788+/**89+ * One bearer route per address, so pairing over Tailscale adds a route next90+ * to the LAN one instead of replacing it. Pairing the same address again91+ * reuses the id and replaces that route.92+ */93+export function bearerConnectionId(environmentId: EnvironmentId, httpBaseUrl: string): string {94+ return `bearer:${environmentId}:${new URL(httpBaseUrl).host}`;packages/client-runtime/src/connection/registry.ts line 852OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -725 +832,21 @@832+ environmentId: EnvironmentId,833+ routeId: string,834+ ) {835+ const removed = yield* withLeaseLock(836+ environmentId,837+ Effect.gen(function* () {838+ const entry = yield* userEntry(environmentId);839+ const routes = connectionRoutes(entry);840+ const route = routes.find((candidate) => connectionRouteId(candidate.target) === routeId);841+ if (route === undefined) return "kept" as const;842+ const remaining = routes.filter((candidate) => candidate !== route);843+ if (remaining.length === 0) return "last" as const;844+ yield* replaceRoutesLocked(entry, remaining);845+ const profile = Option.getOrNull(route.profile);846+ if (profile !== null && isSshConnectionProfile(profile)) {847+ yield* disconnectSsh(environmentId, profile);725848 }849+ return "kept" as const;850+ }),851+ );852+ if (removed === "last") yield* remove(environmentId);
- apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx lines 82 to 89OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +69,21 @@69+ <SettingsSection title="Routes">70+ {routes.map((route, index) => {71+ const id = ids[index]!;72+ const address = connectionRouteAddress(route);73+ return (74+ <Pressable75+ 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+ <SymbolView84+ name="checkmark"85+ size={16}86+ tintColorClassName="accent-icon"87+ type="monochrome"88+ />89+ ) : null}apps/web/src/connection/platform.ts lines 102 to 125Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -89,0 +96,21 @@96+ * as a laptop moving from Wi-Fi to a phone hotspot. Only some browsers expose97+ * `navigator.connection`; elsewhere the periodic route check covers it.98+ */99+const networkPathChanges = Stream.callback<"network-changed">((queue) =>100+ Effect.acquireRelease(101+ Effect.sync(() => {102+ const connection =103+ typeof navigator === "undefined"104+ ? undefined105+ : (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection;106+ if (connection === undefined) return undefined;107+ const listener = () => Queue.offerUnsafe(queue, "network-changed");108+ connection.addEventListener("change", listener);109+ return { connection, listener };110+ }),111+ (subscription) =>112+ Effect.sync(() =>113+ subscription?.connection.removeEventListener("change", subscription.listener),114+ ),115+ ).pipe(Effect.asVoid),116+);docs/user/remote-access.md lines 72 to 74OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -62,3 +62,13 @@6262 its Connections page stays open. If you leave or reload that page, create6363 another link to share.646465+### Reach one machine several ways66+67+A machine can have more than one route: LAN, Tailscale, T3 Connect, or SSH.68+Pair it again over another address, or choose **Add route** next to it in the69+T3 Connect list, and the new route joins the existing one instead of adding a70+second machine. Faster routes go first: LAN, then Tailscale, then T3 Connect.71+72+T3 Code connects over the first route that answers. Away from home, a LAN73+address that does not answer costs one short check before the next route is74+used. While connected over a later route, T3 Code checks the earlier ones whenpackages/client-runtime/src/connection/index.ts line 13OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -9,3 +9,5 @@99 export * as ConnectionOnboarding from "./onboarding.ts";1010 export * from "./presentation.ts";1111 export * as ProfileStore from "./profileStore.ts";12+export * from "./routes.ts";13+export { connectOverRoutes, type RouteCheck } from "./driver.ts";
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/client-runtime/src/connection/driver.ts line 103OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -38,0 +83,21 @@83+) {84+ const routes = connectionRoutes(entry);85+ const checks =86+ routes.length === 187+ ? []88+ : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));89+ const attemptScope = yield* Scope.Scope;90+ let lastError: ConnectionAttemptError = new ConnectionTransientError({91+ reason: "endpoint-unavailable",92+ detail: `${entry.target.label} did not answer on any saved route.`,93+ });94+ // Each route gets its own scope so a half-open session closes before the next try.95+ const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {96+ const routeScope = yield* Scope.fork(attemptScope);97+ return yield* connectRoute(route).pipe(98+ Scope.provide(routeScope),99+ Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),100+ Effect.result,101+ );102+ });103+ let tried = 0;
- packages/client-runtime/src/connection/driver.ts line 114OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -38,0 +94,21 @@94+ // Each route gets its own scope so a half-open session closes before the next try.95+ const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {96+ const routeScope = yield* Scope.fork(attemptScope);97+ return yield* connectRoute(route).pipe(98+ Scope.provide(routeScope),99+ Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),100+ Effect.result,101+ );102+ });103+ let tried = 0;104+ for (const [index, route] of routes.entries()) {105+ const check = checks.length === 0 ? "unchecked" : yield* Fiber.join(checks[index]!);106+ if (check === "silent") continue;107+ tried += 1;108+ const result = yield* attempt(route);109+ if (result._tag === "Success") return result.success;110+ lastError = result.failure;111+ // An incompatible server is the same server on every route.112+ if (lastError.reason === "unsupported") return yield* lastError;113+ }114+ if (tried > 0) return yield* lastError;
- packages/client-runtime/src/connection/onboarding.ts line 286Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -243,3 +282,3 @@243282 "clientRuntime.connection.onboarding.registerSshConnection",244283 )(function* (input: SshConnectionInput) {245284 const registration = yield* prepareSshRegistration(input);apps/mobile/src/connection/onboarding.ts lines 18 to 18OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -13,5 +13,6 @@1313 export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {1414 label: "mobile:connection:connect-pairing-url",1515 scheduler: onboardingScheduler,16- concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },17- execute: (pairingUrl: string) =>16+ concurrency: {17+ mode: "singleFlight",18+ key: (input: { readonly pairingUrl: string }) => input.pairingUrl,packages/client-runtime/src/connection/onboarding.ts line 287Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -243,3 +282,4 @@243282 "clientRuntime.connection.onboarding.registerSshConnection",244283 )(function* (input: SshConnectionInput) {245284 const registration = yield* prepareSshRegistration(input);285+ if (
- apps/mobile/src/connection/onboarding.ts line 18OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -13,5 +13,6 @@1313 export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {1414 label: "mobile:connection:connect-pairing-url",1515 scheduler: onboardingScheduler,16- concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },17- execute: (pairingUrl: string) =>16+ concurrency: {17+ mode: "singleFlight",18+ key: (input: { readonly pairingUrl: string }) => input.pairingUrl,apps/web/src/components/settings/EnvironmentRoutesList.tsx lines 107 to 112OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +92,21 @@92+ collisionDetection={closestCenter}93+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}94+ onDragEnd={handleDragEnd}95+ >96+ <SortableContext items={order} strategy={verticalListSortingStrategy}>97+ <ol aria-label={`Routes to ${environment.label}, preferred first`}>98+ {routes.map((route, index) => (99+ <SortableRouteRow100+ key={connectionRouteId(route.target)}101+ route={route}102+ position={index + 1}103+ inUse={connectionRouteId(route.target) === activeRouteId}104+ // The last route goes with the machine; that is "Remove from105+ // this device", not a route action.106+ removable={routes.length > 1}107+ onRemove={() =>108+ void removeRoute({109+ environmentId: environment.environmentId,110+ routeId: connectionRouteId(route.target),111+ })112+ }
- docs/user/remote-access.md lines 67 to 71OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -62,3 +62,10 @@6262 its Connections page stays open. If you leave or reload that page, create6363 another link to share.646465+### Reach one machine several ways66+67+A machine can have more than one route: LAN, Tailscale, T3 Connect, or SSH. To68+add one, choose **Add route** in the machine's route list, or next to it in the69+T3 Connect list. Pairing the same machine again over another address also adds70+a route instead of a second machine. Faster routes go first: LAN, then71+Tailscale, then T3 Connect.
- packages/client-runtime/src/connection/registry.ts lines 532 to 533Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -447,0 +513,21 @@513+ message: error.message,514+ }),515+ ),516+ );517+518+ const persistedRoutes = (entry: ConnectionCatalogEntry) =>519+ connectionRoutes(entry).map((route) => route.target as PersistedConnectionTarget);520+521+ /**522+ * The entry after its routes change. GitHub trust and an unsupported523+ * verdict both belong to the saved addresses: a changed set may reach a524+ * different server, so both are dropped and the next connection decides.525+ * Reordering keeps the same addresses, so both stay.526+ */527+ const withRoutes = (previous: ConnectionCatalogEntry, routes: ReadonlyArray<ConnectionRoute>) => {528+ const next = entryWithRoutes(previous, routes);529+ if (gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(next)) {530+ return { entry: next, addressesChanged: false };531+ }532+ const { unsupportedReason: _reason, serverUpdateRequired: _update, ...rest } = next;533+ return { entry: rest, addressesChanged: true };packages/client-runtime/src/connection/routes.ts lines 157 to 157OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +137,21 @@137+138+/**139+ * A saved route that reaches the same address as `route`: the same bearer140+ * URL, or the same SSH host. Registering it again replaces that route, even141+ * when it was saved under another id.142+ */143+export function findRouteToSameAddress(144+ routes: ReadonlyArray<ConnectionRoute>,145+ route: ConnectionRoute,146+): ConnectionRoute | undefined {147+ const key = routeAddressKey(route);148+ return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);149+}150+151+function routeAddressKey(route: ConnectionRoute): string | null {152+ const profile = Option.getOrNull(route.profile);153+ switch (profile?._tag) {154+ case "BearerConnectionProfile":155+ return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;156+ case "SshConnectionProfile":157+ return `ssh:${profile.target.username ?? ""}@${profile.target.hostname}:${profile.target.port ?? 22}`;
juliusmarminge merged this979ca66
juliusmarminge closed this
Sign in to join this conversation.





macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed