Skip to content

Commit 72cb009

Browse files
sheehanmunimclaude
andcommitted
fix(client): a timed-out session check no longer locks the composer
One slow /api/auth/session response left the environment session atom in Failure. The scope gate rejects any Failure and the atom never retried, so send stayed disabled ("This connection cannot change threads.") until the window reloaded. With a confirmed grant, transient failures now keep it and retry with capped backoff; rejected credentials and first loads still fail. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0f09627 commit 72cb009

2 files changed

Lines changed: 141 additions & 1 deletion

File tree

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import { EnvironmentId, type AuthSessionState } from "@t3tools/contracts";
3+
import * as Effect from "effect/Effect";
4+
import * as Layer from "effect/Layer";
5+
import * as Option from "effect/Option";
6+
import * as Stream from "effect/Stream";
7+
import * as SubscriptionRef from "effect/SubscriptionRef";
8+
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9+
10+
import { RelayConnectionTarget, type PreparedConnection } from "../connection/model.ts";
11+
import { EnvironmentRegistry } from "../connection/registry.ts";
12+
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
13+
import * as RpcHttp from "../rpc/http.ts";
14+
import { createEnvironmentSessionAtoms } from "./session.ts";
15+
16+
const TARGET = new RelayConnectionTarget({
17+
environmentId: EnvironmentId.make("environment-1"),
18+
label: "Environment",
19+
});
20+
const PREPARED: PreparedConnection = {
21+
environmentId: TARGET.environmentId,
22+
label: TARGET.label,
23+
httpBaseUrl: "https://environment.example.test",
24+
socketUrl: "wss://environment.example.test/ws",
25+
httpAuthorization: { _tag: "Bearer", token: "bearer-token" },
26+
target: TARGET,
27+
};
28+
const SESSION = {
29+
authenticated: true,
30+
auth: {
31+
policy: "remote-reachable",
32+
bootstrapMethods: ["desktop-bootstrap"],
33+
sessionMethods: ["bearer-access-token"],
34+
sessionCookieName: "t3_session",
35+
},
36+
scopes: ["orchestration:read", "orchestration:operate"],
37+
} satisfies AuthSessionState;
38+
39+
function makeSessionAtom(reply: (requestNumber: number) => Promise<Response>) {
40+
let calls = 0;
41+
const fetchFn: typeof fetch = () => reply(++calls);
42+
const layer = Effect.gen(function* () {
43+
const supervisor = {
44+
target: TARGET,
45+
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
46+
} as unknown as EnvironmentSupervisor["Service"];
47+
const registry = {
48+
followStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
49+
stream.pipe(Stream.provideService(EnvironmentSupervisor, supervisor)),
50+
} as unknown as EnvironmentRegistry["Service"];
51+
return Layer.merge(
52+
Layer.succeed(EnvironmentRegistry, registry),
53+
RpcHttp.layerRemoteHttpClient(fetchFn),
54+
);
55+
}).pipe(Layer.unwrap);
56+
const atom = createEnvironmentSessionAtoms(Atom.runtime(layer)).sessionStateAtom(
57+
TARGET.environmentId,
58+
);
59+
return { atom, calls: () => calls };
60+
}
61+
62+
const settle = (
63+
registry: AtomRegistry.AtomRegistry,
64+
atom: ReturnType<typeof makeSessionAtom>["atom"],
65+
) => AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe(Effect.result);
66+
67+
describe("environment session state", () => {
68+
it.effect("keeps a confirmed grant through a failed refresh and retries it", () =>
69+
Effect.gen(function* () {
70+
const session = makeSessionAtom(async (requestNumber) => {
71+
if (requestNumber === 2) throw new TypeError("Failed to fetch");
72+
return Response.json(SESSION);
73+
});
74+
const registry = AtomRegistry.make();
75+
yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
76+
const observed: Array<string> = [];
77+
registry.mount(session.atom);
78+
registry.subscribe(session.atom, (result) => observed.push(result._tag));
79+
80+
expect(yield* settle(registry, session.atom)).toMatchObject({ success: SESSION });
81+
registry.refresh(session.atom);
82+
expect(yield* settle(registry, session.atom)).toMatchObject({ success: SESSION });
83+
84+
expect(session.calls()).toBe(3);
85+
expect(observed).not.toContain("Failure");
86+
}).pipe(Effect.scoped),
87+
);
88+
89+
it.effect("reports a failed first load without retrying", () =>
90+
Effect.gen(function* () {
91+
const session = makeSessionAtom(async () => {
92+
throw new TypeError("Failed to fetch");
93+
});
94+
const registry = AtomRegistry.make();
95+
yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
96+
registry.mount(session.atom);
97+
98+
const result = yield* settle(registry, session.atom);
99+
expect(result._tag).toBe("Failure");
100+
expect(AsyncResult.isFailure(registry.get(session.atom))).toBe(true);
101+
expect(session.calls()).toBe(1);
102+
}).pipe(Effect.scoped),
103+
);
104+
});

‎packages/client-runtime/src/state/session.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
22
import * as Data from "effect/Data";
3+
import * as Duration from "effect/Duration";
34
import * as Effect from "effect/Effect";
45
import * as Option from "effect/Option";
6+
import * as Schedule from "effect/Schedule";
57
import * as Stream from "effect/Stream";
68
import * as SubscriptionRef from "effect/SubscriptionRef";
79
import { HttpClient } from "effect/http";
810
import { AsyncResult, Atom } from "effect/reactivity";
911

1012
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
13+
import { mapRemoteEnvironmentError } from "../connection/errors.ts";
1114
import * as EnvironmentRegistry from "../connection/registry.ts";
1215
import type { PreparedConnection } from "../connection/model.ts";
1316
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
1417
import { environmentEndpointUrl } from "../environment/endpoint.ts";
1518
import * as ManagedRelay from "../relay/managedRelay.ts";
19+
import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
1620
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
1721
import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
1822
import { followStreamInEnvironment } from "./environmentStreams.ts";
@@ -39,6 +43,20 @@ function initialConfigOption<E>(
3943
// Bounded so a wedged environment cannot pin the permissions check (and with it
4044
// the settings UI) in a loading state for long.
4145
const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
46+
const SESSION_STATE_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(
47+
Schedule.modifyDelay(({ duration }) =>
48+
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
49+
),
50+
);
51+
52+
function isTransientSessionError(
53+
error: SessionHttpClientUnavailable | RemoteEnvironmentRequestError,
54+
): boolean {
55+
return (
56+
error._tag !== "SessionHttpClientUnavailable" &&
57+
mapRemoteEnvironmentError(error)._tag === "ConnectionTransientError"
58+
);
59+
}
4260

4361
/**
4462
* Read the granted scopes of this client's session on one environment via its
@@ -138,7 +156,17 @@ function makeEnvironmentSessionAtoms<R, E>(
138156
if (prepared === null) {
139157
return Effect.never;
140158
}
141-
return Effect.gen(function* () {
159+
// Scope checks reject a Failure outright, so one slow response would
160+
// revoke a grant this connection already confirmed until the client
161+
// reloads. With a confirmed grant, keep it (the result stays waiting)
162+
// and retry transient failures; rejected credentials still fail.
163+
const hasConfirmedGrant = Option.isSome(
164+
Option.flatMap(
165+
get.self<AsyncResult.AsyncResult<AuthSessionState, unknown>>(),
166+
AsyncResult.value,
167+
),
168+
);
169+
const fetchSession = Effect.gen(function* () {
142170
const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
143171
const remoteAuthorization = yield* Effect.serviceOption(
144172
RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
@@ -151,6 +179,14 @@ function makeEnvironmentSessionAtoms<R, E>(
151179
remoteAuthorization,
152180
}).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
153181
});
182+
return hasConfirmedGrant
183+
? fetchSession.pipe(
184+
Effect.retry({
185+
while: isTransientSessionError,
186+
schedule: SESSION_STATE_RETRY_SCHEDULE,
187+
}),
188+
)
189+
: fetchSession;
154190
})
155191
.pipe(
156192
Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),

0 commit comments

Comments
 (0)