Skip to content

An open-source, faster Devin alternative

TypeScript

Repo picker: list every repository, a page at a time

Igor Zalutski via Computer036a1464b767
diff --git a/services/managed-agents/src/computer/work/api.ts b/services/managed-agents/src/computer/work/api.ts
index a5285aec..bd46f30b 100644
--- a/services/managed-agents/src/computer/work/api.ts
+++ b/services/managed-agents/src/computer/work/api.ts
@@ -13,6 +13,7 @@
import type { ApiCaller, ApiReply } from "../sessions-api.js";
import type { SessionBrief, WorkContext, WorkContextOp, WorkRefsOp, WorkStampOp } from "./briefs.js";
import type { IndexedItem, ItemsResult, Revision, WorkIndexRpc } from "./index-contract.js";
+import { GRANTED_PAGES_MAX } from "./index-contract.js";
export interface Person {
email: string;
@@ -87,7 +88,7 @@ export interface WorkDeps {
const PARAMS: Record<WorkRouteOp, readonly string[]> = {
"work.repository.get": [],
"work.repository.put": [],
- "work.repositories": [],
+ "work.repositories": ["installation", "page"],
"work.items": ["stage", "cursor", "limit"],
"work.item": [],
"work.history": ["cursor"],
@@ -99,6 +100,7 @@ const NUMBER = /^[1-9]\d{0,8}$/;
const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
const REPO_NAME = /^[A-Za-z0-9._-]{1,100}$/;
+const INSTALLATION_ID = /^[A-Za-z0-9_-]{1,64}$/;
const UNAVAILABLE: WorkReply = { status: 503, error: { code: "unavailable", message: "Work is unavailable. Try again shortly.", retryAfterMs: 5_000 } };
const invalid = (message: string, field: string): WorkReply => ({ status: 400, error: { code: "invalid_request", message, field } });
@@ -129,8 +131,18 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearch
}
case "work.repositories": {
- // What the organization's installations grant, for the picker; the index reads GitHub.
- const result = await index.repositories(deps.accountId);
+ // What the organization's installations grant, a page at a time, for the picker; the index reads GitHub.
+ const installation = query.get("installation");
+ const rawPage = query.get("page");
+ if (installation !== null && !INSTALLATION_ID.test(installation)) return invalid("installation is an installation id.", "installation");
+ if (rawPage !== null && (!/^[1-9]\d{0,2}$/.test(rawPage) || Number(rawPage) > GRANTED_PAGES_MAX)) {
+ return invalid(`page is 1 to ${GRANTED_PAGES_MAX}.`, "page");
+ }
+ if (rawPage !== null && rawPage !== "1" && installation === null) return invalid("A later page is of one installation.", "installation");
+ const result = await index.repositories(deps.accountId, {
+ ...(installation !== null ? { installationId: installation } : {}),
+ ...(rawPage !== null ? { page: Number(rawPage) } : {}),
+ });
if (!result.ok) return { ...UNAVAILABLE, error: { ...UNAVAILABLE.error!, retryAfterMs: result.retryAfterMs } };
return { status: 200, body: { installations: result.installations } };
}
diff --git a/services/managed-agents/src/computer/work/github.ts b/services/managed-agents/src/computer/work/github.ts
index 62d3935a..04096aef 100644
--- a/services/managed-agents/src/computer/work/github.ts
+++ b/services/managed-agents/src/computer/work/github.ts
@@ -364,26 +364,19 @@ export class WorkGitHub {
// ---------------------------------------------------------------- calls
/**
- * The repositories the installation grants, PER_PAGE_MAX a page, at most `max` (in GitHub's
- * order). The one call that reads the installation, not `repo`. `truncated` when it grants more.
+ * One page of the repositories the installation grants, PER_PAGE_MAX a page, in GitHub's order;
+ * `more` when a later page holds others. The one call that reads the installation, not `repo`.
*/
- async grantedRepositories(max: number): Promise<{ repositories: GrantedRepository[]; truncated: boolean }> {
- const repositories: GrantedRepository[] = [];
- let total: number | null = null;
- let full = false;
- // A token keeps the repositories it was minted with: mint afresh, so a grant changed on GitHub shows.
- this.tokens.delete("metadata");
- for (let page = 1; repositories.length < max; page++) {
- const answer = await this.request(`/installation/repositories?per_page=${PER_PAGE_MAX}&page=${page}`, { token: { kind: "metadata" } });
- if (answer.status === 404) throw new GitHubGone("installation_removed", "The GitHub installation is not connected to this organization.");
- const body = this.json<{ total_count?: unknown; repositories?: unknown }>(answer);
- const list = Array.isArray(body.repositories) ? body.repositories : [];
- if (typeof body.total_count === "number") total = body.total_count;
- repositories.push(...list.map(grantedOf).filter((r): r is GrantedRepository => r !== null));
- full = list.length >= PER_PAGE_MAX;
- if (!full) break;
- }
- return { repositories: repositories.slice(0, max), truncated: total !== null ? total > max : full && repositories.length >= max };
+ async grantedPage(page: number): Promise<{ repositories: GrantedRepository[]; more: boolean }> {
+ // A token keeps the repositories it was minted with: a listing starts on a fresh one, so a grant changed on GitHub shows.
+ if (page === 1) this.tokens.delete("metadata");
+ const answer = await this.request(`/installation/repositories?per_page=${PER_PAGE_MAX}&page=${page}`, { token: { kind: "metadata" } });
+ if (answer.status === 404) throw new GitHubGone("installation_removed", "The GitHub installation is not connected to this organization.");
+ const body = this.json<{ total_count?: unknown; repositories?: unknown }>(answer);
+ const list = Array.isArray(body.repositories) ? body.repositories : [];
+ const repositories = list.map(grantedOf).filter((r): r is GrantedRepository => r !== null);
+ const more = typeof body.total_count === "number" ? page * PER_PAGE_MAX < body.total_count : list.length >= PER_PAGE_MAX;
+ return { repositories, more };
}
/** The repository as GitHub names it now, its id and default branch (setRepository's check). */
diff --git a/services/managed-agents/src/computer/work/index-contract.ts b/services/managed-agents/src/computer/work/index-contract.ts
index 39bf4462..3db69ed4 100644
--- a/services/managed-agents/src/computer/work/index-contract.ts
+++ b/services/managed-agents/src/computer/work/index-contract.ts
@@ -41,15 +41,26 @@ export interface GrantingInstallation {
accountType: string;
/** The installation's page on GitHub, where a person grants it more repositories. */
settingsUrl: string;
- /** Most recently pushed first; never pushed last. */
+ /** This page of them, most recently pushed first; never pushed last. */
repositories: GrantedRepository[];
- /** True when the installation grants more than the list holds. */
+ /** The page holding more of them, or null on the last. */
+ nextPage: number | null;
+ /** True when the installation grants more than the pages a listing reads. */
truncated: boolean;
/** Set when GitHub would not list them (the repositories are then empty). A stable code. */
problem: RepositoryProblem | null;
problemMessage: string | null;
}
+/** The last page a listing reads: 10,000 repositories an installation. */
+export const GRANTED_PAGES_MAX = 100;
+
+/** Which page to list, of every installation or of one (`GrantingInstallation.id`). */
+export interface RepositoriesQuery {
+ installationId?: string;
+ page?: number;
+}
+
export type RepositoriesResult = { ok: true; installations: GrantingInstallation[] } | { ok: false; error: "unavailable"; retryAfterMs: number };
/** Who made a write, from the identity the edge asserted. */
@@ -164,7 +175,7 @@ export type WorkWrite<T> = { ok: true; value: T } | { ok: false; status: number;
export interface WorkIndexRpc {
repository(accountId: string): Promise<Repository | null>;
setRepository(accountId: string, choice: RepositoryChoice, by: WorkActor): Promise<WorkWrite<Repository>>;
- repositories(accountId: string): Promise<RepositoriesResult>;
+ repositories(accountId: string, query?: RepositoriesQuery): Promise<RepositoriesResult>;
items(accountId: string, query: ItemsQuery): Promise<ItemsResult>;
item(accountId: string, number: number): Promise<ItemResult>;
history(accountId: string, number: number, cursor?: string): Promise<HistoryResult>;
diff --git a/services/managed-agents/src/computer/work/index-do.ts b/services/managed-agents/src/computer/work/index-do.ts
index e09cd260..353ff724 100644
--- a/services/managed-agents/src/computer/work/index-do.ts
+++ b/services/managed-agents/src/computer/work/index-do.ts
@@ -7,7 +7,7 @@ import { DurableObject } from "cloudflare:workers";
import type { TokenMinter } from "./github.js";
import { WorkIndex } from "./index.js";
-import type { ItemsQuery, RepositoryChoice, WorkActor, WorkIndexRpc } from "./index-contract.js";
+import type { ItemsQuery, RepositoriesQuery, RepositoryChoice, WorkActor, WorkIndexRpc } from "./index-contract.js";
import type { IndexStore, StoreValue } from "./platform.js";
export interface WorkIndexEnv {
@@ -54,8 +54,8 @@ export class WorkIndexDurableObject extends DurableObject<WorkIndexEnv> implemen
return this.index.setRepository(accountId, choice, by);
}
- repositories(accountId: string) {
- return this.index.repositories(accountId);
+ repositories(accountId: string, query?: RepositoriesQuery) {
+ return this.index.repositories(accountId, query);
}
items(accountId: string, query: ItemsQuery) {
diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.ts
index 51e87494..e21f582e 100644
--- a/services/managed-agents/src/computer/work/index.ts
+++ b/services/managed-agents/src/computer/work/index.ts
@@ -58,6 +58,7 @@ import {
type TokenMinter,
type WorkRepo,
} from "./github.js";
+import { GRANTED_PAGES_MAX } from "./index-contract.js";
import type {
HistoryResult,
IndexedItem,
@@ -69,6 +70,7 @@ import type {
OpenStamp,
GrantingInstallation,
ReadState,
+ RepositoriesQuery,
RepositoriesResult,
Repository,
RepositoryChoice,
@@ -114,7 +116,6 @@ const CLOSED_LIMIT_DEFAULT = 50;
const CLOSED_LIMIT_MAX = 100;
const FETCH_PARALLEL = 6;
/** The picker lists at most this many repositories per installation (five pages). */
-export const GRANTED_MAX = 500;
/** Durable Object SQL binds at most 100 parameters per statement. */
const BIND_MAX = 90;
/** Stored bodies re-parsed per step after PARSER_VERSION changes. */
@@ -447,14 +448,18 @@ export class WorkIndex {
}
/**
- * The organization's active installations, each with the repositories it grants, read from
- * GitHub on every call: the picker asks again when the person comes back from granting access.
+ * The organization's active installations (or the one asked for), each with a page of the
+ * repositories it grants, read from GitHub on every call: the picker reads every page, again when
+ * the person comes back from granting access.
* An installation GitHub will not list carries its problem; any other failure answers unavailable.
*/
- async repositories(accountId: string): Promise<RepositoriesResult> {
+ async repositories(accountId: string, query: RepositoriesQuery = {}): Promise<RepositoriesResult> {
this.bind(accountId);
const account = this.deps.account(accountId);
- const active = (await account.listGitHubInstallations()).filter((i) => i.state === "active");
+ const page = query.page ?? 1;
+ const active = (await account.listGitHubInstallations()).filter(
+ (i) => i.state === "active" && (query.installationId === undefined || String(i.id) === query.installationId),
+ );
try {
const installations = await Promise.all(
active.map(async (i): Promise<GrantingInstallation> => {
@@ -474,11 +479,12 @@ export class WorkIndex {
this.listers.set(shown.id, lister);
}
try {
- const { repositories, truncated } = await lister.grantedRepositories(GRANTED_MAX);
- return { ...shown, repositories: repositories.sort(byPushed), truncated, problem: null, problemMessage: null };
+ const { repositories, more } = await lister.grantedPage(page);
+ const nextPage = more && page < GRANTED_PAGES_MAX ? page + 1 : null;
+ return { ...shown, repositories: repositories.sort(byPushed), truncated: more && nextPage === null, nextPage, problem: null, problemMessage: null };
} catch (error) {
if (!(error instanceof GitHubGone)) throw error;
- return { ...shown, repositories: [], truncated: false, problem: error.problem, problemMessage: error.message };
+ return { ...shown, repositories: [], truncated: false, nextPage: null, problem: error.problem, problemMessage: error.message };
}
}),
);
diff --git a/services/managed-agents/test/work-api.test.ts b/services/managed-agents/test/work-api.test.ts
index 14ec78e8..886b5916 100644
--- a/services/managed-agents/test/work-api.test.ts
+++ b/services/managed-agents/test/work-api.test.ts
@@ -84,7 +84,7 @@ async function workIndex(repo: FakeRepo, over: Partial<TokenMinter> = {}) {
const rpc: WorkIndexRpc = {
repository: (a) => index.getRepository(a),
setRepository: (a, c, by) => index.setRepository(a, c, by),
- repositories: (a) => index.repositories(a),
+ repositories: (a, q) => index.repositories(a, q),
items: (a, q) => index.items(a, q),
item: (a, n) => index.item(a, n),
history: (a, n, c) => index.history(a, n, c),
@@ -445,14 +445,26 @@ describe("Work API repositories", () => {
expect(mints).toBe(2);
});
- it("stops at 500 repositories and says so", async () => {
+ it("lists a page at a time, and a later page of one installation", async () => {
const repo = new FakeRepo({});
repo.granted = Array.from({ length: 520 }, (_, i) => ({ id: i + 1, name: `r${i}`, pushedAt: "2026-11-01T00:00:00Z" }));
const w = await workIndex(repo);
- const body = await json(await call(w.env, computer([]).stub, person, "GET", "/work/repositories"));
- expect(body.installations[0].repositories).toHaveLength(500);
- expect(body.installations[0].truncated).toBe(true);
- expect(repo.log.filter((l) => l.startsWith("GET /installation/repositories"))).toHaveLength(5);
+ const first = await json(await call(w.env, computer([]).stub, person, "GET", "/work/repositories"));
+ expect(first.installations[0]).toMatchObject({ nextPage: 2, truncated: false });
+ expect(first.installations[0].repositories).toHaveLength(100);
+ const last = await json(await call(w.env, computer([]).stub, person, "GET", "/work/repositories?installation=12&page=6"));
+ expect(last.installations[0]).toMatchObject({ nextPage: null, truncated: false });
+ expect(last.installations[0].repositories).toHaveLength(21);
+ const other = await json(await call(w.env, computer([]).stub, person, "GET", "/work/repositories?installation=99&page=2"));
+ expect(other.installations).toEqual([]);
+ expect(repo.log.filter((l) => l.startsWith("GET /installation/repositories"))).toHaveLength(2);
+ });
+
+ it("refuses a later page of every installation, or past the last", async () => {
+ const w = await workIndex(new FakeRepo({}));
+ expect((await call(w.env, computer([]).stub, person, "GET", "/work/repositories?page=2")).status).toBe(400);
+ expect((await call(w.env, computer([]).stub, person, "GET", "/work/repositories?installation=12&page=101")).status).toBe(400);
+ expect((await call(w.env, computer([]).stub, person, "GET", "/work/repositories?installation=12&page=0")).status).toBe(400);
});
it("names the problem of an installation GitHub will not list, and answers 503 when GitHub is down", async () => {
diff --git a/web/src/managed-agents/work/api.test.ts b/web/src/managed-agents/work/api.test.ts
index 130697e4..7c5e81df 100644
--- a/web/src/managed-agents/work/api.test.ts
+++ b/web/src/managed-agents/work/api.test.ts
@@ -149,11 +149,54 @@ describe('repositories the installations grant', () => {
new Response(JSON.stringify({ installations }), { status: 200 }),
)
vi.stubGlobal('fetch', fetch)
- expect(await getRepositories()).toEqual(installations)
+ expect(await getRepositories()).toEqual([
+ { ...installations[0], nextPage: null },
+ ])
expect(fetch.mock.calls[0][0]).toBe(
'/api/managed-agents/computer/work/repositories',
)
})
+
+ it('reads every page of an installation, then sorts them together', async () => {
+ const repo = (id: number, pushedAt: string | null) => ({
+ id,
+ owner: 'acme',
+ name: `r${id}`,
+ private: false,
+ defaultBranch: 'main',
+ pushedAt,
+ })
+ const installation = {
+ id: '1',
+ accountLogin: 'acme',
+ accountType: 'Organization',
+ settingsUrl:
+ 'https://github.com/organizations/acme/settings/installations/41',
+ truncated: false,
+ problem: null,
+ problemMessage: null,
+ }
+ const page = (repositories: unknown[], nextPage: number | null) =>
+ new Response(
+ JSON.stringify({
+ installations: [{ ...installation, repositories, nextPage }],
+ }),
+ { status: 200 },
+ )
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(page([repo(1, '2026-01-01T00:00:00Z')], 2))
+ .mockResolvedValueOnce(page([repo(2, null)], 3))
+ .mockResolvedValueOnce(page([repo(3, '2026-11-01T00:00:00Z')], null))
+ vi.stubGlobal('fetch', fetch)
+ const [all] = await getRepositories()
+ expect(all.repositories.map((r) => r.id)).toEqual([3, 1, 2])
+ expect(fetch.mock.calls.map((c) => c[0] as string)).toEqual([
+ '/api/managed-agents/computer/work/repositories',
+ '/api/managed-agents/computer/work/repositories?installation=1&page=2',
+ '/api/managed-agents/computer/work/repositories?installation=1&page=3',
+ ])
+ })
})
describe('retry delay', () => {
diff --git a/web/src/managed-agents/work/api.ts b/web/src/managed-agents/work/api.ts
index 12bb892f..405e339e 100644
--- a/web/src/managed-agents/work/api.ts
+++ b/web/src/managed-agents/work/api.ts
@@ -171,15 +171,17 @@ const GrantedRepositorySchema = z.looseObject({
})
export type GrantedRepository = z.infer<typeof GrantedRepositorySchema>
-// One of the organization's GitHub installations and the repositories it
-// grants, most recently pushed first (the server's order). `settingsUrl` is
-// the installation's page on GitHub, where a person grants it more.
+// One of the organization's GitHub installations and a page of the
+// repositories it grants; `nextPage` is the page holding more, or null on the
+// last. `settingsUrl` is the installation's page on GitHub, where a person
+// grants it more.
const GrantingInstallationSchema = z.looseObject({
id: z.string(),
accountLogin: z.string(),
accountType: z.string(),
settingsUrl: z.string(),
repositories: z.array(GrantedRepositorySchema),
+ nextPage: z.number().int().positive().nullable().optional(),
truncated: z.boolean(),
problem: z.string().nullable(),
problemMessage: z.string().nullable(),
@@ -219,16 +221,56 @@ export function putRepository(choice: RepositoryChoice) {
).then((r) => r.repository)
}
-/** What each of the organization's GitHub installations grants, for the picker. */
-export function getRepositories() {
+function getRepositoriesPage(installation?: string, page = 1) {
+ const query = installation
+ ? `?${new URLSearchParams({ installation, page: String(page) })}`
+ : ''
return apiFetch(
- `${PREFIX}/repositories`,
+ `${PREFIX}/repositories${query}`,
undefined,
RepositoriesSchema,
'/api',
).then((r) => r.installations)
}
+/**
+ * What each of the organization's GitHub installations grants, for the
+ * picker: every page, read up front so a search covers them all. Most
+ * recently pushed first, never pushed last.
+ */
+export async function getRepositories() {
+ const installations = await getRepositoriesPage()
+ return Promise.all(
+ installations.map(async (installation) => {
+ const repositories = [...installation.repositories]
+ let next = installation.nextPage ?? null
+ let truncated = installation.truncated
+ while (next !== null) {
+ const [more] = await getRepositoriesPage(installation.id, next)
+ if (!more) break
+ repositories.push(...more.repositories)
+ next = more.nextPage ?? null
+ truncated = more.truncated
+ }
+ return {
+ ...installation,
+ repositories: repositories.sort(byPushed),
+ nextPage: null,
+ truncated,
+ }
+ }),
+ )
+}
+
+function byPushed(a: GrantedRepository, b: GrantedRepository) {
+ if (a.pushedAt !== b.pushedAt) {
+ if (a.pushedAt === null) return 1
+ if (b.pushedAt === null) return -1
+ return Date.parse(b.pushedAt) - Date.parse(a.pushedAt)
+ }
+ return a.name.localeCompare(b.name)
+}
+
/** What the open-items poll keeps: the page and the ETag it came with. */
export type OpenItemsPoll = { etag: string | null; page: OpenItems }