Skip to content
TypeScript

perf(pull-requests): faster pull request timeline, code tab, summary and search (#22697)

maria5d9a5c980347
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index b3984ea1054..ba49df22612 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -2663,6 +2663,9 @@ it.effect("isolates routed caches for two credentials belonging to the same acco
host: "github.com",
expectedAccountId: "101",
};
+ if (operation === "checks") {
+ yield* service.withRoutingCredential(reference, service.detail(reference));
+ }
yield* service.withRoutingCredential(reference, readOperation(reference));
credential = "restricted";
for (const allowStale of [false, true]) {
@@ -2838,6 +2841,48 @@ it.effect("deduplicates routed PR reports without dropping draft changes", () =>
}),
);
+it.effect(
+ "reuses fresh detail checks without extending their refresh interval on detail cache hits",
+ () =>
+ Effect.gen(function* () {
+ let reads = 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: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ getChangeRequest: () => Effect.succeed(hostedChangeRequest("Description")),
+ getChangeRequestChecks: () =>
+ Effect.sync(() => {
+ reads += 1;
+ return { state: "closed" as const, checks: [] };
+ }),
+ }),
+ ],
+ });
+ yield* TestClock.setTime(1_000);
+ const detail = yield* service.detail(reference);
+ expect(yield* service.checks(reference)).toEqual({
+ state: detail.state,
+ checks: detail.checks,
+ observedAt: detail.observedAt,
+ });
+ expect(reads).toBe(0);
+ yield* TestClock.adjust("16 seconds");
+ yield* service.detail(reference);
+ expect(yield* service.checks(reference)).toMatchObject({
+ state: "closed",
+ observedAt: 17_000,
+ });
+ expect(reads).toBe(1);
+ yield* service.detail(reference);
+ expect((yield* service.checks(reference))?.state).toBe("closed");
+ expect(reads).toBe(1);
+ }),
+);
+
it.effect("preserves check observation time on cache hits and advances it on refresh", () =>
Effect.gen(function* () {
let reads = 0;
@@ -4260,7 +4305,7 @@ it.effect.each(["commit", "credential"] as const)(
}),
);
-it.effect.each(["expiry", "refresh"] as const)(
+it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "refresh"] as const)(
"keeps a loaded diff's original membership scope through an in-flight %s",
(boundary) =>
Effect.gen(function* () {
@@ -4284,17 +4329,40 @@ it.effect.each(["expiry", "refresh"] as const)(
nextCursor: null,
};
}),
- getDiffFileContents: () => Effect.die("an expired file must not be read"),
+ getDiffFileContents: () => Effect.succeed({ oldContents: "old", newContents: "new" }),
}),
],
});
- const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const ref = {
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ ...(boundary.includes("commit") ? { commit: "a".repeat(40) } : {}),
+ };
const loading = yield* Effect.forkChild(service.diff(ref));
yield* Deferred.await(started);
if (boundary === "expiry") yield* TestClock.adjust("61 seconds");
+ else if (boundary === "commit expiry") yield* TestClock.adjust("11 minutes");
+ else if (boundary.includes("cache hit")) yield* TestClock.adjust("30 seconds");
else yield* service.invalidate({ reference: ref });
yield* Deferred.succeed(release, undefined);
yield* Fiber.join(loading);
+ if (boundary.includes("cache hit")) {
+ yield* service.diff(ref);
+ yield* service.diff(ref);
+ yield* TestClock.adjust(boundary.includes("commit") ? "9 minutes" : "29 seconds");
+ assert.deepStrictEqual(
+ yield* service.diffFileContents({
+ ...ref,
+ changeType: "change",
+ oldPath: "private.ts",
+ newPath: "private.ts",
+ }),
+ { oldContents: "old", newContents: "new" },
+ );
+ assert.strictEqual(diffReads, 1);
+ yield* TestClock.adjust(boundary.includes("commit") ? "1 minute" : "2 seconds");
+ }
const error = yield* service
.diffFileContents({
...ref,
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index b37cf7d5766..e967b18ef8c 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -141,9 +141,23 @@ const LIST_CACHE_CAPACITY = 64;
const LIST_STATS_CACHE_CAPACITY = 32;
const DETAIL_CACHE_CAPACITY = 128;
const DIFF_CACHE_CAPACITY = 128;
-const MAX_CACHED_DIFF_PATCH_BYTES = 512 * 1024;
+// Each holder stays within this UTF-16 patch budget as well as its entry-count bound.
+const DIFF_CACHE_PATCH_BUDGET_BYTES = 32 * 1024 * 1024;
const canCacheDiff = (value: PullRequestDiffResult) =>
- value.patch.length * 2 <= MAX_CACHED_DIFF_PATCH_BYTES;
+ value.patch.length * 2 <= DIFF_CACHE_PATCH_BUDGET_BYTES;
+const diffCacheEvictions = (entries: Iterable<readonly [string, PullRequestDiffResult]>) => {
+ let bytes = 0;
+ const evictions: string[] = [];
+ for (const [key, value] of Array.from(entries).toReversed()) {
+ const size = value.patch.length * 2;
+ if (bytes + size > DIFF_CACHE_PATCH_BUDGET_BYTES) {
+ evictions.push(key);
+ } else {
+ bytes += size;
+ }
+ }
+ return evictions;
+};
const FILES_VIEWED_CACHE_CAPACITY = 128;
const VIEWER_CACHE_CAPACITY = 32;
@@ -681,6 +695,7 @@ export const make = Effect.gen(function* () {
const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;
const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;
const readCache = yield* PullRequestReadCache.PullRequestReadCache;
+ const clock = yield* Clock.Clock;
/**
* Where each project's remote is served from, by the remote's recognised base URL: a remote no
@@ -2617,6 +2632,11 @@ export const make = Effect.gen(function* () {
if (oldest !== undefined) held.delete(oldest);
}
held.set(key, { at, value });
+ for (const evicted of diffCacheEvictions(
+ Array.from(held, ([key, snapshot]) => [key, snapshot.value] as const),
+ )) {
+ held.delete(evicted);
+ }
armDiffSweep();
});
const serve = <E>(key: string, read: Effect.Effect<PullRequestDiffResult, E>) => {
@@ -2964,7 +2984,20 @@ export const make = Effect.gen(function* () {
},
{
capacity: DETAIL_CACHE_CAPACITY,
- timeToLive: (exit) => (Exit.isSuccess(exit) ? CHECKS_CACHE_TTL : Duration.zero),
+ // Expire from the read's start so checks seeded from a slow detail read keep their age.
+ timeToLive: (exit) =>
+ !Exit.isSuccess(exit)
+ ? Duration.zero
+ : exit.value === null
+ ? CHECKS_CACHE_TTL
+ : Duration.millis(
+ Math.max(
+ 0,
+ exit.value.observedAt +
+ Duration.toMillis(CHECKS_CACHE_TTL) -
+ clock.currentTimeMillisUnsafe(),
+ ),
+ ),
},
);
@@ -2998,6 +3031,18 @@ export const make = Effect.gen(function* () {
return detailUncached(refOfCacheKey(key)).pipe(
Effect.tap(
Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) {
+ // GitHub detail includes the same checks; the checks TTL counts from their observation.
+ if (
+ value.provider === "github" &&
+ value.observedAt !== undefined &&
+ !(yield* Cache.has(checksCache, key))
+ ) {
+ yield* Cache.set(checksCache, key, {
+ state: value.state,
+ checks: value.checks,
+ observedAt: value.observedAt,
+ });
+ }
recordStats(
statsKey,
{
@@ -3208,10 +3253,10 @@ export const make = Effect.gen(function* () {
...(commit === null ? {} : { commit }),
} as PullRequestDiffInput).pipe(
observeRead,
- Effect.map(({ value, observedAt }) => {
+ Effect.tap(({ value, observedAt }) => {
// Keep the loader's epoch and read time if a refresh occurs during the provider read.
diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt);
- return value;
+ return Effect.void;
}),
);
},
@@ -3220,7 +3265,10 @@ export const make = Effect.gen(function* () {
timeToLive: (exit, key) => {
if (!Exit.isSuccess(exit)) return Duration.zero;
const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[2];
- return commit === null ? DIFF_CACHE_TTL : COMMIT_DIFF_CACHE_TTL;
+ const ttl = Duration.toMillis(commit === null ? DIFF_CACHE_TTL : COMMIT_DIFF_CACHE_TTL);
+ return Duration.millis(
+ Math.max(0, exit.value.observedAt + ttl - clock.currentTimeMillisUnsafe()),
+ );
},
},
);
@@ -3246,7 +3294,7 @@ export const make = Effect.gen(function* () {
if (held > 0) armDiffSweep();
}),
);
- const diff: PullRequestService["Service"]["diff"] = (input) => {
+ const readDiff = (input: PullRequestDiffInput) => {
const key = JSON.stringify([
refCacheKey(input),
input.cursor ?? null,
@@ -3255,22 +3303,24 @@ export const make = Effect.gen(function* () {
? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null)
: null,
]);
- const read = Cache.get(diffCache, key).pipe(
- Effect.tap((value) =>
- canCacheDiff(value)
- ? Effect.void
- : Cache.getSuccess(diffCache, key).pipe(
- Effect.flatMap((current) =>
- Option.isSome(current) && current.value === value
- ? Cache.invalidate(diffCache, key)
- : Effect.void,
- ),
- Effect.uninterruptible,
- ),
+ const evictDiffs = Cache.entries(diffCache).pipe(
+ Effect.flatMap((entries) =>
+ Effect.forEach(
+ diffCacheEvictions(Array.from(entries, ([key, read]) => [key, read.value] as const)),
+ (evicted) => Cache.invalidate(diffCache, evicted),
+ ),
),
+ Effect.uninterruptible,
+ );
+ const read = Cache.get(diffCache, key).pipe(
+ Effect.ensuring(evictDiffs),
Effect.ensuring(Effect.sync(armDiffSweep)),
);
- return staleDiff.serve(key, read);
+ return { key, read };
+ };
+ const diff: PullRequestService["Service"]["diff"] = (input) => {
+ const { key, read } = readDiff(input);
+ return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value)));
};
const filesViewedCache = yield* Cache.makeWith(
@@ -3524,8 +3574,8 @@ export const make = Effect.gen(function* () {
.pipe(Effect.mapError(toPullRequestError("diffFileContents")));
return recordPaths(key, slice, now);
}
- const slice = yield* diff(input);
- return record(key, slice, now);
+ const { value, observedAt } = yield* readDiff(input).read;
+ return record(key, value, observedAt);
});
return { read: credentialCached(read), record, fileKey };
})();
diff --git a/apps/web/src/components/DiffWorkerPoolProvider.tsx b/apps/web/src/components/DiffWorkerPoolProvider.tsx
index 1dd7dcc5ee0..f06b4a5360e 100644
--- a/apps/web/src/components/DiffWorkerPoolProvider.tsx
+++ b/apps/web/src/components/DiffWorkerPoolProvider.tsx
@@ -125,9 +125,7 @@ function DiffWorkerReady({ children }: { children?: ReactNode }) {
);
}
-export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
- const resolvedTheme = useRenderedAppearance();
- const diffThemeName = resolveDiffThemeName(resolvedTheme);
+export function useDiffWorkerPool(diffThemeName: DiffThemeName) {
const [workerPoolSize] = useState(resolveDiffWorkerPoolSize);
const subscribe = useStableCallback((onStoreChange: () => void) => {
if (typeof window === "undefined") return () => {};
@@ -143,11 +141,17 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
}, DIFF_WORKER_IDLE_TTL_MS);
};
});
- const workerPool = useSyncExternalStore(
+ return useSyncExternalStore(
subscribe,
() => sharedWorkerPool?.pool,
() => undefined,
);
+}
+
+export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
+ const resolvedTheme = useRenderedAppearance();
+ const diffThemeName = resolveDiffThemeName(resolvedTheme);
+ const workerPool = useDiffWorkerPool(diffThemeName);
return (
<WorkerPoolContext value={workerPool}>
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx
index fdbe904ad48..de548692f88 100644
--- a/apps/web/src/components/RightPanelTabs.tsx
+++ b/apps/web/src/components/RightPanelTabs.tsx
@@ -726,6 +726,7 @@ function PullRequestSurfaceIcon({
: {}),
repository: surface.repository,
number: surface.number,
+ allowStale: false,
},
}),
).data;
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
index b83ae6c7923..a9c4b86e13f 100644
--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
@@ -8,6 +8,7 @@ import type {
EnvironmentId,
PullRequestDetailView,
PullRequestDiffSide,
+ PullRequestDiffResult,
PullRequestOmittedFileStat,
PullRequestRef,
PullRequestReviewPosition,
@@ -74,6 +75,7 @@ import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { DiffPanelLoadingState } from "../DiffPanelShell";
+import { useDiffWorkerPool } from "../DiffWorkerPoolProvider";
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
import { DiffFileTree } from "../diffs/DiffFileTree";
import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";
@@ -132,6 +134,7 @@ const COMMIT_PAGE_SIZE = 10;
const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";
interface DiffSlice {
+ readonly source: PullRequestDiffResult;
readonly cursor: string | null;
readonly patch: string;
readonly truncated: boolean;
@@ -148,13 +151,15 @@ const REPLACE_FILE_COUNTS_CSS = `
const NO_SLICES: ReadonlyArray<DiffSlice> = [];
-const sliceParses = new WeakMap<DiffSlice, Map<string, RenderablePatch | null>>();
+// Query results outlive the panel's slices, so their parses survive closing and reopening
+// without retaining anything beyond the query cache's lifetime.
+const sliceParses = new WeakMap<PullRequestDiffResult, Map<string, RenderablePatch | null>>();
function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) {
- let parses = sliceParses.get(slice);
+ let parses = sliceParses.get(slice.source);
if (parses === undefined) {
parses = new Map();
- sliceParses.set(slice, parses);
+ sliceParses.set(slice.source, parses);
}
if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null;
const parsed = getRenderablePatch(slice.patch, cacheKey, {
@@ -272,6 +277,8 @@ function PullRequestCodeTab({
revealRequest?: { readonly path: string; readonly nonce: number } | null;
}) {
const resolvedTheme = useRenderedAppearance();
+ // Initialize the shared tokenizer and workers while the diff request is still pending.
+ useDiffWorkerPool(resolveDiffThemeName(resolvedTheme));
const settings = useClientSettings((settings) => ({
diffFilesCollapsed: settings.diffFilesCollapsed,
diffIgnoreWhitespace: settings.diffIgnoreWhitespace,
@@ -353,6 +360,7 @@ function PullRequestCodeTab({
setSliceState((previous) => {
const slices = previous.key === scopeKey ? previous.slices : NO_SLICES;
const next = {
+ source: data,
cursor,
patch: data.patch,
truncated: data.truncated,
diff --git a/apps/web/src/components/pullRequest/PullRequestCommentBody.tsx b/apps/web/src/components/pullRequest/PullRequestCommentBody.tsx
index 12715a9efe3..73554b41ad9 100644
--- a/apps/web/src/components/pullRequest/PullRequestCommentBody.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCommentBody.tsx
@@ -17,9 +17,9 @@ export function PullRequestCommentBody({
useEffect(() => {
const element = content.current;
if (!element) return;
- const measure = () => setOverflowing(element.getBoundingClientRect().height > 240);
- measure();
- return observeResize(element, measure);
+ return observeResize(element, ([entry]) => {
+ if (entry) setOverflowing(entry.contentRect.height > 240);
+ });
}, []);
return (
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index 3d1d8686ae0..9c3faaf3167 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -1,4 +1,5 @@
import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
+import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
import { useAtomValue } from "@effect/atom-react";
import { usePullRequestStack } from "~/state/usePullRequestStack";
@@ -315,6 +316,22 @@ export function PullRequestDetailPanel({
listEntry.number === reference.number
? listEntry
: null;
+ const linkedReference = sourceControlClients.parseChangeRequestUrl(
+ matchingListEntry?.url ?? unavailableHostUrl ?? "",
+ )?.link;
+ useEnvironmentQuery(
+ context === "page" &&
+ supportsThreadPullRequests &&
+ linkedReference &&
+ (reference.host === undefined ||
+ reference.host.toLowerCase() === linkedReference.host.toLowerCase())
+ ? pullRequestEnvironment.linkedThreads({
+ environmentId,
+ input: { ...reference, ...normalizeThreadPullRequestKey(linkedReference) },
+ })
+ : null,
+ );
+ useEnvironmentQuery(pullRequestEnvironment.changeBreakdown({ environmentId, input: reference }));
const [threadPickerOpen, setThreadPickerOpen] = useState(false);
const [openReviewRequest, setOpenReviewRequest] = useState(0);
const [tab, setTab] = useState<PullRequestDetailTab>(initialTab);
diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
index e1fc6d60bd6..912e4c6d7ac 100644
--- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
@@ -97,10 +97,12 @@ export function PullRequestSearchInput({
value,
busy,
onChange,
+ onSubmit,
}: {
value: string;
busy?: boolean;
onChange: (value: string) => void;
+ onSubmit: (value: string) => void;
}) {
const [draft, setDraft] = useState<string | null>(null);
return (
@@ -116,6 +118,14 @@ export function PullRequestSearchInput({
onChange={(event) => {
setDraft(event.currentTarget.value);
onChange(event.currentTarget.value);
+ if ((event.nativeEvent as InputEvent).inputType === "insertFromPaste") {
+ onSubmit(event.currentTarget.value);
+ }
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {
+ onSubmit(event.currentTarget.value);
+ }
}}
placeholder="Search pull requests, or label:bug"
aria-label="Search pull requests"
diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
index 84bfd895917..57ae57924c9 100644
--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
@@ -26,6 +26,7 @@ import {
collectPullRequestListFacets,
narrowPullRequestsToFilters,
mergePullRequestDiffStats,
+ pullRequestDiffStatKey,
pullRequestEntryKey,
rankPullRequestMatches,
readPullRequestListSnapshot,
@@ -104,6 +105,7 @@ import {
usePullRequestList,
usePullRequestListStats,
usePullRequestTurnRefreshes,
+ useSharedPullRequestSummary,
type EnvironmentQueryTarget,
} from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
@@ -195,6 +197,16 @@ export function PullRequestsPage() {
(renderedPullRequestSurface?.environmentId as EnvironmentId | undefined) ??
selectedProject?.environmentId ??
null;
+ const panelSummary = useSharedPullRequestSummary(
+ panelEnvironmentId,
+ renderedPullRequestSurface === null
+ ? null
+ : {
+ ...renderedPullRequestSurface,
+ projectId: renderedPullRequestSurface.projectId as ProjectId,
+ },
+ null,
+ );
const updateSearch = (patch: {
[Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
}) =>
@@ -248,6 +260,7 @@ export function PullRequestsPage() {
const [filtersOpen, setFiltersOpen] = useState(false);
const {
sentQuery,
+ submitQuery,
querySettled,
typedParsed,
sentParsed,
@@ -710,6 +723,22 @@ export function PullRequestsPage() {
const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
+ if (
+ panelEnvironmentId !== null &&
+ panelSummary?.additions !== undefined &&
+ panelSummary.deletions !== undefined
+ ) {
+ const stat = {
+ ...panelSummary,
+ environmentId: panelEnvironmentId,
+ additions: panelSummary.additions,
+ deletions: panelSummary.deletions,
+ };
+ const previous = statsByRow.get(pullRequestDiffStatKey(stat));
+ if (previous?.additions !== stat.additions || previous.deletions !== stat.deletions) {
+ setStatsByRow(mergePullRequestDiffStats(statsByRow, [stat]));
+ }
+ }
const [statsTargetState, setStatsTargetState] = useState<{
readonly key: string;
readonly batches: ReadonlyArray<PullRequestStatsBatch>;
@@ -1076,6 +1105,7 @@ export function PullRequestsPage() {
value={search.q ?? ""}
busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
onChange={(query) => updateListScope({ q: query || undefined })}
+ onSubmit={submitQuery}
/>
);
const panelToggleControls = (
diff --git a/apps/web/src/components/pullRequest/usePullRequestListView.ts b/apps/web/src/components/pullRequest/usePullRequestListView.ts
index 2629fb6a34b..36451f6eab9 100644
--- a/apps/web/src/components/pullRequest/usePullRequestListView.ts
+++ b/apps/web/src/components/pullRequest/usePullRequestListView.ts
@@ -8,11 +8,10 @@ import {
type PullRequestListResult,
type PullRequestListState,
} from "@t3tools/contracts";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useAllEnvironmentShellsBootstrapped, useProjects } from "~/state/entities";
import { useEnvironments } from "~/state/environments";
-import { useDebouncedValue } from "~/state/queries";
import {
applyPullRequestOverrides,
findProjectForRepository,
@@ -185,7 +184,11 @@ export function usePullRequestScope(search: PullRequestsSearch) {
}
export function usePullRequestQueryFilters(search: PullRequestsSearch, typedQuery: string) {
- const sentQuery = useDebouncedValue(typedQuery, SEARCH_DEBOUNCE_MS);
+ const [sentQuery, setSentQuery] = useState(typedQuery);
+ useEffect(() => {
+ const timer = window.setTimeout(() => setSentQuery(typedQuery), SEARCH_DEBOUNCE_MS);
+ return () => window.clearTimeout(timer);
+ }, [typedQuery]);
const typedParsed = parsePullRequestQuery(typedQuery);
const sentParsed = parsePullRequestQuery(sentQuery);
@@ -203,6 +206,7 @@ export function usePullRequestQueryFilters(search: PullRequestsSearch, typedQuer
const hasLocalFilters = Object.keys(localFilters).length > 0;
return {
sentQuery,
+ submitQuery: (query: string) => setSentQuery(query.trim()),
querySettled: typedQuery === sentQuery,
typedParsed,
sentParsed,
diff --git a/apps/web/src/hooks/useOpenPanelPullRequestUrl.ts b/apps/web/src/hooks/useOpenPanelPullRequestUrl.ts
index 791e4ad3a6d..7be2020a804 100644
--- a/apps/web/src/hooks/useOpenPanelPullRequestUrl.ts
+++ b/apps/web/src/hooks/useOpenPanelPullRequestUrl.ts
@@ -75,7 +75,7 @@ export function useOpenPanelPullRequestUrl(threadRef: ScopedThreadRef | null) {
reference && environmentId
? pullRequestEnvironment.detail({
environmentId,
- input: reference,
+ input: { ...reference, allowStale: false },
})
: null,
).data;
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
index 4334bf2f68d..61005227a16 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
@@ -694,6 +694,76 @@ it.effect(
);
layer("GitHubPullRequestApi.layer", (it) => {
+ it.effect.each(["mixed", "merges", "unavailable"] as const)(
+ "reads stats only for displayed non-merge commits (%s)",
+ (kind) =>
+ Effect.gen(function* () {
+ const oids = kind === "merges" ? ["merge"] : ["regular", "merge"];
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ encodeJson({
+ data: {
+ repository: {
+ pullRequest: {
+ author: null,
+ comments: { nodes: [], pageInfo: lastPage },
+ reviews: { nodes: [], pageInfo: lastPage },
+ commits: {
+ nodes: oids.map((oid) => ({
+ commit: {
+ id: "node-" + oid,
+ oid,
+ messageHeadline: oid,
+ committedDate: "2026-07-05T00:00:00Z",
+ parents: { totalCount: oid === "merge" ? 2 : 1 },
+ authors: { nodes: [] },
+ },
+ })),
+ },
+ },
+ },
+ },
+ }),
+ ),
+ ),
+ );
+ if (kind === "unavailable") {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}", false, false, {}, 503)));
+ } else if (kind !== "merges") {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ encodeJson({
+ data: {
+ nodes: [{ __typename: "Commit", oid: "regular", additions: 18, deletions: 7 }],
+ },
+ }),
+ ),
+ ),
+ );
+ }
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ const activity = yield* cli.getPullRequestActivity(pullRequestInput);
+ expect(activity.commits.map((commit) => commit.oid)).toEqual(oids);
+ expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
+ "additions",
+ );
+ expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
+ "deletions",
+ );
+ if (kind === "mixed") {
+ expect(activity.commits[0]).toMatchObject({ additions: 18, deletions: 7 });
+ } else if (kind === "unavailable") {
+ expect(activity.commits[0]).not.toHaveProperty("additions");
+ }
+ expect(variablesOf("PullRequestCommitStats")).toEqual(
+ kind === "merges" ? [] : [{ ids: ["node-regular"] }],
+ );
+ expect(mockedExecute).toHaveBeenCalledTimes(kind === "merges" ? 1 : 2);
+ }),
+ );
+
it.effect("loads the complete hover card with one GraphQL request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
index fd530037666..1099ee1e094 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
@@ -72,6 +72,7 @@ import {
toRepositoryAuthors,
toRepositoryLabels,
toPullRequestActivityPage,
+ toPullRequestCommitStats,
toPullRequestCheckContextsPage,
toPullRequestCore,
toPullRequestFilesViewedPage,
@@ -1989,6 +1990,7 @@ export const make = Effect.gen(function* () {
const { owner, name } = parseRepositorySelector(input.repository);
let author: PullRequestActor | null = null;
let commits: ReadonlyArray<PullRequestCommit> = [];
+ let nonMergeCommitIds: ReadonlyArray<string> = [];
const remarks: PullRequestComment[] = [];
let commentsAfter: string | null = null;
let reviewsAfter: string | null = null;
@@ -2015,6 +2017,7 @@ export const make = Effect.gen(function* () {
if (page === 0) {
author = read.author ?? null;
commits = read.commits ?? [];
+ nonMergeCommitIds = read.nonMergeCommitIds;
}
remarks.push(...read.remarks);
commentsAfter = read.nextCommentsCursor;
@@ -2022,12 +2025,21 @@ export const make = Effect.gen(function* () {
withComments = withComments && commentsAfter !== null;
withReviews = withReviews && reviewsAfter !== null;
}
+ const emptyStats = toPullRequestCommitStats({ nodes: [] });
+ const commitStats =
+ nonMergeCommitIds.length === 0
+ ? emptyStats
+ : yield* client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe(
+ graphql(target),
+ Effect.map(toPullRequestCommitStats),
+ Effect.orElseSucceed(() => emptyStats),
+ );
return {
author,
comments: remarks.toSorted((left, right) =>
left.createdAt.localeCompare(right.createdAt),
),
- commits,
+ commits: commits.map((commit) => ({ ...commit, ...commitStats.get(commit.oid) })),
} satisfies GitHubPullRequestActivity;
},
),
@@ -2131,10 +2143,6 @@ export const make = Effect.gen(function* () {
const entries: GitHubReviewThreadEntry[] = [];
const avatarsByLogin = new Map<string, string>();
const botLogins = new Set<string>();
- const commitStats = new Map<
- string,
- { readonly additions: number; readonly deletions: number }
- >();
let reviewers: ReadonlyArray<PullRequestActor> = [];
let reactions: GitHubReviewThreadPage["reactions"] = [];
const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>();
@@ -2161,7 +2169,6 @@ export const make = Effect.gen(function* () {
for (const [id, message] of read.dismissalsByReviewId)
dismissalsByReviewId.set(id, message);
dismissalCursor = read.nextDismissalCursor;
- for (const [oid, stat] of read.commitStats) commitStats.set(oid, stat);
}
cursor = read.nextCursor;
page += 1;
@@ -2214,7 +2221,6 @@ export const make = Effect.gen(function* () {
reviewers,
avatarsByLogin,
botLogins,
- commitStats,
commits,
viewer,
};
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
index c0c0ac2f1b0..fe9bcaf82c4 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
@@ -645,7 +645,6 @@ describe("getChangeRequest commits", () => {
reviewers: [],
avatarsByLogin: new Map<string, string>(),
botLogins: new Set<string>(),
- commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
viewer: { canUpdate: true, didAuthor: false },
};
@@ -657,6 +656,14 @@ describe("getChangeRequest commits", () => {
author: baseDetail.author,
comments: baseDetail.comments,
commits: [
+ {
+ oid: "graphql-newest",
+ messageHeadline: "Activity metadata",
+ committedDate: "2026-07-06T00:00:00Z",
+ additions: 18,
+ deletions: 7,
+ authors: [],
+ },
{
oid: "view-oldest",
messageHeadline: "gh pr view's oldest commit",
@@ -679,6 +686,11 @@ describe("getChangeRequest commits", () => {
});
expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
+ expect(detail.commits[0]).toMatchObject({
+ messageHeadline: "the newest commit gh pr view drops",
+ additions: 18,
+ deletions: 7,
+ });
}).pipe(
Effect.provide(
layerWith([
@@ -703,7 +715,7 @@ describe("getChangeRequest commits", () => {
number: 7,
});
- expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
+ expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest", "view-oldest"]);
}).pipe(Effect.provide(layerWith([]))),
);
});
@@ -732,7 +744,6 @@ describe("getChangeRequestActivity dismissed reviews", () => {
reviewers: [],
avatarsByLogin: new Map(),
botLogins: new Set(["macroscopeapp"]),
- commitStats: new Map(),
commits: [],
viewer: { canUpdate: true, didAuthor: false },
};
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
index 0071e0ca67f..0116657c641 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
@@ -500,10 +500,6 @@ export const make = Effect.gen(function* () {
reviewers: [],
avatarsByLogin: new Map<string, string>(),
botLogins: new Set<string>(),
- commitStats: new Map<
- string,
- { readonly additions: number; readonly deletions: number }
- >(),
commits: [],
viewer: { canUpdate: true, didAuthor: false },
})),
@@ -512,67 +508,75 @@ export const make = Effect.gen(function* () {
{ concurrency: 2 },
).pipe(
Effect.mapError(fail("getChangeRequestActivity")),
- Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
- author: withAvatar(
- pullRequest.author,
- reviewThreads.avatarsByLogin,
- input.host,
- reviewThreads.botLogins,
- ),
- reviewers: reviewThreads.reviewers,
- reactions: reviewThreads.reactions,
- commits: (reviewThreads.commits.length > 0
- ? reviewThreads.commits
- : pullRequest.commits
- ).map((commit) => ({
- ...commit,
- ...reviewThreads.commitStats.get(commit.oid),
- authors: commit.authors?.map(
- (author) =>
- withAvatar(
- author,
+ Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => {
+ const commitStats = new Map(
+ pullRequest.commits.map(({ oid, additions, deletions }) => [
+ oid,
+ additions === undefined ? {} : { additions, deletions },
+ ]),
+ );
+ return {
+ author: withAvatar(
+ pullRequest.author,
+ reviewThreads.avatarsByLogin,
+ input.host,
+ reviewThreads.botLogins,
+ ),
+ reviewers: reviewThreads.reviewers,
+ reactions: reviewThreads.reactions,
+ commits: (reviewThreads.commits.length > 0
+ ? reviewThreads.commits
+ : pullRequest.commits
+ ).map((commit) => ({
+ ...commit,
+ ...commitStats.get(commit.oid),
+ authors: commit.authors?.map(
+ (author) =>
+ withAvatar(
+ author,
+ reviewThreads.avatarsByLogin,
+ input.host,
+ reviewThreads.botLogins,
+ ) ?? author,
+ ),
+ })),
+ comments: [...pullRequest.comments, ...reviewThreads.comments]
+ .map((comment) => ({
+ ...comment,
+ // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
+ body:
+ comment.kind === "review" &&
+ comment.reviewState?.toUpperCase() === "DISMISSED" &&
+ rendersEmpty(comment.body)
+ ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
+ : comment.body,
+ author: withAvatar(
+ comment.author,
reviewThreads.avatarsByLogin,
input.host,
reviewThreads.botLogins,
- ) ?? author,
- ),
- })),
- comments: [...pullRequest.comments, ...reviewThreads.comments]
- .map((comment) => ({
- ...comment,
- // Dismissal reasons live on timeline events; HTML-only bot reviews need that fallback too.
- body:
- comment.kind === "review" &&
- comment.reviewState?.toUpperCase() === "DISMISSED" &&
- rendersEmpty(comment.body)
- ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
- : comment.body,
- author: withAvatar(
- comment.author,
- reviewThreads.avatarsByLogin,
- input.host,
- reviewThreads.botLogins,
- ),
- reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
- editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
- }))
- .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
- commentCount: pullRequest.comments.length + reviewThreads.commentCount,
- commentsTruncated: reviewThreads.truncated,
- reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
- reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
- ...thread,
- comments: thread.comments.map((comment) => ({
- ...comment,
- author: withAvatar(
- comment.author,
- reviewThreads.avatarsByLogin,
- input.host,
- reviewThreads.botLogins,
- ),
+ ),
+ reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
+ editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
+ }))
+ .toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
+ commentCount: pullRequest.comments.length + reviewThreads.commentCount,
+ commentsTruncated: reviewThreads.truncated,
+ reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
+ reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
+ ...thread,
+ comments: thread.comments.map((comment) => ({
+ ...comment,
+ author: withAvatar(
+ comment.author,
+ reviewThreads.avatarsByLogin,
+ input.host,
+ reviewThreads.botLogins,
+ ),
+ })),
})),
- })),
- })),
+ };
+ }),
),
getReviewThreadComments: (input) =>
diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
index 2417f60aa32..b217d490143 100644
--- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
@@ -128,9 +128,6 @@ const reviewCommit = ({ commit: { authors, ...commit } }: Json) => ({
commit: {
messageHeadline: "",
committedDate: "",
- additions: 0,
- deletions: 0,
- parents: { totalCount: 1 },
...commit,
authors: {
nodes: nodesIn(authors).map((author) => ({
@@ -450,6 +447,8 @@ describe("pull request detail decoding", () => {
nodes: ((raw["commits"] ?? []) as ReadonlyArray<Record<string, unknown>>).map(
({ authors, ...commit }) => ({
commit: {
+ id: "commit-id",
+ parents: { totalCount: 1 },
...commit,
authors: {
nodes: ((authors ?? []) as ReadonlyArray<Record<string, unknown>>).map(
@@ -638,25 +637,27 @@ describe("review thread decoding", () => {
},
});
- it("omits misleading line counts from merge commits", () => {
+ it("selects stats only for non-merge activity commits", () => {
const result = expectSuccess(
- decodeReviewThreadsJson(
+ decodePullRequestActivityJson(
JSON.stringify({
data: {
repository: {
pullRequest: {
- reviewThreads: { totalCount: 0, nodes: [] },
+ author: null,
+ comments: { nodes: [], pageInfo: LAST_PAGE },
+ reviews: { nodes: [], pageInfo: LAST_PAGE },
commits: {
- nodes: [
- {
- commit: {
- oid: "merge123",
- additions: 36_858,
- deletions: 12_928,
- parents: { totalCount: 2 },
- },
+ nodes: [1, 2].map((parents) => ({
+ commit: {
+ id: "commit-" + parents,
+ oid: "sha-" + parents,
+ messageHeadline: "Commit",
+ committedDate: "2026-07-05T00:00:00Z",
+ parents: { totalCount: parents },
+ authors: { nodes: [] },
},
- ],
+ })),
},
},
},
@@ -664,8 +665,8 @@ describe("review thread decoding", () => {
}),
),
);
-
- expect([...result.commitStats]).toEqual([]);
+ expect(result.nonMergeCommitIds).toEqual(["commit-1"]);
+ expect(result.commits?.map((commit) => commit.oid)).toEqual(["sha-1", "sha-2"]);
});
it("decodes the newest commits off the same connection, oldest to newest", () => {
diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts
index 0b6bba8503b..cf4def54bbd 100644
--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts
+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts
@@ -53,6 +53,7 @@ import type {
CheckContext,
LabelCandidates,
PullRequestActivity,
+ PullRequestCommitStats,
PullRequestCheckContexts,
PullRequestCore,
PullRequestFilesViewed,
@@ -1124,6 +1125,7 @@ export function toPullRequestHeads(result: PullRequestHeads.Result): {
}
export interface GitHubPullRequestActivityPage {
+ readonly nonMergeCommitIds: ReadonlyArray<string>;
readonly author?: PullRequestActor | null;
readonly commits?: ReadonlyArray<PullRequestCommit>;
readonly remarks: ReadonlyArray<PullRequestComment>;
@@ -1137,6 +1139,9 @@ export function toPullRequestActivityPage(
const pr = result.repository?.pullRequest;
if (pr == null) return null;
return {
+ nonMergeCommitIds: nodesOf(pr.commits).flatMap(({ commit }) =>
+ commit.parents.totalCount > 1 ? [] : [commit.id],
+ ),
...(pr.author === undefined ? {} : { author: toActor(pr.author) }),
...(pr.commits === undefined
? {}
@@ -1157,6 +1162,25 @@ export function toPullRequestActivityPage(
};
}
+export function toPullRequestCommitStats(result: PullRequestCommitStats.Result) {
+ return new Map(
+ (result.nodes ?? []).flatMap((commit) =>
+ commit?.__typename === "Commit"
+ ? [
+ [
+ commit.oid,
+ {
+ additions: Math.max(0, commit.additions),
+ deletions: Math.max(0, commit.deletions),
+ },
+ ] as const,
+ ]
+ : [],
+ ),
+ );
+}
+
+/** A check context as the rollup reports it; opaque outside this module. */
export type GitHubCheckContext = CheckFields;
function toCheckContexts(nodes: ReadonlyArray<CheckContext>): ReadonlyArray<GitHubCheckContext> {
@@ -1202,11 +1226,11 @@ export interface GitHubReviewThreadComments {
readonly reviewers: ReadonlyArray<PullRequestActor>;
readonly avatarsByLogin: ReadonlyMap<string, string>;
readonly botLogins: ReadonlySet<string>;
- readonly commitStats: ReadonlyMap<
- string,
- { readonly additions: number; readonly deletions: number }
- >;
- /** Empty means unread; preserve existing commits. */
+ /**
+ * Empty wherever the read never happened (an install too old for the field, a degraded page),
+ * which the caller reads as "keep the `gh pr view` list" rather than as "this pull request has
+ * no commits".
+ */
readonly commits: ReadonlyArray<PullRequestCommit>;
readonly viewer: { readonly canUpdate: boolean; readonly didAuthor: boolean };
}
@@ -1226,10 +1250,6 @@ export interface GitHubReviewThreadPage {
readonly reviewers: ReadonlyArray<PullRequestActor>;
readonly avatarsByLogin: ReadonlyMap<string, string>;
readonly botLogins: ReadonlySet<string>;
- readonly commitStats: ReadonlyMap<
- string,
- { readonly additions: number; readonly deletions: number }
- >;
readonly commits: ReadonlyArray<PullRequestCommit>;
readonly viewer: { readonly canUpdate: boolean; readonly didAuthor: boolean };
readonly dismissalsByReviewId: ReadonlyMap<string, string>;
@@ -1350,18 +1370,10 @@ export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewTh
const actor = toActor(raw) ?? toRequestedTeam(raw);
if (actor !== null && !reviewers.has(actor.login)) reviewers.set(actor.login, actor);
}
- const commitStats = new Map<string, { readonly additions: number; readonly deletions: number }>();
const commits: PullRequestCommit[] = [];
for (const { commit } of nodesOf(pullRequest.commits)) {
const oid = trimmed(commit.oid);
if (oid === null) continue;
- // Merge stats count upstream changes against the first parent as PR work.
- if (commit.parents.totalCount <= 1) {
- commitStats.set(oid, {
- additions: Math.max(0, commit.additions),
- deletions: Math.max(0, commit.deletions),
- });
- }
const committedDate = trimmed(commit.committedDate);
if (committedDate === null) continue;
commits.push({
@@ -1390,7 +1402,6 @@ export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewTh
reviewers: [...reviewers.values()],
avatarsByLogin,
botLogins,
- commitStats,
commits,
viewer: toPullRequestViewerFields(pullRequest),
dismissalsByReviewId: toDismissalEntries(pullRequest.reviewDismissals),
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql
index ba103d44ad8..d5a95256fc1 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql
@@ -242,9 +242,13 @@ query PullRequestActivity(
commits(last: 100) @include(if: $head) {
nodes {
commit {
+ id
oid
messageHeadline
committedDate
+ parents(first: 1) {
+ totalCount
+ }
authors(first: 10) {
nodes {
name
@@ -302,6 +306,18 @@ query PullRequestActivity(
}
}
+# Merge commits include upstream changes in their stats, which the timeline does not display.
+# Read only the non-merge commits named by the activity connection.
+query PullRequestCommitStats($ids: [ID!]!) {
+ nodes(ids: $ids) {
+ ... on Commit {
+ oid
+ additions
+ deletions
+ }
+ }
+}
+
# Open pull requests whose head branch has one name, from whichever repository it lives in.
query PullRequestHeads($owner: String!, $name: String!, $head: String!, $after: String) {
repository(owner: $owner, name: $name) {
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
index b6a2524468d..e261ec0240a 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
@@ -131,10 +131,10 @@ export const NodesBot = Schema.Struct({
export interface NodesBot extends Schema.Struct.Type<typeof NodesBot.fields> {}
/** An object with an ID. */
-export const NodesNodeOther = Schema.Struct({
+export const ActorAvatarsNodesNodeOther = Schema.Struct({
__typename: GraphQL.otherTypename<Shared.Typename.Node>()(["User", "Bot"])
})
-export interface NodesNodeOther extends Schema.Struct.Type<typeof NodesNodeOther.fields> {}
+export interface ActorAvatarsNodesNodeOther extends Schema.Struct.Type<typeof ActorAvatarsNodesNodeOther.fields> {}
/** `query ActorAvatars` */
export const ActorAvatars = GraphQL.query("ActorAvatars", {
@@ -155,7 +155,7 @@ export const ActorAvatars = GraphQL.query("ActorAvatars", {
nodes: Schema.Array(Schema.NullOr(Schema.Union([
ActorAvatarsNodesUser,
NodesBot,
- NodesNodeOther
+ ActorAvatarsNodesNodeOther
])))
})
})
@@ -646,6 +646,13 @@ export declare namespace PullRequestPreview {
export type Result = typeof PullRequestPreview.result.Type
}
+/** The connection type for Commit. */
+export const CommitConnection = Schema.Struct({
+ /** Identifies the total count of items in the connection. */
+ totalCount: Shared.Int
+})
+export interface CommitConnection extends Schema.Struct.Type<typeof CommitConnection.fields> {}
+
/** A user is an individual's account on GitHub that owns repositories and can make new content. */
export const UserUser = Schema.Struct({
/** The username used to login. */
@@ -673,12 +680,16 @@ export interface GitActorConnection extends Schema.Struct.Type<typeof GitActorCo
/** Represents a Git commit. */
export const PullRequestActivityRepositoryPullRequestCommitsNodesCommitCommit = Schema.Struct({
+ /** The Node ID of the Commit object */
+ id: Shared.ID,
/** The Git object ID */
oid: Shared.GitObjectID,
/** The Git commit message headline */
messageHeadline: Schema.String,
/** The datetime when this commit was committed. */
committedDate: Shared.DateTime,
+ /** The parents of a commit. */
+ parents: CommitConnection,
/**
* The list of authors for this commit based on the git author and the Co-authored-by
* message trailer. The git author will always be first.
@@ -798,7 +809,7 @@ export const PullRequestActivity = GraphQL.query("PullRequestActivity", {
{ name: "reviewsAfter", body: "String" }
],
selections: [
- { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){author@include(if:$", "head", "){__typename login avatarUrl...on User{name}}commits(last:100)@include(if:$", "head", "){nodes{commit{oid messageHeadline committedDate authors(first:10){nodes{name email user{login}}}}}}comments(first:100 after:$", "commentsAfter", ")@include(if:$", "withComments", "){pageInfo{hasNextPage endCursor}nodes{id body createdAt lastEditedAt url author{__typename login avatarUrl...on User{name}}}}reviews(first:100 after:$", "reviewsAfter", ")@include(if:$", "withReviews", "){pageInfo{hasNextPage endCursor}nodes{id body state submittedAt lastEditedAt url author{__typename login avatarUrl...on User{name}}}}}}"] }
+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){author@include(if:$", "head", "){__typename login avatarUrl...on User{name}}commits(last:100)@include(if:$", "head", "){nodes{commit{id oid messageHeadline committedDate parents(first:1){totalCount}authors(first:10){nodes{name email user{login}}}}}}comments(first:100 after:$", "commentsAfter", ")@include(if:$", "withComments", "){pageInfo{hasNextPage endCursor}nodes{id body createdAt lastEditedAt url author{__typename login avatarUrl...on User{name}}}}reviews(first:100 after:$", "reviewsAfter", ")@include(if:$", "withReviews", "){pageInfo{hasNextPage endCursor}nodes{id body state submittedAt lastEditedAt url author{__typename login avatarUrl...on User{name}}}}}}"] }
],
fragments: []
},
@@ -822,6 +833,51 @@ export declare namespace PullRequestActivity {
export type Result = typeof PullRequestActivity.result.Type
}
+/** Represents a Git commit. */
+export const NodesCommit = Schema.Struct({
+ __typename: Schema.Literal("Commit"),
+ /** The Git object ID */
+ oid: Shared.GitObjectID,
+ /** The number of additions in this commit. */
+ additions: Shared.Int,
+ /** The number of deletions in this commit. */
+ deletions: Shared.Int
+})
+export interface NodesCommit extends Schema.Struct.Type<typeof NodesCommit.fields> {}
+
+/** An object with an ID. */
+export const PullRequestCommitStatsNodesNodeOther = Schema.Struct({
+ __typename: GraphQL.otherTypename<Shared.Typename.Node>()(["Commit"])
+})
+export interface PullRequestCommitStatsNodesNodeOther extends Schema.Struct.Type<typeof PullRequestCommitStatsNodesNodeOther.fields> {}
+
+/** `query PullRequestCommitStats` */
+export const PullRequestCommitStats = GraphQL.query("PullRequestCommitStats", {
+ document: {
+ variables: [
+ { name: "ids", body: "[ID!]!" }
+ ],
+ selections: [
+ { name: "nodes", body: ["(ids:$", "ids", "){__typename...on Commit{oid additions deletions}}"] }
+ ],
+ fragments: []
+ },
+ variables: {
+ ids: Schema.Array(Shared.ID)
+ },
+ result: Schema.Struct({
+ /** Lookup nodes by a list of IDs. */
+ nodes: Schema.Array(Schema.NullOr(Schema.Union([
+ NodesCommit,
+ PullRequestCommitStatsNodesNodeOther
+ ])))
+ })
+})
+export declare namespace PullRequestCommitStats {
+ export type Variables = typeof PullRequestCommitStats.variables.Type
+ export type Result = typeof PullRequestCommitStats.result.Type
+}
+
/** A repository pull request. */
export const NodesPullRequest = Schema.Struct({
/** Identifies the pull request number. */
@@ -1666,4 +1722,4 @@ export declare namespace PullRequestSourceBranch {
}
/** Every operation in pullRequestReads.graphql. */
-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
+export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestCommitStats, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql b/packages/source-control-github/src/server/pullRequestReviews.graphql
index a1c63c67a27..96c35783dc1 100644
--- a/packages/source-control-github/src/server/pullRequestReviews.graphql
+++ b/packages/source-control-github/src/server/pullRequestReviews.graphql
@@ -182,11 +182,6 @@ query ReviewThreads(
oid
messageHeadline
committedDate
- additions
- deletions
- parents(first: 1) {
- totalCount
- }
authors(first: 3) {
nodes {
name
diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts
index aa86ce1fab5..0711ed9ebcf 100644
--- a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts
+++ b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts
@@ -319,13 +319,6 @@ export const PullRequestTimelineItemsConnection = Schema.Struct({
})
export interface PullRequestTimelineItemsConnection extends Schema.Struct.Type<typeof PullRequestTimelineItemsConnection.fields> {}
-/** The connection type for Commit. */
-export const CommitConnection = Schema.Struct({
- /** Identifies the total count of items in the connection. */
- totalCount: Shared.Int
-})
-export interface CommitConnection extends Schema.Struct.Type<typeof CommitConnection.fields> {}
-
/** Represents an actor in a Git commit (ie. an author or committer). */
export const GitActor = Schema.Struct({
/** The name in the Git commit. */
@@ -352,12 +345,6 @@ export const Commit = Schema.Struct({
messageHeadline: Schema.String,
/** The datetime when this commit was committed. */
committedDate: Shared.DateTime,
- /** The number of additions in this commit. */
- additions: Shared.Int,
- /** The number of deletions in this commit. */
- deletions: Shared.Int,
- /** The parents of a commit. */
- parents: CommitConnection,
/**
* The list of authors for this commit based on the git author and the Co-authored-by
* message trailer. The git author will always be first.
@@ -426,7 +413,7 @@ export const ReviewThreads = GraphQL.query("ReviewThreads", {
],
selections: [
{ name: "viewer", body: ["{login}"] },
- { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){reviewThreads(first:100 after:$", "after", "){totalCount pageInfo{hasNextPage endCursor}nodes{id isResolved isOutdated path line diffSide comments(first:10){totalCount pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}viewerCanUpdate viewerDidAuthor author{__typename login avatarUrl}...Reactions comments(first:100){nodes{id lastEditedAt author{__typename login avatarUrl}...Reactions}}reviews(first:100){nodes{id lastEditedAt author{__typename login avatarUrl}...Reactions}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name avatarUrl}...on Bot{login avatarUrl}...on Team{combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}latestReviews(first:50){nodes{state author{__typename login avatarUrl}}}reviewDismissals:timelineItems(itemTypes:[REVIEW_DISMISSED_EVENT]first:100){pageInfo{hasNextPage endCursor}nodes{__typename...on ReviewDismissedEvent{dismissalMessage review{id}}}}commits(last:100){nodes{commit{oid messageHeadline committedDate additions deletions parents(first:1){totalCount}authors(first:3){nodes{name avatarUrl user{login}}}}}}}}"] }
+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){reviewThreads(first:100 after:$", "after", "){totalCount pageInfo{hasNextPage endCursor}nodes{id isResolved isOutdated path line diffSide comments(first:10){totalCount pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}viewerCanUpdate viewerDidAuthor author{__typename login avatarUrl}...Reactions comments(first:100){nodes{id lastEditedAt author{__typename login avatarUrl}...Reactions}}reviews(first:100){nodes{id lastEditedAt author{__typename login avatarUrl}...Reactions}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name avatarUrl}...on Bot{login avatarUrl}...on Team{combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}latestReviews(first:50){nodes{state author{__typename login avatarUrl}}}reviewDismissals:timelineItems(itemTypes:[REVIEW_DISMISSED_EVENT]first:100){pageInfo{hasNextPage endCursor}nodes{__typename...on ReviewDismissedEvent{dismissalMessage review{id}}}}commits(last:100){nodes{commit{oid messageHeadline committedDate authors(first:3){nodes{name avatarUrl user{login}}}}}}}}"] }
],
fragments: [
{ name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url...Reactions}"] },