TypeScript
fix(web): reuse current PR status in the sidebar (#12545)
oliver9f0c9f725d45
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 9d563d3965c..a0d111bd710 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -3404,6 +3404,67 @@ it.effect("a listing narrowed to some projects is its own cache entry", () =>}),);+it.effect(+ "keeps listing freshness tied to read start when filtered reads finish out of order",+ () =>+ Effect.gen(function* () {+ const olderStarted = yield* Deferred.make<void>();+ const releaseOlder = yield* Deferred.make<void>();+ let reads = 0;+ const updatedAt = "2026-07-02T00:00:00Z";+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),+ ],+ providers: [+ fakeProvider("github", {+ listChangeRequests: ({ filters }) =>+ Effect.gen(function* () {+ reads += 1;+ const older = filters?.checks === "failing";+ if (older) {+ yield* Deferred.succeed(olderStarted, undefined);+ yield* Deferred.await(releaseOlder);+ }+ return {+ items: [+ {+ ...changeRequest(1, updatedAt),+ checksState: older ? ("failing" as const) : ("passing" as const),+ mergeability: older ? ("mergeable" as const) : ("conflicting" as const),+ },+ ],+ truncated: false,+ continues: false,+ };+ }),+ }),+ ],+ });+ const olderInput = { state: "open" as const, filters: { checks: "failing" as const } };+ const newerInput = { state: "open" as const, filters: { checks: "passing" as const } };++ const olderRead = yield* service.list(olderInput).pipe(Effect.forkChild());+ yield* Deferred.await(olderStarted);+ yield* TestClock.adjust("1 second");+ const newer = yield* service.list(newerInput);+ yield* Deferred.succeed(releaseOlder, undefined);+ const older = yield* Fiber.join(olderRead);++ assert.strictEqual(older.entries[0]?.checksState, "failing");+ assert.strictEqual(older.entries[0]?.mergeability, "mergeable");+ assert.strictEqual(newer.entries[0]?.checksState, "passing");+ assert.strictEqual(newer.entries[0]?.mergeability, "conflicting");+ assert.strictEqual(typeof older.entries[0]?.observedAt, "number");+ assert.strictEqual(typeof newer.entries[0]?.observedAt, "number");+ assert.isBelow(older.entries[0]!.observedAt!, newer.entries[0]!.observedAt!);++ const cachedOlder = yield* service.list(olderInput);+ assert.strictEqual(cachedOlder.entries[0]?.observedAt, older.entries[0]?.observedAt);+ assert.strictEqual(reads, 2);+ }),+);+it.effect("keeps unrelated PRs warm after a mutation, explicit refresh, and project turn", () =>Effect.gen(function* () {const calls: string[] = [];diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex a653ef94c71..6b4b2bd8bfd 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -611,6 +611,12 @@ function withRateLimitBackoff(Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;}+// Capture before the provider read so a slow response keeps its original freshness through caches.+const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {+ const observedAt = yield* Clock.currentTimeMillis;+ return { value: yield* read, observedAt };+});+export const make = Effect.gen(function* () {const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64);const pullRequestRefreshes = yield* SubscriptionRef.make(0);@@ -1076,6 +1082,7 @@ export const make = Effect.gen(function* () {readonly project: SupportedProject;readonly item: ProviderChangeRequest;readonly viewer: string;+ readonly observedAt: number;}): PullRequestListEntry => {const viewer = input.viewer.toLowerCase();return {@@ -1098,6 +1105,7 @@ export const make = Effect.gen(function* () {deletions: input.item.deletions,createdAt: input.item.createdAt,updatedAt: input.item.updatedAt,+ observedAt: input.observedAt,...(input.item.checksState === undefined || input.item.checksState === null? {}: { checksState: input.item.checksState }),@@ -1246,7 +1254,8 @@ export const make = Effect.gen(function* () {}),}).pipe(- Effect.map((page): RepositoryBatch => {+ observeRead,+ Effect.map(({ value: page, observedAt }): RepositoryBatch => {// The boundary instant was asked for inclusively, so the rows already sent at it// come back with the slice. Dropping them here rather than asking for strictly// older is what keeps their neighbours at the same instant from being skipped.@@ -1262,7 +1271,7 @@ export const make = Effect.gen(function* () {key,entries: items.filter((item) => matchesRowFilters(item, input.filters, viewer))- .map((item) => toEntry({ project, item, viewer })),+ .map((item) => toEntry({ project, item, viewer, observedAt })),errors: [],truncated: page.truncated,nextCursor:@@ -1323,7 +1332,8 @@ export const make = Effect.gen(function* () {? {}: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),}).pipe(- Effect.flatMap((page) =>+ observeRead,+ Effect.flatMap(({ value: page, observedAt }) =>Effect.flatMap(Clock.currentTimeMillis, (now) => {const rows = new Map<string, Array<ProviderChangeRequest>>();for (const [key, visibleAt] of searchVisibleAt) {@@ -1384,7 +1394,7 @@ export const make = Effect.gen(function* () {key: project.cursorKey,entries: items.filter((item) => matchesRowFilters(item, input.filters, viewer))- .map((item) => toEntry({ project, item, viewer })),+ .map((item) => toEntry({ project, item, viewer, observedAt })),errors: [],truncated: page.truncated,nextCursor:@@ -1551,7 +1561,8 @@ export const make = Effect.gen(function* () {: project.api.getChangeRequestSummary(providerInput);return read.pipe(Effect.mapError(toPullRequestError("summary")),- Effect.map((changeRequest): PullRequestSummary => ({+ observeRead,+ Effect.map(({ value: changeRequest, observedAt }): PullRequestSummary => ({provider: project.api.kind,projectId: project.project.id,repository: project.repository,@@ -1564,6 +1575,7 @@ export const make = Effect.gen(function* () {closedAt: changeRequest.closedAt ?? null,mergedAt: changeRequest.mergedAt ?? null,updatedAt: changeRequest.updatedAt,+ observedAt,...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),...(changeRequest.additions === undefined@@ -1634,12 +1646,12 @@ export const make = Effect.gen(function* () {host: project.host,number: input.number,})- .pipe(Effect.mapError(toPullRequestError("detail"))),+ .pipe(Effect.mapError(toPullRequestError("detail")), observeRead),viewerOf(project),],{ concurrency: 2 },).pipe(- Effect.map(([changeRequest, viewer]): PullRequestDetail => ({+ Effect.map(([{ value: changeRequest, observedAt }, viewer]): PullRequestDetail => ({provider: project.api.kind,capabilities: project.api.capabilities,projectId: project.project.id,@@ -1664,6 +1676,7 @@ export const make = Effect.gen(function* () {baseBranch: changeRequest.baseBranch,createdAt: changeRequest.createdAt,updatedAt: changeRequest.updatedAt,+ observedAt,mergedAt: changeRequest.mergedAt,closedAt: changeRequest.closedAt,reviewers: changeRequest.reviewers,@@ -2894,12 +2907,14 @@ export const make = Effect.gen(function* () {closedAt: detail.closedAt,mergedAt: detail.mergedAt,updatedAt: detail.updatedAt,+ observedAt: detail.observedAt,});const shouldReplaceHeldSummary = (key: string, next: PullRequestSummary) => {const current = lastGoodSummary.peek(key);if (current === undefined) return true;if (current.state === "merged" && next.state !== "merged") return false;- return next.updatedAt >= current.updatedAt;+ if (next.updatedAt !== current.updatedAt) return next.updatedAt > current.updatedAt;+ return (next.observedAt ?? -Infinity) >= (current.observedAt ?? -Infinity);};const detail: PullRequestService["Service"]["detail"] = (input) => {const key = refCacheKey(input);diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.tsindex 4591ac0437b..05796283b9b 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts@@ -121,6 +121,13 @@ describe("pull request list decoding", () => {{ statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },// Neither a pass, a failure nor a wait is no verdict rather than a green tick.{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },+ // Cancelled reads as failing here and in the detail header, so the two never flap.+ {+ statusCheckRollup: [+ { name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },+ { name: "test", status: "COMPLETED", conclusion: "CANCELLED" },+ ],+ },{ statusCheckRollup: [] },{},]),@@ -132,6 +139,7 @@ describe("pull request list decoding", () => {"passing","failing",null,+ "failing",null,null,]);diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.tsindex a011702d685..8a1434224ad 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts@@ -1447,8 +1447,9 @@ function toCheckEntries(* GitHub's own indicator reads: a run that has already gone red will not go green by finishing.** Null rather than "passing" for a head commit with no checks at all, so a repository that runs- * none shows nothing instead of a green tick it never earned. Checks whose verdict is neither a- * pass, a failure nor a wait — skipped, cancelled, neutral — count towards neither.+ * none shows nothing instead of a green tick it never earned. A cancelled run is a failure, as+ * GitHub's own rollup and the client's detail rollup both read it; skipped and neutral count+ * towards neither, so the row and the detail header never disagree about one head commit.** Counted off the deduped checks rather than the raw rollup, so the word and the list under it* cannot disagree: the run a re-run replaced is not a verdict twice. A row with no name at all is@@ -1463,7 +1464,7 @@ function rollupChecksState(...(raw ?? []).filter(isNamelessCheck).map((check) => toCheckStatus(check)),];if (statuses.length === 0) return null;- if (statuses.includes("failure")) return "failing";+ if (statuses.includes("failure") || statuses.includes("cancelled")) return "failing";if (statuses.includes("pending") || statuses.includes("action-required")) return "pending";return statuses.includes("success") ? "passing" : null;}diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex f234efff093..e1bc3f151fd 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -34,6 +34,7 @@ import {type ReactNode,useCallback,useEffect,+ useMemo,useRef,useState,} from "react";@@ -62,7 +63,11 @@ import { ScrollArea } from "~/components/ui/scroll-area";import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";import { faviconUrlForOrigin } from "~/lib/favicon";import { useTheme } from "~/hooks/useTheme";-import { pullRequestEnvironment } from "~/state/pullRequests";+import {+ newestPullRequestSummary,+ pullRequestEnvironment,+ useSharedPullRequestSummary,+} from "~/state/pullRequests";import { useEnvironmentQuery } from "~/state/query";import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";@@ -800,19 +805,26 @@ function PullRequestSurfaceIcon({},}),).data;+ const reference = useMemo(+ () => ({+ projectId: surface.projectId as ProjectId,+ repository: surface.repository,+ number: surface.number,+ }),+ [surface.projectId, surface.repository, surface.number],+ );+ const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference, null);// The compact tab intentionally shows lifecycle and draft state only. Conflict warnings have// their own presentation on surfaces that have mergeability, while this tab stays stable as// detail data arrives.- const status =- linkedSnapshot !== null- ? linkedSnapshot- : detail === null- ? (seed ?? null)- : { state: detail.state, isDraft: detail.isDraft };+ const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;if (status === null) {return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;}- const presentation = resolvePullRequestState({ state: status.state, isDraft: status.isDraft });+ const presentation = resolvePullRequestState({+ state: status.state,+ isDraft: status.isDraft ?? detail?.isDraft ?? seed?.isDraft ?? false,+ });return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;}diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsxindex 016a2c2e431..5b2945042ac 100644--- a/apps/web/src/components/ThreadStatusIndicators.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.tsx@@ -76,15 +76,24 @@ export function useLinkedThreadPullRequest();const fallback =current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;- const host = fallback == null ? undefined : parseChangeRequestUrl(fallback.url)?.host;- const reference =- fallback == null ? null : { ...fallback, ...(host === undefined ? {} : { host }) };+ // Stable per link: the shared summary effect keys on this object, and a sidebar row must not+ // touch the cache on every render.+ const reference = useMemo(() => {+ if (fallback == null) return null;+ const host = parseChangeRequestUrl(fallback.url)?.host;+ return { ...fallback, ...(host === undefined ? {} : { host }) };+ }, [fallback]);const queried = useEnvironmentQuery(!enabled || environmentId === null || reference === null? null: linkedPullRequestDetailAtom({ environmentId, input: reference }),- ).data;- const detail = useSharedPullRequestSummary(environmentId, reference, queried);+ );+ const detail = useSharedPullRequestSummary(+ environmentId,+ reference,+ queried.data,+ queried.dataUpdatedAt,+ );return useMemo(() => {if (current !== null) return linkedPullRequestSnapshotStatus(current);diff --git a/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsxindex 20100339ecb..e9797016aad 100644--- a/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx+++ b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx@@ -109,6 +109,7 @@ function ChecksBody({export function PullRequestChecksPopover({checksState,checks,+ stale = false,environmentId,reference,threadRef = null,@@ -117,6 +118,7 @@ export function PullRequestChecksPopover({checksState: PullRequestChecksState;/** The checks already in hand, for the detail header. Absent on a listing row. */checks?: ReadonlyArray<PullRequestCheck>;+ stale?: boolean;environmentId?: EnvironmentId;reference?: PullRequestRef;/** Thread the popover sits beside; a listing row has none. */@@ -125,7 +127,7 @@ export function PullRequestChecksPopover({}) {const presentation = pullRequestChecksStatePresentation(checksState);// Counts beat the rollup's own wording where they are known, the way GitHub's own header reads.- const summary = checks === undefined ? null : summarizePullRequestChecks(checks);+ const summary = checks === undefined || stale ? null : summarizePullRequestChecks(checks);return (<Popover>{/* A listing row is itself a button, so the trigger renders as a span: a nested button is@@ -148,7 +150,11 @@ export function PullRequestChecksPopover({<PopoverPopup align="start" className="w-80 max-w-full" side="bottom"><p className="mb-2 font-medium text-sm">{presentation.label}</p>{summary === null ? null : <p className="mb-2 text-muted-foreground text-xs">{summary}</p>}- {checks !== undefined ? (+ {stale ? (+ <p className="text-muted-foreground text-xs">+ Check details are out of date. Refresh the pull request to update them.+ </p>+ ) : checks !== undefined ? (<ChecksBody checks={checks} threadRef={threadRef} />) : environmentId !== undefined && reference !== undefined ? (<LazyChecksBodydiff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsxindex 18320ae3356..884bef0bf0b 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx@@ -41,7 +41,8 @@ vi.mock("~/lib/sourceControlActions", () => ({usePreparePullRequestThreadAction: () => ({ run: prepareThread }),}));vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));-vi.mock("~/state/pullRequests", () => ({+vi.mock("~/state/pullRequests", async (importOriginal) => ({+ ...(await importOriginal<typeof import("~/state/pullRequests")>()),pullRequestEnvironment: { detail: () => "detail", activity: () => "activity" },usePullRequestTurnRefresh: () => 0,useSharedPullRequestSummary: () => null,diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 31d81315c2e..c605409b180 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -78,8 +78,13 @@ import { useProjects, useServerConfigs } from "~/state/entities";import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";import { useEnvironmentQuery } from "~/state/query";import { useLiveRefresh } from "~/hooks/useLiveRefresh";-import { pullRequestEnvironment } from "~/state/pullRequests";-import { usePullRequestTurnRefresh, useSharedPullRequestSummary } from "~/state/pullRequests";+import {+ pullRequestEnvironment,+ pullRequestListEntryToSummary,+ newestPullRequestSummary,+ usePullRequestTurnRefresh,+ useSharedPullRequestSummary,+} from "~/state/pullRequests";import { useAtomCommand } from "~/state/use-atom-command";import { PullRequestStackMenu } from "./PullRequestStackMenu";import { PullRequestThreadLinks } from "./PullRequestThreadLinks";@@ -167,6 +172,7 @@ import {PullRequestMetaLine,PullRequestReviewOutcomeIcon,pullRequestChecksState,+ pullRequestChecksStatePresentation,pullRequestReviewOutcomeToneClassName,resolvePullRequestState,summarizePullRequestChecks,@@ -521,10 +527,11 @@ export function PullRequestDetailPanel({}) {const environmentConfigs = useServerConfigs();const projects = useProjects();- const repositoryIdentity = projects.find(+ const project = projects.find((project) =>project.id === requestedReference.projectId && project.environmentId === environmentId,- )?.repositoryIdentity;+ );+ const repositoryIdentity = project?.repositoryIdentity;const supportsThreadPullRequests =environmentConfigs.get(environmentId)?.environment.capabilities.threadPullRequests === true;const reference = useMemo(@@ -542,6 +549,8 @@ export function PullRequestDetailPanel({const matchingListEntry =listEntry?.projectId === reference.projectId &&listEntry.repository.toLowerCase() === reference.repository.toLowerCase() &&+ (reference.host === undefined ||+ listEntry.host.toLowerCase() === reference.host.toLowerCase()) &&listEntry.number === reference.number? listEntry: null;@@ -675,14 +684,47 @@ export function PullRequestDetailPanel({cached: cachedDetail,reference,});- const sharedSummary = useSharedPullRequestSummary(environmentId, reference, resolvedCoreDetail);+ const listSummary = useMemo(+ () => (matchingListEntry === null ? null : pullRequestListEntryToSummary(matchingListEntry)),+ [matchingListEntry],+ );+ const detailSummary = useMemo(+ () =>+ detailQuery.data === null+ ? null+ : {+ ...detailQuery.data,+ checksState: pullRequestChecksState(detailQuery.data.checks),+ },+ [detailQuery.data],+ );+ const observedSummary = useSharedPullRequestSummary(+ environmentId,+ reference,+ detailSummary,+ detailQuery.dataUpdatedAt,+ );+ // The list row is also published to the shared cache, but only after this commit's layout+ // effects run, so it is compared directly rather than trusted to be there already.+ const sharedSummary = useMemo(+ () =>+ newestPullRequestSummary(+ resolvedCoreDetail,+ newestPullRequestSummary(observedSummary, listSummary),+ ),+ [resolvedCoreDetail, observedSummary, listSummary],+ );const coreDetail = useMemo(() =>resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail? resolvedCoreDetail: {...resolvedCoreDetail,- ...sharedSummary,+ title: sharedSummary.title,+ state: sharedSummary.state,+ headBranch: sharedSummary.headBranch,+ baseBranch: sharedSummary.baseBranch,+ updatedAt: sharedSummary.updatedAt,author: sharedSummary.author ?? resolvedCoreDetail.author,additions: sharedSummary.additions ?? resolvedCoreDetail.additions,deletions: sharedSummary.deletions ?? resolvedCoreDetail.deletions,@@ -720,6 +762,7 @@ export function PullRequestDetailPanel({},[activity, coreDetail],);+ const handoffSummary = detail ?? sharedSummary;const keybindings = useAtomValue(primaryServerKeybindingsAtom);const { copyToClipboard: copyReference } = useCopyToClipboard<string>({target: "pull request reference",@@ -945,9 +988,11 @@ export function PullRequestDetailPanel({const acting =pickableEnvironments.find((entry) => entry.environmentId === chosenEnvironmentId) ?? null;const actingEnvironmentId = acting?.environmentId ?? environmentId;+ const checkoutRoot =+ acting?.workspaceRoot ?? detail?.workspaceRoot ?? project?.workspaceRoot ?? null;const prepareThread = usePreparePullRequestThreadAction({environmentId: actingEnvironmentId,- cwd: acting?.workspaceRoot ?? detail?.workspaceRoot ?? null,+ cwd: checkoutRoot,});const finishAction = async (@@ -1178,7 +1223,7 @@ export function PullRequestDetailPanel({// already work — and it moves the branch under everything else that is open there.mode: "worktree" | "local" = "worktree",) => {- if (!detail || handoff !== null) return;+ if (!handoffSummary || handoff !== null) return;if (attachTarget !== null && task !== null) {writeTaskToComposer(attachTarget, task);toastManager.add({@@ -1188,6 +1233,7 @@ export function PullRequestDetailPanel({});return;}+ if (checkoutRoot === null) return;setHandoff(kind);// The menu closes on the press and takes its "Preparing..." label with it, so this is the// only thing answering for the checkout. It carries no timeout of its own: a loading toast@@ -1198,7 +1244,10 @@ export function PullRequestDetailPanel({});// Wherever the reader chose to act: the thread, the checkout it is pointed at and the composer// the task lands in are all one server's, and picking another one moves all three.- const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);+ const projectRef = scopeProjectRef(+ actingEnvironmentId,+ acting?.projectId ?? handoffSummary.projectId,+ );// The thread is opened before the checkout rather than after it, because the project's setup// script only runs for a checkout that knows which thread it is for — and a worktree with no// dependencies installed is not something anyone can test.@@ -1219,7 +1268,7 @@ export function PullRequestDetailPanel({return;}const prepared = await prepareThread.run({- reference: detail.url,+ reference: handoffSummary.url,mode,threadId: opened.threadId,});@@ -1348,7 +1397,7 @@ export function PullRequestDetailPanel({};const startCheckout = (mode: "worktree" | "local") => {- if (!detail) return;+ if (!handoffSummary) return;void startHandoff(`checkout:${mode}`, null, mode);};@@ -1380,20 +1429,20 @@ export function PullRequestDetailPanel({baseBranch: detail.baseBranch,reviewThreads: detail.reviewThreads,comments: detail.comments,- checks: detail.checks,+ checks: checksStale ? [] : detail.checks,commentsTruncated: detail.commentsTruncated,}),);};const startResolveConflicts = () => {- if (!detail) return;+ if (!handoffSummary) return;void startHandoff("conflicts", {prompt: buildResolveConflictsPrompt({- number: detail.number,- url: detail.url,- headBranch: detail.headBranch,- baseBranch: detail.baseBranch,+ number: handoffSummary.number,+ url: handoffSummary.url,+ headBranch: handoffSummary.headBranch,+ baseBranch: handoffSummary.baseBranch,}),});};@@ -1443,7 +1492,17 @@ export function PullRequestDetailPanel({const can = (action: PullRequestAction) =>detail?.capabilities.actions.includes(action) === true &&detail.viewerPermissions.actions.includes(action);- const checksState = detail ? pullRequestChecksState(detail.checks) : null;+ const detailChecksState = detail ? pullRequestChecksState(detail.checks) : null;+ const latestChecksState =+ sharedSummary?.checksState === undefined ? detailChecksState : sharedSummary.checksState;+ // List rollups can omit workflows awaiting approval. Only refreshed detail can clear those.+ const checksState =+ latestChecksState !== "failing" &&+ detail?.checks.some((check) => check.status === "action-required")+ ? "pending"+ : latestChecksState;+ // A newer rollup cannot tell us which runs changed or how many passed.+ const checksStale = checksState !== detailChecksState;// The merge state remains in one stable slot from waiting through completion. Conflicts take// the slot while they need a person; the armed badge remains beside them so that state is not lost.const primaryAction = detail@@ -1494,7 +1553,13 @@ export function PullRequestDetailPanel({const statePresentation = detail? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft }): null;- const checksSummary = detail ? summarizePullRequestChecks(detail.checks) : null;+ const checksSummary = checksStale+ ? checksState === null+ ? "No checks reported"+ : pullRequestChecksStatePresentation(checksState).label+ : detail+ ? summarizePullRequestChecks(detail.checks)+ : null;// Approvals that still stand, and only those. A superseded one is dimmed beside the reviewer// who gave it, so counting it here would have the header assert in a number what the row next// to it has just qualified.@@ -1509,10 +1574,108 @@ export function PullRequestDetailPanel({).length: 0;+ const checkoutControl =+ context === "page" ? (+ <Menu>+ <Tooltip>+ <TooltipTrigger+ render={+ <MenuTrigger+ disabled={handoff !== null || checkoutRoot === null}+ render={+ <Button+ size="xs"+ variant="outline"+ aria-label={handoff?.startsWith("checkout") ? "Checking out..." : "Check out"}+ >+ <GitBranchIcon aria-hidden className="size-3.5" />+ <span className="@max-[35rem]/pr-header:hidden">+ {handoff?.startsWith("checkout") ? "Checking out..." : "Check out"}+ </span>+ <ChevronDownIcon aria-hidden className="size-3.5 text-muted-foreground" />+ </Button>+ }+ />+ }+ />+ <TooltipPopup>Check out this pull request</TooltipPopup>+ </Tooltip>+ <MenuPopup align="end" side="bottom" className="min-w-72">+ <MenuItem onClick={() => startCheckout("worktree")}>+ <GitBranchIcon className="mt-1 size-3.5 shrink-0 self-start" />+ <span className="flex min-w-0 flex-col">+ <span>In a separate worktree</span>+ <span className="text-xs text-muted-foreground">+ Its own folder and thread. Nothing you have open moves.+ </span>+ </span>+ </MenuItem>+ <MenuItem onClick={() => startCheckout("local")}>+ <FolderGit2Icon className="mt-1 size-3.5 shrink-0 self-start" />+ <span className="flex min-w-0 flex-col">+ <span>In this repository</span>+ <span className="text-xs text-muted-foreground">+ Switches the branch you are working in, like `gh pr checkout`.+ </span>+ </span>+ </MenuItem>+ {pickableEnvironments.length > 0 ? (+ <ActOnEnvironmentPicker+ environments={pickableEnvironments}+ value={actingEnvironmentId}+ onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}+ disabled={handoff !== null}+ />+ ) : null}+ </MenuPopup>+ </Menu>+ ) : null;++ const resolveConflictsControl = (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="inline-flex shrink-0">+ <Button+ size="xs"+ variant="destructive-outline"+ disabled={handoff !== null || (attachTarget === null && checkoutRoot === null)}+ onClick={startResolveConflicts}+ aria-label={handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"}+ >+ <PullRequestGlyph.conflicting aria-hidden className="size-3.5" />+ <span className="@max-[30rem]/pr-header:hidden">+ {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"}+ </span>+ </Button>+ </span>+ }+ />+ <TooltipPopup side="top">+ {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"}+ </TooltipPopup>+ </Tooltip>+ );+// The list already has the pull request's identity and summary. Keep them on screen// and let the richer detail read replace the remaining placeholders in place.if (detailQuery.isPending && !detail) {- return <PullRequestDetailGhost seed={matchingListEntry} />;+ return (+ <PullRequestDetailGhost+ seed={matchingListEntry}+ summary={sharedSummary}+ actions={+ handoffSummary ? (+ <TooltipProvider delay={150} closeDelay={150} timeout={400}>+ {checkoutControl}+ {handoffSummary.state === "open" && handoffSummary.mergeability === "conflicting"+ ? resolveConflictsControl+ : null}+ </TooltipProvider>+ ) : undefined+ }+ />+ );}return (@@ -1720,71 +1883,7 @@ export function PullRequestDetailPanel({threadRef={null}/>) : null}- {/* Checking a pull request out is the reason to open one here at all, so it is a- button of its own rather than a side effect of asking an agent for something.- It asks where, because the two answers are not interchangeable: one leaves your- work where it is, the other moves the repository you are standing in. Only on- the page: beside a thread the branch is already checked out right there. */}- {context === "page" ? (- <Menu>- <Tooltip>- <TooltipTrigger- render={- <MenuTrigger- disabled={handoff !== null}- render={- <Button- size="xs"- variant="outline"- aria-label={- handoff?.startsWith("checkout") ? "Checking out..." : "Check out"- }- >- <GitBranchIcon aria-hidden className="size-3.5" />- <span className="@max-[35rem]/pr-header:hidden">- {handoff?.startsWith("checkout") ? "Checking out..." : "Check out"}- </span>- <ChevronDownIcon- aria-hidden- className="size-3.5 text-muted-foreground"- />- </Button>- }- />- }- />- <TooltipPopup>Check out this pull request</TooltipPopup>- </Tooltip>- <MenuPopup align="end" side="bottom" className="min-w-72">- <MenuItem onClick={() => startCheckout("worktree")}>- <GitBranchIcon className="mt-1 size-3.5 shrink-0 self-start" />- <span className="flex min-w-0 flex-col">- <span>In a separate worktree</span>- <span className="text-xs text-muted-foreground">- Its own folder and thread. Nothing you have open moves.- </span>- </span>- </MenuItem>- <MenuItem onClick={() => startCheckout("local")}>- <FolderGit2Icon className="mt-1 size-3.5 shrink-0 self-start" />- <span className="flex min-w-0 flex-col">- <span>In this repository</span>- <span className="text-xs text-muted-foreground">- Switches the branch you are working in, like `gh pr checkout`.- </span>- </span>- </MenuItem>- {pickableEnvironments.length > 0 ? (- <ActOnEnvironmentPicker- environments={pickableEnvironments}- value={actingEnvironmentId}- onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}- disabled={handoff !== null}- />- ) : null}- </MenuPopup>- </Menu>- ) : null}+ {checkoutControl}{/* Said where the Merge button is, because it is the answer to why nobody haspressed it: the merge is already asked for, and the host is holding it. */}{autoMergeArmed && primaryAction !== "auto-merge-armed" ? (@@ -1809,31 +1908,7 @@ export function PullRequestDetailPanel({</Tooltip>) : null}{primaryAction === "resolve" ? (- <Tooltip>- <TooltipTrigger- render={- <span className="inline-flex shrink-0">- <Button- size="xs"- variant="destructive-outline"- disabled={handoff !== null}- onClick={startResolveConflicts}- aria-label={- handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"- }- >- <PullRequestGlyph.conflicting aria-hidden className="size-3.5" />- <span className="@max-[30rem]/pr-header:hidden">- {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"}- </span>- </Button>- </span>- }- />- <TooltipPopup side="top">- {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts"}- </TooltipPopup>- </Tooltip>+ resolveConflictsControl) : primaryAction === "ready" ? (<Tooltip><TooltipTrigger@@ -2474,7 +2549,7 @@ export function PullRequestDetailPanel({</ToggleGroup>{tab === "summary" ? (<span className="ml-auto inline-flex shrink-0 items-center">- {workflowApprovalsRequired > 0 && can("approve-workflows") ? (+ {workflowApprovalsRequired > 0 && !checksStale && can("approve-workflows") ? (<Tooltip><TooltipTriggerrender={@@ -2516,6 +2591,7 @@ export function PullRequestDetailPanel({{checksState !== null ? (<PullRequestChecksPopoverchecks={detail.checks}+ stale={checksStale}checksState={checksState}threadRef={threadRef}/>@@ -2649,12 +2725,14 @@ export function PullRequestDetailPanel({reference={reference}detail={detail}activityPending={activityPending}+ checksStale={checksStale}activityError={activityError}pendingFinding={handoff}fixFindingLabel={handoffLabels.fixFinding}fixCheckLabel={handoffLabels.fixCheck}onFixFinding={startFixFinding}onRefresh={refreshDetail}+ onRefreshChecks={refreshFromHost}/></div>) : null}diff --git a/apps/web/src/components/pullRequest/PullRequestGhosts.tsx b/apps/web/src/components/pullRequest/PullRequestGhosts.tsxindex f8c92235654..c82129df13b 100644--- a/apps/web/src/components/pullRequest/PullRequestGhosts.tsx+++ b/apps/web/src/components/pullRequest/PullRequestGhosts.tsx@@ -7,8 +7,9 @@* both themes) and the single `animate-skeleton` pulse, applied once on the container so any* number of bars costs one opacity animation.*/-import type { PullRequestListEntry } from "@t3tools/contracts";+import type { PullRequestListEntry, PullRequestSummary } from "@t3tools/contracts";import { ArrowLeftIcon } from "lucide-react";+import type { ReactNode } from "react";import { cn } from "~/lib/utils";import { formatRelativeTimeLabel } from "~/timestampFormat";@@ -72,16 +73,33 @@ export function PullRequestListGhost({* boundaries in the ghost prevents the loaded pull request from replacing one layout with* another a moment later.*/-export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry | null }) {+export function PullRequestDetailGhost({+ seed: entry,+ summary,+ actions,+}: {+ seed?: PullRequestListEntry | null;+ summary?: PullRequestSummary | null;+ actions?: ReactNode;+}) {+ const seed = summary+ ? {+ ...entry,+ ...summary,+ isDraft: summary.isDraft ?? entry?.isDraft,+ }+ : entry;const statePresentation = seed? resolvePullRequestState({state: seed.state,- isDraft: seed.isDraft,+ isDraft: seed.isDraft ?? false,}): null;- const checksPresentation = seed?.checksState- ? pullRequestChecksStatePresentation(seed.checksState)- : null;+ // Passing list rollups can omit workflows awaiting approval; wait for detail to claim success.+ const checksPresentation =+ seed?.checksState === "failing" || seed?.checksState === "pending"+ ? pullRequestChecksStatePresentation(seed.checksState)+ : null;return (<div@@ -92,7 +110,7 @@ export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry |!seed && "motion-safe:animate-skeleton",)}>- <div className="shrink-0 border-b border-border/60">+ <div className="@container/pr-header shrink-0 border-b border-border/60"><div className="flex h-7 items-center justify-between gap-3 px-4"><div className="flex min-w-0 flex-1 items-center gap-1.5">{seed && statePresentation ? (@@ -114,8 +132,8 @@ export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry |)}</div><div className="flex shrink-0 items-center gap-1">- <GhostBar className="h-5 w-16 rounded-md" />- <GhostBar className="size-5 rounded-md" />+ {actions ?? <GhostBar className="h-5 w-16 rounded-md" />}+ <GhostBar className="size-6 rounded-md" /></div></div>@@ -129,7 +147,7 @@ export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry |{seed ? (<><PullRequestActorLabel- actor={seed.author}+ actor={seed.author ?? null}className="font-medium"tooltip={false}/>@@ -165,8 +183,8 @@ export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry |<GhostBar className="w-10" />{seed ? (<PullRequestDiffStat- additions={seed.additions}- deletions={seed.deletions}+ additions={seed.additions ?? 0}+ deletions={seed.deletions ?? 0}className="font-mono text-xs"/>) : (@@ -217,7 +235,7 @@ export function PullRequestDetailGhost({ seed }: { seed?: PullRequestListEntry |<GhostBar className="w-10" /></div><div className="flex items-center gap-1">- {seed ? (+ {seed?.labels ? (seed.labels.slice(0, 3).map((label) => {const color = pullRequestLabelColor(label.color);return (diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsxindex e89b38c28e1..b2096c87ded 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx@@ -461,18 +461,21 @@ export function PullRequestSummaryTab({reference,detail,activityPending,+ checksStale = false,activityError,pendingFinding,fixFindingLabel = "Fix in a thread",fixCheckLabel = "Fix",onFixFinding,onRefresh,+ onRefreshChecks = onRefresh,}: {environmentId: EnvironmentId;threadRef: ScopedThreadRef | null;reference: PullRequestRef;detail: PullRequestDetailView;activityPending: boolean;+ checksStale?: boolean;activityError: string | null;/** The hand-off currently preparing, if any, so only the finding it belongs to says so. */pendingFinding?: string | null;@@ -480,6 +483,7 @@ export function PullRequestSummaryTab({fixCheckLabel?: string;onFixFinding?: (finding: PullRequestFinding) => void;onRefresh: () => void;+ onRefreshChecks?: () => void;}) {// Keyed by the pull request, so opening another one starts at the end of its conversation// rather than wherever the last one had been read back to.@@ -872,7 +876,14 @@ export function PullRequestSummaryTab({</Section><Section key={`checks:${detail.url}`} title="Checks" defaultOpen={false}>- {detail.checks.length === 0 ? (+ {checksStale ? (+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <span>Check details are out of date.</span>+ <Button size="xs" variant="ghost" onClick={onRefreshChecks}>+ Refresh+ </Button>+ </div>+ ) : detail.checks.length === 0 ? (<p className="text-xs text-muted-foreground">No checks reported.</p>) : (detail.checks.map((check, index) => {diff --git a/apps/web/src/state/pullRequests.test.ts b/apps/web/src/state/pullRequests.test.tsnew file mode 100644index 00000000000..48ee5b51b88--- /dev/null+++ b/apps/web/src/state/pullRequests.test.ts@@ -0,0 +1,83 @@+import { ProjectId, type PullRequestSummary } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { newestPullRequestObservation, newestPullRequestSummary } from "./pullRequests";++function summary(overrides: Partial<PullRequestSummary> = {}): PullRequestSummary {+ return {+ provider: "github",+ projectId: ProjectId.make("pull-request-cache-test"),+ repository: "acme/widget",+ number: 7,+ title: "Improve widget",+ url: "https://github.com/acme/widget/pull/7",+ state: "open",+ isDraft: false,+ headBranch: "improve-widget",+ baseBranch: "main",+ updatedAt: "2026-09-10T00:00:00Z",+ author: { login: "oliver", name: null, avatarUrl: null },+ mergeability: "mergeable",+ checksState: "passing",+ ...overrides,+ };+}++const observed = (value: PullRequestSummary, observedAt: number) => ({+ summary: value,+ observedAt,+});++describe("pull request summary cache", () => {+ it("orders same-dated snapshots by the server's read time, not by arrival", () => {+ const stale = observed(summary({ observedAt: 200 }), 500);+ const held = observed(+ summary({ mergeability: "conflicting", checksState: "failing", observedAt: 300 }),+ 100,+ );+ expect(newestPullRequestObservation(stale, held)?.summary).toMatchObject({+ mergeability: "conflicting",+ checksState: "failing",+ observedAt: 300,+ });+ // An older filtered or server-cached response finishing last must not roll status back.+ expect(newestPullRequestObservation(held, stale)).toBe(held);+ // The same read seen again is not a new observation.+ expect(newestPullRequestObservation(held, { ...held, observedAt: 900 })).toBe(held);+ });++ it("uses arrival order only when neither snapshot carries a server read time", () => {+ const first = observed(summary(), 100);+ const later = observed(summary({ checksState: "failing" }), 200);+ expect(newestPullRequestObservation(first, later)).toMatchObject({ observedAt: 200 });+ expect(newestPullRequestObservation(later, first)).toBe(later);+ // A stamped read beats an unstamped one regardless of which arrived last.+ const stamped = observed(summary({ observedAt: 50 }), 1);+ expect(newestPullRequestObservation(later, stamped)?.summary.observedAt).toBe(50);+ expect(newestPullRequestObservation(stamped, later)).toBe(stamped);+ });++ it("keeps known status when a newer snapshot omits it, and clears it when told to", () => {+ const list = observed(summary({ reviewDecision: "approved", observedAt: 100 }), 100);+ const sparse = observed(+ summary({ checksState: undefined, reviewDecision: undefined, observedAt: 200 }),+ 200,+ );+ expect(newestPullRequestObservation(list, sparse)?.summary).toMatchObject({+ checksState: "passing",+ reviewDecision: "approved",+ });+ const cleared = observed(summary({ checksState: null, observedAt: 300 }), 300);+ expect(newestPullRequestObservation(list, cleared)?.summary.checksState).toBeNull();+ });++ it("treats merged as final and otherwise prefers the later host update", () => {+ const merged = summary({ state: "merged", updatedAt: "2026-09-01T00:00:00Z" });+ const reopened = summary({ updatedAt: "2026-09-12T00:00:00Z", observedAt: 900 });+ expect(newestPullRequestSummary(merged, reopened)).toBe(merged);+ expect(newestPullRequestSummary(reopened, merged)).toBe(merged);+ const older = summary({ updatedAt: "2026-09-11T00:00:00Z", observedAt: 999 });+ expect(newestPullRequestSummary(older, reopened)).toBe(reopened);+ expect(newestPullRequestSummary(reopened, older)).toBe(reopened);+ });+});diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.tsindex e2e840c89c4..365c6812d09 100644--- a/apps/web/src/state/pullRequests.ts+++ b/apps/web/src/state/pullRequests.ts@@ -8,6 +8,7 @@ import type {EnvironmentId,PullRequestListInput,PullRequestListStatsInput,+ PullRequestListEntry,PullRequestRef,PullRequestSummary,} from "@t3tools/contracts";@@ -30,49 +31,147 @@ export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFampullRequestEnvironment.refreshes,);+export interface ObservedPullRequestSummary {+ readonly summary: PullRequestSummary;+ /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */+ readonly observedAt: number;+}+const observedPullRequestSummaryAtom = Atom.family((key: string) =>- Atom.make<PullRequestSummary | null>(null).pipe(+ Atom.make<ObservedPullRequestSummary | null>(null).pipe(Atom.setIdleTTL(5 * 60_000),Atom.withLabel(`web-pull-requests:observed-summary:${key}`),),);+/**+ * Positive when `incoming` is the newer snapshot. Merged is final. Then the host's own update+ * time, then the server's read-start time, which survives its caches; a snapshot without one+ * never beats a stamped read. Zero when neither side carries a read time.+ */+function compareSummaries(current: PullRequestSummary, incoming: PullRequestSummary): number {+ const merged = Number(incoming.state === "merged") - Number(current.state === "merged");+ if (merged !== 0) return merged;+ const updated = Date.parse(incoming.updatedAt) - Date.parse(current.updatedAt);+ if (updated !== 0) return updated;+ if (current.observedAt === undefined && incoming.observedAt === undefined) return 0;+ return (incoming.observedAt ?? -Infinity) - (current.observedAt ?? -Infinity);+}+export function newestPullRequestSummary(current: PullRequestSummary | null,observed: PullRequestSummary | null,): PullRequestSummary | null {if (current === null) return observed;if (observed === null) return current;- if (current.state === "merged") return current;- if (observed.state === "merged") return observed;- return Date.parse(observed.updatedAt) >= Date.parse(current.updatedAt) ? observed : current;+ return compareSummaries(current, observed) >= 0 ? observed : current;+}++/** Reuse list status without treating its deferred line-count placeholders as real stats. */+export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {+ return {+ provider: entry.provider,+ projectId: entry.projectId,+ repository: entry.repository,+ number: entry.number,+ title: entry.title,+ url: entry.url,+ state: entry.state,+ isDraft: entry.isDraft,+ headBranch: entry.headBranch,+ baseBranch: entry.baseBranch,+ updatedAt: entry.updatedAt,+ ...(entry.observedAt === undefined ? {} : { observedAt: entry.observedAt }),+ author: entry.author,+ ...(entry.reviewDecision === undefined ? {} : { reviewDecision: entry.reviewDecision }),+ ...(entry.checksState === undefined ? {} : { checksState: entry.checksState }),+ mergeability: entry.mergeability,+ };+}++// A project has one remote, so its id already pins the host. Leaving the host out lets a list+// row, a hostless legacy reference and a URL-derived thread reference share one entry.+function pullRequestSummaryKey(environmentId: EnvironmentId, reference: PullRequestRef): string {+ return JSON.stringify([+ environmentId,+ reference.projectId,+ reference.repository.toLowerCase(),+ reference.number,+ ]);+}++/** The observation to hold after `incoming` arrives. Returns `current` itself on a tie. */+export function newestPullRequestObservation(+ current: ObservedPullRequestSummary | null,+ incoming: ObservedPullRequestSummary | null,+): ObservedPullRequestSummary | null {+ if (current === null) return incoming;+ if (incoming === null) return current;+ let order = compareSummaries(current.summary, incoming.summary);+ // Client clocks only break ties between snapshots that both lack a server read time.+ if (+ order === 0 &&+ current.summary.observedAt === undefined &&+ incoming.summary.observedAt === undefined+ ) {+ order = incoming.observedAt - current.observedAt;+ }+ if (!(order > 0)) return current;+ // A sparse summary must not erase known status, or carry old detail stats into a new list read.+ return {+ ...incoming,+ summary: {+ ...incoming.summary,+ isDraft: incoming.summary.isDraft ?? current.summary.isDraft,+ mergeability: incoming.summary.mergeability ?? current.summary.mergeability,+ reviewDecision:+ incoming.summary.reviewDecision === undefined+ ? current.summary.reviewDecision+ : incoming.summary.reviewDecision,+ checksState:+ incoming.summary.checksState === undefined+ ? current.summary.checksState+ : incoming.summary.checksState,+ },+ };+}++function observePullRequestSummary(+ environmentId: EnvironmentId,+ reference: PullRequestRef,+ summary: PullRequestSummary,+ observedAt: number,+): void {+ const atom = observedPullRequestSummaryAtom(pullRequestSummaryKey(environmentId, reference));+ appAtomRegistry.modify(atom, (previous) => {+ const next = newestPullRequestObservation(previous, { summary, observedAt });+ return next === previous ? [false, previous] : [true, next];+ });}export function useSharedPullRequestSummary(environmentId: EnvironmentId | null,reference: PullRequestRef | null,current: PullRequestSummary | null,+ observedAt: number | null = null,): PullRequestSummary | null {const key =environmentId === null || reference === null? "none"- : JSON.stringify([- environmentId,- reference.projectId,- reference.host?.toLowerCase() ?? null,- reference.repository.toLowerCase(),- reference.number,- ]);+ : pullRequestSummaryKey(environmentId, reference);const atom = observedPullRequestSummaryAtom(key);const observed = useAtomValue(atom);useLayoutEffect(() => {- if (environmentId === null || current === null) return;- appAtomRegistry.modify(atom, (previous) => {- const next = newestPullRequestSummary(previous, current);- return next === previous ? [false, previous] : [true, next];- });- }, [atom, current, environmentId]);- return newestPullRequestSummary(current, observed);+ if (environmentId === null || reference === null || current === null || observedAt === null)+ return;+ observePullRequestSummary(environmentId, reference, current, observedAt);+ }, [current, environmentId, reference, observedAt]);+ return (+ newestPullRequestObservation(+ observed,+ current === null || observedAt === null ? null : { summary: current, observedAt },+ )?.summary ?? current+ );}export const pullRequestStackAtom = createPullRequestStackAtomFamily(connectionAtomRuntime,@@ -90,6 +189,7 @@ interface MergedEnvironmentQueryView<A> {/** The first environment that failed. Others may still have answered — this is not fatal. */readonly error: string | null;readonly isPending: boolean;+ readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;}/**@@ -110,6 +210,7 @@ function createMergedEnvironmentQuery<Input, A>(Atom.make((get): MergedEnvironmentQueryView<A> => {const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;const values: Array<readonly [EnvironmentId, A]> = [];+ const observations: Array<readonly [EnvironmentId, A, number]> = [];let error: string | null = null;let isPending = false;for (const target of targets) {@@ -120,12 +221,16 @@ function createMergedEnvironmentQuery<Input, A>(}const value = Option.getOrNull(AsyncResult.value(result));if (value !== null) values.push([target.environmentId, value]);+ if (result._tag === "Success") {+ observations.push([target.environmentId, result.value, result.timestamp]);+ }}- return { values, error, isPending };+ return { values, error, isPending, observations };}).pipe(Atom.withLabel(`${label}:${key}`)),);const empty = Atom.make<MergedEnvironmentQueryView<A>>({values: [],+ observations: [],error: null,isPending: false,}).pipe(Atom.withLabel(`${label}:empty`));@@ -187,6 +292,23 @@ export function usePullRequestList(targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,): MergedPullRequestListView {const query = usePullRequestListsQuery(targets);+ useLayoutEffect(() => {+ for (const [environmentId, answer, observedAt] of query.observations) {+ for (const entry of answer.entries) {+ observePullRequestSummary(+ environmentId,+ {+ projectId: entry.projectId,+ host: entry.host,+ repository: entry.repository,+ number: entry.number,+ },+ pullRequestListEntryToSummary(entry),+ observedAt,+ );+ }+ }+ }, [query.observations]);const data = useMemo(() => mergePullRequestLists(query.values), [query.values]);return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };}diff --git a/apps/web/src/state/query.ts b/apps/web/src/state/query.tsindex b2823a51e33..f5cb765a247 100644--- a/apps/web/src/state/query.ts+++ b/apps/web/src/state/query.ts@@ -9,6 +9,7 @@ const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(falsexport interface EnvironmentQueryView<A> {readonly data: A | null;+ readonly dataUpdatedAt: number | null;readonly error: string | null;readonly isPending: boolean;readonly isSuccess: boolean;@@ -30,6 +31,7 @@ export function useEnvironmentQuery<A, E>(const refresh = useAtomRefresh(selectedAtom);return {data: Option.getOrNull(AsyncResult.value(result)),+ dataUpdatedAt: result._tag === "Success" ? result.timestamp : null,error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,isPending: atom !== null && result.waiting,isSuccess: result._tag === "Success",diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex b146810a8ae..1a3c2d50b20 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -525,6 +525,8 @@ export const PullRequestListEntry = Schema.Struct({deletions: NonNegativeInt,createdAt: IsoDateTime,updatedAt: IsoDateTime,+ /** Server epoch milliseconds when the provider read started; preserved on cache hits. */+ observedAt: Schema.optional(Schema.Finite),viewerReviewRequested: Schema.Boolean,labels: Schema.Array(PullRequestLabel),/** Absent where the host does not summarise its reviews, which is every host but GitHub. */@@ -736,6 +738,8 @@ export const PullRequestSummary = Schema.Struct({closedAt: Schema.optional(Schema.NullOr(Schema.String)),mergedAt: Schema.optional(Schema.NullOr(Schema.String)),updatedAt: IsoDateTime,+ /** Server epoch milliseconds when the provider read started; preserved on cache hits. */+ observedAt: Schema.optional(Schema.Finite),author: Schema.optional(Schema.NullOr(PullRequestActor)),additions: Schema.optional(NonNegativeInt),deletions: Schema.optional(NonNegativeInt),@@ -841,6 +845,8 @@ export const PullRequestDetail = Schema.Struct({baseBranch: TrimmedNonEmptyString,createdAt: IsoDateTime,updatedAt: IsoDateTime,+ /** Server epoch milliseconds when the provider read started; preserved on cache hits. */+ observedAt: Schema.optional(Schema.Finite),mergedAt: Schema.NullOr(IsoDateTime),closedAt: Schema.NullOr(IsoDateTime),reviewers: Schema.Array(PullRequestActor),