@devries-cameron20 / t3code Mirror · read-only / commits / f4e140764f
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, 17:00 UTC

fix(web): pull request checks stay current after a checks refresh (#25008)

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

Julius Marminge committed Oct 25, 2026 at 18:01 UTC f4e140764fba579ccb77a3dabe2dd0bcee98d037
9 files changed +320 -97
apps/web/src/components/RightPanelTabs.tsx
+1 -1
@@ -735,7 +735,7 @@ function PullRequestSurfaceIcon({
735 repository: surface.repository,
736 number: surface.number,
737 };
738 - const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference, null);
738 + const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference);
739 const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;
740 if (status === null) {
741 return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;
apps/web/src/components/ThreadStatusIndicators.tsx
+3 -7
@@ -95,17 +95,13 @@ export function useLinkedThreadPullRequest(
95 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
96 // Preserve reference identity so sidebar renders do not touch the summary cache.
97 const reference = fallback == null ? null : linkedPullRequestReference(fallback);
98 - const queried = useEnvironmentQuery(
98 + // Mounted for its answers, which land in the shared summary read below.
99 + useEnvironmentQuery(
100 !enabled || environmentId === null || reference === null
101 ? null
102 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
103 );
103 - const detail = useSharedPullRequestSummary(
104 - environmentId,
105 - reference,
106 - queried.data,
107 - queried.dataUpdatedAt,
108 - );
104 + const detail = useSharedPullRequestSummary(environmentId, reference);
105
106 if (current !== null) return currentStatus;
107 return detail === null
apps/web/src/components/pullRequest/PullRequestsPage.tsx
-1
@@ -205,7 +205,6 @@ export function PullRequestsPage() {
205 ...renderedPullRequestSurface,
206 projectId: renderedPullRequestSurface.projectId as ProjectId,
207 },
208 - null,
208 );
209 const updateSearch = (patch: {
210 [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
apps/web/src/components/pullRequest/usePullRequestDetail.ts
+3 -28
@@ -2,11 +2,10 @@ import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-req
2 import {
3 AuthSourceControlWriteScope,
4 type EnvironmentId,
5 - type PullRequestDetail,
5 type PullRequestListEntry,
6 type PullRequestRef,
7 } from "@t3tools/contracts";
9 -import { useEffect, useEffectEvent, useState } from "react";
8 +import { useState } from "react";
9
10 import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
11 import { useServerConfigs } from "~/state/entities";
@@ -21,18 +20,12 @@ import {
20 import {
21 readPullRequestDetailSnapshot,
22 resolveDisplayedPullRequestDetail,
24 - writePullRequestDetailSnapshot,
23 } from "./pullRequestDetail.logic";
26 -import { pullRequestChecksState } from "./pullRequestPresentation";
24
25 export function pullRequestRefKey(reference: PullRequestRef) {
26 return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
27 }
28
32 -function pullRequestDetailSummary(data: PullRequestDetail | null) {
33 - return data === null ? null : { ...data, checksState: pullRequestChecksState(data.checks) };
34 -}
35 -
29 /**
30 * Loads a pull request's detail and activity and merges them, with the snapshot cache, the shared
31 * summary and the list row, into the detail the panel shows.
@@ -95,24 +88,7 @@ export function usePullRequestDetail(
88 } else if (detailQuery.data !== null && detailQuery.data !== cachedDetail) {
89 setCachedDetail(detailQuery.data);
90 }
98 - const saveDetailSnapshot = useEffectEvent((data: PullRequestDetail) => {
99 - writePullRequestDetailSnapshot(
100 - typeof window === "undefined" ? undefined : window.localStorage,
101 - environmentId,
102 - reference,
103 - data,
104 - );
105 - });
106 - useEffect(() => {
107 - if (detailQuery.data !== null) saveDetailSnapshot(detailQuery.data);
108 - }, [detailQuery.data]);
109 - const detailSummary = pullRequestDetailSummary(liveDetail);
110 - const observedSummary = useSharedPullRequestSummary(
111 - environmentId,
112 - reference,
113 - detailSummary,
114 - Math.max(detailQuery.dataUpdatedAt, checksQuery.dataUpdatedAt),
115 - );
91 + const observedSummary = useSharedPullRequestSummary(environmentId, reference);
92 const activity = activityQuery.data;
93 const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
94 live: liveDetail,
@@ -122,8 +98,7 @@ export function usePullRequestDetail(
98 // Every hook runs above this line: a hook between the merge and the panel's plain readers of
99 // `detail` would cost it its cache scope.
100 const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
125 - // The list row is also published to the shared cache, but only after this commit's layout
126 - // effects run, so it is compared directly rather than trusted to be there already.
101 + // The row can come from the page's stored snapshot, which no answer has published yet.
102 const sharedSummary = newestPullRequestSummary(
103 resolvedCoreDetail,
104 newestPullRequestSummary(observedSummary, listSummary),
apps/web/src/state/pullRequests.test.ts
+73
@@ -4,6 +4,9 @@ import { describe, expect, it } from "vite-plus/test";
4
5 import {
6 newestPullRequestObservation,
7 + observedPullRequestSummary,
8 + observePullRequestChecks,
9 + observePullRequestMetadata,
10 newestPullRequestSummary,
11 threadPullRequestLinkToSummary,
12 } from "./pullRequests";
@@ -114,3 +117,73 @@ describe("pull request summary cache", () => {
117 ).toBeNull();
118 });
119 });
120 +
121 +describe("pull request observations", () => {
122 + const fromSummary = (value: PullRequestSummary, observedAt: number) =>
123 + observePullRequestMetadata({ metadata: null, checks: null }, observed(value, observedAt));
124 + const checksRead = (
125 + checksState: "passing" | "failing" | "pending" | null,
126 + readAt: number | undefined,
127 + observedAt: number,
128 + ) => ({ checksState, readAt, observedAt });
129 +
130 + it("keeps a newer list's mergeability when a checks read lands after it", () => {
131 + const detail = summary({
132 + mergeability: "conflicting",
133 + checksState: "pending",
134 + observedAt: 100,
135 + });
136 + let state = fromSummary(detail, 1);
137 + state = observePullRequestMetadata(
138 + state,
139 + observed(summary({ mergeability: "mergeable", checksState: "pending", observedAt: 200 }), 2),
140 + );
141 + state = observePullRequestChecks(state, checksRead("passing", 300, 3));
142 + expect(observedPullRequestSummary(state)).toMatchObject({
143 + mergeability: "mergeable",
144 + checksState: "passing",
145 + });
146 + });
147 +
148 + it("keeps a newer checks read when an older list read lands after it", () => {
149 + let state = fromSummary(
150 + summary({ mergeability: "conflicting", checksState: "pending", observedAt: 100 }),
151 + 1,
152 + );
153 + state = observePullRequestChecks(state, checksRead("passing", 300, 2));
154 + state = observePullRequestMetadata(
155 + state,
156 + observed(summary({ mergeability: "mergeable", checksState: "pending", observedAt: 250 }), 3),
157 + );
158 + expect(observedPullRequestSummary(state)).toMatchObject({
159 + mergeability: "mergeable",
160 + checksState: "passing",
161 + });
162 + });
163 +
164 + it("lets a newer read's checks replace an older checks read", () => {
165 + let state = fromSummary(summary({ checksState: "pending", observedAt: 100 }), 1);
166 + state = observePullRequestChecks(state, checksRead("passing", 300, 2));
167 + state = observePullRequestMetadata(
168 + state,
169 + observed(summary({ checksState: "failing", observedAt: 400 }), 3),
170 + );
171 + expect(observedPullRequestSummary(state)?.checksState).toBe("failing");
172 + });
173 +
174 + it("orders checks by arrival when the server reports no read time", () => {
175 + let state = fromSummary(summary({ checksState: "pending" }), 1);
176 + state = observePullRequestChecks(state, checksRead("passing", undefined, 2));
177 + expect(observedPullRequestSummary(state)?.checksState).toBe("passing");
178 + state = observePullRequestChecks(state, checksRead("failing", undefined, 1));
179 + expect(observedPullRequestSummary(state)?.checksState).toBe("passing");
180 + });
181 +
182 + it("shows nothing until some read has described the pull request", () => {
183 + const state = observePullRequestChecks(
184 + { metadata: null, checks: null },
185 + checksRead("failing", 1, 1),
186 + );
187 + expect(observedPullRequestSummary(state)).toBeNull();
188 + });
189 +});
apps/web/src/state/pullRequests.ts
+148 -57
@@ -8,6 +8,7 @@ import {
8 import type {
9 EnvironmentId,
10 ProjectId,
11 + PullRequestChecksState,
12 PullRequestListInput,
13 PullRequestFilterOptionsInput,
14 PullRequestListStatsInput,
@@ -20,9 +21,10 @@ import {
21 threadPullRequestKeyOf,
22 visibleThreadPullRequests,
23 } from "@t3tools/client-runtime/thread-pull-requests";
24 +import * as Clock from "effect/Clock";
25 +import * as Effect from "effect/Effect";
26 import * as Option from "effect/Option";
24 -import { AsyncResult, Atom } from "effect/reactivity";
25 -import { useLayoutEffect } from "react";
27 +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
28
29 import { connectionAtomRuntime } from "../connection/runtime";
30 import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -31,28 +33,17 @@ import {
33 type EnvironmentPullRequestStat,
34 type MergedPullRequestList,
35 } from "../components/pullRequest/pullRequestList.logic";
36 +import { writePullRequestDetailSnapshot } from "../components/pullRequest/pullRequestDetail.logic";
37 +import { pullRequestChecksState } from "../components/pullRequest/pullRequestPresentation";
38 import { formatEnvironmentQueryError } from "./query";
39 import { environmentThreadShells } from "./threads";
40
37 -export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
38 -export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
39 - connectionAtomRuntime,
40 - pullRequestEnvironment.refreshes,
41 -);
42 -
41 export interface ObservedPullRequestSummary {
42 readonly summary: PullRequestSummary;
43 /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */
44 readonly observedAt: number;
45 }
46
49 -const observedPullRequestSummaryAtom = Atom.family((key: string) =>
50 - Atom.make<ObservedPullRequestSummary | null>(null).pipe(
51 - Atom.setIdleTTL(5 * 60_000),
52 - Atom.withLabel(`web-pull-requests:observed-summary:${key}`),
53 - ),
54 -);
55 -
47 function compareSummaries(current: PullRequestSummary, incoming: PullRequestSummary): number {
48 const merged = Number(incoming.state === "merged") - Number(current.state === "merged");
49 if (merged !== 0) return merged;
@@ -136,18 +127,151 @@ export function newestPullRequestObservation(
127 };
128 }
129
130 +export interface ObservedPullRequestChecks {
131 + readonly checksState: PullRequestChecksState | null;
132 + /** Server read time, when the server reports one. */
133 + readonly readAt: number | undefined;
134 + /** Client arrival time. */
135 + readonly observedAt: number;
136 +}
137 +
138 +/**
139 + * Checks are reread far more often than the rest of a pull request, so they keep their own
140 + * freshness: a checks read must not carry old metadata forward, and a list read must not take
141 + * back newer checks.
142 + */
143 +export interface PullRequestObservations {
144 + readonly metadata: ObservedPullRequestSummary | null;
145 + readonly checks: ObservedPullRequestChecks | null;
146 +}
147 +
148 +const noObservations: PullRequestObservations = { metadata: null, checks: null };
149 +
150 +const pullRequestObservationsAtom = Atom.family((key: string) =>
151 + Atom.make<PullRequestObservations>(noObservations).pipe(
152 + Atom.setIdleTTL(5 * 60_000),
153 + Atom.withLabel(`web-pull-requests:observations:${key}`),
154 + ),
155 +);
156 +
157 +export function observePullRequestChecks(
158 + current: PullRequestObservations,
159 + incoming: ObservedPullRequestChecks,
160 +): PullRequestObservations {
161 + const previous = current.checks;
162 + const newer =
163 + previous === null ||
164 + (previous.readAt !== undefined && incoming.readAt !== undefined
165 + ? incoming.readAt >= previous.readAt
166 + : incoming.observedAt >= previous.observedAt);
167 + return newer ? { ...current, checks: incoming } : current;
168 +}
169 +
170 +export function observePullRequestMetadata(
171 + current: PullRequestObservations,
172 + incoming: ObservedPullRequestSummary,
173 +): PullRequestObservations {
174 + const metadata = newestPullRequestObservation(current.metadata, incoming);
175 + const next = metadata === current.metadata ? current : { ...current, metadata };
176 + const { checksState } = incoming.summary;
177 + return checksState === undefined
178 + ? next
179 + : observePullRequestChecks(next, {
180 + checksState,
181 + readAt: incoming.summary.observedAt,
182 + observedAt: incoming.observedAt,
183 + });
184 +}
185 +
186 +export function observedPullRequestSummary(
187 + observations: PullRequestObservations,
188 +): PullRequestSummary | null {
189 + const { metadata, checks } = observations;
190 + if (metadata === null) return null;
191 + return checks === null
192 + ? metadata.summary
193 + : { ...metadata.summary, checksState: checks.checksState };
194 +}
195 +
196 +function recordObservation(
197 + registry: AtomRegistry.AtomRegistry,
198 + key: string,
199 + observe: (current: PullRequestObservations) => PullRequestObservations,
200 +): void {
201 + registry.modify(pullRequestObservationsAtom(key), (previous) => {
202 + const next = observe(previous);
203 + return next === previous ? [false, previous] : [true, next];
204 + });
205 +}
206 +
207 function observePullRequestSummary(
208 + registry: AtomRegistry.AtomRegistry,
209 key: string,
210 summary: PullRequestSummary,
211 observedAt: number,
212 ): void {
144 - const atom = observedPullRequestSummaryAtom(key);
145 - appAtomRegistry.modify(atom, (previous) => {
146 - const next = newestPullRequestObservation(previous, { summary, observedAt });
147 - return next === previous ? [false, previous] : [true, next];
148 - });
213 + recordObservation(registry, key, (current) =>
214 + observePullRequestMetadata(current, { summary, observedAt }),
215 + );
216 }
217
218 +function snapshotStorage(): Storage | undefined {
219 + return typeof window === "undefined" ? undefined : window.localStorage;
220 +}
221 +
222 +// Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
223 +export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
224 + list: ({ environmentId }, answer, registry) =>
225 + Effect.map(Clock.currentTimeMillis, (observedAt) => {
226 + for (const entry of answer.entries) {
227 + observePullRequestSummary(
228 + registry,
229 + pullRequestSummaryKey(environmentId, entry),
230 + pullRequestListEntryToSummary(entry),
231 + observedAt,
232 + );
233 + }
234 + }),
235 + detail: ({ environmentId, input }, detail, registry) =>
236 + Effect.map(Clock.currentTimeMillis, (at) => {
237 + // Only fresh reads seed the cold-start snapshot; a stale one could replace a newer record.
238 + if (input.allowStale === false) {
239 + writePullRequestDetailSnapshot(snapshotStorage(), environmentId, input, detail);
240 + }
241 + observePullRequestSummary(
242 + registry,
243 + pullRequestSummaryKey(environmentId, input),
244 + { ...detail, checksState: pullRequestChecksState(detail.checks) },
245 + at,
246 + );
247 + }),
248 + checks: ({ environmentId, input }, checks, registry) =>
249 + Effect.map(Clock.currentTimeMillis, (observedAt) => {
250 + if (checks === null) return;
251 + recordObservation(registry, pullRequestSummaryKey(environmentId, input), (current) =>
252 + observePullRequestChecks(current, {
253 + checksState: pullRequestChecksState(checks.checks),
254 + readAt: checks.observedAt,
255 + observedAt,
256 + }),
257 + );
258 + }),
259 +});
260 +
261 +export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
262 + connectionAtomRuntime,
263 + pullRequestEnvironment.refreshes,
264 + ({ environmentId, input }, summary, registry) =>
265 + Effect.map(Clock.currentTimeMillis, (observedAt) =>
266 + observePullRequestSummary(
267 + registry,
268 + pullRequestSummaryKey(environmentId, input),
269 + summary,
270 + observedAt,
271 + ),
272 + ),
273 +);
274 +
275 export function threadPullRequestLinkToSummary(
276 link: ThreadPullRequestLink,
277 projectId: ProjectId,
@@ -196,18 +320,16 @@ const savedPullRequestSummaryAtom = Atom.family((key: string) =>
320 ),
321 );
322
323 +/** The newest of every list, detail, checks and linked-summary answer and the thread's saved link. */
324 export function useSharedPullRequestSummary(
325 environmentId: EnvironmentId | null,
326 reference: PullRequestRef | null,
202 - current: PullRequestSummary | null,
203 - observedAt: number | null = null,
327 ): PullRequestSummary | null {
328 const key =
329 environmentId === null || reference === null
330 ? "none"
331 : pullRequestSummaryKey(environmentId, reference);
209 - const atom = observedPullRequestSummaryAtom(key);
210 - const observed = useAtomValue(atom);
332 + const observations = useAtomValue(pullRequestObservationsAtom(key));
333 const saved = useAtomValue(
334 savedPullRequestSummaryAtom(
335 environmentId === null || reference === null
@@ -215,16 +337,7 @@ export function useSharedPullRequestSummary(
337 : savedPullRequestKey(environmentId, reference),
338 ),
339 );
218 - useLayoutEffect(() => {
219 - if (key === "none" || current === null || observedAt === null) return;
220 - observePullRequestSummary(key, current, observedAt);
221 - }, [current, key, observedAt]);
222 - const summary =
223 - newestPullRequestObservation(
224 - observed,
225 - current === null || observedAt === null ? null : { summary: current, observedAt },
226 - )?.summary ?? current;
227 - return newestPullRequestSummary(summary, saved);
340 + return newestPullRequestSummary(observedPullRequestSummary(observations), saved);
341 }
342 export const pullRequestStackAtom = createPullRequestStackAtomFamily(
343 connectionAtomRuntime,
@@ -240,7 +353,6 @@ interface MergedEnvironmentQueryView<A> {
353 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
354 readonly error: string | null;
355 readonly isPending: boolean;
243 - readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;
356 }
357
358 // Use one derived atom for variable fan-out; unreachable environments must not hide other rows.
@@ -254,7 +366,6 @@ function createMergedEnvironmentQuery<Input, A>(
366 Atom.make((get): MergedEnvironmentQueryView<A> => {
367 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
368 const values: Array<readonly [EnvironmentId, A]> = [];
257 - const observations: Array<readonly [EnvironmentId, A, number]> = [];
369 let error: string | null = null;
370 let isPending = false;
371 for (const target of targets) {
@@ -265,16 +376,12 @@ function createMergedEnvironmentQuery<Input, A>(
376 }
377 const value = Option.getOrNull(AsyncResult.value(result));
378 if (value !== null) values.push([target.environmentId, value]);
268 - if (result._tag === "Success") {
269 - observations.push([target.environmentId, result.value, result.timestamp]);
270 - }
379 }
272 - return { values, error, isPending, observations };
380 + return { values, error, isPending };
381 }).pipe(Atom.withLabel(`${label}:${key}`)),
382 );
383 const empty = Atom.make<MergedEnvironmentQueryView<A>>({
384 values: [],
277 - observations: [],
385 error: null,
386 isPending: false,
387 }).pipe(Atom.withLabel(`${label}:empty`));
@@ -337,22 +444,6 @@ export function usePullRequestList(
444 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
445 ): MergedPullRequestListView {
446 const query = usePullRequestListsQuery(targets);
340 - useLayoutEffect(() => {
341 - for (const [environmentId, answer, observedAt] of query.observations) {
342 - for (const entry of answer.entries) {
343 - observePullRequestSummary(
344 - pullRequestSummaryKey(environmentId, {
345 - projectId: entry.projectId,
346 - host: entry.host,
347 - repository: entry.repository,
348 - number: entry.number,
349 - }),
350 - pullRequestListEntryToSummary(entry),
351 - observedAt,
352 - );
353 - }
354 - }
355 - }, [query.observations]);
447 const data = mergePullRequestLists(query.values);
448 return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
449 }
packages/client-runtime/src/state/pullRequests.ts
+15
@@ -13,6 +13,7 @@ import {
13 type EnvironmentId,
14 type PullRequestActor,
15 type PullRequestActionInput,
16 + type PullRequestListInput,
17 type PullRequestDetail,
18 type PullRequestDiffInput,
19 type PullRequestRef,
@@ -36,6 +37,7 @@ import {
37 createEnvironmentRpcQueryAtomFamily,
38 createEnvironmentRpcSubscriptionAtomFamily,
39 createEnvironmentQueryAtomFamily,
40 + type QueryAnswerHandler,
41 } from "./runtime.ts";
42 import { createPullRequestRouter } from "./pullRequestRouting.ts";
43 import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
@@ -123,6 +125,7 @@ function createPullRequestRefreshAtomFamily<R, E>(
125 export function createLinkedPullRequestSummaryAtomFamily<R, E>(
126 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
127 refreshes = createPullRequestRefreshAtomFamily(runtime),
128 + onAnswer?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>,
129 ) {
130 const routedRequest = createPullRequestRouter();
131 return createEnvironmentRpcQueryAtomFamily(runtime, {
@@ -134,9 +137,17 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
137 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
138 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
139 isFinal: (summary) => summary.state === "merged",
140 + ...(onAnswer === undefined ? {} : { onAnswer }),
141 });
142 }
143
144 +/** Lets a client record what each answer says where it lands, rather than watching the data. */
145 +export interface PullRequestAnswerHandlers {
146 + readonly list?: QueryAnswerHandler<PullRequestListInput, PullRequestListResult>;
147 + readonly detail?: QueryAnswerHandler<PullRequestRef, PullRequestDetail>;
148 + readonly checks?: QueryAnswerHandler<PullRequestRef, PullRequestChecks | null>;
149 +}
150 +
151 export function createPullRequestStackAtomFamily<R, E>(
152 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
153 refreshes = createPullRequestRefreshAtomFamily(runtime),
@@ -172,6 +183,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
183 EnvironmentRegistry | PullRequestDiffLoader.PullRequestDiffLoader | R,
184 E
185 >,
186 + onAnswer: PullRequestAnswerHandlers = {},
187 ) {
188 const refreshes = createPullRequestRefreshAtomFamily(runtime);
189 const commandScheduler = createAtomCommandScheduler();
@@ -198,6 +210,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
210 execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
211 staleTimeMs: 60_000,
212 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
213 + ...(onAnswer.detail === undefined ? {} : { onAnswer: onAnswer.detail }),
214 }),
215 );
216 const preview = writableQueryFamily(
@@ -329,6 +342,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
342 staleTimeMs: 30_000,
343 refreshTrigger: ({ environmentId, input }) =>
344 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
345 + ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
346 }),
347 /**
348 * Its own query because the listing is quicker without them — measured over twelve
@@ -358,6 +372,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
372 execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
373 staleTimeMs: 45_000,
374 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
375 + ...(onAnswer.checks === undefined ? {} : { onAnswer: onAnswer.checks }),
376 }),
377 ),
378 activity,
packages/client-runtime/src/state/runtime.test.ts
+53
@@ -44,6 +44,7 @@ import {
44 createRuntimeCommand,
45 scheduleAtomCommandEffect,
46 executeAtomQuery,
47 + type QueryAnswerHandler,
48 } from "./runtime.ts";
49
50 const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({
@@ -92,8 +93,10 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
93 initialState,
94 rpcSession,
95 isFinal,
96 + onAnswer,
97 }: {
98 readonly refreshTrigger?: Atom.Atom<unknown>;
99 + readonly onAnswer?: QueryAnswerHandler<undefined, A>;
100 readonly isFinal?: (value: A) => boolean;
101 readonly idleTtlMs?: number;
102 readonly persistence?: QueryPersistence<A>;
@@ -142,6 +145,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
145 ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),
146 ...(idleTtlMs === undefined ? {} : { idleTtlMs }),
147 ...(isFinal === undefined ? {} : { isFinal }),
148 + ...(onAnswer === undefined ? {} : { onAnswer }),
149 });
150
151 return {
@@ -1152,6 +1156,55 @@ describe("persisted environment queries", () => {
1156 ),
1157 );
1158
1159 + it.effect("hands each server answer to onAnswer before readers see it", () =>
1160 + Effect.scoped(
1161 + Effect.gen(function* () {
1162 + const answers: Array<readonly [string, string | null]> = [];
1163 + let served = 0;
1164 + const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1165 + const harness = yield* makeEnvironmentQueryHarness(
1166 + Effect.sync(() => `answer-${++served}`),
1167 + {
1168 + onAnswer: (_target, value, registry) =>
1169 + Effect.sync(() => {
1170 + answers.push([value, registry.get(recorded)]);
1171 + registry.set(recorded, value);
1172 + }),
1173 + },
1174 + );
1175 + const registry = yield* mountEnvironmentQuery(harness.atom);
1176 + expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1177 + expect(registry.get(recorded)).toBe("answer-1");
1178 + registry.refresh(harness.atom);
1179 + expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1180 + expect(answers).toEqual([
1181 + ["answer-1", null],
1182 + ["answer-2", "answer-1"],
1183 + ]);
1184 + }),
1185 + ),
1186 + );
1187 +
1188 + it.effect("does not hand a value restored from persistence to onAnswer", () =>
1189 + Effect.scoped(
1190 + Effect.gen(function* () {
1191 + const answers: Array<string> = [];
1192 + const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1193 + persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1194 + initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1195 + onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1196 + });
1197 + const registry = yield* mountEnvironmentQuery(harness.atom);
1198 + expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1199 + expect(answers).toEqual([]);
1200 + yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1201 + yield* Effect.yieldNow;
1202 + expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1203 + expect(answers).toEqual(["server"]);
1204 + }),
1205 + ),
1206 + );
1207 +
1208 it.effect("keeps cached content available when revalidation fails", () =>
1209 Effect.scoped(
1210 Effect.gen(function* () {
packages/client-runtime/src/state/runtime.ts
+24 -3
@@ -101,8 +101,20 @@ interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
101 readonly input: Input;
102 }) => Atom.Atom<unknown> | undefined;
103 readonly isFinal?: (value: A) => boolean;
104 + /**
105 + * Runs where each server answer lands, before readers see it, so derived records (summaries,
106 + * snapshots, watches) come from the producer instead of from components watching the data.
107 + * Cached and emitted provisional values are not answers.
108 + */
109 + readonly onAnswer?: QueryAnswerHandler<Input, A>;
110 }
111
112 +export type QueryAnswerHandler<Input, A> = (
113 + target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
114 + value: A,
115 + registry: AtomRegistry.AtomRegistry,
116 +) => Effect.Effect<void>;
117 +
118 interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
119 readonly sensitiveInput?: boolean;
120 readonly label: string;
@@ -652,7 +664,15 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
664 );
665 }
666 };
655 - if (!options.persistence) return execute().pipe(Effect.map(share));
667 + const onAnswer = options.onAnswer;
668 + const answer = () =>
669 + onAnswer === undefined
670 + ? execute().pipe(Effect.map(share))
671 + : execute().pipe(
672 + Effect.map(share),
673 + Effect.tap((value) => onAnswer(target, value, get.registry)),
674 + );
675 + if (!options.persistence) return answer();
676 const persistence = options.persistence;
677 const cacheKey = JSON.stringify([options.label, target.input]);
678 const previous = Option.flatMap(
@@ -670,8 +690,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
690 return cached.value;
691 }
692 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
673 - return yield* execute().pipe(
674 - Effect.map(share),
693 + return yield* answer().pipe(
694 Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
695 );
696 });
@@ -776,6 +795,7 @@ export function createEnvironmentRpcQueryAtomFamily<
795 readonly input: EnvironmentRpcInput<TTag>;
796 }) => Atom.Atom<unknown> | undefined;
797 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
798 + readonly onAnswer?: QueryAnswerHandler<EnvironmentRpcInput<TTag>, EnvironmentRpcSuccess<TTag>>;
799 },
800 ) {
801 return createEnvironmentQueryAtomFamily(runtime, {
@@ -788,6 +808,7 @@ export function createEnvironmentRpcQueryAtomFamily<
808 : { refreshIntervalMs: options.refreshIntervalMs }),
809 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
810 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
811 + ...(options.onAnswer === undefined ? {} : { onAnswer: options.onAnswer }),
812 execute: (
813 input: EnvironmentRpcInput<TTag>,
814 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,