Skip to content

Commit c82cea6

Browse files
fix(clients): one-shot reads retry once an unreachable environment reconnects
Reads that fail at once while an environment is retrying now run again when it brings up a new session, instead of keeping the error until a manual retry. - client-runtime: the catalog exposes each environment's session generation, which changes only when a new session is established. - web and mobile file trees re-read folders that failed. - mobile pull request list retries a failed next page. - mobile fresh asset URLs re-mint after a failure; the stale comment in refreshAssetUrl is corrected. - web composer import says the source environment is unreachable rather than that the attachment is gone. - the runtime session-replacement test is renamed and asserts the backoff failure it now reports. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c989141 commit c82cea6

10 files changed

Lines changed: 256 additions & 11 deletions

File tree

‎apps/mobile/src/features/files/useFileTreeEntries.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1+
import { useAtomSubscribe } from "@effect/atom-react";
12
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
23
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
34
import * as Cause from "effect/Cause";
5+
import { Atom } from "effect/reactivity";
46
import { useEffect, useReducer, useRef, useState } from "react";
57

8+
import { environmentCatalog } from "../../connection/catalog";
69
import { appAtomRegistry } from "../../state/atom-registry";
710
import { projectEnvironment } from "../../state/projects";
811
import { useDebouncedValue } from "../../state/queries";
912
import { useEnvironmentQuery } from "../../state/query";
1013

14+
const noSessionGeneration = Atom.make(0);
15+
1116
export function useFileTreeEntries(input: {
1217
readonly cwd: string | null;
1318
readonly environmentId: EnvironmentId | null;
@@ -94,6 +99,16 @@ export function useFileTreeEntries(input: {
9499
render();
95100
});
96101
};
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+
useAtomSubscribe(
105+
environmentId === null
106+
? noSessionGeneration
107+
: environmentCatalog.sessionGenerationAtom(environmentId),
108+
() => {
109+
for (const path of directories.errors.keys()) void loadDirectory(path);
110+
},
111+
);
97112
const { refresh: refreshRoot, data: rootData } = root;
98113
const { refresh: refreshSearch, data: searchData } = search;
99114
const snapshot = (() => {

‎apps/mobile/src/features/pull-requests/usePullRequestList.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { RegistryContext, useAtomValue } from "@effect/atom-react";
1+
import { RegistryContext, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
44
import * as Cause from "effect/Cause";
55
import * as Effect from "effect/Effect";
66
import * as Option from "effect/Option";
77
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
88
import { use, useCallback, useMemo, useState } from "react";
9+
import { environmentCatalog } from "../../connection/catalog";
910
import {
1011
composerPullRequests,
1112
pullRequestListPagesFamily,
@@ -142,6 +143,15 @@ const refreshLoadFamily = Atom.family((scopeKey: string) =>
142143
),
143144
);
144145

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+
145155
const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
146156
AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
147157

@@ -156,6 +166,12 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
156166
// Starting one kind of load clears the other, so at most one holds an error.
157167
const loadError = settledError(refresh) ?? settledError(page);
158168

169+
// A page asked for while an environment was unreachable fails at once; ask again once it is
170+
// back, since the error stops loading on scroll.
171+
useAtomSubscribe(sessionsFamily(scopeKey), () => {
172+
if (settledError(page) !== null && !refresh.waiting) registry.set(pageAtom, true);
173+
});
174+
159175
const loadMore = (retry = false) => {
160176
if (page.waiting || refresh.waiting || (!retry && loadError)) return;
161177
if (!continuations(registry, targets).length) return;

‎apps/mobile/src/state/assets.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const state = vi.hoisted(() => ({
1919

2020
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
2121
vi.mock("@effect/atom-react", () => ({
22+
useAtomSubscribe: () => undefined,
2223
useAtomValue: (atom: unknown) =>
2324
atom === state.assetAtom
2425
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
@@ -39,6 +40,9 @@ vi.mock("./query", () => ({
3940
}));
4041
vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
4142
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
43+
vi.mock("../connection/catalog", () => ({
44+
environmentCatalog: { sessionGenerationAtom: () => null },
45+
}));
4246
vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
4347
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
4448
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),

‎apps/mobile/src/state/assets.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useAtomValue } from "@effect/atom-react";
1+
import { useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
33
import {
44
assetUrlStateFromResult,
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
1313
import { Atom, AsyncResult } from "effect/reactivity";
1414
import { useCallback } from "react";
1515

16+
import { environmentCatalog } from "../connection/catalog";
1617
import { connectionAtomRuntime } from "../connection/runtime";
1718
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
1819
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
@@ -112,7 +113,7 @@ export async function refreshAssetUrl(
112113
reportFailure: false,
113114
...(signal ? { signal } : {}),
114115
});
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.
116117
const connection = appAtomRegistry.get(connectionAtom);
117118
if (connection._tag === "None") return null;
118119
const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
@@ -154,6 +155,7 @@ const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
154155
const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
155156
Atom.withLabel("fresh-asset-url:none"),
156157
);
158+
const noSessionGeneration = Atom.make(0);
157159

158160
/**
159161
* A signed URL minted when the reader mounts, not a cached one: cached links can
@@ -166,9 +168,19 @@ export function useFreshAssetUrl(
166168
): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
167169
const connection = usePreparedConnection(environmentId);
168170
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
169-
return useAtomValue(
171+
const atom =
170172
resource === null
171173
? noFreshAssetUrl
172-
: freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
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+
useAtomSubscribe(
178+
environmentId === null
179+
? noSessionGeneration
180+
: environmentCatalog.sessionGenerationAtom(environmentId),
181+
() => {
182+
if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
183+
},
173184
);
185+
return useAtomValue(atom);
174186
}

‎apps/web/src/components/chat/useComposerContextImport.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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";
18
import type { RefObject } from "react";
29
import type { ChatComposerProps } from "./ChatComposer";
310
import {
@@ -49,6 +56,10 @@ import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
4956
import { useStableCallback } from "../../hooks/useStableCallback";
5057
import { countPreparingComposerImages } from "./preparingComposerImages";
5158

59+
const isUnreachable = Schema.is(
60+
Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]),
61+
);
62+
5263
async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
5364
try {
5465
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
@@ -162,7 +173,12 @@ export function useComposerContextImport(input: {
162173
? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
163174
: null;
164175
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+
);
166182
return;
167183
}
168184
const blob = await downloadAttachmentBlob(url);
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
sessionGeneration: null as unknown as Atom.Writable<number>,
14+
}));
15+
16+
vi.mock("~/connection/catalog", () => ({
17+
environmentCatalog: { sessionGenerationAtom: () => mocks.sessionGeneration },
18+
}));
19+
vi.mock("~/state/projects", () => ({
20+
projectEnvironment: {
21+
listEntries: () =>
22+
Atom.make((get) =>
23+
get(mocks.reachable)
24+
? AsyncResult.success({
25+
entries: [{ path: "README.md", kind: "file" }],
26+
truncated: false,
27+
})
28+
: AsyncResult.failure(Cause.fail(new Error("Environment is reconnecting."))),
29+
),
30+
},
31+
}));
32+
33+
function setup() {
34+
mocks.reachable = Atom.make(false);
35+
mocks.sessionGeneration = Atom.make(1);
36+
}
37+
38+
function Probe() {
39+
const directory = useDirectoryEntries(EnvironmentId.make("env-files"), "/repo");
40+
return (
41+
<output>{directory.error ?? directory.entries.map((entry) => entry.path).join(",")}</output>
42+
);
43+
}
44+
45+
describe("useDirectoryEntries", () => {
46+
it("reads a folder that failed while unreachable again once a new session is up", async () => {
47+
setup();
48+
await using screen = await render(
49+
<RegistryContext.Provider value={appAtomRegistry}>
50+
<Probe />
51+
</RegistryContext.Provider>,
52+
// A bare hook probe; nothing here navigates.
53+
{ router: false },
54+
);
55+
await expect.element(screen.getByText("Environment is reconnecting.")).toBeInTheDocument();
56+
57+
await act(() => {
58+
appAtomRegistry.set(mocks.reachable, true);
59+
appAtomRegistry.set(mocks.sessionGeneration, 2);
60+
});
61+
await expect.element(screen.getByText("README.md")).toBeInTheDocument();
62+
});
63+
});

‎apps/web/src/components/files/useDirectoryEntries.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
2+
import { useAtomSubscribe } from "@effect/atom-react";
23
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
34
import * as Cause from "effect/Cause";
45
import { useEffect, useRef, useState } from "react";
56

7+
import { environmentCatalog } from "~/connection/catalog";
68
import { appAtomRegistry } from "~/rpc/atomRegistry";
79
import { projectEnvironment } from "~/state/projects";
810

@@ -100,6 +102,12 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
100102
};
101103
}, [startRequest]);
102104

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+
useAtomSubscribe(environmentCatalog.sessionGenerationAtom(environmentId), () => {
108+
for (const path of errors.keys()) void load(path);
109+
});
110+
103111
const entries: ProjectEntry[] = [];
104112
const visit = (path: string) => {
105113
for (const entry of directories.get(path) ?? []) {
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
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 Stream from "effect/Stream";
6+
import * as SubscriptionRef from "effect/SubscriptionRef";
7+
import { Atom, AtomRegistry } from "effect/reactivity";
8+
9+
import {
10+
AVAILABLE_CONNECTION_STATE,
11+
ConnectionTransientError,
12+
type SupervisorConnectionState,
13+
} from "../connection/model.ts";
14+
import * as EnvironmentRegistry from "../connection/registry.ts";
15+
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
16+
import { createEnvironmentCatalogAtoms } from "./connections.ts";
17+
18+
const ENVIRONMENT_ID = EnvironmentId.make("catalog-environment");
19+
20+
const connectionState = (
21+
overrides: Partial<SupervisorConnectionState>,
22+
): SupervisorConnectionState => ({
23+
...AVAILABLE_CONNECTION_STATE,
24+
desired: true,
25+
network: "online",
26+
...overrides,
27+
});
28+
29+
describe("environment catalog atoms", () => {
30+
it.effect("changes the session generation only when a new session comes up", () =>
31+
Effect.scoped(
32+
Effect.gen(function* () {
33+
const state = yield* SubscriptionRef.make(
34+
connectionState({ phase: "connected", attempt: 1, generation: 1 }),
35+
);
36+
const supervisor = {
37+
state,
38+
} as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
39+
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
40+
_environmentId,
41+
stream,
42+
) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
43+
const registry = EnvironmentRegistry.EnvironmentRegistry.of({
44+
followStream,
45+
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
46+
const catalog = createEnvironmentCatalogAtoms(
47+
Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)),
48+
);
49+
const atom = catalog.sessionGenerationAtom(ENVIRONMENT_ID);
50+
const atoms = AtomRegistry.make();
51+
const unmount = atoms.mount(atom);
52+
yield* Effect.addFinalizer(() =>
53+
Effect.sync(() => {
54+
unmount();
55+
atoms.dispose();
56+
}),
57+
);
58+
const lastFailure = new ConnectionTransientError({ reason: "transport", detail: "Down." });
59+
const generationAfter = (next: SupervisorConnectionState) =>
60+
SubscriptionRef.set(state, next).pipe(
61+
Effect.andThen(Effect.yieldNow),
62+
Effect.map(() => atoms.get(atom)),
63+
);
64+
65+
yield* Effect.yieldNow;
66+
expect(atoms.get(atom)).toBe(1);
67+
// A retry reports the generation it is attempting before it is established.
68+
expect(
69+
yield* generationAfter(
70+
connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
71+
),
72+
).toBe(1);
73+
expect(
74+
yield* generationAfter(
75+
connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
76+
),
77+
).toBe(1);
78+
expect(
79+
yield* generationAfter(
80+
connectionState({ phase: "connected", attempt: 2, generation: 2 }),
81+
),
82+
).toBe(2);
83+
}),
84+
),
85+
);
86+
});

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,23 @@ export function createEnvironmentCatalogAtoms<R, E>(
120120
),
121121
);
122122

123+
/**
124+
* The generation of the environment's latest established session, kept while it reconnects.
125+
* It changes only when a new session comes up, so a one-shot read that failed while the
126+
* environment was unreachable can key on it, or watch it, to run again once it is back.
127+
*/
128+
const sessionGenerationAtom = Atom.family((environmentId: EnvironmentIdType) =>
129+
Atom.make((get): number => {
130+
const state = Option.getOrElse(
131+
AsyncResult.value(get(stateAtom(environmentId))),
132+
() => AVAILABLE_CONNECTION_STATE,
133+
);
134+
return state.phase === "connected"
135+
? state.generation
136+
: Option.getOrElse(get.self<number>(), () => 0);
137+
}).pipe(Atom.withLabel(`environment-session-generation:${environmentId}`)),
138+
);
139+
123140
const register = createRuntimeCommand(runtime, {
124141
label: "environment-catalog:register",
125142
scheduler: commandScheduler,
@@ -197,6 +214,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
197214
networkStatusAtom,
198215
networkStatusValueAtom,
199216
stateAtom,
217+
sessionGenerationAtom,
200218
register,
201219
remove,
202220
removeRoute,

0 commit comments

Comments
 (0)