The best way to control Claude Code, Codex and more from any computer or phone
fix(client-runtime): reopened files show host edits instead of the first read (#29409)
Julius Marminge committed
Nov 12, 2026 at 19:32 UTC
1e96606cb26b381a08dab4981d13e832b3573b11
6 files changed
+166
-40
apps/web/src/state/revisionedQuery.test.ts
+18
-5
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
4
import { revisionedQuery } from "./revisionedQuery";
5
6
// A stand-in query that counts its fetches.
7
-function setup() {
7
+function setup(readQuery: (cache: Atom.Atom<number>) => Atom.Atom<number> = (cache) => cache) {
8
let fetches = 0;
9
// Node removal runs on the registry's scheduler; releasing flushes it so the
10
// next mount of the same revision builds a fresh node, as a React remount does.
@@ -15,10 +15,12 @@ function setup() {
15
return () => {};
16
},
17
});
18
- const query = Atom.make(() => {
19
- fetches += 1;
20
- return fetches;
21
- }).pipe(Atom.keepAlive);
18
+ const query = readQuery(
19
+ Atom.make(() => {
20
+ fetches += 1;
21
+ return fetches;
22
+ }).pipe(Atom.keepAlive),
23
+ );
24
const mount = async (revision: string | null | undefined) => {
25
const release = registry.mount(revisionedQuery(query, revision));
26
// A stale read refetches in a microtask, after the render that read it.
@@ -77,6 +79,17 @@ describe("revisionedQuery", () => {
79
expect(fetches()).toBe(2);
80
});
81
82
+ it("counts a query as cached while the atom it reads through keeps the value", async () => {
83
+ // Like an environment query: its own node goes with its last reader, the cache stays.
84
+ const { mount, fetches } = setup((cache) =>
85
+ Atom.transform(cache, (get) => get(cache), { initialValueTarget: cache }),
86
+ );
87
+
88
+ (await mount(undefined))();
89
+ (await mount("mutation-1"))();
90
+ expect(fetches()).toBe(2);
91
+ });
92
+
93
it("does not refetch a cached query on a first read before any workspace change", async () => {
94
const { mount, fetches } = setup();
95
apps/web/src/state/revisionedQuery.ts
+10
-4
@@ -6,8 +6,14 @@ import { Atom, type AtomRegistry } from "effect/reactivity";
6
const readRevisions = new WeakMap<AtomRegistry.AtomRegistry, WeakMap<object, string | null>>();
7
8
// The registry keys serializable atoms' nodes by their key, not the atom.
9
-const queryKey = (query: Atom.Atom<unknown>) =>
10
- Atom.isSerializable(query) ? query[Atom.SerializableTypeId].key : query;
9
+const hasNode = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<unknown>) =>
10
+ registry.getNodes().has(Atom.isSerializable(atom) ? atom[Atom.SerializableTypeId].key : atom);
11
+
12
+// A query's own node can go with its last reader while the atom it takes its value from
13
+// (an environment query's cache, on an idle TTL) still holds the value.
14
+const isCached = (registry: AtomRegistry.AtomRegistry, query: Atom.Atom<unknown>) =>
15
+ hasNode(registry, query) ||
16
+ (query.initialValueTarget !== undefined && hasNode(registry, query.initialValueTarget));
17
18
const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
19
Atom.family((revision: string | null) =>
@@ -25,14 +31,14 @@ const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
31
? revisions.get(query) !== revision
32
: // A reader without a revision may have cached it before the latest
33
// workspace change; a query nobody has read yet fetches fresh anyway.
28
- revision !== null && get.registry.getNodes().has(queryKey(query));
34
+ revision !== null && isCached(get.registry, query);
35
// Deferred: this builds while React renders, and a refresh would synchronously
36
// re-render the query's other readers, which React rejects.
37
if (stale) {
38
const registry = get.registry;
39
queueMicrotask(() => {
40
// No node, as after the registry is disposed: nothing cached to refetch.
35
- if (registry.getNodes().has(queryKey(query))) registry.refresh(query);
41
+ if (isCached(registry, query)) registry.refresh(query);
42
});
43
}
44
revisions.set(query, revision);
packages/client-runtime/src/state/assets.ts
+2
-2
@@ -28,7 +28,6 @@ import type { ProjectFaviconCache, ProjectFaviconTarget } from "../projectFavico
28
import { createEnvironmentQueryAtomFamily } from "./runtime.ts";
29
30
const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
31
-const ASSET_URL_STALE_TIME_MS = 5 * 60_000;
31
const ASSET_URL_IDLE_TTL_MS = 60 * 60_000;
32
export const ASSET_URL_MAX_IN_FLIGHT = 6;
33
@@ -291,7 +290,8 @@ export function createAssetEnvironmentAtoms<R, E>(
290
const createUrl = createEnvironmentQueryAtomFamily(runtime, {
291
label: "environment-data:assets:create-url",
292
execute,
294
- staleTimeMs: ASSET_URL_STALE_TIME_MS,
293
+ // Each mint signs a new URL, so a remounted reader reuses its URL until renewal is due.
294
+ staleTimeMs: ASSET_URL_REFRESH_INTERVAL_MS,
295
idleTtlMs: ASSET_URL_IDLE_TTL_MS,
296
refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
297
refreshTrigger: ({ input }) =>
packages/client-runtime/src/state/filesystem.ts
-1
@@ -154,7 +154,6 @@ export function createFilesystemEnvironmentAtoms<R, E>(
154
// lists it again. The short TTL only keeps the old listing on screen while it refreshes.
155
idleTtlMs: BROWSE_IDLE_TTL_MS,
156
staleTimeMs: 0,
157
- revalidateOnRemount: true,
157
}),
158
};
159
}
packages/client-runtime/src/state/runtime.test.ts
+85
@@ -1,4 +1,7 @@
1
import { describe, expect, it } from "@effect/vitest";
2
+import * as NodeV8 from "node:v8";
3
+import * as NodeVM from "node:vm";
4
+import { vi } from "vite-plus/test";
5
import {
6
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
7
EnvironmentId,
@@ -163,6 +166,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
166
167
return {
168
runtime,
169
+ family,
170
atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
171
supervisorSession,
172
supervisorState,
@@ -1132,6 +1136,87 @@ describe("environment query lifecycle", () => {
1136
),
1137
);
1138
1139
+ it.effect("refetches when mounted again after its stale time, while still cached", () =>
1140
+ Effect.scoped(
1141
+ Effect.gen(function* () {
1142
+ let now = 0;
1143
+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1144
+ let contents = "before edit";
1145
+ let fetches = 0;
1146
+ const harness = yield* makeEnvironmentQueryHarness(
1147
+ Effect.sync(() => {
1148
+ fetches += 1;
1149
+ return contents;
1150
+ }),
1151
+ );
1152
+ const registry = AtomRegistry.make();
1153
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1154
+ const read = readEnvironmentQuery(registry, harness.atom);
1155
+ const remount = Effect.gen(function* () {
1156
+ const unmount = registry.mount(harness.atom);
1157
+ yield* Effect.yieldNow;
1158
+ const value = yield* read;
1159
+ unmount();
1160
+ yield* Effect.yieldNow;
1161
+ return value;
1162
+ });
1163
+
1164
+ expect(yield* remount).toBe("before edit");
1165
+ contents = "after edit";
1166
+
1167
+ // Inside the harness's 60s stale time: the cached value stands.
1168
+ now = 30_000;
1169
+ expect(yield* remount).toBe("before edit");
1170
+ expect(fetches).toBe(1);
1171
+
1172
+ // Past the stale time, well inside the default 5 minute idle TTL.
1173
+ now = 61_000;
1174
+ expect(yield* remount).toBe("after edit");
1175
+ expect(fetches).toBe(2);
1176
+ }),
1177
+ ),
1178
+ );
1179
+
1180
+ it.effect("keeps its cache when collected while unmounted, inside its stale time", () =>
1181
+ Effect.scoped(
1182
+ Effect.gen(function* () {
1183
+ NodeV8.setFlagsFromString("--expose-gc");
1184
+ const gc = NodeVM.runInNewContext("gc") as () => void;
1185
+ using _now = vi.spyOn(Date, "now").mockReturnValue(0);
1186
+ let fetches = 0;
1187
+ const harness = yield* makeEnvironmentQueryHarness(
1188
+ Effect.sync(() => {
1189
+ fetches += 1;
1190
+ return fetches;
1191
+ }),
1192
+ );
1193
+ const registry = AtomRegistry.make();
1194
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1195
+ // `Atom.family` holds members weakly, so the test must hold none: another environment
1196
+ // than `harness.atom`'s, which the harness holds.
1197
+ const environmentId = EnvironmentId.make("unheld-environment");
1198
+ const query = () => harness.family({ environmentId, input: undefined });
1199
+ const first = new WeakRef(query());
1200
+ const remount = Effect.gen(function* () {
1201
+ const unmount = registry.mount(query());
1202
+ yield* Effect.yieldNow;
1203
+ const value = yield* readEnvironmentQuery(registry, query());
1204
+ unmount();
1205
+ return value;
1206
+ });
1207
+ // A WeakRef target survives until the current job ends, so collect after it.
1208
+ const collect = Effect.yieldNow.pipe(Effect.andThen(Effect.sync(gc)));
1209
+
1210
+ expect(yield* remount).toBe(1);
1211
+ yield* collect;
1212
+ expect(yield* remount).toBe(1);
1213
+ yield* collect;
1214
+ expect(first.deref()).toBe(query());
1215
+ expect(fetches).toBe(1);
1216
+ }),
1217
+ ),
1218
+ );
1219
+
1220
it.effect.each([true, false])("loads thread link metadata with server support %s", (supported) =>
1221
Effect.scoped(
1222
Effect.gen(function* () {
packages/client-runtime/src/state/runtime.ts
+51
-28
@@ -11,7 +11,6 @@ import {
11
import * as Cause from "effect/Cause";
12
import * as Effect from "effect/Effect";
13
import * as Exit from "effect/Exit";
14
-import { identity } from "effect/Function";
14
import * as Option from "effect/Option";
15
import * as Schema from "effect/Schema";
16
import * as Stream from "effect/Stream";
@@ -97,13 +96,6 @@ interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
96
readonly persistence?: QueryPersistence<A>;
97
readonly staleTimeMs?: number;
98
readonly idleTtlMs?: number;
100
- /**
101
- * Check staleness each time the query is mounted again. By default the idle
102
- * TTL keeps the stale-while-revalidate node warm, so a remount within it
103
- * reads the cached value without checking. The cached value still shows
104
- * while the query revalidates.
105
- */
106
- readonly revalidateOnRemount?: boolean;
99
readonly refreshIntervalMs?: number;
100
readonly refreshTrigger?: (target: {
101
readonly environmentId: EnvironmentIdType;
@@ -567,6 +559,45 @@ const refreshEveryUntilFinal =
559
{ initialValueTarget: self },
560
);
561
562
+const isStale = (result: AsyncResult.AsyncResult<unknown, unknown>, staleTimeMs: number) => {
563
+ if (result.waiting) return false;
564
+ const success =
565
+ result._tag === "Failure" ? Option.getOrUndefined(result.previousSuccess) : result;
566
+ if (success?._tag !== "Success") return result._tag === "Failure";
567
+ // @effect-diagnostics-next-line globalDate:off - `AsyncResult` timestamps come from `Date.now`.
568
+ return Date.now() - success.timestamp >= staleTimeMs;
569
+};
570
+
571
+/**
572
+ * Stale-while-revalidate on every mount. `Atom.swr` checks only when its node builds, which an idle
573
+ * TTL skips on a remount; this layer has no TTL (a transform drops it) while `self` keeps the cache.
574
+ * It reads `self` as a dependency, not a subscription, so `self` goes idle with its last reader.
575
+ */
576
+const revalidateOnMount =
577
+ (staleTimeMs: number) =>
578
+ <A, E>(
579
+ self: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
580
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
581
+ Atom.transform(
582
+ self,
583
+ (get) => {
584
+ const current = get(self);
585
+ if (Option.isNone(get.self()) && isStale(current, staleTimeMs)) {
586
+ let active = true;
587
+ get.addFinalizer(() => {
588
+ active = false;
589
+ });
590
+ // Deferred out of the build, which runs while React renders. A plain read drops this
591
+ // node before the task runs, so only a mount refetches.
592
+ get.registry.schedulerAsync.makeDispatcher().scheduleTask(() => {
593
+ if (active && isStale(get.once(self), staleTimeMs)) get.refresh(self);
594
+ }, 0);
595
+ }
596
+ return current;
597
+ },
598
+ { initialValueTarget: self },
599
+ );
600
+
601
/**
602
* A query result's data alone. A refetch always publishes a new result (a new
603
* timestamp, `waiting` on and off), while equal data keeps its identity, so a
@@ -685,15 +716,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
716
readonly input: Input;
717
}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
718
const connectionAtom = environmentConnectionAtoms(runtime);
719
+ // `Atom.family` holds members weakly and the mounted layer has no TTL, so each member lives
720
+ // as long as its cache: keyed weakly, this lets both go once the cache's TTL ends.
721
+ const membersByCache = new WeakMap<Atom.Atom<unknown>, Atom.Atom<unknown>>();
722
const family = Atom.family((key: string) => {
723
const target = parseEnvironmentRpcKey<Input>(key);
724
const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
691
- // `Atom.swr` checks staleness only when its node builds. To revalidate on
692
- // remount, the wrappers drop on unmount and the source alone keeps the
693
- // cached value warm.
694
- const keepWarm = Atom.setIdleTTL(idleTtlMs);
695
- const keepSourceWarm = options.revalidateOnRemount ? keepWarm : identity;
696
- const keepWrapperWarm = options.revalidateOnRemount ? identity : keepWarm;
725
const queryAtom = runtime
726
.atom<
727
A,
@@ -817,14 +845,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
845
);
846
});
847
})
820
- .pipe(
821
- keepSourceWarm,
822
- Atom.swr({
823
- staleTime: options.staleTimeMs ?? 30_000,
824
- revalidateOnMount: true,
825
- }),
826
- keepWrapperWarm,
827
- );
848
+ .pipe(Atom.setIdleTTL(idleTtlMs));
849
const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
850
options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
851
const intervalQuery =
@@ -832,11 +853,17 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
853
? queryAtom
854
: queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
855
const refreshTrigger = options.refreshTrigger?.(target);
835
- return (
856
+ const cache = (
857
refreshTrigger === undefined
858
? intervalQuery
859
: intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
839
- ).pipe(keepWrapperWarm, Atom.withLabel(`${options.label}:${key}`));
860
+ ).pipe(Atom.setIdleTTL(idleTtlMs));
861
+ const member = cache.pipe(
862
+ revalidateOnMount(options.staleTimeMs ?? 30_000),
863
+ Atom.withLabel(`${options.label}:${key}`),
864
+ );
865
+ membersByCache.set(cache, member);
866
+ return member;
867
});
868
return (target) => family(environmentRpcKey(target));
869
}
@@ -934,7 +961,6 @@ export function createEnvironmentRpcQueryAtomFamily<
961
readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
962
readonly staleTimeMs?: number;
963
readonly idleTtlMs?: number;
937
- readonly revalidateOnRemount?: boolean;
964
readonly refreshIntervalMs?: number;
965
readonly refreshTrigger?: (target: {
966
readonly environmentId: EnvironmentIdType;
@@ -949,9 +975,6 @@ export function createEnvironmentRpcQueryAtomFamily<
975
...(options.persistence === undefined ? {} : { persistence: options.persistence }),
976
...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
977
...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
952
- ...(options.revalidateOnRemount === undefined
953
- ? {}
954
- : { revalidateOnRemount: options.revalidateOnRemount }),
978
...(options.refreshIntervalMs === undefined
979
? {}
980
: { refreshIntervalMs: options.refreshIntervalMs }),