@devries-cameron20 / t3code-1 / commits / 9e32c95576
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(client-runtime): show routes whose host refused this device's sign-in (#33199)

Julius Marminge committed Nov 16, 2026 at 18:20 UTC 9e32c95576f75c45d543778900b2186ece9c6711
21 files changed +368 -30
apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx
+17
@@ -28,6 +28,7 @@ import { AppText as Text } from "../../components/ui/AppText";
28 import { StatusPill } from "../../components/StatusPill";
29 import { environmentCatalog } from "../../connection/catalog";
30 import { cn } from "../../lib/cn";
31 +import { environmentPresentations } from "../../state/presentation";
32 import { environmentSession } from "../../state/session";
33 import { useAtomCommand } from "../../state/use-atom-command";
34 import { connectionTone } from "../connection/connectionTone";
@@ -59,6 +60,8 @@ export function EnvironmentRoutesSection({
60 }) {
61 const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
62 const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
63 + const refusedRouteIds =
64 + useAtomValue(environmentPresentations.presentationAtom(environmentId))?.refusedRouteIds ?? [];
65 const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
66 const session = AsyncResult.getOrElse(sessionResult, () => null);
67 const [permissionsOpen, setPermissionsOpen] = useState(false);
@@ -195,6 +198,7 @@ export function EnvironmentRoutesSection({
198 position={index + 1}
199 count={routes.length}
200 inUse={id === activeRouteId}
201 + refused={refusedRouteIds.includes(id)}
202 editing={editing}
203 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
204 lifted={index === dragFrom}
@@ -228,6 +232,7 @@ function RouteRow(props: {
232 readonly position: number;
233 readonly count: number;
234 readonly inUse: boolean;
235 + readonly refused: boolean;
236 readonly editing: boolean;
237 readonly offset: number;
238 readonly lifted: boolean;
@@ -241,6 +246,10 @@ function RouteRow(props: {
246 const { route, lifted, offset } = props;
247 const label = connectionRouteLabel(route);
248 const address = connectionRouteAddress(route);
249 + const refusedHint =
250 + props.refused && address !== null
251 + ? "The host refused this device's sign-in. Pair this address again with Add route."
252 + : null;
253 const style = useAnimatedStyle(() => ({
254 transform: [
255 {
@@ -282,7 +291,9 @@ function RouteRow(props: {
291 address,
292 isLearned(route) ? "Found automatically" : null,
293 props.inUse ? "In use" : null,
294 + props.refused ? "Sign-in refused" : null,
295 `Route ${props.position} of ${props.count}`,
296 + refusedHint,
297 ]
298 .filter((part) => part !== null)
299 .join(", ")}
@@ -307,12 +318,18 @@ function RouteRow(props: {
318 {props.inUse ? (
319 <StatusPill {...connectionTone("connected")} label="In use" size="compact" />
320 ) : null}
321 + {props.refused ? (
322 + <StatusPill {...connectionTone("error")} label="Sign-in refused" size="compact" />
323 + ) : null}
324 </View>
325 {address !== null ? (
326 <Text numberOfLines={1} className="text-sm text-foreground-muted">
327 {isLearned(route) ? `${address} · found automatically` : address}
328 </Text>
329 ) : null}
330 + {refusedHint !== null ? (
331 + <Text className="text-sm text-foreground-muted">{refusedHint}</Text>
332 + ) : null}
333 </View>
334 </View>
335 {props.editing ? (
apps/mobile/src/state/remote-environment-projections.test.ts
+1
@@ -32,6 +32,7 @@ function presentation(
32 entry: { target: target(environmentId, endpoint), profile: Option.none(), enabled: true },
33 connection: { phase: "connected", error: null, traceId: null },
34 serverConfig,
35 + refusedRouteIds: [],
36 };
37 }
38
apps/mobile/src/state/workspace-connection-atoms.test.ts
+1
@@ -29,6 +29,7 @@ function presentation(): EnvironmentPresentation {
29 },
30 connection: { phase: "connected", error: null, traceId: null },
31 serverConfig: null,
32 + refusedRouteIds: [],
33 };
34 }
35 function harness() {
apps/mobile/src/state/workspaceModel.test.ts
+1
@@ -48,6 +48,7 @@ function environment(
48 traceId: phase === "error" ? "trace-1" : null,
49 },
50 serverConfig: null,
51 + refusedRouteIds: [],
52 };
53 }
54
apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx
+1
@@ -108,6 +108,7 @@ function setup() {
108 enabled: true,
109 },
110 connection: { phase: "connected", error: null, traceId: null },
111 + refusedRouteIds: [],
112 serverConfig: null,
113 },
114 ]),
apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx
+1
@@ -64,6 +64,7 @@ function routesList(routes: ReadonlyArray<ConnectionRoute>) {
64 entry,
65 connection: { phase: "available", error: null, traceId: null },
66 serverConfig: null,
67 + refusedRouteIds: [],
68 };
69 return <EnvironmentRoutesList environment={environment} onAddRoute={() => undefined} />;
70 }
apps/web/src/components/settings/EnvironmentRoutesList.tsx
+13
@@ -108,6 +108,7 @@ export function EnvironmentRoutesList({
108 route={route}
109 position={index + 1}
110 inUse={connectionRouteId(route.target) === activeRouteId}
111 + refused={environment.refusedRouteIds.includes(connectionRouteId(route.target))}
112 removable={routes.length > 1 && !isLearned(route)}
113 onRemove={() => void confirmRemove(route)}
114 />
@@ -129,12 +130,14 @@ function SortableRouteRow({
130 route,
131 position,
132 inUse,
133 + refused,
134 removable,
135 onRemove,
136 }: {
137 readonly route: ConnectionRoute;
138 readonly position: number;
139 readonly inUse: boolean;
140 + readonly refused: boolean;
141 readonly removable: boolean;
142 readonly onRemove: () => void;
143 }) {
@@ -168,6 +171,11 @@ function SortableRouteRow({
171 In use
172 </span>
173 ) : null}
174 + {refused ? (
175 + <span className="rounded-sm bg-destructive/8 px-1 text-2xs font-normal text-destructive-foreground">
176 + Sign-in refused
177 + </span>
178 + ) : null}
179 </p>
180 {address !== null ? (
181 <p className="truncate text-2xs text-muted-foreground">
@@ -175,6 +183,11 @@ function SortableRouteRow({
183 {isLearned(route) ? " · found automatically" : ""}
184 </p>
185 ) : null}
186 + {refused && address !== null ? (
187 + <p className="text-2xs text-muted-foreground">
188 + The host refused this device's sign-in. Pair this address again with Add route.
189 + </p>
190 + ) : null}
191 </div>
192 <button
193 type="button"
apps/web/src/components/settings/IntegrationsSettings.browser.test.tsx
+1
@@ -59,6 +59,7 @@ const environments: EnvironmentPresentation[] = [
59 enabled: true,
60 },
61 connection: { phase: "connected", error: null, traceId: null },
62 + refusedRouteIds: [],
63 serverConfig: config,
64 },
65 ];
apps/web/test/fakeEnvironment.ts
+1
@@ -547,6 +547,7 @@ export const fakeDriver = {
547 target: entry.target,
548 },
549 session,
550 + refusedRouteIds: [],
551 }),
552 preflight: () => Effect.succeed(true),
553 checkHost: () => Effect.succeed<RouteCheck>("unchecked"),
docs/user/remote-access.md
+3 -1
@@ -158,7 +158,9 @@ T3 Code connects over the first route that answers. Away from home, a LAN
158 address that does not answer is checked briefly and skipped. It is only tried
159 again, after the other routes, if none of them connect. While connected over a
160 later route, T3 Code checks the earlier ones when your network changes, when you
161 -return to the app, and every minute, and moves back as soon as one works.
161 +return to the app, and every minute, and moves back as soon as one works. A
162 +route whose machine refused this device's sign-in is marked **Sign-in
163 +refused**; pair that address again with **Add route** to use it.
164
165 On web and desktop, select the route count under the machine's name in
166 **Settings → Environments** to see its routes. Drag a route to change the order,
packages/client-runtime/src/connection/driver.ts
+45 -21
@@ -15,8 +15,10 @@ import type {
15 PreparedConnection,
16 } from "./model.ts";
17 import { ConnectionTransientError } from "./model.ts";
18 +import { isHostCredentialRefusal } from "./errors.ts";
19 import * as ConnectionResolver from "./resolver.ts";
20 import {
21 + connectionRouteId,
22 connectionRoutes,
23 routeEntry,
24 routeHttpBaseUrl,
@@ -37,14 +39,22 @@ export type ConnectionDriverProgress =
39 readonly prepared: PreparedConnection;
40 };
41
40 -export interface EnvironmentConnectionLease {
42 +export interface RouteConnection {
43 readonly prepared: PreparedConnection;
44 readonly session: RpcSession.RpcSession;
45 }
46
47 +export interface EnvironmentConnectionLease extends RouteConnection {
48 + /** Saved routes whose host refused this device's credential before another route connected. */
49 + readonly refusedRouteIds: ReadonlyArray<string>;
50 +}
51 +
52 export type RouteCheck = "answered" | "silent" | "unchecked";
46 -/** "unprepared" means the route answered its check but could not be prepared. */
47 -export type RoutePreflight = "ready" | "unprepared" | "silent" | "unchecked";
53 +/**
54 + * "unprepared" means the route answered its check but could not be prepared;
55 + * "refused" means its host refused this device's credential.
56 + */
57 +export type RoutePreflight = "ready" | "refused" | "unprepared" | "silent" | "unchecked";
58
59 const ROUTE_CHECK_TIMEOUT_MS = 2_500;
60 // Preferred direct routes share one head start, so a relay connection does not
@@ -73,7 +83,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
83 checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
84 connectRoute: (
85 route: ConnectionRoute,
76 - ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
86 + ) => Effect.Effect<RouteConnection, ConnectionAttemptError, R | Scope.Scope>,
87 ) {
88 const routes = usableRoutes(entry);
89 const checks =
@@ -84,6 +94,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
94 const attemptScope = yield* Scope.Scope;
95 let transient: ConnectionAttemptError | undefined;
96 let blocked: ConnectionAttemptError | undefined;
97 + const refusedRouteIds: Array<string> = [];
98 // Each route gets its own scope so a half-open session closes before the next try.
99 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
100 const routeScope = yield* Scope.fork(attemptScope);
@@ -95,6 +106,8 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
106 if (result._tag === "Failure") {
107 if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
108 else blocked ??= result.failure;
109 + if (isHostCredentialRefusal(result.failure))
110 + refusedRouteIds.push(connectionRouteId(route.target));
111 }
112 return result;
113 });
@@ -112,7 +125,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
125 continue;
126 }
127 const result = yield* attempt(route);
115 - if (result._tag === "Success") return result.success;
128 + if (result._tag === "Success") return { ...result.success, refusedRouteIds };
129 // An incompatible server is the same server on every route.
130 if (result.failure.reason === "unsupported") return yield* result.failure;
131 }
@@ -127,7 +140,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
140 // retries, the retry reaches it sooner than waiting here would.
141 if (transient !== undefined && stillSilent.some((entry) => entry.route === route)) break;
142 const result = yield* attempt(route);
130 - if (result._tag === "Success") return result.success;
143 + if (result._tag === "Success") return { ...result.success, refusedRouteIds };
144 if (result.failure.reason === "unsupported") return yield* result.failure;
145 }
146 return yield* (
@@ -140,6 +153,25 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
153 );
154 });
155
156 +export const preflightRoute = (
157 + check: Effect.Effect<RouteCheck>,
158 + prepare: Effect.Effect<unknown, ConnectionAttemptError>,
159 +): Effect.Effect<RoutePreflight> =>
160 + check.pipe(
161 + Effect.filterOrElse(
162 + (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
163 + () =>
164 + prepare.pipe(
165 + Effect.as<RoutePreflight>("ready"),
166 + Effect.catch((error) =>
167 + Effect.succeed<RoutePreflight>(
168 + isHostCredentialRefusal(error) ? "refused" : "unprepared",
169 + ),
170 + ),
171 + ),
172 + ),
173 + );
174 +
175 /** @public */
176 export const make = Effect.gen(function* () {
177 const resolver = yield* ConnectionResolver.ConnectionResolver;
@@ -226,26 +258,18 @@ export const make = Effect.gen(function* () {
258 Effect.forkScoped,
259 );
260 }
229 - return { prepared, session } satisfies EnvironmentConnectionLease;
261 + return { prepared, session } satisfies RouteConnection;
262 }),
263 );
264 });
265
266 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
235 - (sendsTokenInClear(connectionRoutes(entry), route)
236 - ? Effect.succeed("silent" as const)
237 - : checkRoute(entry, route)
238 - ).pipe(
239 - Effect.filterOrElse(
240 - (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
241 - () =>
242 - resolver.prepare(routeEntry(entry, route)).pipe(
243 - Effect.as<RoutePreflight>("ready"),
244 - Effect.orElseSucceed((): RoutePreflight => "unprepared"),
245 - ),
246 - ),
247 - Effect.withSpan("ConnectionDriver.preflight"),
248 - );
267 + preflightRoute(
268 + sendsTokenInClear(connectionRoutes(entry), route)
269 + ? Effect.succeed("silent" as const)
270 + : checkRoute(entry, route),
271 + resolver.prepare(routeEntry(entry, route)),
272 + ).pipe(Effect.withSpan("ConnectionDriver.preflight"));
273
274 return ConnectionDriver.of({ connect, preflight, checkHost });
275 });
packages/client-runtime/src/connection/errors.ts
+10
@@ -26,6 +26,16 @@ export function credentialMissingError(connectionId: string): ConnectionBlockedE
26 });
27 }
28
29 +/** The host itself answered and refused this device's credential, which pairing again fixes. */
30 +export function isHostCredentialRefusal(error: ConnectionAttemptError): boolean {
31 + return (
32 + error._tag === "ConnectionBlockedError" &&
33 + error.hop === "server" &&
34 + (error.reason === "authentication" || error.reason === "permission") &&
35 + error.failureCause !== "clock_skew"
36 + );
37 +}
38 +
39 export function environmentMismatchError(input: {
40 readonly expected: EnvironmentId;
41 readonly actual: EnvironmentId;
packages/client-runtime/src/connection/model.ts
+5
@@ -181,8 +181,12 @@ export interface SupervisorConnectionState {
181 readonly generation: number;
182 readonly lastFailure: ConnectionAttemptError | null;
183 readonly retryAt: number | null;
184 + /** While connected: saved routes whose host refused this device's credential on the way. */
185 + readonly refusedRouteIds: ReadonlyArray<string>;
186 }
187
188 +export const NO_REFUSED_ROUTES: ReadonlyArray<string> = Object.freeze([]);
189 +
190 export type ConnectionProjectionPhase = "disconnected" | "synchronizing" | "ready";
191
192 export function connectionProjectionPhase(
@@ -210,4 +214,5 @@ export const AVAILABLE_CONNECTION_STATE: SupervisorConnectionState = Object.free
214 generation: 0,
215 lastFailure: null,
216 retryAt: null,
217 + refusedRouteIds: NO_REFUSED_ROUTES,
218 });
packages/client-runtime/src/connection/presentation.test.ts
+1
@@ -50,6 +50,7 @@ function supervisorState(overrides: Partial<SupervisorConnectionState>): Supervi
50 generation: 0,
51 lastFailure: null,
52 retryAt: null,
53 + refusedRouteIds: [],
54 ...overrides,
55 };
56 }
packages/client-runtime/src/connection/presentation.ts
+2
@@ -36,6 +36,8 @@ export interface EnvironmentPresentation {
36 readonly entry: ConnectionCatalogEntry;
37 readonly connection: EnvironmentConnectionPresentation;
38 readonly serverConfig: EnvironmentServerConfig | null;
39 + /** See `SupervisorConnectionState.refusedRouteIds`. */
40 + readonly refusedRouteIds: ReadonlyArray<string>;
41 }
42
43 export function presentConnectionState(
packages/client-runtime/src/connection/supervisor.test.ts
+177 -1
@@ -147,6 +147,14 @@ function blocked(message = "Authentication required.") {
147 });
148 }
149
150 +function hostRefusal() {
151 + return new ConnectionBlockedError({
152 + reason: "authentication",
153 + detail: "The environment credential is invalid.",
154 + hop: "server",
155 + });
156 +}
157 +
158 function awaitState(
159 state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
160 predicate: (value: SupervisorConnectionState) => boolean,
@@ -241,7 +249,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
249
250 yield* reportProgress({ stage: "synchronizing", prepared });
251 yield* session.ready;
244 - return { prepared, session } satisfies ConnectionDriver.EnvironmentConnectionLease;
252 + return { prepared, session } satisfies ConnectionDriver.RouteConnection;
253 });
254
255 const connect = Effect.fn("TestConnectionDriver.connect")(function* (
@@ -2078,6 +2086,174 @@ describe("EnvironmentSupervisor routes", () => {
2086 }),
2087 );
2088
2089 + it.effect("does not report a route that failed before reaching its host's sign-in", () =>
2090 + Effect.gen(function* () {
2091 + const failures = [
2092 + new ConnectionBlockedError({
2093 + reason: "permission",
2094 + detail: "T3 Connect is not enabled on this machine.",
2095 + hop: "tunnel",
2096 + failureCause: "tunnel_not_enabled",
2097 + }),
2098 + new ConnectionBlockedError({
2099 + reason: "authentication",
2100 + detail: "This device's clock is wrong.",
2101 + hop: "server",
2102 + failureCause: "clock_skew",
2103 + }),
2104 + ];
2105 + for (const failure of failures) {
2106 + const harness = yield* makeHarness({
2107 + checkRoute: () => Effect.succeed("answered"),
2108 + prepare: (_attempt, target) =>
2109 + target._tag === "BearerConnectionTarget"
2110 + ? Effect.fail(failure)
2111 + : Effect.succeed(preparedFor(target)),
2112 + });
2113 + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
2114 + initiallyDesired: true,
2115 + }).pipe(Effect.provide(harness.dependencies));
2116 +
2117 + const state = yield* awaitState(supervisor.state, (value) => value.phase === "connected");
2118 + expect(state.refusedRouteIds).toEqual([]);
2119 + }
2120 + }),
2121 + );
2122 +
2123 + it.effect("reports a preferred route whose host refuses sign-in once it answers again", () =>
2124 + Effect.gen(function* () {
2125 + const lanReachable = yield* Ref.make(false);
2126 + const lanRefuses = yield* Ref.make(true);
2127 + const checkRoute = (route: ConnectionRoute) =>
2128 + route.target._tag === "BearerConnectionTarget"
2129 + ? Ref.get(lanReachable).pipe(
2130 + Effect.map((reachable): ConnectionDriver.RouteCheck =>
2131 + reachable ? "answered" : "silent",
2132 + ),
2133 + )
2134 + : Effect.succeed<ConnectionDriver.RouteCheck>("unchecked");
2135 + const harness = yield* makeHarness({
2136 + checkRoute,
2137 + preflight: (route) =>
2138 + ConnectionDriver.preflightRoute(
2139 + checkRoute(route),
2140 + Ref.get(lanRefuses).pipe(
2141 + Effect.flatMap((refuses) =>
2142 + refuses && route.target._tag === "BearerConnectionTarget"
2143 + ? Effect.fail(hostRefusal())
2144 + : Effect.succeed(preparedFor(route.target)),
2145 + ),
2146 + ),
2147 + ),
2148 + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
2149 + });
2150 + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
2151 + initiallyDesired: true,
2152 + }).pipe(Effect.provide(harness.dependencies));
2153 +
2154 + const connected = yield* awaitState(supervisor.state, (state) => state.phase === "connected");
2155 + expect(connected.refusedRouteIds).toEqual([]);
2156 +
2157 + yield* Ref.set(lanReachable, true);
2158 + yield* harness.wake("network-changed");
2159 + const state = yield* awaitState(
2160 + supervisor.state,
2161 + (value) => value.refusedRouteIds.length > 0,
2162 + );
2163 + expect(state).toMatchObject({
2164 + phase: "connected",
2165 + generation: connected.generation,
2166 + refusedRouteIds: [LAN_TARGET.connectionId],
2167 + });
2168 + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
2169 + "RelayConnectionTarget",
2170 + );
2171 +
2172 + yield* Ref.set(lanRefuses, false);
2173 + yield* harness.wake("network-changed");
2174 + const overLan = yield* awaitState(
2175 + supervisor.state,
2176 + (value) => value.phase === "connected" && value.generation > connected.generation,
2177 + );
2178 + expect(
2179 + connectionRouteId(
2180 + Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target,
2181 + ),
2182 + ).toBe(LAN_TARGET.connectionId);
2183 + expect(overLan.refusedRouteIds).toEqual([]);
2184 + }),
2185 + );
2186 +
2187 + it.effect("keeps reporting a refused route after moving to a better route", () =>
2188 + Effect.gen(function* () {
2189 + const loopbackTarget = new BearerConnectionTarget({
2190 + environmentId: TARGET.environmentId,
2191 + label: TARGET.label,
2192 + connectionId: "bearer:loopback",
2193 + });
2194 + const entry: ConnectionCatalogEntry = {
2195 + target: loopbackTarget,
2196 + profile: Option.some(
2197 + new BearerConnectionProfile({
2198 + connectionId: loopbackTarget.connectionId,
2199 + environmentId: TARGET.environmentId,
2200 + label: TARGET.label,
2201 + httpBaseUrl: "http://127.0.0.1:3773/",
2202 + wsBaseUrl: "ws://127.0.0.1:3773/",
2203 + }),
2204 + ),
2205 + alternateRoutes: [LAN_ROUTE, { target: RELAY_TARGET, profile: Option.none() }],
2206 + enabled: true,
2207 + };
2208 + const lanReachable = yield* Ref.make(false);
2209 + const checkRoute = (route: ConnectionRoute) =>
2210 + connectionRouteId(route.target) === LAN_TARGET.connectionId
2211 + ? Ref.get(lanReachable).pipe(
2212 + Effect.map((reachable): ConnectionDriver.RouteCheck =>
2213 + reachable ? "answered" : "silent",
2214 + ),
2215 + )
2216 + : Effect.succeed<ConnectionDriver.RouteCheck>(
2217 + route.target._tag === "BearerConnectionTarget" ? "answered" : "unchecked",
2218 + );
2219 + const prepare = (target: ConnectionTarget) =>
2220 + connectionRouteId(target) === loopbackTarget.connectionId
2221 + ? Effect.fail(hostRefusal())
2222 + : Effect.succeed(preparedFor(target));
2223 + const harness = yield* makeHarness({
2224 + checkRoute,
2225 + preflight: (route) =>
2226 + ConnectionDriver.preflightRoute(checkRoute(route), prepare(route.target)),
2227 + prepare: (_attempt, target) => prepare(target),
2228 + });
2229 + const supervisor = yield* EnvironmentSupervisor.make(entry, {
2230 + initiallyDesired: true,
2231 + }).pipe(Effect.provide(harness.dependencies));
2232 +
2233 + const overRelay = yield* awaitState(
2234 + supervisor.state,
2235 + (state) => state.phase === "connected" && state.generation === 1,
2236 + );
2237 + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
2238 + "RelayConnectionTarget",
2239 + );
2240 + expect(overRelay.refusedRouteIds).toEqual([loopbackTarget.connectionId]);
2241 +
2242 + yield* Ref.set(lanReachable, true);
2243 + yield* harness.wake("network-changed");
2244 + const overLan = yield* awaitState(
2245 + supervisor.state,
2246 + (state) => state.phase === "connected" && state.generation === 2,
2247 + );
2248 + expect(
2249 + connectionRouteId(
2250 + Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target,
2251 + ),
2252 + ).toBe(LAN_TARGET.connectionId);
2253 + expect(overLan.refusedRouteIds).toEqual([loopbackTarget.connectionId]);
2254 + }),
2255 + );
2256 +
2257 it.effect("tries every route when none answers the reachability check", () =>
2258 Effect.gen(function* () {
2259 const harness = yield* makeHarness({
packages/client-runtime/src/connection/supervisor.ts
+50 -6
@@ -23,6 +23,7 @@ import {
23 type ConnectionTarget,
24 ConnectionTransientError,
25 type NetworkStatus,
26 + NO_REFUSED_ROUTES,
27 type PreparedConnection,
28 type SupervisorConnectionState,
29 } from "./model.ts";
@@ -99,8 +100,20 @@ interface PendingRetryTrace {
100
101 type ConnectedLease = ConnectionDriver.EnvironmentConnectionLease & {
102 readonly activeRoute: ConnectionRoute | undefined;
103 + readonly generation: number;
104 };
105
106 +function mergeRefusedRoutes(
107 + known: ReadonlyArray<string>,
108 + refused: ReadonlyArray<string>,
109 + keep: (routeId: string) => boolean,
110 +): ReadonlyArray<string> {
111 + const next = [...new Set([...known, ...refused])].filter(keep);
112 + return next.length === known.length && next.every((id, index) => id === known[index])
113 + ? known
114 + : next;
115 +}
116 +
117 interface TracedAttemptFailure {
118 readonly error: ConnectionAttemptError;
119 readonly attemptSpan: Option.Option<Tracer.Span>;
@@ -189,6 +202,7 @@ function availableState(intent: SupervisorIntent, generation: number): Superviso
202 generation,
203 lastFailure: null,
204 retryAt: null,
205 + refusedRouteIds: NO_REFUSED_ROUTES,
206 };
207 }
208
@@ -207,6 +221,7 @@ function offlineState(
221 generation,
222 lastFailure,
223 retryAt: null,
224 + refusedRouteIds: NO_REFUSED_ROUTES,
225 };
226 }
227
@@ -226,6 +241,7 @@ function connectingState(
241 generation,
242 lastFailure,
243 retryAt: null,
244 + refusedRouteIds: NO_REFUSED_ROUTES,
245 };
246 }
247
@@ -325,6 +341,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
341 const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));
342 const preferredRouteId = yield* Ref.make(Option.none<string>());
343 const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
344 + // Outlives sessions so a reconnect shows a refusal seen earlier; a route leaves once it connects.
345 + const refusedRoutes = yield* Ref.make(NO_REFUSED_ROUTES);
346 // The generation keeps a check that started before a reset from recording
347 // its stale failures after it.
348 const silentRoutes = yield* Ref.make({
@@ -414,10 +432,25 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
432 }
433 return { generation: previous.generation, routes };
434 });
417 - const index = results.indexOf("ready");
418 - if (index === -1) return;
435 const live = yield* SubscriptionRef.get(session);
436 if (Option.isNone(live) || live.value !== lease.session) return;
437 + const refused = better
438 + .filter((_route, position) => results[position] === "refused")
439 + .map((route) => connectionRouteId(route.target));
440 + if (refused.length > 0) {
441 + const known = yield* Ref.updateAndGet(refusedRoutes, (current) =>
442 + mergeRefusedRoutes(current, refused, () => true),
443 + );
444 + yield* SubscriptionRef.updateSome(state, (current) =>
445 + current.phase === "connected" &&
446 + current.generation === lease.generation &&
447 + current.refusedRouteIds !== known
448 + ? Option.some({ ...current, refusedRouteIds: known })
449 + : Option.none(),
450 + );
451 + }
452 + const index = results.indexOf("ready");
453 + if (index === -1) return;
454 yield* signal({
455 _tag: "BetterRouteAvailable",
456 routeId: connectionRouteId(better[index]!.target),
@@ -1026,13 +1059,21 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1059 } satisfies AttemptOutcome;
1060 }
1061
1062 + const routes = yield* currentRoutes;
1063 + const activeRouteId = connectionRouteId(active.lease.prepared.target);
1064 const connectedLease: ConnectedLease = {
1065 ...active.lease,
1031 - activeRoute: (yield* currentRoutes).find(
1032 - (route) =>
1033 - connectionRouteId(route.target) === connectionRouteId(active.lease.prepared.target),
1034 - ),
1066 + activeRoute: routes.find((route) => connectionRouteId(route.target) === activeRouteId),
1067 + generation,
1068 };
1069 + const refusedRouteIds = yield* Ref.updateAndGet(refusedRoutes, (known) =>
1070 + mergeRefusedRoutes(
1071 + known,
1072 + active.lease.refusedRouteIds,
1073 + (id) =>
1074 + id !== activeRouteId && routes.some((route) => connectionRouteId(route.target) === id),
1075 + ),
1076 + );
1077 const connectedAt = yield* Clock.currentTimeMillis;
1078 yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared));
1079 yield* SubscriptionRef.set(session, Option.some(connectedLease.session));
@@ -1048,6 +1089,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1089 generation,
1090 lastFailure: null,
1091 retryAt: null,
1092 + refusedRouteIds,
1093 });
1094
1095 const connectedExit = yield* Effect.raceFirst(
@@ -1216,6 +1258,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1258 generation,
1259 lastFailure: error,
1260 retryAt: null,
1261 + refusedRouteIds: NO_REFUSED_ROUTES,
1262 });
1263 const applicationActivated = yield* waitForSignal;
1264 if (applicationActivated) {
@@ -1264,6 +1307,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1307 generation,
1308 lastFailure: latestFailure,
1309 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
1310 + refusedRouteIds: NO_REFUSED_ROUTES,
1311 });
1312 const applicationActivated = yield* waitForRetrySignal(delayMs);
1313 if (applicationActivated) {
packages/client-runtime/src/linkRequest.test.ts
+1
@@ -145,6 +145,7 @@ const presentation = (
145 httpBaseUrl,
146 })),
147 } as unknown as ServerConfig),
148 + refusedRouteIds: [],
149 };
150 };
151
packages/client-runtime/src/state/presentation.test.ts
+18
@@ -136,6 +136,24 @@ describe("presentations with providers", () => {
136 h.registry.dispose();
137 }
138 });
139 +
140 + it("follows refused routes when nothing else about the connection changes", () => {
141 + const h = harness();
142 + const atom = h.full.presentationsWithProvidersAtom;
143 + const stop = h.registry.subscribe(atom, () => {});
144 + try {
145 + h.registry.set(h.state, AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE }));
146 + expect(h.registry.get(atom).get(FIRST)?.refusedRouteIds).toEqual([]);
147 + h.registry.set(
148 + h.state,
149 + AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, refusedRouteIds: ["direct"] }),
150 + );
151 + expect(h.registry.get(atom).get(FIRST)?.refusedRouteIds).toEqual(["direct"]);
152 + } finally {
153 + stop();
154 + h.registry.dispose();
155 + }
156 + });
157 });
158
159 describe("connection presentation", () => {
packages/client-runtime/src/state/presentation.ts
+11 -1
@@ -39,6 +39,10 @@ function sameConnection(
39 return left.phase === right.phase && left.error === right.error && left.traceId === right.traceId;
40 }
41
42 +function sameRouteIds(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
43 + return left.length === right.length && left.every((routeId, index) => right[index] === routeId);
44 +}
45 +
46 function withoutProviders(
47 config: ServerConfig | null,
48 previous: EnvironmentServerConfig | null,
@@ -99,11 +103,16 @@ export function createEnvironmentPresentationAtoms<E>(input: {
103 get(input.serverConfigValueAtom(environmentId)),
104 previous?.serverConfig ?? null,
105 ),
106 + refusedRouteIds:
107 + previous !== null && sameRouteIds(previous.refusedRouteIds, state.refusedRouteIds)
108 + ? previous.refusedRouteIds
109 + : state.refusedRouteIds,
110 } satisfies EnvironmentPresentation;
111 return previous !== null &&
112 previous.entry === next.entry &&
113 previous.connection === next.connection &&
106 - previous.serverConfig === next.serverConfig
114 + previous.serverConfig === next.serverConfig &&
115 + previous.refusedRouteIds === next.refusedRouteIds
116 ? previous
117 : next;
118 }).pipe(Atom.withLabel(`environment-presentation:${environmentId}`)),
@@ -173,6 +182,7 @@ export function createEnvironmentPresentationAtoms<E>(input: {
182 prior !== undefined &&
183 prior.entry === presentation.entry &&
184 prior.connection === presentation.connection &&
185 + prior.refusedRouteIds === presentation.refusedRouteIds &&
186 prior.serverConfig === serverConfig
187 ? prior
188 : { ...presentation, serverConfig },
packages/client-runtime/src/state/shell-sync.test.ts
+8
@@ -196,6 +196,7 @@ describe("environment shell synchronization", () => {
196 generation: 1,
197 lastFailure: null,
198 retryAt: null,
199 + refusedRouteIds: [],
200 });
201 yield* Queue.offer(events, { kind: "snapshot", snapshot: batchSnapshot });
202 yield* Queue.offer(events, { kind: "synchronized" });
@@ -467,6 +468,7 @@ describe("environment shell synchronization", () => {
468 generation: 0,
469 lastFailure: null,
470 retryAt: null,
471 + refusedRouteIds: [],
472 });
473 yield* Queue.offer(events, {
474 kind: "snapshot",
@@ -487,6 +489,7 @@ describe("environment shell synchronization", () => {
489 generation: 1,
490 lastFailure: null,
491 retryAt: null,
492 + refusedRouteIds: [],
493 });
494 yield* SubscriptionRef.set(supervisorState, {
495 desired: false,
@@ -497,6 +500,7 @@ describe("environment shell synchronization", () => {
500 generation: 2,
501 lastFailure: null,
502 retryAt: null,
503 + refusedRouteIds: [],
504 });
505 yield* Deferred.await(saveStarted);
506
@@ -509,6 +513,7 @@ describe("environment shell synchronization", () => {
513 generation: 3,
514 lastFailure: null,
515 retryAt: null,
516 + refusedRouteIds: [],
517 });
518 yield* SubscriptionRef.changes(shellState).pipe(
519 Stream.filter((state) => state.status === "synchronizing"),
@@ -609,6 +614,7 @@ describe("environment shell synchronization", () => {
614 generation: 0,
615 lastFailure: null,
616 retryAt: null,
617 + refusedRouteIds: [],
618 });
619 yield* Queue.offer(events, {
620 kind: "snapshot",
@@ -631,6 +637,7 @@ describe("environment shell synchronization", () => {
637 generation: 1,
638 lastFailure: null,
639 retryAt: null,
640 + refusedRouteIds: [],
641 });
642 yield* Deferred.await(unenrichedSaveStarted);
643
@@ -725,6 +732,7 @@ describe("environment shell synchronization", () => {
732 generation: 0,
733 lastFailure: null,
734 retryAt: null,
735 + refusedRouteIds: [],
736 });
737 yield* Queue.offer(events, {
738 kind: "snapshot",