@devries-cameron20 / t3code Mirror · read-only / commits / 4092c4ac56
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 12:00 UTC

fix(client): retry the permissions check after a reconnect (#27008)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 29, 2026 at 12:49 UTC 4092c4ac567b791c84c20a15403f2b7d5051d42d
6 files changed +230 -16
apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx
+12 -3
@@ -12,7 +12,10 @@ import {
12 isLearned,
13 } from "@t3tools/client-runtime/connection";
14 import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
15 -import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
15 +import {
16 + AUTH_SCOPE_OPTIONS,
17 + sessionPermissionsUnavailableMessage,
18 +} from "@t3tools/shared/authScopeOptions";
19 import { AsyncResult } from "effect/reactivity";
20 import * as Option from "effect/Option";
21 import { useState } from "react";
@@ -163,8 +166,14 @@ export function EnvironmentRoutesSection({
166 </>
167 ) : (
168 <Text className="text-sm text-foreground-muted">
166 - Permissions not checked. Connect to this environment to view this session’s
167 - permissions.
169 + {sessionPermissionsUnavailableMessage({
170 + connected: activeRouteId !== null,
171 + failed: sessionResult._tag === "Failure",
172 + rejected:
173 + sessionResult._tag !== "Failure" &&
174 + !sessionResult.waiting &&
175 + session?.authenticated === false,
176 + })}
177 </Text>
178 )}
179 </View>
apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+9 -5
@@ -8,6 +8,7 @@ import {
8 type ServerProvider,
9 } from "@t3tools/contracts";
10 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11 +import { sessionPermissionsUnavailableMessage } from "@t3tools/shared/authScopeOptions";
12 import * as Cause from "effect/Cause";
13 import * as Exit from "effect/Exit";
14 import { AsyncResult } from "effect/reactivity";
@@ -208,11 +209,14 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
209 </Text>
210 ) : !allowed ? (
211 <Text className="px-2 text-sm text-foreground-muted">
211 - {AsyncResult.isFailure(sessionResult)
212 - ? "Could not verify your permissions. Reconnect to try again."
213 - : session === null
214 - ? "Checking permissions…"
215 - : "This connection does not have permission to manage the environment."}
212 + {AsyncResult.isFailure(sessionResult) || session === null || !session.authenticated
213 + ? sessionPermissionsUnavailableMessage({
214 + connected,
215 + failed: AsyncResult.isFailure(sessionResult),
216 + rejected:
217 + !AsyncResult.isFailure(sessionResult) && session?.authenticated === false,
218 + })
219 + : "This connection does not have permission to manage the environment."}
220 </Text>
221 ) : null}
222 {error ? (
apps/web/src/components/settings/SessionPermissions.tsx
+9 -2
@@ -1,5 +1,8 @@
1 import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
2 -import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
2 +import {
3 + AUTH_SCOPE_OPTIONS,
4 + sessionPermissionsUnavailableMessage,
5 +} from "@t3tools/shared/authScopeOptions";
6 import { useEnvironmentSessionState } from "~/state/session";
7
8 export function SessionPermissions({
@@ -32,7 +35,11 @@ export function SessionPermissions({
35 </div>
36 ) : (
37 <p className="py-3 text-xs text-muted-foreground">
35 - Permissions not checked. Connect to this environment to view this session’s permissions.
38 + {sessionPermissionsUnavailableMessage({
39 + connected,
40 + failed: session.hasError,
41 + rejected: !session.hasError && !session.isPending && session.data?.authenticated === false,
42 + })}
43 </p>
44 );
45 }
packages/client-runtime/src/state/session.test.ts new
+133
@@ -0,0 +1,133 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import { EnvironmentId, type AuthSessionState } from "@t3tools/contracts";
3 +import * as Clock from "effect/Clock";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Queue from "effect/Queue";
8 +import * as Stream from "effect/Stream";
9 +import * as SubscriptionRef from "effect/SubscriptionRef";
10 +import * as TestClock from "effect/testing/TestClock";
11 +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12 +
13 +import {
14 + AVAILABLE_CONNECTION_STATE,
15 + PrimaryConnectionTarget,
16 + type PreparedConnection,
17 +} from "../connection/model.ts";
18 +import * as EnvironmentRegistry from "../connection/registry.ts";
19 +import * as EnvironmentSupervisor from "../connection/supervisor.ts";
20 +import * as RpcHttp from "../rpc/http.ts";
21 +import type { RpcSession } from "../rpc/session.ts";
22 +import { createEnvironmentSessionAtoms } from "./session.ts";
23 +
24 +const TARGET = new PrimaryConnectionTarget({
25 + environmentId: EnvironmentId.make("environment-1"),
26 + label: "Test environment",
27 + httpBaseUrl: "https://environment.example.test",
28 + wsBaseUrl: "wss://environment.example.test",
29 +});
30 +const PREPARED: PreparedConnection = {
31 + environmentId: TARGET.environmentId,
32 + label: TARGET.label,
33 + httpBaseUrl: "https://environment.example.test",
34 + socketUrl: "wss://environment.example.test/ws",
35 + httpAuthorization: { _tag: "Bearer", token: "bearer-token" },
36 + target: TARGET,
37 +};
38 +const SESSION = {
39 + authenticated: true,
40 + auth: {
41 + policy: "remote-reachable",
42 + bootstrapMethods: [],
43 + sessionMethods: [],
44 + sessionCookieName: "t3_session",
45 + },
46 + scopes: ["orchestration:read"],
47 +} satisfies AuthSessionState;
48 +
49 +const rpcSession = (): RpcSession => ({ closed: Effect.never }) as unknown as RpcSession;
50 +
51 +const makeHarness = Effect.fn("TestSessionState.makeHarness")(function* (
52 + reply: (requestNumber: number) => Promise<Response>,
53 +) {
54 + let requestCount = 0;
55 + const transport = yield* SubscriptionRef.make(Option.some(rpcSession()));
56 + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
57 + target: TARGET,
58 + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
59 + session: transport,
60 + prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
61 + connect: Effect.void,
62 + disconnect: Effect.void,
63 + retryNow: Effect.void,
64 + } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
65 + const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
66 + _environmentId,
67 + stream,
68 + ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
69 + const runtime = Atom.runtime(
70 + Layer.mergeAll(
71 + Layer.succeed(
72 + EnvironmentRegistry.EnvironmentRegistry,
73 + EnvironmentRegistry.EnvironmentRegistry.of({
74 + followStream,
75 + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
76 + ),
77 + RpcHttp.layerRemoteHttpClient(async () => reply(++requestCount)),
78 + // The test's clock, so the retry wait moves with `TestClock.adjust`.
79 + Layer.succeed(Clock.Clock, yield* Clock.Clock),
80 + ),
81 + );
82 + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
83 + Effect.sync(() => registry.dispose()),
84 + );
85 + const results = yield* Queue.unbounded<AsyncResult.AsyncResult<AuthSessionState, unknown>>();
86 + const atom = createEnvironmentSessionAtoms(runtime).sessionStateAtom(TARGET.environmentId);
87 + const unsubscribe = registry.subscribe(atom, (result) => Queue.offerUnsafe(results, result), {
88 + immediate: true,
89 + });
90 + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
91 + const nextSettled = Effect.fn("TestSessionState.nextSettled")(function* () {
92 + for (;;) {
93 + const result = yield* Queue.take(results);
94 + if (!result.waiting && result._tag !== "Initial") return result;
95 + }
96 + });
97 + return { transport, nextSettled };
98 +});
99 +
100 +const unreachable = () => Promise.reject(new TypeError("Network request failed"));
101 +
102 +describe("environment session state", () => {
103 + it.effect("fetches permissions again when the connection is re-established", () =>
104 + Effect.gen(function* () {
105 + const harness = yield* makeHarness((requestNumber) =>
106 + requestNumber === 1 ? unreachable() : Promise.resolve(Response.json(SESSION)),
107 + );
108 + expect((yield* harness.nextSettled())._tag).toBe("Failure");
109 +
110 + yield* SubscriptionRef.set(harness.transport, Option.some(rpcSession()));
111 +
112 + expect(yield* harness.nextSettled()).toMatchObject({ _tag: "Success", value: SESSION });
113 + }),
114 + );
115 +
116 + it.effect("retries a failed permission check with backoff that restarts per connection", () =>
117 + Effect.gen(function* () {
118 + const harness = yield* makeHarness((requestNumber) =>
119 + requestNumber <= 3 ? unreachable() : Promise.resolve(Response.json(SESSION)),
120 + );
121 + expect((yield* harness.nextSettled())._tag).toBe("Failure");
122 +
123 + yield* TestClock.adjust("2 seconds");
124 + expect((yield* harness.nextSettled())._tag).toBe("Failure");
125 +
126 + yield* SubscriptionRef.set(harness.transport, Option.some(rpcSession()));
127 + expect((yield* harness.nextSettled())._tag).toBe("Failure");
128 +
129 + yield* TestClock.adjust("2 seconds");
130 + expect(yield* harness.nextSettled()).toMatchObject({ _tag: "Success", value: SESSION });
131 + }),
132 + );
133 +});
packages/client-runtime/src/state/session.ts
+51 -6
@@ -14,6 +14,7 @@ import type { PreparedConnection } from "../connection/model.ts";
14 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
15 import * as ManagedRelay from "../relay/managedRelay.ts";
16 import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
17 +import type { RpcSession } from "../rpc/session.ts";
18 import { safeErrorLogAttributes } from "../errors/safeLog.ts";
19 import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
20 import { followStreamInEnvironment } from "./environmentStreams.ts";
@@ -39,6 +40,8 @@ function initialConfigOption<E>(
40
41 const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
42 const MAX_SESSION_STATE_TIMEOUT_MS = 60_000;
43 +const SESSION_STATE_RETRY_BASE_MS = 2_000;
44 +const SESSION_STATE_RETRY_MAX_MS = 60_000;
45
46 export const fetchEnvironmentSessionState = Effect.fn(
47 "clientRuntime.state.fetchEnvironmentSessionState",
@@ -136,13 +139,38 @@ function makeEnvironmentSessionAtoms<R, E>(
139 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
140 );
141
139 - const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
140 - runtime
142 + const transportSessionAtom = Atom.family((environmentId: EnvironmentId) =>
143 + runtime.atom(
144 + followStreamInEnvironment(
145 + environmentId,
146 + Stream.unwrap(
147 + EnvironmentSupervisor.EnvironmentSupervisor.pipe(
148 + Effect.map((supervisor) => SubscriptionRef.changes(supervisor.session)),
149 + ),
150 + ),
151 + ),
152 + { initialValue: Option.none() },
153 + ),
154 + );
155 +
156 + const sessionStateAtom = Atom.family((environmentId: EnvironmentId) => {
157 + let consecutiveFailures = 0;
158 + let backoffConnection: RpcSession | null = null;
159 + return runtime
160 .atom((get) => {
161 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
143 - if (prepared === null) {
162 + // Each established connection fetches anew, and a failure retries while it stays up,
163 + // so a fetch that failed mid-reconnect cannot outlive the socket that recovered.
164 + const connection = AsyncResult.getOrElse(get(transportSessionAtom(environmentId)), () =>
165 + Option.none(),
166 + );
167 + if (prepared === null || Option.isNone(connection)) {
168 return Effect.never;
169 }
170 + if (connection.value !== backoffConnection) {
171 + backoffConnection = connection.value;
172 + consecutiveFailures = 0;
173 + }
174 return Effect.gen(function* () {
175 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
176 const remoteAuthorization = yield* Effect.serviceOption(
@@ -155,14 +183,31 @@ function makeEnvironmentSessionAtoms<R, E>(
183 signer,
184 remoteAuthorization,
185 }).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
158 - });
186 + }).pipe(
187 + Effect.tap(() =>
188 + Effect.sync(() => {
189 + consecutiveFailures = 0;
190 + }),
191 + ),
192 + Effect.tapError(() => {
193 + const delayMs = Math.min(
194 + SESSION_STATE_RETRY_BASE_MS * 2 ** consecutiveFailures,
195 + SESSION_STATE_RETRY_MAX_MS,
196 + );
197 + consecutiveFailures += 1;
198 + return Effect.sleep(delayMs).pipe(
199 + Effect.andThen(Effect.sync(() => get.refreshSelf())),
200 + Effect.forkScoped,
201 + );
202 + }),
203 + );
204 })
205 .pipe(
206 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
207 Atom.setIdleTTL(5 * 60_000),
208 Atom.withLabel(`environment-session-state:${environmentId}`),
164 - ),
165 - );
209 + );
210 + });
211
212 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
213 Atom.make(
packages/shared/src/authScopeOptions.ts
+16
@@ -104,3 +104,19 @@ export const AUTH_SCOPE_OPTIONS: ReadonlyArray<{
104 description: "Change managed tunnel connectivity.",
105 },
106 ];
107 +
108 +/** Shown instead of the granted scopes while they are unknown, so every surface says the same thing. */
109 +export function sessionPermissionsUnavailableMessage(input: {
110 + readonly connected: boolean;
111 + /** The check errored; the client retries it while connected. */
112 + readonly failed: boolean;
113 + /** The environment answered that this session is not signed in; retrying will not change that. */
114 + readonly rejected: boolean;
115 +}): string {
116 + if (!input.connected) return "Connect to this environment to view this session’s permissions.";
117 + if (input.rejected)
118 + return "This environment did not accept your session. Reconnect to try again.";
119 + return input.failed
120 + ? "Could not verify your permissions. Retrying automatically."
121 + : "Checking permissions…";
122 +}