The best way to control Claude Code, Codex and more from any computer or phone
fix(client-runtime): searches and refreshes no longer wait on an unreachable environment (#25703)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 21:26 UTC
8e86eb2b4d631aee43db6846256f5df6aab090c2
11 files changed
+479
-30
apps/mobile/src/features/files/useFileTreeEntries.ts
+16
@@ -1,13 +1,18 @@
1
+import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
2
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
4
import * as Cause from "effect/Cause";
5
+import { Atom } from "effect/reactivity";
6
import { useEffect, useReducer, useRef, useState } from "react";
7
8
+import { environmentCatalog } from "../../connection/catalog";
9
import { appAtomRegistry } from "../../state/atom-registry";
10
import { projectEnvironment } from "../../state/projects";
11
import { useDebouncedValue } from "../../state/queries";
12
import { useEnvironmentQuery } from "../../state/query";
13
14
+const noSessionGeneration = Atom.make(0);
15
+
16
export function useFileTreeEntries(input: {
17
readonly cwd: string | null;
18
readonly environmentId: EnvironmentId | null;
@@ -94,6 +99,17 @@ export function useFileTreeEntries(input: {
99
render();
100
});
101
};
102
+ // A folder read fails at once while its environment is unreachable; read it again once a new
103
+ // session is up rather than leaving the error until someone refreshes.
104
+ const sessionGeneration =
105
+ environmentId === null
106
+ ? noSessionGeneration
107
+ : environmentCatalog.sessionGenerationAtom(environmentId);
108
+ // A listener alone does not compute the atom, so nothing would follow the connection.
109
+ useAtomMount(sessionGeneration);
110
+ useAtomSubscribe(sessionGeneration, () => {
111
+ for (const path of directories.errors.keys()) void loadDirectory(path);
112
+ });
113
const { refresh: refreshRoot, data: rootData } = root;
114
const { refresh: refreshSearch, data: searchData } = search;
115
const snapshot = (() => {
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+24
-1
@@ -1,4 +1,4 @@
1
-import { RegistryContext, useAtomValue } from "@effect/atom-react";
1
+import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
2
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
4
import * as Cause from "effect/Cause";
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
6
import * as Option from "effect/Option";
7
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
8
import { use, useCallback, useMemo, useState } from "react";
9
+import { environmentCatalog } from "../../connection/catalog";
10
import {
11
composerPullRequests,
12
pullRequestListPagesFamily,
@@ -142,6 +143,15 @@ const refreshLoadFamily = Atom.family((scopeKey: string) =>
143
),
144
);
145
146
+// Changes when any of the scope's environments brings up a new session.
147
+const sessionsFamily = Atom.family((scopeKey: string) =>
148
+ Atom.make((get) =>
149
+ (JSON.parse(scopeKey) as readonly ListTarget[])
150
+ .map(({ environmentId }) => get(environmentCatalog.sessionGenerationAtom(environmentId)))
151
+ .join(),
152
+ ),
153
+);
154
+
155
const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
156
AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
157
@@ -156,6 +166,19 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
166
// Starting one kind of load clears the other, so at most one holds an error.
167
const loadError = settledError(refresh) ?? settledError(page);
168
169
+ // A page or refresh asked for while an environment was unreachable fails at once, and its
170
+ // error stops loading on scroll. Once it is back, ask for the page again; a refresh's error is
171
+ // stale by then because the list queries re-run on reconnect.
172
+ // A listener alone does not compute the atom, so nothing would follow the connections.
173
+ useAtomMount(sessionsFamily(scopeKey));
174
+ useAtomSubscribe(sessionsFamily(scopeKey), () => {
175
+ const pageResult = registry.get(pageAtom);
176
+ const refreshResult = registry.get(refreshAtom);
177
+ if (settledError(refreshResult) !== null) registry.set(refreshAtom, Atom.Reset);
178
+ else if (settledError(pageResult) !== null && !refreshResult.waiting)
179
+ registry.set(pageAtom, true);
180
+ });
181
+
182
// Read from the registry, not the render: a second onEndReached before React re-renders must
183
// see the load the first one started.
184
const loadMore = (retry = false) => {
apps/mobile/src/state/assets.test.ts
+5
@@ -19,6 +19,8 @@ const state = vi.hoisted(() => ({
19
20
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
21
vi.mock("@effect/atom-react", () => ({
22
+ useAtomMount: () => undefined,
23
+ useAtomSubscribe: () => undefined,
24
useAtomValue: (atom: unknown) =>
25
atom === state.assetAtom
26
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
@@ -39,6 +41,9 @@ vi.mock("./query", () => ({
41
}));
42
vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
43
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
44
+vi.mock("../connection/catalog", () => ({
45
+ environmentCatalog: { sessionGenerationAtom: () => null },
46
+}));
47
vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
48
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
49
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),
apps/mobile/src/state/assets.ts
+18
-5
@@ -1,4 +1,4 @@
1
-import { useAtomValue } from "@effect/atom-react";
1
+import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
2
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
3
import {
4
assetUrlStateFromResult,
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
13
import { Atom, AsyncResult } from "effect/reactivity";
14
import { useCallback } from "react";
15
16
+import { environmentCatalog } from "../connection/catalog";
17
import { connectionAtomRuntime } from "../connection/runtime";
18
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
19
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
@@ -112,7 +113,7 @@ export async function refreshAssetUrl(
113
reportFailure: false,
114
...(signal ? { signal } : {}),
115
});
115
- // The query can wait through a reconnect; resolve against the connection that answered it.
116
+ // A route can change while the query runs; resolve against the connection now current.
117
const connection = appAtomRegistry.get(connectionAtom);
118
if (connection._tag === "None") return null;
119
const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
@@ -154,6 +155,7 @@ const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
155
const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
156
Atom.withLabel("fresh-asset-url:none"),
157
);
158
+const noSessionGeneration = Atom.make(0);
159
160
/**
161
* A signed URL minted when the reader mounts, not a cached one: cached links can
@@ -166,9 +168,20 @@ export function useFreshAssetUrl(
168
): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
169
const connection = usePreparedConnection(environmentId);
170
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
169
- return useAtomValue(
171
+ const atom =
172
resource === null
173
? noFreshAssetUrl
172
- : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
173
- );
174
+ : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision });
175
+ // Minting fails at once while the environment is unreachable; mint again once a new session is
176
+ // up instead of keeping the error until Retry.
177
+ const sessionGeneration =
178
+ environmentId === null
179
+ ? noSessionGeneration
180
+ : environmentCatalog.sessionGenerationAtom(environmentId);
181
+ // A listener alone does not compute the atom, so nothing would follow the connection.
182
+ useAtomMount(sessionGeneration);
183
+ useAtomSubscribe(sessionGeneration, () => {
184
+ if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
185
+ });
186
+ return useAtomValue(atom);
187
}
apps/web/src/components/chat/useComposerContextImport.ts
+17
-1
@@ -1,3 +1,10 @@
1
+import {
2
+ ConnectionBlockedError,
3
+ ConnectionTransientError,
4
+} from "@t3tools/client-runtime/connection";
5
+import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
6
+import * as Cause from "effect/Cause";
7
+import * as Schema from "effect/Schema";
8
import type { RefObject } from "react";
9
import type { ChatComposerProps } from "./ChatComposer";
10
import {
@@ -49,6 +56,10 @@ import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
56
import { useStableCallback } from "../../hooks/useStableCallback";
57
import { countPreparingComposerImages } from "./preparingComposerImages";
58
59
+const isUnreachable = Schema.is(
60
+ Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]),
61
+);
62
+
63
async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
64
try {
65
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
@@ -162,7 +173,12 @@ export function useComposerContextImport(input: {
173
? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
174
: null;
175
if (!url) {
165
- fail("The original attachment is no longer available.");
176
+ const cause = result._tag === "Failure" ? Cause.squash(result.cause) : null;
177
+ fail(
178
+ isUnreachable(cause)
179
+ ? "The environment it came from is not reachable right now."
180
+ : "The original attachment is no longer available.",
181
+ );
182
return;
183
}
184
const blob = await downloadAttachmentBlob(url);
apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
new
+66
@@ -0,0 +1,66 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import * as Cause from "effect/Cause";
4
+import { AsyncResult, Atom } from "effect/reactivity";
5
+import { describe, expect, it, vi } from "vite-plus/test";
6
+
7
+import { appAtomRegistry } from "~/rpc/atomRegistry";
8
+import { act, render } from "../../../test/render";
9
+import { useDirectoryEntries } from "./useDirectoryEntries";
10
+
11
+const mocks = vi.hoisted(() => ({
12
+ reachable: null as unknown as Atom.Writable<boolean>,
13
+ connectedSession: null as unknown as Atom.Writable<number>,
14
+}));
15
+
16
+vi.mock("~/connection/catalog", () => ({
17
+ // Derived like the real one, which only follows the connection once something computes it.
18
+ environmentCatalog: {
19
+ sessionGenerationAtom: () => Atom.make((get) => get(mocks.connectedSession)),
20
+ },
21
+}));
22
+vi.mock("~/state/projects", () => ({
23
+ projectEnvironment: {
24
+ listEntries: () =>
25
+ Atom.make((get) =>
26
+ get(mocks.reachable)
27
+ ? AsyncResult.success({
28
+ entries: [{ path: "README.md", kind: "file" }],
29
+ truncated: false,
30
+ })
31
+ : AsyncResult.failure(Cause.fail(new Error("Environment is reconnecting."))),
32
+ ),
33
+ },
34
+}));
35
+
36
+function setup() {
37
+ mocks.reachable = Atom.make(false);
38
+ mocks.connectedSession = Atom.make(1);
39
+}
40
+
41
+function Probe() {
42
+ const directory = useDirectoryEntries(EnvironmentId.make("env-files"), "/repo");
43
+ return (
44
+ <output>{directory.error ?? directory.entries.map((entry) => entry.path).join(",")}</output>
45
+ );
46
+}
47
+
48
+describe("useDirectoryEntries", () => {
49
+ it("reads a folder that failed while unreachable again once a new session is up", async () => {
50
+ setup();
51
+ await using screen = await render(
52
+ <RegistryContext.Provider value={appAtomRegistry}>
53
+ <Probe />
54
+ </RegistryContext.Provider>,
55
+ // A bare hook probe; nothing here navigates.
56
+ { router: false },
57
+ );
58
+ await expect.element(screen.getByText("Environment is reconnecting.")).toBeInTheDocument();
59
+
60
+ await act(() => {
61
+ appAtomRegistry.set(mocks.reachable, true);
62
+ appAtomRegistry.set(mocks.connectedSession, 2);
63
+ });
64
+ await expect.element(screen.getByText("README.md")).toBeInTheDocument();
65
+ });
66
+});
apps/web/src/components/files/useDirectoryEntries.ts
+11
@@ -1,8 +1,10 @@
1
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
2
+import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
3
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
4
import * as Cause from "effect/Cause";
5
import { useEffect, useRef, useState } from "react";
6
7
+import { environmentCatalog } from "~/connection/catalog";
8
import { appAtomRegistry } from "~/rpc/atomRegistry";
9
import { projectEnvironment } from "~/state/projects";
10
@@ -100,6 +102,15 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
102
};
103
}, [startRequest]);
104
105
+ // A folder read fails at once while its environment is unreachable; read it again once a new
106
+ // session is up rather than leaving the error until someone retries by hand.
107
+ const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
108
+ // A listener alone does not compute the atom, so nothing would follow the connection.
109
+ useAtomMount(sessionGeneration);
110
+ useAtomSubscribe(sessionGeneration, () => {
111
+ for (const path of errors.keys()) void load(path);
112
+ });
113
+
114
const entries: ProjectEntry[] = [];
115
const visit = (path: string) => {
116
for (const entry of directories.get(path) ?? []) {
packages/client-runtime/src/state/connections.test.ts
new
+122
@@ -0,0 +1,122 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import { EnvironmentId } 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 { Atom, AtomRegistry } from "effect/reactivity";
9
+
10
+import {
11
+ AVAILABLE_CONNECTION_STATE,
12
+ ConnectionTransientError,
13
+ type SupervisorConnectionState,
14
+} from "../connection/model.ts";
15
+import * as EnvironmentRegistry from "../connection/registry.ts";
16
+import * as EnvironmentSupervisor from "../connection/supervisor.ts";
17
+import type * as RpcSession from "../rpc/session.ts";
18
+import { createEnvironmentCatalogAtoms } from "./connections.ts";
19
+
20
+const ENVIRONMENT_ID = EnvironmentId.make("catalog-environment");
21
+
22
+const connectionState = (
23
+ overrides: Partial<SupervisorConnectionState>,
24
+): SupervisorConnectionState => ({
25
+ ...AVAILABLE_CONNECTION_STATE,
26
+ desired: true,
27
+ network: "online",
28
+ ...overrides,
29
+});
30
+
31
+const makeCatalogHarness = Effect.fn("TestCatalog.makeHarness")(function* () {
32
+ const state = yield* SubscriptionRef.make(
33
+ connectionState({ phase: "connected", attempt: 1, generation: 1 }),
34
+ );
35
+ const session = yield* SubscriptionRef.make(Option.some({} as RpcSession.RpcSession));
36
+ const supervisor = {
37
+ state,
38
+ session,
39
+ } as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
40
+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
41
+ _environmentId,
42
+ stream,
43
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
44
+ const registry = EnvironmentRegistry.EnvironmentRegistry.of({
45
+ followStream,
46
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
47
+ const catalog = createEnvironmentCatalogAtoms(
48
+ Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)),
49
+ );
50
+ const atom = catalog.sessionGenerationAtom(ENVIRONMENT_ID);
51
+ const atoms = AtomRegistry.make();
52
+ const unmount = atoms.mount(atom);
53
+ yield* Effect.addFinalizer(() =>
54
+ Effect.sync(() => {
55
+ unmount();
56
+ atoms.dispose();
57
+ }),
58
+ );
59
+ yield* Effect.yieldNow;
60
+ /** Moves the supervisor to `next`, with a new session object when one is established. */
61
+ const generationAfter = (
62
+ next: SupervisorConnectionState,
63
+ nextSession: Option.Option<RpcSession.RpcSession> = Option.none(),
64
+ ) =>
65
+ SubscriptionRef.set(session, nextSession).pipe(
66
+ Effect.andThen(SubscriptionRef.set(state, next)),
67
+ Effect.andThen(Effect.yieldNow),
68
+ Effect.map(() => atoms.get(atom)),
69
+ );
70
+ return { generation: () => atoms.get(atom), generationAfter };
71
+});
72
+
73
+const lastFailure = new ConnectionTransientError({ reason: "transport", detail: "Down." });
74
+const newSession = () => Option.some({} as RpcSession.RpcSession);
75
+
76
+describe("environment catalog atoms", () => {
77
+ it.effect("changes the session generation only when a new session comes up", () =>
78
+ Effect.scoped(
79
+ Effect.gen(function* () {
80
+ const { generation, generationAfter } = yield* makeCatalogHarness();
81
+ const first = generation();
82
+ // A retry reports the generation it is attempting before it is established.
83
+ expect(
84
+ yield* generationAfter(
85
+ connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
86
+ ),
87
+ ).toBe(first);
88
+ expect(
89
+ yield* generationAfter(
90
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
91
+ ),
92
+ ).toBe(first);
93
+ expect(
94
+ yield* generationAfter(
95
+ connectionState({ phase: "connected", attempt: 2, generation: 2 }),
96
+ newSession(),
97
+ ),
98
+ ).not.toBe(first);
99
+ }),
100
+ ),
101
+ );
102
+
103
+ it.effect("changes when a replaced supervisor's first session reuses an old generation", () =>
104
+ Effect.scoped(
105
+ Effect.gen(function* () {
106
+ const { generation, generationAfter } = yield* makeCatalogHarness();
107
+ const first = generation();
108
+ yield* generationAfter(
109
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
110
+ );
111
+ // Re-pairing or editing a route installs a new supervisor, whose counter starts over.
112
+ yield* generationAfter(connectionState({ phase: "available", generation: 0 }));
113
+ expect(
114
+ yield* generationAfter(
115
+ connectionState({ phase: "connected", attempt: 1, generation: 1 }),
116
+ newSession(),
117
+ ),
118
+ ).not.toBe(first);
119
+ }),
120
+ ),
121
+ );
122
+});
packages/client-runtime/src/state/connections.ts
+5
@@ -17,6 +17,7 @@ import {
17
import {
18
createAtomCommandScheduler,
19
createRuntimeCommand,
20
+ environmentSessionGenerationAtom,
21
followStreamInEnvironment,
22
} from "./runtime.ts";
23
@@ -120,6 +121,9 @@ export function createEnvironmentCatalogAtoms<R, E>(
121
),
122
);
123
124
+ const sessionGenerationAtom = (environmentId: EnvironmentIdType) =>
125
+ environmentSessionGenerationAtom(runtime, environmentId);
126
+
127
const register = createRuntimeCommand(runtime, {
128
label: "environment-catalog:register",
129
scheduler: commandScheduler,
@@ -197,6 +201,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
201
networkStatusAtom,
202
networkStatusValueAtom,
203
stateAtom,
204
+ sessionGenerationAtom,
205
register,
206
remove,
207
removeRoute,
packages/client-runtime/src/state/runtime.test.ts
+95
-5
@@ -42,6 +42,7 @@ import {
42
selectEnvironmentQueryData,
43
createEnvironmentSubscriptionAtomFamily,
44
createRuntimeCommand,
45
+ environmentSessionGenerationAtom,
46
scheduleAtomCommandEffect,
47
executeAtomQuery,
48
type QueryAnswerHandler,
@@ -476,7 +477,7 @@ describe("environment query lifecycle", () => {
477
);
478
479
it.effect(
479
- "retries an interrupted query without exposing a failure during session replacement",
480
+ "hides a session replacement, reports the relay backoff, and recovers on reconnect",
481
() =>
482
Effect.scoped(
483
Effect.gen(function* () {
@@ -534,25 +535,33 @@ describe("environment query lifecycle", () => {
535
queryConnectionState({ phase: "connecting", stage: "preparing" }),
536
);
537
yield* Effect.yieldNow;
538
+ const relayFailure = new ConnectionTransientError({
539
+ reason: "transport",
540
+ detail: "Relay session is reconnecting.",
541
+ });
542
yield* SubscriptionRef.set(
543
harness.supervisorState,
544
queryConnectionState({
545
phase: "backoff",
546
stage: null,
542
- lastFailure: new ConnectionTransientError({
543
- reason: "transport",
544
- detail: "Relay session is reconnecting.",
545
- }),
547
+ lastFailure: relayFailure,
548
retryAt: 1,
549
}),
550
);
551
yield* Effect.yieldNow;
552
+ // The query has never answered, so it reports why the environment is retrying.
553
+ const backingOff = registry.get(harness.atom);
554
+ expect(backingOff.waiting).toBe(false);
555
+ expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
556
+ relayFailure,
557
+ );
558
559
yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
560
yield* SubscriptionRef.set(
561
harness.supervisorState,
562
queryConnectionState({ generation: 2 }),
563
);
564
+ yield* Effect.yieldNow;
565
expect(
566
yield* AtomRegistry.getResult(registry, harness.atom, {
567
suspendOnWaiting: true,
@@ -707,6 +716,87 @@ describe("environment query lifecycle", () => {
716
),
717
);
718
719
+ it.effect.each([
720
+ { phase: "backoff", stage: null, retryAt: 1 },
721
+ { phase: "connecting", stage: "opening", retryAt: null },
722
+ ] as const)(
723
+ "settles a query it never answered while its environment retries ($phase)",
724
+ (retrying) =>
725
+ Effect.scoped(
726
+ Effect.gen(function* () {
727
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
728
+ initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
729
+ });
730
+ const registry = yield* mountEnvironmentQuery(harness.atom);
731
+ yield* Effect.yieldNow;
732
+
733
+ const result = registry.get(harness.atom);
734
+ expect(result.waiting).toBe(false);
735
+ expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
736
+ OFFLINE_QUERY_FAILURE,
737
+ );
738
+
739
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
740
+ yield* Effect.yieldNow;
741
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
742
+ }),
743
+ ),
744
+ );
745
+
746
+ it.effect("a refresh started on a new session generation answers from that session", () =>
747
+ Effect.scoped(
748
+ Effect.gen(function* () {
749
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
750
+ initialState: queryConnectionState({
751
+ phase: "backoff",
752
+ stage: null,
753
+ lastFailure: OFFLINE_QUERY_FAILURE,
754
+ retryAt: 1,
755
+ }),
756
+ });
757
+ const registry = yield* mountEnvironmentQuery(harness.atom);
758
+ // Callers hold the failure a read got while the environment was retrying.
759
+ const failed = yield* Effect.promise(() =>
760
+ executeAtomQuery(registry, harness.atom, { reportFailure: false }),
761
+ );
762
+ expect(AsyncResult.isFailure(failed)).toBe(true);
763
+
764
+ const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
765
+ const sessionGeneration = environmentSessionGenerationAtom(
766
+ harness.runtime,
767
+ QUERY_ENVIRONMENT.environmentId,
768
+ );
769
+ const unmount = registry.mount(sessionGeneration);
770
+ const unsubscribe = registry.subscribe(sessionGeneration, () => {
771
+ void executeAtomQuery(registry, harness.atom, {
772
+ refresh: true,
773
+ reportFailure: false,
774
+ }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
775
+ });
776
+ yield* Effect.addFinalizer(() =>
777
+ Effect.sync(() => {
778
+ unsubscribe();
779
+ unmount();
780
+ }),
781
+ );
782
+ yield* Effect.yieldNow;
783
+
784
+ yield* SubscriptionRef.set(
785
+ harness.supervisorSession,
786
+ Option.some({} as RpcSession.RpcSession),
787
+ );
788
+ yield* SubscriptionRef.set(
789
+ harness.supervisorState,
790
+ queryConnectionState({ generation: 2 }),
791
+ );
792
+ expect(yield* Deferred.await(answered)).toMatchObject({
793
+ _tag: "Success",
794
+ value: "connected",
795
+ });
796
+ }),
797
+ ),
798
+ );
799
+
800
it.effect("keeps a genuine query failure settled while reconnecting", () =>
801
Effect.scoped(
802
Effect.gen(function* () {
packages/client-runtime/src/state/runtime.ts
+100
-18
@@ -17,7 +17,7 @@ import * as Stream from "effect/Stream";
17
import * as SubscriptionRef from "effect/SubscriptionRef";
18
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
19
20
-import type { ConnectionAttemptError } from "../connection/model.ts";
20
+import type { ConnectionAttemptError, SupervisorConnectionState } from "../connection/model.ts";
21
import * as EnvironmentRegistry from "../connection/registry.ts";
22
import {
23
type EnvironmentRpcInput,
@@ -560,22 +560,28 @@ const refreshEveryUntilFinal =
560
export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
561
Option.getOrNull(AsyncResult.value(result));
562
563
-export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
563
+type EnvironmentConnection = readonly [
564
+ SupervisorConnectionState,
565
+ Option.Option<RpcSession.RpcSession>,
566
+];
567
+
568
+const connectionAtomsByRuntime = new WeakMap<
569
+ object,
570
+ (
571
+ environmentId: EnvironmentIdType,
572
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
573
+>();
574
+
575
+/**
576
+ * One connection atom per environment for every query on a runtime, so a reader of the session
577
+ * generation and a query it re-runs see the same connection change at once.
578
+ */
579
+function environmentConnectionAtoms<R, ER>(
580
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
565
- options: EnvironmentQueryAtomOptions<
566
- Input,
567
- A,
568
- E,
569
- | EnvironmentSupervisor.EnvironmentSupervisor
570
- | EnvironmentRegistry.EnvironmentRegistry
571
- | AtomRegistry.AtomRegistry
572
- | R
573
- >,
574
-): (target: {
575
- readonly environmentId: EnvironmentIdType;
576
- readonly input: Input;
577
-}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
578
- const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
581
+) {
582
+ const existing = connectionAtomsByRuntime.get(runtime);
583
+ if (existing !== undefined) return existing;
584
+ const family = Atom.family((environmentId: EnvironmentIdType) =>
585
runtime.atom(
586
followStreamInEnvironment(
587
environmentId,
@@ -591,7 +597,72 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
597
),
598
{ initialValue: null },
599
),
594
- );
600
+ ) as (
601
+ environmentId: EnvironmentIdType,
602
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
603
+ connectionAtomsByRuntime.set(runtime, family);
604
+ return family;
605
+}
606
+
607
+const sessionGenerationAtomsByRuntime = new WeakMap<
608
+ object,
609
+ (environmentId: EnvironmentIdType) => Atom.Atom<number>
610
+>();
611
+
612
+/**
613
+ * Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
614
+ * can watch it to run again. Keyed on the session object because the supervisor's `generation`
615
+ * restarts when the registry installs a new supervisor (re-pairing, route edits).
616
+ */
617
+export function environmentSessionGenerationAtom<R, ER>(
618
+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
619
+ environmentId: EnvironmentIdType,
620
+): Atom.Atom<number> {
621
+ let family = sessionGenerationAtomsByRuntime.get(runtime);
622
+ if (family === undefined) {
623
+ const connectionAtom = environmentConnectionAtoms(runtime);
624
+ const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
625
+ Atom.make(
626
+ (get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
627
+ const previous = Option.getOrElse(
628
+ get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
629
+ () => ({ session: null, count: 0 }),
630
+ );
631
+ const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
632
+ if (connection === null || connection[0].phase !== "connected") return previous;
633
+ const session = Option.getOrNull(connection[1]);
634
+ return session === null || session === previous.session
635
+ ? previous
636
+ : { session, count: previous.count + 1 };
637
+ },
638
+ ),
639
+ );
640
+ family = Atom.family((id: EnvironmentIdType) =>
641
+ Atom.make((get) => get(sessionsSeen(id)).count).pipe(
642
+ Atom.withLabel(`environment-session-generation:${id}`),
643
+ ),
644
+ );
645
+ sessionGenerationAtomsByRuntime.set(runtime, family);
646
+ }
647
+ return family(environmentId);
648
+}
649
+
650
+export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
651
+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
652
+ options: EnvironmentQueryAtomOptions<
653
+ Input,
654
+ A,
655
+ E,
656
+ | EnvironmentSupervisor.EnvironmentSupervisor
657
+ | EnvironmentRegistry.EnvironmentRegistry
658
+ | AtomRegistry.AtomRegistry
659
+ | R
660
+ >,
661
+): (target: {
662
+ readonly environmentId: EnvironmentIdType;
663
+ readonly input: Input;
664
+}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
665
+ const connectionAtom = environmentConnectionAtoms(runtime);
666
const family = Atom.family((key: string) => {
667
const target = parseEnvironmentRpcKey<Input>(key);
668
const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
@@ -647,7 +718,18 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
718
: Effect.never;
719
case "connecting":
720
case "backoff":
650
- return Effect.never;
721
+ // A retry can take minutes. A query with an answer keeps showing it while it
722
+ // waits; one with nothing to show reports the failure the retry is recovering
723
+ // from, so its reader stops loading, and re-runs when the connection settles.
724
+ return connectionState.lastFailure !== null &&
725
+ Option.isNone(
726
+ Option.flatMap(
727
+ get.self<AsyncResult.AsyncResult<A, unknown>>(),
728
+ AsyncResult.value,
729
+ ),
730
+ )
731
+ ? Effect.fail(connectionState.lastFailure)
732
+ : Effect.never;
733
case "available":
734
case "offline":
735
case "blocked":