@devries-cameron20 / t3code-1 / commits / 4d679a6324
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(client): equal query refetches no longer re-render PR rows (#20850)

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

Julius Marminge committed Oct 17, 2026 at 05:06 UTC 4d679a63244e0f6a2118df6a6488ed1295a87797
5 files changed +209 -54
apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx
+26 -26
@@ -1,4 +1,5 @@
1 import { EnvironmentId, type PullRequestCheck } from "@t3tools/contracts";
2 +import { AsyncResult } from "effect/reactivity";
3 import { act } from "react";
4 import { createRoot, type Root } from "react-dom/client";
5 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
@@ -13,34 +14,33 @@ vi.mock(import("~/state/entities"), async (importOriginal) => ({
14 ...(await importOriginal()),
15 useServerConfigs: (() => new Map()) as never,
16 }));
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 +});
38 vi.mock(import("~/state/query"), async (importOriginal) => ({
39 ...(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 }),
44 }));
45 vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({
46 ...(await importOriginal()),
apps/web/src/components/chat/ThreadDetailsPrRow.tsx
+38 -19
@@ -1,5 +1,6 @@
1 import { ThreadDetailsControl } from "./ThreadDetailsControl";
2 import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
3 +import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
4 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
5 import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
6 import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
@@ -11,6 +12,7 @@ import {
12 GitBranchIcon,
13 TriangleAlertIcon,
14 } from "lucide-react";
15 +import { AsyncResult } from "effect/reactivity";
16 import { useState, type MouseEvent as ReactMouseEvent } from "react";
17
18 import { useLiveRefresh } from "~/hooks/useLiveRefresh";
@@ -18,7 +20,11 @@ import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh
20 import { cn } from "~/lib/utils";
21 import { useServerConfigs } from "~/state/entities";
22 import { pullRequestEnvironment } from "~/state/pullRequests";
21 -import { useEnvironmentQuery } from "~/state/query";
23 +import {
24 + useEnvironmentQueryIsNewer,
25 + useEnvironmentQueryRefresh,
26 + useEnvironmentQuerySelector,
27 +} from "~/state/query";
28
29 import {
30 buildFixFindingsHandoff,
@@ -64,6 +70,10 @@ import {
70 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
71 } from "./threadDetailsPanelStyles";
72
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 +
77 export function ThreadDetailsPrRow({
78 environmentId,
79 pr,
@@ -101,37 +111,46 @@ export function ThreadDetailsPrRow({
111 ? { projectId: project.id as ProjectId, repository, number }
112 : null
113 : null;
104 - const detailQuery = useEnvironmentQuery(
114 + const detailAtom =
115 reference === null
116 ? null
117 : pullRequestEnvironment.detail({
118 environmentId,
119 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);
125 const supportsChecks =
126 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
129 ? pullRequestEnvironment.checks({ environmentId, input: reference })
117 - : null,
118 - );
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);
135 const detail =
120 - detailQuery.data === null
136 + detailData === null
137 ? null
122 - : checksQuery.data !== null && checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt
123 - ? { ...detailQuery.data, ...checksQuery.data }
124 - : detailQuery.data;
138 + : checksData !== null && checksAreNewer
139 + ? { ...detailData, ...checksData }
140 + : detailData;
141 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
142 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
127 - useLiveRefresh(detailQuery.isPending ? null : detailQuery.refresh, {
128 - enabled: open,
129 - key: `workspace-pr:${refreshKey}`,
130 - intervalMs: 10 * 60_000,
131 - });
143 + useLiveRefresh(
144 + () => {
145 + if (!detailQuery.isPending()) detailQuery.refresh();
146 + },
147 + { enabled: open, key: `workspace-pr:${refreshKey}`, intervalMs: 10 * 60_000 },
148 + );
149 usePullRequestChecksRefresh({
133 - refresh: checksQuery.isPending || detailQuery.isPending ? null : checksQuery.refresh,
134 - enabled: open && supportsChecks && !(checksQuery.isSuccess && checksQuery.data === null),
150 + refresh: () => {
151 + if (!checksQuery.isPending() && !detailQuery.isPending()) checksQuery.refresh();
152 + },
153 + enabled: open && supportsChecks && !checksSettledEmpty,
154 key: `workspace-pr-checks:${refreshKey}`,
155 checks: detail?.checks ?? [],
156 });
apps/web/src/state/query.ts
+67 -7
@@ -1,7 +1,8 @@
1 -import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
1 +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
2 import * as Cause from "effect/Cause";
3 import * as Option from "effect/Option";
4 import { AsyncResult, Atom } from "effect/reactivity";
5 +import { useContext } from "react";
6
7 const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
8 Atom.withLabel("web-environment-query:empty"),
@@ -24,6 +25,14 @@ export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string
25 : "The environment request failed.";
26 }
27
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 +
36 export function useEnvironmentQuery<A, E>(
37 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
38 ): EnvironmentQueryView<A, E> {
@@ -32,12 +41,7 @@ export function useEnvironmentQuery<A, E>(
41 const refresh = useAtomRefresh(selectedAtom);
42 return {
43 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),
45 error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
46 failure:
47 result._tag === "Failure" ? Option.getOrNull(Cause.findErrorOption(result.cause)) : null,
@@ -46,3 +50,59 @@ export function useEnvironmentQuery<A, E>(
50 refresh,
51 };
52 }
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
+57
@@ -31,6 +31,7 @@ import {
31 environmentRpcKey,
32 createAtomCommandScheduler,
33 createEnvironmentQueryAtomFamily,
34 + selectEnvironmentQueryData,
35 createEnvironmentSubscriptionAtomFamily,
36 createRuntimeCommand,
37 scheduleAtomCommandEffect,
@@ -373,6 +374,62 @@ describe("finite environment subscription lifecycle", () => {
374 });
375
376 describe("environment query lifecycle", () => {
377 + it.effect("keeps the previous value when a refetch returns equal content", () =>
378 + Effect.scoped(
379 + Effect.gen(function* () {
380 + let checks = [{ name: "ci", status: "passed" }];
381 + const execute = Effect.sync(() => ({ checks: checks.map((check) => ({ ...check })) }));
382 + const harness = yield* makeEnvironmentQueryHarness(execute);
383 + const registry = yield* mountEnvironmentQuery(harness.atom);
384 +
385 + const first = yield* readEnvironmentQuery(registry, harness.atom);
386 + registry.refresh(harness.atom);
387 + const equal = yield* readEnvironmentQuery(registry, harness.atom);
388 + expect(equal).toBe(first);
389 +
390 + checks = [{ name: "ci", status: "failed" }];
391 + registry.refresh(harness.atom);
392 + const changed = yield* readEnvironmentQuery(registry, harness.atom);
393 + expect(changed).not.toBe(first);
394 + expect(changed.checks[0]?.status).toBe("failed");
395 + }),
396 + ),
397 + );
398 +
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 +
433 it.effect(
434 "retries an interrupted query without exposing a failure during session replacement",
435 () =>
packages/client-runtime/src/state/runtime.ts
+21 -2
@@ -1,6 +1,7 @@
1 import type { QueryPersistence } from "./queryPersistence.ts";
2 import { createCommandPermissions } from "./commandPermissions.ts";
3 import { followStreamInEnvironment } from "./environmentStreams.ts";
4 +import { reuseUnchanged } from "./serverConfigProjection.ts";
5 export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
6 import {
7 type ClientGuardedRpcTag,
@@ -514,6 +515,14 @@ const refreshEveryUntilFinal =
515 { initialValueTarget: self },
516 );
517
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 +
526 export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
527 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
528 options: EnvironmentQueryAtomOptions<
@@ -560,8 +569,17 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
569 const connection = Option.getOrNull(
570 AsyncResult.value(get(connectionAtom(target.environmentId))),
571 );
572 + // A refetch that returns equal content keeps the previous value's
573 + // references, so readers of the data skip re-rendering on idle polls.
574 + const share = (value: A): A =>
575 + reuseUnchanged(
576 + Option.getOrUndefined(
577 + Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
578 + ),
579 + value,
580 + );
581 const emit = (value: A) =>
564 - Effect.sync(() => get.setSelf(AsyncResult.success(value, { waiting: true }))).pipe(
582 + Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
583 // A value set while the atom builds wins over the build's own
584 // result, so a query that then settled synchronously would stay
585 // waiting forever. Suspend on a promise (`yieldNow` is drained
@@ -604,7 +622,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
622 );
623 }
624 };
607 - if (!options.persistence) return execute();
625 + if (!options.persistence) return execute().pipe(Effect.map(share));
626 const persistence = options.persistence;
627 const cacheKey = JSON.stringify([options.label, target.input]);
628 const previous = Option.flatMap(
@@ -623,6 +641,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
641 }
642 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
643 return yield* execute().pipe(
644 + Effect.map(share),
645 Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
646 );
647 });