Skip to content
TypeScript

fix(pull-requests): keep cached PR chrome on reopen (#9294)

mariad897641d738c
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index d688430bdf5..28c44e8d1b2 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -1,4 +1,5 @@
import { assert, it } from "@effect/vitest";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
@@ -77,6 +78,27 @@ function changeRequest(number: number, updatedAt: string): ProviderChangeRequest
};
}
+function hostedChangeRequest(body: string, additions = 1) {
+ return {
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ body,
+ additions,
+ changedFiles: 2,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ mergeCapabilities: { merge: true, squash: true, rebase: true },
+ viewerPermissions: {
+ actions: ["merge"] as const,
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"] as const,
+ requestReviewers: true,
+ },
+ };
+}
+
function unusable(provider: SourceControlProviderKind, reason: "missing-tool" | "unauthenticated") {
return new PullRequestProviderError({
provider,
@@ -2934,7 +2956,7 @@ it.effect(
}),
);
-it.effect("shares linked summaries and only recovers transient failures for display reads", () =>
+it.effect("shares linked summaries and reuses them for display without asking the host again", () =>
Effect.gen(function* () {
let calls = 0;
let failing = false;
@@ -2984,7 +3006,8 @@ it.effect("shares linked summaries and only recovers transient failures for disp
const stale = yield* service.summary(reference);
assert.strictEqual(stale.updatedAt, "2026-07-02T00:00:00Z");
- assert.strictEqual(calls, 3);
+ // Display reads keep the last title and state rather than asking the host again.
+ assert.strictEqual(calls, 2);
yield* service.invalidate({ reference });
const invalidated = yield* Effect.flip(service.summary(reference));
@@ -2992,6 +3015,151 @@ it.effect("shares linked summaries and only recovers transient failures for disp
}),
);
+it.effect("answers a known pull request immediately while the host refreshes", () =>
+ Effect.gen(function* () {
+ const gate = yield* Deferred.make<void>();
+ let calls = 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.gen(function* () {
+ calls += 1;
+ if (calls > 1) yield* Deferred.await(gate);
+ return hostedChangeRequest("cached body", 4);
+ }),
+ }),
+ ],
+ });
+
+ const first = yield* service.detail(reference);
+ assert.strictEqual(first.body, "cached body");
+ assert.strictEqual(first.additions, 4);
+
+ yield* TestClock.adjust("16 seconds");
+ const second = yield* service.detail(reference);
+ assert.strictEqual(second.body, "cached body");
+ assert.strictEqual(second.additions, 4);
+ yield* Effect.yieldNow;
+ assert.strictEqual(calls, 2);
+ }),
+);
+
+it.effect("does not ask the host again for a linked summary it already holds", () =>
+ Effect.gen(function* () {
+ let calls = 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", {
+ getChangeRequestSummary: () =>
+ Effect.sync(() => {
+ calls += 1;
+ return changeRequest(1, "2026-07-02T00:00:00Z");
+ }),
+ }),
+ ],
+ });
+
+ const first = yield* service.summary(reference);
+ assert.strictEqual(first.title, "Change request 1");
+ yield* TestClock.adjust("61 seconds");
+ const second = yield* service.summary(reference);
+ assert.strictEqual(second.title, "Change request 1");
+ assert.strictEqual(calls, 1);
+ }),
+);
+
+it.effect("does not let a stale detail reopen overwrite a fresher linked summary", () =>
+ Effect.gen(function* () {
+ const gate = yield* Deferred.make<void>();
+ let detailCalls = 0;
+ let summaryTitle = "old title";
+ let summaryState: "open" | "merged" = "open";
+ 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.gen(function* () {
+ detailCalls += 1;
+ if (detailCalls > 1) yield* Deferred.await(gate);
+ return hostedChangeRequest("old body", 4);
+ }),
+ getChangeRequestSummary: () =>
+ Effect.succeed({
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ title: summaryTitle,
+ state: summaryState,
+ }),
+ }),
+ ],
+ });
+
+ const first = yield* service.detail(reference);
+ assert.strictEqual(first.title, "Change request 1");
+
+ summaryTitle = "merged title";
+ summaryState = "merged";
+ yield* TestClock.adjust("61 seconds");
+ const settled = yield* service.summary(reference, { recoverTransientFailure: false });
+ assert.strictEqual(settled.title, "merged title");
+ assert.strictEqual(settled.state, "merged");
+
+ yield* TestClock.adjust("16 seconds");
+ const stale = yield* service.detail(reference);
+ assert.strictEqual(stale.title, "Change request 1");
+ yield* Effect.yieldNow;
+
+ const display = yield* service.summary(reference);
+ assert.strictEqual(display.title, "merged title");
+ assert.strictEqual(display.state, "merged");
+ assert.strictEqual(detailCalls, 2);
+ }),
+);
+
+it.effect("does not let a still-cached detail overwrite a fresher linked summary", () =>
+ Effect.gen(function* () {
+ let summaryTitle = "old title";
+ let summaryState: "open" | "merged" = "open";
+ 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.succeed(hostedChangeRequest("old body", 4)),
+ getChangeRequestSummary: () =>
+ Effect.succeed({
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ title: summaryTitle,
+ state: summaryState,
+ }),
+ }),
+ ],
+ });
+
+ const first = yield* service.detail(reference);
+ assert.strictEqual(first.title, "Change request 1");
+
+ summaryTitle = "merged title";
+ summaryState = "merged";
+ const settled = yield* service.summary(reference, { recoverTransientFailure: false });
+ assert.strictEqual(settled.state, "merged");
+
+ const cached = yield* service.detail(reference);
+ assert.strictEqual(cached.title, "Change request 1");
+ yield* Effect.yieldNow;
+
+ const display = yield* service.summary(reference);
+ assert.strictEqual(display.title, "merged title");
+ assert.strictEqual(display.state, "merged");
+ }),
+);
+
it.effect("keeps recent detail on a transient refresh failure but not after invalidation", () =>
Effect.gen(function* () {
let failing = false;
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index ffa96af12f0..752cdf1aa5e 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -2001,7 +2001,25 @@ export const make = Effect.gen(function* () {
},
}),
);
- return { read, record };
+ /**
+ * A change request already read does not wait on the host again. `reuse` answers from
+ * what we hold and spends nothing — title, author, and state barely move, and a linked
+ * thread already names the change request. `revalidate` answers the same way and
+ * refreshes behind it, so line counts and the rest can change in place.
+ */
+ const serveHeld = (
+ key: string,
+ effect: Effect.Effect<A, PullRequestError>,
+ mode: "reuse" | "revalidate",
+ ) => {
+ const snapshot = held.get(key);
+ if (snapshot === undefined) return read(key, effect);
+ if (mode === "reuse") return Effect.succeed(snapshot.value);
+ return Effect.sync(() => runFork(Effect.ignore(read(key, effect)))).pipe(
+ Effect.as(snapshot.value),
+ );
+ };
+ return { peek: (key: string) => held.get(key)?.value, read, record, serveHeld };
};
const lastGoodSummary = makeLastGoodRead<PullRequestSummary>(DETAIL_CACHE_CAPACITY);
const lastGoodDetail = makeLastGoodRead<PullRequestDetail>(DETAIL_CACHE_CAPACITY);
@@ -2059,7 +2077,7 @@ export const make = Effect.gen(function* () {
const cached = Cache.get(summaryCache, key);
return options?.recoverTransientFailure === false
? cached.pipe(Effect.tap((value) => lastGoodSummary.record(key, value)))
- : lastGoodSummary.read(key, cached);
+ : lastGoodSummary.serveHeld(key, cached, "reuse");
};
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
@@ -2149,9 +2167,42 @@ export const make = Effect.gen(function* () {
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETAIL_CACHE_TTL : Duration.zero),
},
);
+ const summaryFromDetail = (detail: PullRequestDetail): PullRequestSummary => ({
+ provider: detail.provider,
+ projectId: detail.projectId,
+ repository: detail.repository,
+ number: detail.number,
+ title: detail.title,
+ url: detail.url,
+ state: detail.state,
+ headBranch: detail.headBranch,
+ baseBranch: detail.baseBranch,
+ updatedAt: detail.updatedAt,
+ });
+ 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;
+ };
const detail: PullRequestService["Service"]["detail"] = (input) => {
const key = refCacheKey(input);
- return lastGoodDetail.read(key, Cache.get(detailCache, key));
+ // Record the summary from a host or cache read, not the stale value
+ // `serveHeld` returns immediately. Skip the write when that read is older
+ // than a later strict summary — display reuse would otherwise keep the
+ // regression and never ask the host again.
+ return lastGoodDetail.serveHeld(
+ key,
+ Cache.get(detailCache, key).pipe(
+ Effect.tap((value) => {
+ const summary = summaryFromDetail(value);
+ return shouldReplaceHeldSummary(key, summary)
+ ? lastGoodSummary.record(key, summary)
+ : Effect.void;
+ }),
+ ),
+ "revalidate",
+ );
};
const activityCache = yield* Cache.makeWith(
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index a109b161438..5044bddeb78 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -120,10 +120,13 @@ import {
pullRequestFindingKey,
pullRequestHandoffLabels,
readableFailure,
+ readPullRequestDetailSnapshot,
+ resolveDisplayedPullRequestDetail,
resolvePullRequestPrimaryControl,
resolveBaseFreshness,
type PullRequestFinding,
shouldRefreshPullRequestActivity,
+ writePullRequestDetailSnapshot,
} from "./pullRequestDetail.logic";
import { canEditPullRequestChangeRequest } from "./pullRequestEditing.logic";
import {
@@ -558,7 +561,44 @@ export function PullRequestDetailPanel({
const activityQuery = useEnvironmentQuery(
pullRequestEnvironment.activity({ environmentId, input: reference }),
);
- const coreDetail = detailQuery.data;
+ const [cachedDetail, setCachedDetail] = useState(() =>
+ readPullRequestDetailSnapshot(
+ typeof window === "undefined" ? undefined : window.localStorage,
+ environmentId,
+ reference,
+ ),
+ );
+ useEffect(() => {
+ setCachedDetail(
+ readPullRequestDetailSnapshot(
+ typeof window === "undefined" ? undefined : window.localStorage,
+ environmentId,
+ reference,
+ ),
+ );
+ }, [environmentId, pullRequestKey, reference.projectId, reference.repository, reference.number]);
+ useEffect(() => {
+ if (detailQuery.data === null) return;
+ writePullRequestDetailSnapshot(
+ typeof window === "undefined" ? undefined : window.localStorage,
+ environmentId,
+ reference,
+ detailQuery.data,
+ );
+ setCachedDetail(detailQuery.data);
+ }, [
+ detailQuery.data,
+ environmentId,
+ pullRequestKey,
+ reference.projectId,
+ reference.repository,
+ reference.number,
+ ]);
+ const coreDetail = resolveDisplayedPullRequestDetail({
+ live: detailQuery.data,
+ cached: cachedDetail,
+ reference,
+ });
const activity = activityQuery.data;
const detail = useMemo(
() =>
@@ -1240,6 +1280,8 @@ export function PullRequestDetailPanel({
).length
: 0;
+ // A reopen already has last time's title, author, and counts. Keep them on screen
+ // and let the live read replace fields — especially the diff counts — in place.
if (detailQuery.isPending && !detail) {
return <PullRequestDetailGhost />;
}
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
index 348cbd47789..c51429ff6d8 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
@@ -2,6 +2,7 @@ import {
PullRequestAction,
type PullRequestCheck,
type PullRequestComment,
+ type PullRequestDetail,
type PullRequestDetailView,
type PullRequestReviewThread,
} from "@t3tools/contracts";
@@ -31,12 +32,15 @@ import {
pullRequestHandoffLabels,
pullRequestReviewOutcome,
readableFailure,
+ readPullRequestDetailSnapshot,
+ resolveDisplayedPullRequestDetail,
resolvePullRequestPrimaryControl,
shouldRefreshPullRequestActivity,
resolveBaseFreshness,
buildPullRequestTimeline,
describePullRequestState,
editPullRequestThreadComment,
+ writePullRequestDetailSnapshot,
} from "./pullRequestDetail.logic";
import type { ReviewCommentContext } from "~/reviewCommentContext";
@@ -1317,3 +1321,103 @@ describe("which actions need the host read again after they run", () => {
}
});
});
+
+describe("cached pull request detail", () => {
+ const reference = { projectId: "project-1", repository: "acme/web", number: 7 };
+ const detail = (overrides: Partial<PullRequestDetail> = {}): PullRequestDetail =>
+ ({
+ provider: "github",
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge"],
+ mergeMethods: ["merge"],
+ search: true,
+ review: {
+ inlineComment: true,
+ reply: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ },
+ reviewers: { request: true, listCandidates: true },
+ },
+ viewerPermissions: {
+ actions: ["merge"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: true,
+ },
+ projectId: "project-1",
+ projectTitle: "web",
+ workspaceRoot: "/repo",
+ repository: "acme/web",
+ number: 7,
+ title: "Cache the title",
+ body: "who made it",
+ url: "https://github.com/acme/web/pull/7",
+ author: { login: "octocat", name: null, avatarUrl: "https://avatars.example/octocat" },
+ state: "open",
+ isDraft: false,
+ mergeability: "mergeable",
+ additions: 12,
+ deletions: 3,
+ changedFiles: 2,
+ headBranch: "feat/cache",
+ baseBranch: "main",
+ createdAt: "2026-07-01T00:00:00.000Z",
+ updatedAt: "2026-07-02T00:00:00.000Z",
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ labels: [],
+ checks: [],
+ mergeCapabilities: { merge: true, squash: true, rebase: true },
+ ...overrides,
+ }) as PullRequestDetail;
+
+ const makeStorage = () => {
+ const held = new Map<string, string>();
+ return {
+ getItem: (key: string) => held.get(key) ?? null,
+ setItem: (key: string, value: string) => void held.set(key, value),
+ };
+ };
+
+ it("hydrates the last title, author, and counts so a reopen does not ghost the tab", () => {
+ const storage = makeStorage();
+ writePullRequestDetailSnapshot(storage, "env-1", reference, detail());
+ const snapshot = readPullRequestDetailSnapshot(storage, "env-1", reference);
+ expect(snapshot?.title).toBe("Cache the title");
+ expect(snapshot?.author?.login).toBe("octocat");
+ expect(snapshot?.additions).toBe(12);
+ expect(snapshot?.deletions).toBe(3);
+ });
+
+ it("keeps a cached tab painted while the live read replaces the counts", () => {
+ const cached = detail();
+ const live = detail({ additions: 40, deletions: 9, title: "Cache the title" });
+ expect(resolveDisplayedPullRequestDetail({ live, cached, reference })?.additions).toBe(40);
+ expect(resolveDisplayedPullRequestDetail({ live: null, cached, reference })?.additions).toBe(
+ 12,
+ );
+ });
+
+ it("does not paint another change request's snapshot", () => {
+ expect(
+ resolveDisplayedPullRequestDetail({
+ live: null,
+ cached: detail({ number: 8 }),
+ reference,
+ }),
+ ).toBeNull();
+ expect(readPullRequestDetailSnapshot(makeStorage(), "env-2", reference)).toBeNull();
+ });
+
+ it("shrugs off corrupt storage and no storage at all", () => {
+ const storage = makeStorage();
+ storage.setItem("t3.pullRequests.detail:env-1:project-1:acme/web#7", "{not json");
+ expect(readPullRequestDetailSnapshot(storage, "env-1", reference)).toBeNull();
+ expect(readPullRequestDetailSnapshot(undefined, "env-1", reference)).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
index 755bcdf5244..cffe33f8d83 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
@@ -1,19 +1,22 @@
-import type {
- PullRequestAction,
- PullRequestActor,
- PullRequestBaseComparison,
- PullRequestCheck,
- PullRequestChecksState,
- PullRequestComment,
- PullRequestCommit,
- PullRequestDetailView,
- PullRequestMergeability,
- PullRequestReaction,
- PullRequestReviewThread,
- PullRequestState,
- PullRequestUpdateMethod,
- SourceControlProviderKind,
- VcsRef,
+import * as Schema from "effect/Schema";
+
+import {
+ PullRequestDetail,
+ type PullRequestAction,
+ type PullRequestActor,
+ type PullRequestBaseComparison,
+ type PullRequestCheck,
+ type PullRequestChecksState,
+ type PullRequestComment,
+ type PullRequestCommit,
+ type PullRequestDetailView,
+ type PullRequestMergeability,
+ type PullRequestReaction,
+ type PullRequestReviewThread,
+ type PullRequestState,
+ type PullRequestUpdateMethod,
+ type SourceControlProviderKind,
+ type VcsRef,
} from "@t3tools/contracts";
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
@@ -1009,3 +1012,75 @@ const ACTION_NEEDS_HOST_REFRESH: Record<PullRequestAction, boolean> = {
export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): boolean {
return ACTION_NEEDS_HOST_REFRESH[action];
}
+
+type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
+
+export interface PullRequestDetailSnapshotRef {
+ readonly projectId: string;
+ readonly repository: string;
+ readonly number: number;
+}
+
+const pullRequestDetailSnapshotKey = (
+ environmentId: string,
+ reference: PullRequestDetailSnapshotRef,
+) =>
+ `t3.pullRequests.detail:${environmentId}:${reference.projectId}:${reference.repository}#${reference.number}`;
+
+const decodeDetailSnapshot = Schema.decodeUnknownOption(PullRequestDetail);
+
+/**
+ * The last detail answered for this change request, brought back across a reload. The registry
+ * the queries live in is recreated with the renderer, so without this a reopen cold-starts
+ * into a full-tab ghost even though the title, author, and the rest barely moved. Hydrated,
+ * the chrome stays and the live read replaces fields in place — line counts included.
+ */
+export function readPullRequestDetailSnapshot(
+ storage: SnapshotStorage | undefined,
+ environmentId: string,
+ reference: PullRequestDetailSnapshotRef,
+): PullRequestDetail | null {
+ try {
+ const raw = storage?.getItem(pullRequestDetailSnapshotKey(environmentId, reference));
+ if (!raw) return null;
+ const decoded = decodeDetailSnapshot(JSON.parse(raw));
+ return decoded._tag === "Some" ? decoded.value : null;
+ } catch {
+ return null;
+ }
+}
+
+export function writePullRequestDetailSnapshot(
+ storage: SnapshotStorage | undefined,
+ environmentId: string,
+ reference: PullRequestDetailSnapshotRef,
+ detail: PullRequestDetail,
+): void {
+ try {
+ storage?.setItem(
+ pullRequestDetailSnapshotKey(environmentId, reference),
+ JSON.stringify(detail),
+ );
+ } catch {
+ // Quota or a private-mode store: the next open waits on the live read, which is the
+ // cold start this snapshot exists to avoid, not a failure of its own.
+ }
+}
+
+/** Live host state wins; a snapshot is only the same change request, never a neighbour's. */
+export function resolveDisplayedPullRequestDetail(input: {
+ readonly live: PullRequestDetail | null;
+ readonly cached: PullRequestDetail | null;
+ readonly reference: PullRequestDetailSnapshotRef;
+}): PullRequestDetail | null {
+ if (input.live !== null) return input.live;
+ if (
+ input.cached !== null &&
+ input.cached.projectId === input.reference.projectId &&
+ input.cached.repository.toLowerCase() === input.reference.repository.toLowerCase() &&
+ input.cached.number === input.reference.number
+ ) {
+ return input.cached;
+ }
+ return null;
+}