Skip to content

Commit 4f864cf

Browse files
perf(web): pull request rows skip checks polls that change nothing
The query result still publishes a new AsyncResult on every refetch (new timestamp, waiting on and off), so reading the whole result re-rendered the row on every poll. The row now subscribes to the data alone, to a derived "checks are newer" boolean, and to whether checks settled empty, and reads the pending flag only when its refresh fires. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c2b7caa commit 4f864cf

5 files changed

Lines changed: 174 additions & 55 deletions

File tree

‎apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx‎

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { EnvironmentId, type PullRequestCheck } from "@t3tools/contracts";
2+
import { AsyncResult } from "effect/reactivity";
23
import { act } from "react";
34
import { createRoot, type Root } from "react-dom/client";
45
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
@@ -13,34 +14,33 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({
1314
...(await importOriginal()),
1415
useServerConfigs: (() => new Map()) as never,
1516
}));
17+
const queryData = () => ({
18+
number: 1,
19+
title: "Test PR",
20+
state: "open",
21+
isDraft: false,
22+
mergeability: "mergeable",
23+
headBranch: "feature",
24+
baseBranch: "main",
25+
changedFiles: 1,
26+
additions: 1,
27+
deletions: 0,
28+
checks: [state.status, ...(state.extraStatus ? [state.extraStatus] : [])].map((status) => ({
29+
name: `CI-${status}`,
30+
status,
31+
description: null,
32+
url: null,
33+
})),
34+
capabilities: { actions: ["merge"], mergeMethods: ["merge"] },
35+
viewerPermissions: { actions: ["merge"] },
36+
mergeCapabilities: { merge: true, squash: false, rebase: false },
37+
});
1638
vi.mock(import("~/state/query"), async (importOriginal) => ({
1739
...(await importOriginal()),
18-
useEnvironmentQuery: (() => ({
19-
data: {
20-
number: 1,
21-
title: "Test PR",
22-
state: "open",
23-
isDraft: false,
24-
mergeability: "mergeable",
25-
headBranch: "feature",
26-
baseBranch: "main",
27-
changedFiles: 1,
28-
additions: 1,
29-
deletions: 0,
30-
checks: [state.status, ...(state.extraStatus ? [state.extraStatus] : [])].map((status) => ({
31-
name: `CI-${status}`,
32-
status,
33-
description: null,
34-
url: null,
35-
})),
36-
capabilities: { actions: ["merge"], mergeMethods: ["merge"] },
37-
viewerPermissions: { actions: ["merge"] },
38-
mergeCapabilities: { merge: true, squash: false, rebase: false },
39-
},
40-
dataUpdatedAt: 1,
41-
isPending: false,
42-
refresh: vi.fn(),
43-
})) as never,
40+
useEnvironmentQuerySelector: ((_atom: unknown, select: (result: unknown) => unknown) =>
41+
select(AsyncResult.success(queryData()))) as never,
42+
useEnvironmentQueryIsNewer: () => true,
43+
useEnvironmentQueryRefresh: () => ({ refresh: vi.fn(), isPending: () => false }),
4444
}));
4545
vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({
4646
...(await importOriginal()),

‎apps/web/src/components/chat/ThreadDetailsPrRow.tsx‎

Lines changed: 38 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ThreadDetailsControl } from "./ThreadDetailsControl";
22
import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
3+
import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
34
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
45
import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
56
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
@@ -11,14 +12,19 @@ import {
1112
GitBranchIcon,
1213
TriangleAlertIcon,
1314
} from "lucide-react";
15+
import { AsyncResult } from "effect/reactivity";
1416
import { useState, type MouseEvent as ReactMouseEvent } from "react";
1517

1618
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
1719
import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
1820
import { cn } from "~/lib/utils";
1921
import { useServerConfigs } from "~/state/entities";
2022
import { pullRequestEnvironment } from "~/state/pullRequests";
21-
import { useEnvironmentQuery } from "~/state/query";
23+
import {
24+
useEnvironmentQueryIsNewer,
25+
useEnvironmentQueryRefresh,
26+
useEnvironmentQuerySelector,
27+
} from "~/state/query";
2228

2329
import {
2430
buildFixFindingsHandoff,
@@ -64,6 +70,10 @@ import {
6470
THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
6571
} from "./threadDetailsPanelStyles";
6672

73+
// A server without checks for this pull request answers null; polling it again finds nothing new.
74+
const isSettledWithoutChecks = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
75+
result._tag === "Success" && result.value === null;
76+
6777
export function ThreadDetailsPrRow({
6878
environmentId,
6979
pr,
@@ -101,40 +111,46 @@ export function ThreadDetailsPrRow({
101111
? { projectId: project.id as ProjectId, repository, number }
102112
: null
103113
: null;
104-
const detailQuery = useEnvironmentQuery(
114+
const detailAtom =
105115
reference === null
106116
? null
107117
: pullRequestEnvironment.detail({
108118
environmentId,
109119
input: { ...reference, allowStale: false },
110-
}),
111-
);
120+
});
121+
// Read the queries part by part: every poll publishes a new result (a new
122+
// timestamp, `waiting` on and off) even when nothing in it changed.
123+
const detailData = useEnvironmentQuerySelector(detailAtom, selectEnvironmentQueryData);
124+
const detailQuery = useEnvironmentQueryRefresh(detailAtom);
112125
const supportsChecks =
113126
serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
114-
const checksQuery = useEnvironmentQuery(
115-
supportsChecks && reference !== null && detailQuery.data !== null
127+
const checksAtom =
128+
supportsChecks && reference !== null && detailData !== null
116129
? pullRequestEnvironment.checks({ environmentId, input: reference })
117-
: null,
118-
);
119-
// Every refetch moves the timestamps; comparing them first keeps `detail`
120-
// stable while the data itself is unchanged.
121-
const checksAreNewer = checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt;
130+
: null;
131+
const checksData = useEnvironmentQuerySelector(checksAtom, selectEnvironmentQueryData);
132+
const checksSettledEmpty = useEnvironmentQuerySelector(checksAtom, isSettledWithoutChecks);
133+
const checksQuery = useEnvironmentQueryRefresh(checksAtom);
134+
const checksAreNewer = useEnvironmentQueryIsNewer(checksAtom, detailAtom);
122135
const detail =
123-
detailQuery.data === null
136+
detailData === null
124137
? null
125-
: checksQuery.data !== null && checksAreNewer
126-
? { ...detailQuery.data, ...checksQuery.data }
127-
: detailQuery.data;
138+
: checksData !== null && checksAreNewer
139+
? { ...detailData, ...checksData }
140+
: detailData;
128141
const open = reference !== null && (detail?.state ?? pr?.state) === "open";
129142
const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
130-
useLiveRefresh(detailQuery.isPending ? null : detailQuery.refresh, {
131-
enabled: open,
132-
key: `workspace-pr:${refreshKey}`,
133-
intervalMs: 10 * 60_000,
134-
});
143+
useLiveRefresh(
144+
() => {
145+
if (!detailQuery.isPending()) detailQuery.refresh();
146+
},
147+
{ enabled: open, key: `workspace-pr:${refreshKey}`, intervalMs: 10 * 60_000 },
148+
);
135149
usePullRequestChecksRefresh({
136-
refresh: checksQuery.isPending || detailQuery.isPending ? null : checksQuery.refresh,
137-
enabled: open && supportsChecks && !(checksQuery.isSuccess && checksQuery.data === null),
150+
refresh: () => {
151+
if (!checksQuery.isPending() && !detailQuery.isPending()) checksQuery.refresh();
152+
},
153+
enabled: open && supportsChecks && !checksSettledEmpty,
138154
key: `workspace-pr-checks:${refreshKey}`,
139155
checks: detail?.checks ?? [],
140156
});

‎apps/web/src/state/query.ts‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
1+
import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
22
import * as Cause from "effect/Cause";
33
import * as Option from "effect/Option";
44
import { AsyncResult, Atom } from "effect/reactivity";
5+
import { useContext } from "react";
56

67
const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
78
Atom.withLabel("web-environment-query:empty"),
@@ -24,6 +25,14 @@ export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string
2425
: "The environment request failed.";
2526
}
2627

28+
function queryUpdatedAt(result: AsyncResult.AsyncResult<unknown, unknown>): number {
29+
return result._tag === "Success"
30+
? result.timestamp
31+
: result._tag === "Failure"
32+
? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
33+
: 0;
34+
}
35+
2736
export function useEnvironmentQuery<A, E>(
2837
atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
2938
): EnvironmentQueryView<A, E> {
@@ -32,12 +41,7 @@ export function useEnvironmentQuery<A, E>(
3241
const refresh = useAtomRefresh(selectedAtom);
3342
return {
3443
data: Option.getOrNull(AsyncResult.value(result)),
35-
dataUpdatedAt:
36-
result._tag === "Success"
37-
? result.timestamp
38-
: result._tag === "Failure"
39-
? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
40-
: 0,
44+
dataUpdatedAt: queryUpdatedAt(result),
4145
error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
4246
failure:
4347
result._tag === "Failure" ? Option.getOrNull(Cause.findErrorOption(result.cause)) : null,
@@ -46,3 +50,59 @@ export function useEnvironmentQuery<A, E>(
4650
refresh,
4751
};
4852
}
53+
54+
/**
55+
* Reads one part of a query's result. Every refetch publishes a new result (a
56+
* new timestamp, `waiting` on and off), and this re-renders only when the
57+
* selected part changes. `select` must be defined outside the component: a new
58+
* function per render would rebuild the derived atom every render.
59+
*/
60+
export function useEnvironmentQuerySelector<A, E, B>(
61+
atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
62+
select: (result: AsyncResult.AsyncResult<A, E>) => B,
63+
): B {
64+
return useAtomValue(atom ?? EMPTY_ASYNC_RESULT_ATOM, select);
65+
}
66+
67+
type QueryResultAtom = Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>;
68+
// Lives as long as both queries do, so a row keeps the same comparison atom across renders.
69+
const queryIsNewerAtoms = new WeakMap<
70+
QueryResultAtom,
71+
WeakMap<QueryResultAtom, Atom.Atom<boolean>>
72+
>();
73+
function queryIsNewerAtom(query: QueryResultAtom, than: QueryResultAtom): Atom.Atom<boolean> {
74+
let byThan = queryIsNewerAtoms.get(query);
75+
if (byThan === undefined) {
76+
byThan = new WeakMap();
77+
queryIsNewerAtoms.set(query, byThan);
78+
}
79+
let atom = byThan.get(than);
80+
if (atom === undefined) {
81+
atom = Atom.make((get) => queryUpdatedAt(get(query)) >= queryUpdatedAt(get(than)));
82+
byThan.set(than, atom);
83+
}
84+
return atom;
85+
}
86+
87+
/** Whether `query` last succeeded no earlier than `than`, without re-rendering on every refetch. */
88+
export function useEnvironmentQueryIsNewer(
89+
query: QueryResultAtom | null,
90+
than: QueryResultAtom | null,
91+
): boolean {
92+
return useAtomValue(
93+
queryIsNewerAtom(query ?? EMPTY_ASYNC_RESULT_ATOM, than ?? EMPTY_ASYNC_RESULT_ATOM),
94+
);
95+
}
96+
97+
/**
98+
* The query's refresh, plus its pending state read when called rather than
99+
* subscribed to, for callers that only gate a refresh on it.
100+
*/
101+
export function useEnvironmentQueryRefresh<A, E>(
102+
atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
103+
): { readonly refresh: () => void; readonly isPending: () => boolean } {
104+
const registry = useContext(RegistryContext);
105+
const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
106+
const refresh = useAtomRefresh(selectedAtom);
107+
return { refresh, isPending: () => atom !== null && registry.get(selectedAtom).waiting };
108+
}

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
environmentRpcKey,
3232
createAtomCommandScheduler,
3333
createEnvironmentQueryAtomFamily,
34+
selectEnvironmentQueryData,
3435
createEnvironmentSubscriptionAtomFamily,
3536
createRuntimeCommand,
3637
scheduleAtomCommandEffect,
@@ -395,6 +396,40 @@ describe("environment query lifecycle", () => {
395396
),
396397
);
397398

399+
it.effect("does not notify a data-only reader when a refetch returns equal content", () =>
400+
Effect.scoped(
401+
Effect.gen(function* () {
402+
let status = "passed";
403+
const execute = Effect.sync(() => ({ checks: [{ name: "ci", status }] }));
404+
const harness = yield* makeEnvironmentQueryHarness(execute);
405+
const registry = yield* mountEnvironmentQuery(harness.atom);
406+
yield* readEnvironmentQuery(registry, harness.atom);
407+
408+
const data = Atom.map(harness.atom, selectEnvironmentQueryData);
409+
const seen: Array<unknown> = [];
410+
let resultNotifications = 0;
411+
const unsubscribeData = registry.subscribe(data, (value) => seen.push(value), {
412+
immediate: true,
413+
});
414+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribeData));
415+
const unsubscribeResult = registry.subscribe(harness.atom, () => resultNotifications++);
416+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribeResult));
417+
418+
registry.refresh(harness.atom);
419+
yield* readEnvironmentQuery(registry, harness.atom);
420+
// The result itself still moves (timestamp, `waiting`), which SWR relies on.
421+
expect(resultNotifications).toBeGreaterThan(0);
422+
expect(seen).toHaveLength(1);
423+
424+
status = "failed";
425+
registry.refresh(harness.atom);
426+
yield* readEnvironmentQuery(registry, harness.atom);
427+
expect(seen).toHaveLength(2);
428+
expect(seen[1]).toEqual({ checks: [{ name: "ci", status: "failed" }] });
429+
}),
430+
),
431+
);
432+
398433
it.effect(
399434
"retries an interrupted query without exposing a failure during session replacement",
400435
() =>

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,14 @@ const refreshEveryUntilFinal =
515515
{ initialValueTarget: self },
516516
);
517517

518+
/**
519+
* A query result's data alone. A refetch always publishes a new result (a new
520+
* timestamp, `waiting` on and off), while equal data keeps its identity, so a
521+
* reader of only this skips the refetches that changed nothing.
522+
*/
523+
export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
524+
Option.getOrNull(AsyncResult.value(result));
525+
518526
export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
519527
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
520528
options: EnvironmentQueryAtomOptions<

0 commit comments

Comments
 (0)