TypeScript
fix(prs): reuse GitHub data and defer optional reads (#9835)
maria110bbe6b55d6
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 43ba73d325e..eb2f913c920 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -3057,6 +3057,114 @@ it.effect("fills in the line counts for the rows it is given", () =>]);}),);+it.effect(+ "reuses counts across overlapping pages until expiry, explicit invalidation, or a reference changes",+ () =>+ Effect.gen(function* () {+ const asked: number[][] = [];+ const ref = (number: number) => ({+ projectId: "p1" as ProjectId,+ repository: "acme/web",+ number,+ });+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),+ ],+ providers: [+ fakeProvider("github", {+ listChangeRequestStats: (input) => {+ asked.push(input.changeRequests.map((ref) => ref.number));+ return Effect.succeed(+ input.changeRequests.map((ref) => ({ ...ref, additions: 12, deletions: 3 })),+ );+ },+ }),+ ],+ });++ yield* service.listStats({ refs: [ref(1), ref(2)] });+ const overlapping = yield* service.listStats({ refs: [ref(2), ref(3)] });+ assert.deepStrictEqual(+ overlapping.stats.map((stat) => stat.number),+ [2, 3],+ );+ yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });+ assert.deepStrictEqual(asked, [[1, 2], [3]]);++ yield* service.invalidate({ reference: ref(2) });+ yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });+ assert.deepStrictEqual(asked, [[1, 2], [3], [2]]);++ yield* TestClock.adjust("61 seconds");+ yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] });+ assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3]]);++ yield* service.refreshAfterTurn;+ yield* service.listStats({ refs: [ref(1)] });+ assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1]]);++ yield* service.invalidate({});+ yield* service.listStats({ refs: [ref(1)] });+ assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1], [1]]);+ }),+);++it.effect("reads the fresh diff when detail or summary discovers a changed revision", () =>+ Effect.gen(function* () {+ const summaryStarted = yield* Deferred.make<void>();+ const releaseSummary = yield* Deferred.make<void>();+ let revision = "2026-07-02T00:00:00Z";+ let patch = "old patch";+ let diffCalls = 0;+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };+ const service = yield* makeService({+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],+ providers: [+ fakeProvider("github", {+ getChangeRequest: () =>+ Effect.sync(() => ({ ...hostedChangeRequest("body"), updatedAt: revision })),+ getChangeRequestSummary: () =>+ Effect.gen(function* () {+ const result = changeRequest(1, revision);+ yield* Deferred.succeed(summaryStarted, undefined);+ yield* Deferred.await(releaseSummary);+ return result;+ }),+ getDiff: () =>+ Effect.sync(() => {+ diffCalls += 1;+ return { patch, truncated: false, nextCursor: null };+ }),+ }),+ ],+ });++ const coldSummary = yield* service.summary(reference).pipe(Effect.forkChild());+ yield* Deferred.await(summaryStarted);+ yield* service.detail(reference);+ assert.strictEqual((yield* service.diff(reference)).patch, "old patch");+ revision = "2026-07-02T00:01:00Z";+ patch = "new patch";+ yield* TestClock.adjust("16 seconds");+ yield* service.detail(reference);+ yield* Effect.yieldNow;+ assert.strictEqual((yield* service.detail(reference)).updatedAt, revision);+ yield* Deferred.succeed(releaseSummary, undefined);+ yield* Fiber.join(coldSummary);+ yield* service.summary(reference, { recoverTransientFailure: false });+ assert.strictEqual((yield* service.diff(reference)).patch, "new patch");+ assert.strictEqual(diffCalls, 2);++ revision = "2026-07-02T00:02:00Z";+ patch = "summary-discovered patch";+ yield* TestClock.adjust("61 seconds");+ yield* service.summary(reference, { recoverTransientFailure: false });+ assert.strictEqual((yield* service.diff(reference)).patch, patch);+ assert.strictEqual(diffCalls, 3);+ }),+);+it.effect("keeps the rows when the line counts cannot be read", () =>Effect.gen(function* () {const service = yield* makeService({@@ -3080,6 +3188,7 @@ it.effect(Effect.gen(function* () {let coreCalls = 0;let activityCalls = 0;+ let statsCalls = 0;const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };const service = yield* makeService({projects: [@@ -3087,6 +3196,10 @@ it.effect(],providers: [fakeProvider("github", {+ listChangeRequestStats: () => {+ statsCalls += 1;+ return Effect.succeed([]);+ },getChangeRequest: () => {coreCalls += 1;return Effect.succeed({@@ -3126,6 +3239,16 @@ it.effect(assert.strictEqual(coreCalls, 1);assert.strictEqual(activityCalls, 0);+ const counts = yield* service.listStats({ refs: [reference] });+ assert.strictEqual(statsCalls, 0);+ assert.deepStrictEqual(counts.stats, [+ {+ ...reference,+ additions: core.additions,+ deletions: core.deletions,+ },+ ]);+yield* Effect.all([service.activity(reference), service.activity(reference)], {concurrency: 2,});diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex ceba7ce32e0..a8d3dc2fdea 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -2136,6 +2136,21 @@ export const make = Effect.gen(function* () {Math.max(turnRefreshEpoch, refEpochs.get(refScope(ref)) ?? 0);const refCacheKey = (ref: PullRequestRef) =>JSON.stringify([refEpoch(ref), ref.projectId, ref.repository, ref.number]);+ // Counts belong to a PR, not a filtered page. Background reads and filter changes reuse+ // them; explicit refreshes, mutations, and turns strand old and in-flight results.+ const statsCacheKey = (key: string) => JSON.stringify([listingsEpoch, key]);+ const recentStats = new Map<+ string,+ { readonly at: number; readonly value: PullRequestDiffStat }+ >();+ const recordStats = (key: string, value: PullRequestDiffStat, at: number) => {+ recentStats.delete(key);+ recentStats.set(key, { at, value });+ if (recentStats.size > REF_EPOCH_CAPACITY) {+ const oldest = recentStats.keys().next().value;+ if (oldest !== undefined) recentStats.delete(oldest);+ }+ };const bumpRefEpoch = (ref: PullRequestRef) => {const scope = refScope(ref);if (!refEpochs.has(scope) && refEpochs.size >= REF_EPOCH_CAPACITY) {@@ -2175,13 +2190,15 @@ export const make = Effect.gen(function* () {const summary: PullRequestService["Service"]["summary"] = (input, options) => {const key = refCacheKey(input);const cached = Cache.get(summaryCache, key);- if (options?.recoverTransientFailure !== false) {- return lastGoodSummary.serveHeld(key, cached, "reuse");- }const held = lastGoodSummary.peek(key);- return held?.state === "merged"+ return held !== undefined &&+ (options?.recoverTransientFailure !== false || held.state === "merged")? Effect.succeed(held)- : cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)));+ : cached.pipe(+ Effect.tap((value) =>+ shouldReplaceHeldSummary(key, value) ? lastGoodSummary.record(key, value) : Effect.void,+ ),+ );};// Keys serialize positionally and parse back in the lookup, so the cache is the only holder@@ -2263,8 +2280,25 @@ export const make = Effect.gen(function* () {const detailCache = yield* Cache.makeWith((key: string) => {+ const statsKey = statsCacheKey(key);const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];- return detailUncached({ projectId, repository, number } as PullRequestRef);+ return detailUncached({ projectId, repository, number } as PullRequestRef).pipe(+ Effect.tap(+ Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) {+ recordStats(+ statsKey,+ {+ projectId: value.projectId,+ repository: value.repository,+ number: value.number,+ additions: value.additions,+ deletions: value.deletions,+ },+ yield* Clock.currentTimeMillis,+ );+ }),+ ),+ );},{capacity: DETAIL_CACHE_CAPACITY,@@ -2360,38 +2394,69 @@ export const make = Effect.gen(function* () {input.number,input.cursor ?? null,input.commit ?? null,+ input.commit === undefined+ ? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null)+ : null,]);return staleDiff(key, Cache.get(diffCache, key));};const listStatsCache = yield* Cache.makeWith((key: string) => {- const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number]>];+ const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number, number]>];return listStatsUncached({refs: refs.map(([projectId, repository, number]) => ({ projectId, repository, number })),- } as unknown as PullRequestListStatsInput);+ } as unknown as PullRequestListStatsInput).pipe(+ Effect.flatMap((result) =>+ Clock.currentTimeMillis.pipe(Effect.map((at) => ({ result, at }))),+ ),+ );},{capacity: LIST_STATS_CACHE_CAPACITY,timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_STATS_CACHE_TTL : Duration.zero),},);- // The stats read leans on the host's search API — the scarcest limit of them all — so it- // shares between clients like every other read. Refs are sorted so one page's worth of rows- // is one key however the client assembled them, and the listings epoch rides along so the- // refresh that forgets the listing forgets its decorations with it.- const listStats: PullRequestService["Service"]["listStats"] = (input) => {- if (input.refs.length === 0) return Effect.succeed({ stats: [] });- const key = JSON.stringify([+ const statsBatchKey = (refs: Iterable<PullRequestRef>) =>+ JSON.stringify([listingsEpoch,- input.refs- .map((ref) => [ref.projectId, ref.repository, ref.number] as const)+ [...refs]+ .map((ref) => [ref.projectId, ref.repository, ref.number, refEpoch(ref)] as const).toSorted((left, right) =>`${left[0]} ${left[1]} ${left[2]}`.localeCompare(`${right[0]} ${right[1]} ${right[2]}`),),]);- return Cache.get(listStatsCache, key);- };+ // Exact batches share in-flight reads; overlapping pages reuse each row already fetched.+ const listStats: PullRequestService["Service"]["listStats"] = Effect.fn(+ "PullRequestService.listStats",+ )(function* (input: PullRequestListStatsInput) {+ if (input.refs.length === 0) return { stats: [] };+ const now = yield* Clock.currentTimeMillis;+ const held: PullRequestDiffStat[] = [];+ const missing = new Map<string, PullRequestRef>();+ for (const ref of input.refs) {+ const key = statsCacheKey(refCacheKey(ref));+ const cached = recentStats.get(key);+ if (cached !== undefined && now - cached.at < Duration.toMillis(LIST_STATS_CACHE_TTL)) {+ held.push(cached.value);+ } else {+ missing.set(key, ref);+ }+ }+ if (missing.size === 0) return { stats: held };+ const key = statsBatchKey(missing.values());+ const { result, at } = yield* Cache.get(listStatsCache, key);+ for (const [key, ref] of missing) {+ const stat = result.stats.find(+ (stat) =>+ stat.projectId === ref.projectId &&+ stat.repository.toLowerCase() === ref.repository.toLowerCase() &&+ stat.number === ref.number,+ );+ if (stat !== undefined) recordStats(key, stat, at);+ }+ return { stats: [...held, ...result.stats] };+ });const invalidate: PullRequestService["Service"]["invalidate"] = (input) => {const reference = input.reference;diff --git a/apps/server/src/sourceControl/githubGraphQlBudget.test.ts b/apps/server/src/sourceControl/githubGraphQlBudget.test.tsindex a166bf0dbba..a5b0680fafc 100644--- a/apps/server/src/sourceControl/githubGraphQlBudget.test.ts+++ b/apps/server/src/sourceControl/githubGraphQlBudget.test.ts@@ -9,11 +9,11 @@ const NEXT_RESET_AT = "2026-08-13T15:00:00.000Z";const BEFORE_RESET = Date.parse("2026-08-13T13:30:00.000Z");const AFTER_RESET = Date.parse("2026-08-13T14:00:01.000Z");-function rateLimit(remaining: number, limit = 5_000, resetAt = RESET_AT): string {+function rateLimit(remaining: number, limit = 5_000, resetAt = RESET_AT, cost = 14): string {return JSON.stringify({data: {viewer: { login: "bilal" },- rateLimit: { cost: 14, limit, remaining, resetAt },+ rateLimit: { cost, limit, remaining, resetAt },},});}@@ -86,6 +86,27 @@ describe("GitHub GraphQL budget", () => {}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),);+ it.effect("learns a cheaper observed cost without restoring reserved quota", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ const query = "query { viewer { login } }";+ yield* budget.observe("github.com", rateLimit(512, 5_000, RESET_AT, 8));+ yield* budget.query("github.com", query);+ // The admission reserved eight points, but the completed read only cost one.+ yield* budget.observe("github.com", rateLimit(511, 5_000, RESET_AT, 1));++ for (let count = 0; count < 4; count += 1) {+ expect(yield* budget.query("github.com", query)).toContain("rateLimit");+ }+ const error = yield* Effect.flip(budget.query("github.com", query));+ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ retryAt: Date.parse(RESET_AT),+ });+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );+it.effect("ignores a response from an older reset window", () =>Effect.gen(function* () {yield* TestClock.setTime(BEFORE_RESET);diff --git a/apps/server/src/sourceControl/githubGraphQlBudget.ts b/apps/server/src/sourceControl/githubGraphQlBudget.tsindex 9c43de8e058..9ece27547f5 100644--- a/apps/server/src/sourceControl/githubGraphQlBudget.ts+++ b/apps/server/src/sourceControl/githubGraphQlBudget.ts@@ -122,15 +122,20 @@ export const make = Effect.gen(function* () {const previous = current.get(key);// Concurrent reads can finish out of order. Quota only falls within one reset window, and// an answer from an older window must not replace the current one.- if (- previous !== undefined &&- (snapshot.resetAtMs < previous.resetAtMs ||- (snapshot.resetAtMs === previous.resetAtMs && snapshot.remaining >= previous.remaining))- ) {+ if (previous !== undefined && snapshot.resetAtMs < previous.resetAtMs) {return current;}const next = new Map(current);- next.set(key, snapshot);+ // Keep the conservative balance, but learn the observed cost even when our reservation+ // was larger. Otherwise one expensive read makes every later cheap read spend its cost.+ next.set(+ key,+ previous !== undefined &&+ snapshot.resetAtMs === previous.resetAtMs &&+ snapshot.remaining >= previous.remaining+ ? { ...previous, cost: snapshot.cost }+ : snapshot,+ );return next;});});diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 4a3af4b02c5..76e50b60003 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -228,9 +228,8 @@ const TABS: ReadonlyArray<{ value: DetailTab; label: string }> = [{ value: "code", label: "Code" },];-// The diff viewer pulls in its worker pool, so it stays out of the bundle until Code is opened.-// Named rather than inlined so the panel can also call it itself, to start the download before-// anyone has clicked the tab.+// The diff viewer pulls in its worker pool, so load it only when the reader approaches Code.+// Start the download on tab hover or focus, before the click, without loading it for every PR.const loadCodeTab = () => import("./PullRequestCodeTab");const PullRequestCodeTab = lazy(loadCodeTab);@@ -524,14 +523,21 @@ export function PullRequestDetailPanel({// summary needs it too — a large description re-parses its whole markdown on every return// to the tab. `visibility` keeps boxes, sizes and scroll offsets, and takes hidden content// out of the tab order and the accessibility tree.- const [mountedTabs, setMountedTabs] = useState<ReadonlySet<DetailTab>>(- () => new Set<DetailTab>(["summary"]),- );+ const tabScopeKey = `${environmentId}:${pullRequestKey}`;+ const [tabMountState, setTabMountState] = useState(() => ({+ key: tabScopeKey,+ tabs: new Set<DetailTab>(["summary"]),+ }));+ // A previously visited Code tab must not fetch diffs for every later PR while hidden.+ const mountedTabs =+ tabMountState.key === tabScopeKey ? tabMountState.tabs : new Set<DetailTab>([tab]);useEffect(() => {- setMountedTabs((previous) =>- previous.has(tab) ? previous : new Set<DetailTab>(previous).add(tab),- );- }, [tab]);+ setTabMountState((previous) => {+ if (previous.key !== tabScopeKey) return { key: tabScopeKey, tabs: new Set([tab]) };+ if (previous.tabs.has(tab)) return previous;+ return { key: tabScopeKey, tabs: new Set(previous.tabs).add(tab) };+ });+ }, [tab, tabScopeKey]);const [chromeCondensed, setChromeCondensed] = useState(false);// Each mounted tab remembers its own scroll chrome; short tabs cannot scroll to reopen it.const chromeStateByTab = useRef<Partial<Record<DetailTab, boolean>>>({});@@ -568,12 +574,6 @@ export function PullRequestDetailPanel({// Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself// alone. One at a time whatever the key: they all check the same pull request out.const [handoff, setHandoff] = useState<string | null>(null);- // The chunk is fetched as soon as the panel exists rather than waiting for the Code tab to be- // clicked, so a reader who does click it lands on a chunk already in the module cache.- useEffect(() => {- void loadCodeTab();- }, []);-const detailQuery = useEnvironmentQuery(pullRequestEnvironment.detail({ environmentId, input: reference }),);@@ -699,12 +699,13 @@ export function PullRequestDetailPanel({);useEffect(() => {if (!coreDetail) return;- const next = { key: pullRequestKey, updatedAt: coreDetail.updatedAt };+ const next = { key: tabScopeKey, updatedAt: coreDetail.updatedAt };if (shouldRefreshPullRequestActivity(activityRevision.current, next)) {activityQuery.refresh();+ setRefreshToken((token) => token + 1);}activityRevision.current = next;- }, [activityQuery.refresh, coreDetail, pullRequestKey]);+ }, [activityQuery.refresh, coreDetail, tabScopeKey]);useLayoutEffect(() => {if (!resolvedCoreDetail) return;onStateChange?.({@@ -713,16 +714,14 @@ export function PullRequestDetailPanel({state: resolvedCoreDetail.state,});}, [onStateChange, resolvedCoreDetail]);- // Core detail is cheap enough to re-read while this stays open. Activity is heavier, so the- // revision effect above reads it only after this same pull request reports a change. Keyed by+ // Reuse activity and diff until core detail reports a changed revision. Keyed by// the pull request rather than by the panel, because this one panel shows a different pull// request every time it is opened.useLiveRefresh(() => {detailQuery.refresh();- setRefreshToken((token) => token + 1);},- { key: `pull-request:${reference.projectId}:${reference.repository}#${reference.number}` },+ { key: `pull-request:${environmentId}:${pullRequestKey}` },);// The button, on the other hand, goes around the server's cache rather than through it: it is// the answer for a reader who can see that what they are looking at is behind. The@@ -2143,7 +2142,12 @@ export function PullRequestDetailPanel({}}>{visibleTabs.map((item) => (- <Toggle key={item.value} value={item.value}>+ <Toggle+ key={item.value}+ value={item.value}+ onPointerEnter={item.value === "code" ? () => void loadCodeTab() : undefined}+ onFocus={item.value === "code" ? () => void loadCodeTab() : undefined}+ >{item.label}</Toggle>))}diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsxindex 6ee686a9de7..ae7aee0168f 100644--- a/apps/web/src/components/pullRequest/PullRequestRow.tsx+++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx@@ -97,11 +97,11 @@ function PullRequestRowImpl({aria-current={selected ? "true" : undefined}onClick={() => onSelect(entry)}className={cn(- "grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-3 rounded-lg px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ "@container/pr-row grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-3 rounded-lg px-3 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",// Offscreen rows are skipped for style, layout and paint: a long list costs what the// viewport shows, not what the pages have loaded. The intrinsic size keeps the// scrollbar honest while a row is skipped.- "[contain-intrinsic-block-size:54px] [content-visibility:auto]",+ "[contain-intrinsic-block-size:66px] [content-visibility:auto]",selected ? "bg-accent" : "hover:bg-accent/60",)}>@@ -111,12 +111,36 @@ function PullRequestRowImpl({mergeability={entry.mergeability}baseBranch={entry.baseBranch}/>- <span className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-0.5">+ <span className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5"><span className="col-start-1 row-start-1 block truncate text-sm font-medium text-foreground">{entry.title}</span>- <span className="col-start-2 row-start-1 justify-self-end whitespace-nowrap text-xs text-muted-foreground/70 tabular-nums">- {formatRelativeTimeLabel(entry.updatedAt)}+ <span className="col-start-2 row-start-1 flex max-w-36 items-center justify-self-end gap-2 text-xs">+ {/* Only a verdict somebody has actually given: "review required" is the absence of+ one, and saying so on every unreviewed row would say nothing. */}+ {entry.reviewDecision === "approved" || entry.reviewDecision === "changes-requested" ? (+ <span+ className={cn(+ "sr-only @md/pr-row:not-sr-only @md/pr-row:min-w-0 @md/pr-row:truncate",+ entry.reviewDecision === "approved"+ ? "text-emerald-600/90 dark:text-emerald-400/80"+ : "text-amber-600/90 dark:text-amber-400/80",+ )}+ >+ {entry.reviewDecision === "approved" ? "Approved" : "Changes requested"}+ </span>+ ) : null}+ {entry.checksState === undefined ? null : (+ <PullRequestChecksPopover+ checksState={entry.checksState}+ environmentId={entry.environmentId}+ reference={{+ projectId: entry.projectId,+ repository: entry.repository,+ number: entry.number,+ }}+ />+ )}</span><PullRequestMetaLine className="@container/pr-row-meta col-start-1 row-start-2 overflow-hidden text-xs text-muted-foreground/70">{matchedElsewhere ? (@@ -170,37 +194,13 @@ function PullRequestRowImpl({labelClassName="sr-only @xs/pr-row-meta:not-sr-only @xs/pr-row-meta:truncate"/>{entry.labels.length > 0 ? <PullRequestRowLabels labels={entry.labels} /> : null}- {/* Only a verdict somebody has actually given: "review required" is the absence of- one, and saying so on every unreviewed row would say nothing. */}- {entry.reviewDecision === "approved" || entry.reviewDecision === "changes-requested" ? (- <span- className={cn(- "min-w-0 truncate",- entry.reviewDecision === "approved"- ? "text-emerald-600/90 dark:text-emerald-400/80"- : "text-amber-600/90 dark:text-amber-400/80",- )}- >- {entry.reviewDecision === "approved" ? "Approved" : "Changes requested"}- </span>- ) : null}- {entry.checksState === undefined ? null : (- <PullRequestChecksPopover- checksState={entry.checksState}- environmentId={entry.environmentId}- reference={{- projectId: entry.projectId,- repository: entry.repository,- number: entry.number,- }}- />- )}</PullRequestMetaLine>- <PullRequestDiffStat- additions={entry.additions}- deletions={entry.deletions}- className="col-start-2 row-start-2 justify-self-end text-xs"- />+ <span className="col-start-2 row-start-2 flex items-center justify-self-end gap-3 whitespace-nowrap text-[11px] text-muted-foreground/70 tabular-nums">+ <PullRequestDiffStat additions={entry.additions} deletions={entry.deletions} />+ <span className="hidden @sm/pr-row:inline">+ {formatRelativeTimeLabel(entry.updatedAt)}+ </span>+ </span></span></button>);diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.tsindex b3fc1da8d0a..9b0043ef90b 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts@@ -69,8 +69,30 @@ function entry(}describe("visible pull request line-count targets", () => {+ it("reuses counts supplied by the listing and only requests missing counts", () => {+ const entries = [+ entry({ number: 1, additions: 12, deletions: 0 }),+ entry({ number: 2, additions: 0, deletions: 7 }),+ entry({ number: 3, additions: 0, deletions: 0 }),+ ];+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));+ const keys = pullRequestStatsKeysToRequest(+ entriesByKey,+ new Set(entries.map(pullRequestEntryKey)),+ [],+ new Map(),+ );++ expect(pullRequestStatsBatches(entriesByKey, keys)[0]?.input.refs).toEqual([+ { projectId: "project-1", repository: "pingdotgg/t3code", number: 3 },+ ]);+ });+it("does not request a row again after its received batch is pruned", () => {- const entries = [entry({ number: 1 }), entry({ number: 2 })];+ const entries = [+ entry({ additions: 0, deletions: 0, number: 1 }),+ entry({ additions: 0, deletions: 0, number: 2 }),+ ];const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const firstKey = pullRequestEntryKey(entries[0]!);const secondKey = pullRequestEntryKey(entries[1]!);@@ -97,7 +119,9 @@ describe("visible pull request line-count targets", () => {});it("drops historical rows after a long scroll so refresh stays bounded to the viewport", () => {- const entries = Array.from({ length: 500 }, (_, index) => entry({ number: index + 1 }));+ const entries = Array.from({ length: 500 }, (_, index) =>+ entry({ additions: 0, deletions: 0, number: index + 1 }),+ );const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const batches = entries.map((item) => pullRequestStatsBatches(entriesByKey, new Set([pullRequestEntryKey(item)]))[0]!,@@ -112,7 +136,9 @@ describe("visible pull request line-count targets", () => {});it("keeps every per-environment batch within the stats contract limit", () => {- const entries = Array.from({ length: 501 }, (_, index) => entry({ number: index + 1 }));+ const entries = Array.from({ length: 501 }, (_, index) =>+ entry({ additions: 0, deletions: 0, number: index + 1 }),+ );const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const batches = pullRequestStatsBatches(entriesByKey,@@ -125,9 +151,9 @@ describe("visible pull request line-count targets", () => {it("selects visible rows for date modes and every uncached row for size modes", () => {const entries = [- entry({ number: 1 }),- entry({ number: 2 }),- entry({ number: 3, environmentId: "env-2" as EnvironmentId }),+ entry({ additions: 0, deletions: 0, number: 1 }),+ entry({ additions: 0, deletions: 0, number: 2 }),+ entry({ additions: 0, deletions: 0, number: 3, environmentId: "env-2" as EnvironmentId }),];const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const [firstKey, secondKey] = entries.map(pullRequestEntryKey);@@ -162,7 +188,11 @@ describe("visible pull request line-count targets", () => {});it("refreshes only visible rows unless size sorting needs every loaded row", () => {- const entries = [entry({ number: 1 }), entry({ number: 2 }), entry({ number: 3 })];+ const entries = [+ entry({ additions: 0, deletions: 0, number: 1 }),+ entry({ additions: 0, deletions: 0, number: 2 }),+ entry({ additions: 0, deletions: 0, number: 3 }),+ ];const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const visibleKeys = new Set([pullRequestEntryKey(entries[1]!)]);const cachedStats = mergePullRequestDiffStats(@@ -198,7 +228,10 @@ describe("visible pull request line-count targets", () => {});it("ignores a late refresh after the filter or stats policy changes", () => {- const entries = [entry({ number: 1 }), entry({ number: 2 })];+ const entries = [+ entry({ additions: 0, deletions: 0, number: 1 }),+ entry({ additions: 0, deletions: 0, number: 2 }),+ ];const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const visibleKeys = new Set([pullRequestEntryKey(entries[1]!)]);const requestedScope = { key: "open", policy: "visible" } as const;@@ -217,7 +250,10 @@ describe("visible pull request line-count targets", () => {});it("does not add request batches again while rows are active or cached", () => {- const entries = [entry({ number: 1 }), entry({ number: 2 })];+ const entries = [+ entry({ additions: 0, deletions: 0, number: 1 }),+ entry({ additions: 0, deletions: 0, number: 2 }),+ ];const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));const first = pullRequestStatsRequestBatches({entriesByKey,@@ -724,7 +760,7 @@ describe("default merge-readiness ranking", () => {]);});- it("puts the smallest measured change first inside a readiness tier", () => {+ it("keeps readiness order stable when optional diff counts arrive", () => {const larger = entry({number: 1,checksState: "passing",@@ -752,7 +788,14 @@ describe("default merge-readiness ranking", () => {expect(rankPullRequestsByMergeReadiness([larger, unknown, smaller]).map((row) => row.number),- ).toEqual([2, 1, 3]);+ ).toEqual([3, 1, 2]);+ expect(+ rankPullRequestsByMergeReadiness([+ larger,+ { ...unknown, additions: 500, deletions: 200 },+ smaller,+ ]).map((row) => row.number),+ ).toEqual([3, 1, 2]);});it("keeps authored work first and ranks each group by readiness", () => {diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.tsindex af1bd6ab4fb..af71c934ad6 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts@@ -469,7 +469,11 @@ export function pullRequestStatsKeysToRequest([...enteredKeys].filter((key) => {const entry = entriesByKey.get(key);return (- entry !== undefined && !requested.has(key) && !statsByRow.has(pullRequestDiffStatKey(entry))+ entry !== undefined &&+ entry.additions === 0 &&+ entry.deletions === 0 &&+ !requested.has(key) &&+ !statsByRow.has(pullRequestDiffStatKey(entry)));}),);@@ -1006,11 +1010,10 @@ export function rankPullRequestMatches<Entry extends PullRequestListEntry>(* verdict, then everything else still open. Drafts stay in that third tier because their author* has not made them mergeable yet. Finished work follows open work when all states are visible. A* known conflict is never ready, whatever its checks, review or state say, so it stays at the- * bottom. Smaller measured changes come first within a tier; recency only breaks a remaining tie.+ * bottom. Recency breaks ties, so optional diff counts never move the queue beneath the reader.*/export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEntry>(entries: ReadonlyArray<Entry>,- hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,): ReadonlyArray<Entry> {const tier = (entry: Entry) => {if (entry.mergeability === "conflicting") return 4;@@ -1023,10 +1026,7 @@ export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEnreturn entries.toSorted((left, right) => {const byTier = tier(left) - tier(right);if (byTier !== 0) return byTier;- const byMeasurement = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));- if (byMeasurement !== 0) return byMeasurement;- const bySize = left.additions + left.deletions - (right.additions + right.deletions);- return bySize !== 0 ? bySize : right.updatedAt.localeCompare(left.updatedAt);+ return right.updatedAt.localeCompare(left.updatedAt);});}@@ -1042,7 +1042,7 @@ export function sortPullRequestGroups<Entry extends PullRequestListEntry>(if (sort === "ready") {return searchText.trim().length === 0- ? sortWithinGroups((entries) => rankPullRequestsByMergeReadiness(entries, hasMeasuredSize))+ ? sortWithinGroups(rankPullRequestsByMergeReadiness): groups;}if (sort === "updated") return groups;diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsxindex bcc22daa4a9..48a558be8e0 100644--- a/apps/web/src/routes/_chat.pull-requests.tsx+++ b/apps/web/src/routes/_chat.pull-requests.tsx@@ -292,7 +292,7 @@ function PullRequestsRouteView() {const search = Route.useSearch();const sort = search.sort ?? "ready";const statsPolicy: PullRequestStatsPolicy =- sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";+ sort === "largest" || sort === "smallest" ? "eager" : "visible";const navigate = useNavigate({ from: Route.fullPath });const keybindings = useAtomValue(primaryServerKeybindingsAtom);const { environments } = useEnvironments();@@ -838,11 +838,7 @@ function PullRequestsRouteView() {} finally {setInvalidating(false);}- refreshList();- baselineQuery.refresh();- facetQuery.refresh();- authoredQuery.refresh();- reviewingQuery.refresh();+ refreshList(true);const visible = visibleStatsKeys.current;const batches = pullRequestStatsRefreshBatches({requestedScope: requestedStatsScope,@@ -955,7 +951,7 @@ function PullRequestsRouteView() {environmentKey,scope: scopeKey,query: sentQuery,- data,+ data: { ...data, entries: ordered?.key === filterKey ? ordered.entries : data.entries },...(partitions === undefined ? {} : { partitions }),};});@@ -1017,7 +1013,7 @@ function PullRequestsRouteView() {// `ordered` is declared above, ahead of the snapshot write, but grown here from this round's// own answer.useEffect(() => {- if (!answered) return;+ if (!answered || listQuery.isPending || (listQuery.error && listQuery.data === null)) return;setOrdered((previous) => {if (previous === null || previous.key !== filterKey) {return {@@ -1045,7 +1041,15 @@ function PullRequestsRouteView() {// reads, so its order stands; a row that moved was updated, and moving is the news.return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentParsed.text) };});- }, [answered, filterKey, sentCursors, sentParsed.text]);+ }, [+ answered,+ filterKey,+ sentCursors,+ sentParsed.text,+ listQuery.isPending,+ listQuery.error,+ listQuery.data,+ ]);// Carrying on where the last answer stopped, and only raising the page size for the hosts that// could not say where that was.@@ -1081,11 +1085,20 @@ function PullRequestsRouteView() {// re-reads only its own slice, so the rows loaded before it would never see a merge, a close,// or a retitle. Going back to a single page long enough to cover everything on screen lets the// merge above bring every row up to date in place.- const refreshList = () => {+ const refreshList = (includeRelated = false) => {+ const related = includeRelated+ ? [+ ...baselineTargets,+ ...facetTargets,+ ...partitionTargets.authored,+ ...partitionTargets.reviewing,+ ]+ : [];if (sentCursors === null) {- listQuery.refresh();+ listQuery.refresh([...listTargets, ...related]);return;}+ if (related.length > 0) listQuery.refresh(related);const loadedCount = ordered?.key === filterKey ? ordered.entries.length : pageSize;setPage({key: filterKey,@@ -1117,9 +1130,7 @@ function PullRequestsRouteView() {// host's rate limit.useLiveRefresh(() => {- refreshList();- authoredQuery.refresh();- reviewingQuery.refresh();+ refreshList(true);},{ enabled: pullRequestsSupported },);@@ -1209,54 +1220,6 @@ function PullRequestsRouteView() {);const scrollRef = useRef<HTMLDivElement>(null);- const sentinelRef = useRef<HTMLDivElement>(null);- useEffect(() => {- const sentinel = sentinelRef.current;- // A failed page must stop the observer. Retained rows keep the sentinel on screen, so- // re-arming it after a failure would ask for the next page again, forever.- //- // Rows on screen are also what makes reaching the sentinel mean anything: with none, it- // sits directly below the empty state and is always in view, so a search that matches- // nothing would page through the whole host on its own — one listing of every repository- // per step — while the reader looks at an empty page. With nothing to scroll past, the- // next page is asked for rather than assumed.- if (- !sentinel ||- entries.length === 0 ||- listData?.truncated !== true ||- listQuery.isPending ||- listQuery.error !== null ||- // The rows on screen belong to the previous question, so nothing about them says where- // this one carries on from. Growing the page under them would answer neither.- showingCarried ||- // Asking past the cap is refused, which would strand the list on an error the retry- // could never clear, so growth stops here and the rest stays on the host. A continuation- // does not grow the page at all, so the cap does not apply to it.- (!canContinue && pageSize >= MAX_PAGE_SIZE)- ) {- return;- }- const observer = new IntersectionObserver(- (observed) => {- if (observed.some((entry) => entry.isIntersecting)) {- loadMore();- }- },- // Start the next page slightly before the sentinel is on screen.- { root: scrollRef.current, rootMargin: "240px" },- );- observer.observe(sentinel);- return () => observer.disconnect();- }, [- entries.length,- filterKey,- canContinue,- listData?.truncated,- listQuery.error,- listQuery.isPending,- pageSize,- showingCarried,- ]);/*** The line counts, asked for once the rows are on screen. On GitHub they are forty per cent of@@ -1633,7 +1596,7 @@ function PullRequestsRouteView() {/>) : firstLoad ? (<PullRequestListGhost rows={7} />- ) : listQuery.error && listData === null ? (+ ) : listQuery.error && entries.length === 0 ? (<PullRequestsUnavailableState error={listQuery.error} onRetry={() => listQuery.refresh()} />) : carriedToNothing ? (<PullRequestListGhost rows={7} />@@ -1699,22 +1662,33 @@ function PullRequestsRouteView() {</div>)}- {listQuery.error && listData !== null ? (+ {listQuery.error && entries.length > 0 ? (<div className="flex items-center justify-between gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs">- <span>The latest request failed. Showing the last pull requests loaded.</span>+ <span>{listQuery.error} Showing the last pull requests loaded.</span><Button size="xs" variant="outline" onClick={() => listQuery.refresh()}>Retry</Button></div>) : null}{listData?.truncated && entries.length > 0 ? (- <div ref={sentinelRef} className="flex justify-center py-2 text-xs text-muted-foreground">+ <div className="flex justify-center py-3 text-xs text-muted-foreground">{loadingMore ? (<span className="flex items-center gap-2"><LoaderIcon aria-hidden className="size-3.5 animate-spin" />- Loading more+ {sentCursors === null ? "Updating pull requests" : "Loading more"}</span>- ) : null}+ ) : canContinue || pageSize < MAX_PAGE_SIZE ? (+ <Button+ size="sm"+ variant="outline"+ onClick={loadMore}+ disabled={listQuery.isPending || showingCarried}+ >+ Load more pull requests+ </Button>+ ) : (+ <span>Narrow your search to find more pull requests.</span>+ )}</div>) : null}</>@@ -1979,10 +1953,7 @@ function PullRequestsRouteView() {// Merging, closing or reopening changes the row this panel was opened from, so// the list behind it is out of date the moment the host takes the action.onActed={() => {- refreshList();- baselineQuery.refresh();- authoredQuery.refresh();- reviewingQuery.refresh();+ refreshList(true);}}/></RightPanelTabs>@@ -2244,7 +2215,7 @@ function PullRequestsColumn({return (// Painted flat like the chat column: the inset underneath carries the chrome grain, and a// content surface that lets it show reads as a different background than every thread.- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">+ <div className="@container/pr-list flex min-h-0 min-w-0 flex-1 flex-col bg-background">{/* A closed right panel leaves this column full-width, so the shared headerreserves native window controls and hosts the controls strip itself: ondesktop the header is a drag-region, and only a no-drag descendant wins@@ -2325,8 +2296,10 @@ function PullRequestsColumn({content actually passing under the chrome fades. */}<WorkspacePageContainer width="expanded" className="gap-4"><div className="flex flex-col gap-3">- <div ref={inFlowSearchRef} className="flex items-center gap-2">- {searchInput}+ <div ref={inFlowSearchRef} className="flex flex-wrap items-center gap-2">+ <div className="min-w-0 basis-full @lg/pr-list:basis-0 @lg/pr-list:flex-1">+ {searchInput}+ </div>{sortMenu}{filtersMenu}{!condensed ? (diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.tsindex 99b2ef37c99..eaec7206673 100644--- a/apps/web/src/state/pullRequests.ts+++ b/apps/web/src/state/pullRequests.ts@@ -130,8 +130,8 @@ function createMergedEnvironmentQuery<Input, A>((override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {const refreshTargets =override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);- for (const target of refreshTargets) {- appAtomRegistry.refresh(atomFor(target));+ for (const atom of new Set(refreshTargets.map(atomFor))) {+ appAtomRegistry.refresh(atom);}},[key],@@ -173,7 +173,7 @@ export interface MergedPullRequestListView {readonly data: MergedPullRequestList | null;readonly error: string | null;readonly isPending: boolean;- readonly refresh: () => void;+ readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;}/** One listing per environment, merged into the single list the page renders. */diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 6144d8507a9..d0da18a7226 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -75,8 +75,8 @@ export function pullRequestDetailToVcsStatus(}/**- * Every read shells out to the GitHub CLI, so results are reused for a short while and- * refreshed explicitly. Mutations run serially per environment: `gh` actions on the same+ * Reopening a PR within a minute reuses detail and activity. Explicit refreshes and+ * turn notifications still revalidate. Mutations run serially per environment: actions on the same* pull request are order-sensitive, and the detail view refetches after each one.*/export function createPullRequestEnvironmentAtoms<R, E>(@@ -91,7 +91,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(const activity = createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:activity",tag: WS_METHODS.pullRequestsActivity,- staleTimeMs: 15_000,+ staleTimeMs: 60_000,refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),});return {@@ -118,7 +118,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(detail: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:detail",tag: WS_METHODS.pullRequestsDetail,- staleTimeMs: 15_000,+ staleTimeMs: 60_000,refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),}),activity,