TypeScript
fix(pull-requests): a filtered list fills its page instead of waiting for a scroll (#23923)
Julius Marminge30465453489c
diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsxindex ea287c16cf8..0eb0e545b2b 100644--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx@@ -348,6 +348,15 @@ export function PullRequestsScreen(onPress={() => void result.loadMore(true)}/></View>+ ) : result.hasMore ? (+ // A filtered page can be too short to scroll, which leaves nothing to reach the end of.+ <View className="items-center py-4">+ <Button+ label="Load more"+ accessibilityLabel="Load more pull requests"+ onPress={() => void result.loadMore()}+ />+ </View>) : undefined}ListEmptyComponent={diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex a3cb8ae76d4..95571b4e5e9 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -3047,6 +3047,91 @@ it.effect("refuses a way of updating a branch that the host or the viewer does n}),);+it.effect("keeps reading a host's thinned-out slices until a filtered page is full", () =>+ Effect.gen(function* () {+ const reads: Array<number> = [];+ const rows = Array.from({ length: 40 }, (_, index) => ({+ ...changeRequest(index + 1, `2026-07-${String(40 - index).padStart(2, "0")}T00:00:00Z`),+ labels: index % 2 === 0 ? [{ name: "bug", color: null }] : [],+ }));+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: SourceControlProviderKind.make("gitlab"),+ }),+ ],+ providers: [+ fakeProvider(SourceControlProviderKind.make("gitlab"), {+ listChangeRequests: (input) => {+ const delivered = input.cursor?.delivered ?? 0;+ reads.push(delivered);+ return Effect.succeed({+ items: rows.slice(delivered, delivered + input.limit),+ truncated: delivered + input.limit < rows.length,+ continues: true,+ });+ },+ }),+ ],+ });++ const bugs = yield* service.list({ state: "open", limit: 4, filters: { labels: [["bug"]] } });+ assert.deepStrictEqual(+ bugs.entries.map((entry) => entry.number),+ [1, 3, 5, 7],+ );+ assert.deepStrictEqual(reads, [0, 4]);++ reads.length = 0;+ const none = yield* service.list({+ state: "open",+ limit: 4,+ filters: { labels: [["missing"]] },+ });+ assert.deepStrictEqual(none.entries, []);+ assert.strictEqual(reads.length, 5);+ assert.match(Object.values(none.nextCursors)[0] ?? "", /\|20\|/);+ }),+);++it.effect("hands a host's own resume position back on the next read", () =>+ Effect.gen(function* () {+ const resumed: Array<string | undefined> = [];+ const service = yield* makeService({+ projects: [+ project({+ id: "p1",+ title: "on gitlab",+ workspaceRoot: "/a",+ repository: "group/project",+ provider: SourceControlProviderKind.make("gitlab"),+ }),+ ],+ providers: [+ fakeProvider(SourceControlProviderKind.make("gitlab"), {+ listChangeRequests: (input) => {+ resumed.push(input.cursor?.resumeAfter);+ return Effect.succeed({+ items: [changeRequest(resumed.length, "2026-07-02T00:00:00Z")],+ truncated: true,+ continues: true,+ resumeAfter: `2026-07-01T00:00:00.000Z~${resumed.length}`,+ });+ },+ }),+ ],+ });++ const first = yield* service.list({ state: "open", limit: 1 });+ yield* service.list({ state: "open", limit: 1, cursors: first.nextCursors });+ assert.deepStrictEqual(resumed, [undefined, "2026-07-01T00:00:00.000Z~1"]);+ }),+);+it.effect("judges the review filter only on a host that summarises its reviews", () =>Effect.gen(function* () {const service = yield* makeService({diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex bc763834f7f..8fad44c2905 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -123,6 +123,7 @@ function supersedesReading(current: PullRequestReading | undefined, next: PullReconst DEFAULT_REPOSITORY_LIST_LIMIT = 99;const REPOSITORY_CONCURRENCY = 12;const REPOSITORY_SEARCH_CHUNK = 100;+const FILTERED_LIST_READS = 5;/*** Every read leaves the process — a CLI per repository, against hosts whose limits are low@@ -341,7 +342,7 @@ interface ListCursor extends ProviderListCursor {}const LIST_CURSOR_PATTERN =- /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?$/;+ /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?(?:\|([\w.:~+-]{1,128}))?$/;function parseListCursor(raw: string): ListCursor | null {const match = LIST_CURSOR_PATTERN.exec(raw);@@ -351,6 +352,7 @@ function parseListCursor(raw: string): ListCursor | null {updatedBefore: match[1]!,delivered: Number(match[2]),seenAt: seenAt === undefined ? [] : seenAt.split(",").map(Number),+ ...(match[4] === undefined ? {} : { resumeAfter: match[4] }),};}@@ -368,6 +370,7 @@ function nextListCursor(delivered: ReadonlyArray<ProviderChangeRequest>,/** A provider may consume malformed offset-paged rows that never appear in `delivered`. */cursorAdvance = delivered.length,+ resumeAfter?: string,): string | null {if (fetched.length === 0) return null;// Taken from what the host answered rather than from what survived de-duplication: a slice can@@ -375,7 +378,7 @@ function nextListCursor(// repository's boring afternoon — and reading "nothing new" as "nothing left" would end the// walk on the instant it was stuck on, with everything older unreachable for good.const oldest = fetched.reduce((left, right) => (right.updatedAt < left.updatedAt ? right : left));- return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance);+ return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance, resumeAfter);}function listCursorAt(@@ -383,12 +386,14 @@ function listCursorAt(boundary: string,fetched: ReadonlyArray<ProviderChangeRequest>,deliveredCount: number,+ resumeAfter?: string,): string {const seenAt = new Set([...(previous?.updatedBefore === boundary ? previous.seenAt : []),...fetched.filter((item) => item.updatedAt === boundary).map((item) => item.number),]);- return `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`;+ const cursor = `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`;+ return resumeAfter === undefined ? cursor : `${cursor}|${resumeAfter}`;}function isProviderUnusable(error: PullRequestProviderError): boolean {@@ -1165,11 +1170,13 @@ export const make = Effect.gen(function* () {const cursorOf = (project: SupportedProject): ListCursor | undefined =>continuation?.get(project.cursorKey);- const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {+ const readSlice = (+ project: SupportedProject,+ cursor: ListCursor | undefined,+ ): Effect.Effect<RepositoryBatch> => {{const viewer = viewers[project.host]!;const key = project.cursorKey;- const cursor = cursorOf(project);return project.api.listChangeRequests({cwd: project.project.workspaceRoot,@@ -1188,6 +1195,7 @@ export const make = Effect.gen(function* () {updatedBefore: cursor.updatedBefore,delivered: cursor.delivered,seenAt: cursor.seenAt,+ resumeAfter: cursor.resumeAfter,},}),})@@ -1214,7 +1222,13 @@ export const make = Effect.gen(function* () {truncated: page.truncated,nextCursor:page.continues && page.truncated- ? nextListCursor(cursor, page.items, items, page.cursorAdvance)+ ? nextListCursor(+ cursor,+ page.items,+ items,+ page.cursorAdvance,+ page.resumeAfter,+ ): null,};}),@@ -1235,6 +1249,32 @@ export const make = Effect.gen(function* () {}};+ // Filters a host cannot apply thin out the slices it hands over, so a repository keeps+ // reading until it has a page's worth or runs out. The reads are bounded: a filter that+ // matches nothing would otherwise walk the repository's whole history in one request.+ const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {+ const fill = (batch: RepositoryBatch, reads: number): Effect.Effect<RepositoryBatch> => {+ const cursor = batch.nextCursor === null ? null : parseListCursor(batch.nextCursor);+ if (+ input.filters === undefined ||+ cursor === null ||+ batch.entries.length >= limit ||+ reads >= FILTERED_LIST_READS+ ) {+ return Effect.succeed(batch);+ }+ return readSlice(project, cursor).pipe(+ Effect.flatMap((next) =>+ // A slice that failed keeps the cursor before it, so the reader can try again.+ next.errors.length > 0+ ? Effect.succeed(batch)+ : fill({ ...next, entries: [...batch.entries, ...next.entries] }, reads + 1),+ ),+ );+ };+ return readSlice(project, cursorOf(project)).pipe(Effect.flatMap((batch) => fill(batch, 1)));+ };+const readTogether = (chunk: ReadonlyArray<SupportedProject>,): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex daa166e654e..882bef676a8 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -144,6 +144,12 @@ export interface ProviderChangeRequestPage {* may need to count malformed raw rows it consumed too.*/readonly cursorAdvance?: number;+ /**+ * Where a host that can only page from the top carries on: an opaque position past the last+ * row delivered, handed back as the cursor's `resumeAfter`. Unlike a count of rows it survives+ * rows above it closing between reads.+ */+ readonly resumeAfter?: string;readonly continues: boolean;}@@ -160,6 +166,7 @@ export interface ProviderListCursor {* applying their limit so a full page of tied updates does not repeat the same prefix.*/readonly seenAt?: ReadonlyArray<number> | undefined;+ readonly resumeAfter?: string | undefined;}export interface ProviderBatchedChangeRequest extends ProviderChangeRequest {diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.tsindex 121876d80dc..3a9ef4e852b 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts@@ -448,20 +448,87 @@ describe("GitCafePullRequestProvider", () => {}).pipe(Effect.provide(server.layer));});- it.effect("leaves an author GitCafe has no profile for to be narrowed by login", () => {- const server = fakeGitCafe({ "GET /repos/owner/repo/pulls": { items: [pull], next: null } });+ it.effect("finds a GitHub-synced author's actor on their pull requests to narrow by it", () => {+ const synced = {+ ...pull,+ number: 8,+ author: { kind: "github", actorId: "act_synced", login: "Synced", avatarUrl: null },+ };+ const server = fakeGitCafe({+ "GET /repos/owner/repo/pulls": (request: SentRequest) =>+ request.query.get("authors") === '["act_synced"]'+ ? { items: [synced], next: null }+ : request.query.get("after") === null+ ? { items: [pull], next: "o1" }+ : { items: [synced], next: null },+ });return Effect.gen(function* () {const provider = yield* GitCafePullRequestProvider.make;- const page = yield* provider.listChangeRequests({- ...target,- state: "open",- involvement: "all",- viewer: "alice",- limit: 10,- filters: { author: "synced-only" },- });- assert.strictEqual(page.items.length, 1);- assert.isNull(server.sent.at(-1)!.query.get("authors"));+ const list = (author: string) =>+ provider.listChangeRequests({+ ...target,+ state: "open",+ involvement: "all",+ viewer: "alice",+ limit: 10,+ filters: { author },+ });+ const page = yield* list("synced");+ assert.deepStrictEqual(+ page.items.map((item) => item.number),+ [8],+ );+ assert.strictEqual(server.sent.at(-1)!.query.get("authors"), '["act_synced"]');+ // Once seen, the actor is narrowed by straight away.+ const sentBefore = server.sent.length;+ yield* list("synced");+ assert.deepStrictEqual(+ server.sent.slice(sentBefore).map((request) => request.query.get("authors")),+ [null, '["act_synced"]'],+ );+ // An author on none of the pages it reads gets nothing rather than unnarrowed rows a+ // continuation would count against a different listing.+ const missing = yield* list("nobody");+ assert.deepStrictEqual(missing, { items: [], truncated: false, continues: false });+ }).pipe(Effect.provide(server.layer));+ });++ it.effect("carries a listing on after the last row delivered when rows above it close", () => {+ const created = (number: number) => `2026-09-12T12:00:0${9 - number}Z`;+ let pulls = [1, 2, 3, 4, 5].map((number) => ({ ...pull, number, createdAt: created(number) }));+ const server = fakeGitCafe({+ "GET /repos/owner/repo/pulls": (request: SentRequest) => {+ const offset = Number(request.query.get("after")?.slice(1) ?? 0);+ const end = offset + Number(request.query.get("limit"));+ return { items: pulls.slice(offset, end), next: end < pulls.length ? `o${end}` : null };+ },+ });+ return Effect.gen(function* () {+ const provider = yield* GitCafePullRequestProvider.make;+ const list = (cursor?: { readonly resumeAfter?: string }) =>+ provider.listChangeRequests({+ ...target,+ state: "open",+ involvement: "all",+ viewer: "alice",+ limit: 2,+ ...(cursor === undefined+ ? {}+ : { cursor: { updatedBefore: timestamp, delivered: 2, ...cursor } }),+ });+ const first = yield* list();+ assert.deepStrictEqual(+ first.items.map((item) => item.number),+ [1, 2],+ );+ pulls = pulls.filter((candidate) => candidate.number !== 1);+ const next = yield* list({ resumeAfter: first.resumeAfter! });+ assert.deepStrictEqual(+ next.items.map((item) => item.number),+ [3, 4],+ );+ assert.isTrue(next.truncated);+ assert.isTrue(next.continues);}).pipe(Effect.provide(server.layer));});diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex 4f6294e19ce..23c488e03b4 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -47,6 +47,13 @@ const CAPABILITIES: PullRequestCapabilities = {const PAGE_SIZE = 100;const MAX_PAGES = 10;+/**+ * Pages read looking for a GitHub-synced author before a listing filtered by them gives up. The+ * login only appears on their pull requests, so one older than this many is out of reach.+ */+const AUTHOR_DISCOVERY_PAGES = 5;+/** Bounds the logins remembered from listings; a repository's authors fit many times over. */+const KNOWN_AUTHORS_LIMIT = 10_000;/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */const DIFF_FILES_BATCH = 64;/**@@ -168,6 +175,13 @@ function stackHeadsCurrent();}+const POSITION = /^(.+)~(\d+)$/u;+const parsePosition = (raw: string | undefined) => {+ const match = raw === undefined ? null : POSITION.exec(raw);+ const created = match === null ? Number.NaN : Date.parse(match[1]!);+ return match === null || Number.isNaN(created) ? null : { created, number: Number(match[2]) };+};+const withDetails = (files: ReadonlyArray<Json.GitCafeDiffFile>,details: ReadonlyArray<Json.GitCafeDiffFile>,@@ -179,6 +193,18 @@ const withDetails = (/** @public Service construction is part of the canonical Effect module API. */export const make = Effect.gen(function* () {const api = yield* GitCafeApi.GitCafeApi;+ // GitCafe filters by actor id and has no lookup from a GitHub login to the actor sync made for+ // it, so the pairs are learned from the pull requests every listing reads.+ const knownAuthors = new Map<string, string>();+ const authorKey = (host: string, login: string) =>+ `${host.toLowerCase()}\n${login.toLowerCase()}`;+ const learnAuthors = (host: string, pulls: ReadonlyArray<Json.GitCafePull>) => {+ for (const { author } of pulls) {+ if (author.kind !== "github") continue;+ if (knownAuthors.size >= KNOWN_AUTHORS_LIMIT) knownAuthors.clear();+ knownAuthors.set(authorKey(host, author.login), author.actorId);+ }+ };const failure = (operation: string, detail: string, cause?: unknown) =>new PullRequestProviderError({@@ -263,8 +289,9 @@ export const make = Effect.gen(function* () {});/**- * GitCafe filters by ids, so label names and the author's handle are looked up first. A name it- * cannot resolve is left out, and the service narrows the rows by name instead.+ * GitCafe filters by ids, so label names and the author's handle are looked up first. A label it+ * cannot resolve is left out, and the service narrows the rows by name instead. An author it+ * cannot resolve comes back as `unresolvedAuthor` for the listing to find.*/const listFilterParams = Effect.fn("GitCafePullRequestProvider.listFilterParams")(function* (input: ProviderRepositoryRef & {@@ -276,7 +303,7 @@ export const make = Effect.gen(function* () {) {const filters = input.filters;const params: Array<readonly [string, string]> = [];- if (filters === undefined) return params;+ if (filters === undefined) return { params, unresolvedAuthor: null };if (filters.draft !== undefined)params.push([filters.draft === "only" ? "states" : "stateNots", encodeIds(["draft"])]);const groups = filters.labels ?? [];@@ -303,8 +330,8 @@ export const make = Effect.gen(function* () {}if (filters.author !== undefined && !input.authorNarrowed) {const handle = resolvePullRequestAuthorFilter(filters.author, input.viewer);- // A GitHub-synced author with no GitCafe profile has no handle here; their rows are- // narrowed by login instead. A profile matches what GitHub sync authored for it too.+ // A profile matches what GitHub sync authored for it too. A GitHub-synced author with no+ // profile is known only by the actor on their pull requests.const user = yield* read("listChangeRequests",input,@@ -319,9 +346,13 @@ export const make = Effect.gen(function* () {: Effect.succeed(Option.none()),}),);- if (Option.isSome(user)) params.push(["authors", encodeIds([user.value.actorId])]);+ const actorId = Option.isSome(user)+ ? user.value.actorId+ : knownAuthors.get(authorKey(input.host, handle));+ if (actorId === undefined) return { params, unresolvedAuthor: handle };+ params.push(["authors", encodeIds([actorId])]);}- return params;+ return { params, unresolvedAuthor: null };});const readComments = (operation: string, input: PullRef) =>@@ -635,18 +666,12 @@ export const make = Effect.gen(function* () {actorId = principal.value.actorId;}}- const filterParams = yield* listFilterParams(+ const { params: filterParams, unresolvedAuthor } = yield* listFilterParams({ ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },base,);- const limit = Math.max(1, input.limit);- const items: Array<Json.GitCafePull> = [];- let next: string | null = null;- do {- const query = new URLSearchParams({- limit: String(Math.min(PAGE_SIZE, limit - items.length)),- sort: "newest",- });+ const readPage = (rows: number, after: string | null) => {+ const query = new URLSearchParams({ limit: String(rows), sort: "newest" });if (input.state !== "all") query.set("state", input.state);if (input.query?.trim()) query.set("q", input.query.trim());for (const [key, value] of filterParams) query.set(key, value);@@ -655,18 +680,57 @@ export const make = Effect.gen(function* () {input.involvement === "reviewing" ? "reviewers" : "authors",encodeIds([actorId]),);- if (next !== null) query.set("after", next);- const page: typeof Json.GitCafePulls.Type = yield* read(+ if (after !== null) query.set("after", after);+ return read("listChangeRequests",input,{ path: `${base}/pulls?${query}` },Json.GitCafePulls,+ ).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));+ };+ if (unresolvedAuthor !== null) {+ // Rows are only ever handed out narrowed by actor, so a continuation always carries on+ // the same narrowed listing.+ const key = authorKey(input.host, unresolvedAuthor);+ let after: string | null = null;+ let pages = 0;+ do {+ const page: typeof Json.GitCafePulls.Type = yield* readPage(PAGE_SIZE, after);+ pages += 1;+ after = page.items.length === 0 ? null : page.next;+ } while (!knownAuthors.has(key) && after !== null && pages < AUTHOR_DISCOVERY_PAGES);+ const found = knownAuthors.get(key);+ if (found === undefined)+ return { items: [], truncated: after !== null, continues: false };+ filterParams.push(["authors", encodeIds([found])]);+ }+ const limit = Math.max(1, input.limit);+ const items: Array<Json.GitCafePull> = [];+ // GitCafe pages by an opaque token and orders by creation, so a continuation reads from the+ // top and keeps only the rows created after the last one delivered. A count of rows would+ // skip one for every row above it that closed in between.+ const resume = parsePosition(input.cursor?.resumeAfter);+ const isNew = (pull: Json.GitCafePull) => {+ if (resume === null) return true;+ const created = Date.parse(pull.createdAt);+ return (+ created < resume.created || (created === resume.created && pull.number < resume.number)+ );+ };+ let next: string | null = null;+ do {+ const page: typeof Json.GitCafePulls.Type = yield* readPage(+ resume === null ? Math.min(PAGE_SIZE, limit - items.length) : PAGE_SIZE,+ next,);- items.push(...page.items);+ items.push(...page.items.filter(isNew));next = page.items.length === 0 ? null : page.next;} while (next !== null && items.length < limit);+ const delivered = items.slice(0, limit);+ const last = delivered.at(-1);return {- items: items.slice(0, limit).map((pull) => {+ ...(last === undefined ? {} : { resumeAfter: `${last.createdAt}~${last.number}` }),+ items: delivered.map((pull) => {const item = Json.toChangeRequest(pull, input);return input.involvement === "reviewing" && actorId !== undefined? {@@ -675,8 +739,8 @@ export const make = Effect.gen(function* () {}: item;}),- truncated: next !== null,- continues: false,+ truncated: next !== null || items.length > limit,+ continues: true,};},),