Skip to content

Commit b2cd784

Browse files
committed
fix(github): adapt PR #884 pagination for migration, platform and SDK
2 parents 2715609 + c9c7fbf commit b2cd784

34 files changed

Lines changed: 825 additions & 205 deletions

‎apps/api/src/modules/github/github.controller.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,11 @@ export async function deleteRepo(c: Context) {
7171
return c.json(data, 200);
7272
}
7373
export async function listBranches(c: Context) {
74-
75-
const data = await operationData(c, ops().listBranches(call(c), repo(c)));
76-
return c.json({ data }, 200);
74+
const data = await operationData(c, ops().listBranches(call(c), {
75+
...repo(c),
76+
page: Number(c.req.query("page") ?? 1),
77+
}));
78+
return c.json(data, 200);
7779
}
7880
export async function getCloneToken(c: Context) {
7981

@@ -265,4 +267,4 @@ function parseRepoListParams(c: Context): RepoListParams {
265267
: undefined,
266268
sort: sort === "name" || sort === "stars" || sort === "updated" ? sort : undefined,
267269
};
268-
}
270+
}

‎apps/api/src/modules/projects/project.controller.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,9 +390,10 @@ export async function listBranches(c: Context) {
390390
const result = await getPlatformKernel().projects.listBranches(
391391
operationContext(c),
392392
param(c, "id"),
393+
{ page: Number(c.req.query("page") ?? 1) },
393394
);
394395
applyOperationContext(c, result.context);
395-
return c.json({ success: true, data: result.data });
396+
return c.json({ success: true, ...result.data });
396397
}
397398

398399
/**

‎apps/api/test/modules/github/github-sdk-parity.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { createShip, type VerifiedIdentity } from "@repo/sdk/native";
99
import { OpenshipClient } from "@repo/sdk/client";
1010
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
1111
import { githubRoutes } from "../../../src/modules/github/github.routes";
12+
import { projectRoutes } from "../../../src/modules/projects/project.routes";
1213
import { systemRoutes } from "../../../src/modules/system/system.routes";
1314
import { healthRoutes } from "../../../src/modules/health/health.routes";
1415
import { handleApiError } from "../../../src/middleware/error-handler";
@@ -17,7 +18,7 @@ import { setStoredDeviceToken } from "@repo/platform/engine/modules/github/githu
1718
import { flushAudit } from "@repo/platform/engine/lib/audit-emitter";
1819
import { eq } from "@repo/db";
1920
installFakeRunner();
20-
const app = new Hono().onError(handleApiError).route("/api/health", healthRoutes).route("/api/github", githubRoutes).route("/api/system", systemRoutes);
21+
const app = new Hono().onError(handleApiError).route("/api/health", healthRoutes).route("/api/github", githubRoutes).route("/api/system", systemRoutes).route("/api/projects", projectRoutes);
2122
async function clients(actor: SeededOwner, organizationId = actor.orgId, limits: Partial<VerifiedIdentity> = {}) {
2223
const user = (await repos.user.findById(actor.userId))!;
2324
const ship = createShip({ platform: getPlatformKernel(), identity: { resolve: async () => ({ user, sessionId: "git-test", ...limits }) } });
@@ -38,6 +39,40 @@ const entry = (path: string, type = "file") => ({ name: path.split("/").pop(), p
3839
afterEach(async () => { vi.clearAllMocks(); await setStoredDeviceToken(null); });
3940

4041
describe("GitHub operations shared by SDK and HTTP", () => {
42+
it("returns branch pagination through native operations and HTTP without truncating later pages", async () => {
43+
const c = await clients(await seedOwner());
44+
const branch = { name: "main", commit: { sha: "abc", url: "https://api.github.com/commit/abc" }, protected: false };
45+
provider.fetch.mockResolvedValue([branch]);
46+
for (const client of [c.native, c.remote]) {
47+
expect(await client.github.listBranches({ owner: "acme", repo: "app", page: 2 })).toEqual({
48+
data: [branch],
49+
pagination: { page: 2, perPage: 100, hasMore: false },
50+
});
51+
expect(provider.fetch.mock.lastCall?.[0].params).toEqual({ page: 2, per_page: 100 });
52+
await expect(client.github.listBranches({ owner: "acme", repo: "app", page: -1 })).rejects.toBeDefined();
53+
}
54+
});
55+
56+
it("preserves page metadata and project authorization for linked-repository branch lists", async () => {
57+
const owner = await seedOwner();
58+
const c = await clients(owner);
59+
const group = await repos.projectGroup.create({ organizationId: owner.orgId, name: "Branches", slug: `branches-${owner.userId}` });
60+
const project = await repos.project.create({ organizationId: owner.orgId, groupId: group.id, name: "Branches", slug: `branches-${owner.userId}`, gitOwner: "acme", gitRepo: "app", gitProvider: "github" });
61+
const other = await clients(await seedOwner());
62+
provider.fetch.mockResolvedValue([{ name: "main", commit: { sha: "abc", url: "https://api.github.com/commit/abc" }, protected: false }]);
63+
for (const client of [c.native, c.remote]) {
64+
expect(await client.projects.listBranches(project.id, { page: 2 })).toMatchObject({
65+
data: [{ name: "main", sha: "abc", protected: false }],
66+
pagination: { page: 2, perPage: 100, hasMore: false },
67+
});
68+
}
69+
const calls = provider.fetch.mock.calls.length;
70+
for (const client of [other.native, other.remote]) {
71+
await expect(client.projects.listBranches(project.id, { page: 2 })).rejects.toMatchObject({ code: "NOT_FOUND" });
72+
}
73+
expect(provider.fetch).toHaveBeenCalledTimes(calls);
74+
});
75+
4176
it("preserves repository presentation and limits installation tokens to the requested repository", async () => {
4277
const c = await clients(await seedOwner());
4378
provider.fetch.mockResolvedValue(detail);
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { ExecutionContext as RequestContext } from "@repo/platform";
3+
import { githubFetch } from "@repo/platform/engine/modules/github/github.auth";
4+
import {
5+
GITHUB_BRANCH_PAGE_SIZE,
6+
getBranch,
7+
listBranches,
8+
} from "@repo/platform/engine/modules/github/github.service";
9+
import type { GitHubBranch } from "@repo/platform/engine/modules/github/github.types";
10+
11+
vi.mock("@repo/platform/engine/modules/github/github.auth", () => ({
12+
githubFetch: vi.fn(),
13+
getGitHubAuthMode: vi.fn(),
14+
}));
15+
16+
const ctx = {} as RequestContext;
17+
const branch = (name: string): GitHubBranch =>
18+
({ name, commit: { sha: `sha-${name}` }, protected: false }) as GitHubBranch;
19+
20+
describe("listBranches", () => {
21+
beforeEach(() => {
22+
vi.mocked(githubFetch).mockReset();
23+
});
24+
25+
it("requests one page", async () => {
26+
const branches = [branch("alpha"), branch("main")];
27+
vi.mocked(githubFetch).mockResolvedValue(branches);
28+
29+
const result = await listBranches(ctx, "owner", "repo", { page: 2 });
30+
31+
expect(githubFetch).toHaveBeenCalledWith(
32+
expect.objectContaining({
33+
params: { page: 2, per_page: GITHUB_BRANCH_PAGE_SIZE },
34+
}),
35+
);
36+
expect(result).toEqual({
37+
branches,
38+
page: 2,
39+
perPage: GITHUB_BRANCH_PAGE_SIZE,
40+
hasMore: false,
41+
});
42+
});
43+
44+
it("reports another page when the current page is full", async () => {
45+
const branches = Array.from({ length: GITHUB_BRANCH_PAGE_SIZE }, (_, index) =>
46+
branch(`branch-${index}`),
47+
);
48+
vi.mocked(githubFetch).mockResolvedValue(branches);
49+
50+
const result = await listBranches(ctx, "owner", "repo");
51+
52+
expect(result.hasMore).toBe(true);
53+
expect(result.page).toBe(1);
54+
});
55+
56+
it("verifies the named branch directly without accepting a tag or relying on the first page", async () => {
57+
vi.mocked(githubFetch).mockResolvedValue(branch("feature/beyond-page-one"));
58+
expect(await getBranch(ctx, "owner", "repo", "feature/beyond-page-one")).toMatchObject({
59+
name: "feature/beyond-page-one",
60+
});
61+
expect(githubFetch).toHaveBeenCalledWith(
62+
expect.objectContaining({
63+
url: "https://api.github.com/repos/owner/repo/branches/feature%2Fbeyond-page-one",
64+
}),
65+
);
66+
});
67+
68+
it("distinguishes a missing branch from an unavailable provider", async () => {
69+
vi.mocked(githubFetch).mockRejectedValue(new Error("GitHub API error (404): Not Found"));
70+
expect(await getBranch(ctx, "owner", "repo", "missing")).toBeNull();
71+
vi.mocked(githubFetch).mockRejectedValue(new Error("GitHub API error (503): Unavailable"));
72+
await expect(getBranch(ctx, "owner", "repo", "main")).rejects.toThrow("503");
73+
});
74+
});

‎apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/Sidebar.tsx‎

Lines changed: 9 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"use client";
22

3-
import React, { useCallback, useRef } from "react";
3+
import React, { useCallback, useState } from "react";
44
import { GitBranch, Rocket, Github, Loader2, Globe, Container, Server, Layers, Check, AlertCircle, Key, Plus, Copy, ExternalLink } from "lucide-react";
55
import { useI18n, interpolate } from "@/components/i18n-provider";
6-
import { CustomSelect } from "@/components/ui/CustomSelect";
6+
import { RepositoryBranchSelect } from "@/components/github/RepositoryBranchSelect";
77
import DropdownMenu from "@/components/ui/DropdownMenu";
88
import DomainSettings from "./DomainSettings";
99
import BuildSummary from "./BuildSummary";
@@ -191,32 +191,6 @@ const Sidebar: React.FC = () => {
191191
// connect-account flow, local builds don't need a remote credential.
192192
const cloneGate = useCloneStrategyGate();
193193

194-
// Lazy branch list. In config-edit mode the wizard hydrates from saved data
195-
// with only the current branch seeded (no repo round-trip on load). The full
196-
// list is fetched once, on first open of the branch dropdown — never for
197-
// local-sourced projects (no remote repo to list).
198-
const branchesFetchedRef = useRef(false);
199-
const loadBranches = useCallback(async () => {
200-
if (branchesFetchedRef.current) return;
201-
if (!config.projectId || !config.owner || config.owner === "local") return;
202-
// Only when the list is "thin" (config-edit seeds just the current branch);
203-
// the first-deploy path already preloads the full list via prepare.
204-
if (config.branches.length > 1) return;
205-
branchesFetchedRef.current = true;
206-
try {
207-
const res = await projectsApi.getBranches(config.projectId);
208-
const names: string[] = (res?.data ?? [])
209-
.map((b: { name?: string }) => b?.name)
210-
.filter((n: unknown): n is string => typeof n === "string" && n.length > 0);
211-
if (names.length) {
212-
const merged = Array.from(new Set([config.branch, ...names].filter(Boolean)));
213-
updateConfig({ branches: merged });
214-
}
215-
} catch {
216-
branchesFetchedRef.current = false; // allow a retry on next open
217-
}
218-
}, [config.projectId, config.owner, config.branch, config.branches.length, updateConfig]);
219-
220194
const handleOpenEnvironmentCreator = useCallback(() => {
221195
if (!config.projectId) return;
222196

@@ -478,24 +452,22 @@ const Sidebar: React.FC = () => {
478452
</div>
479453
{config.branches.length > 0 && (
480454
<div className="mt-3">
481-
<CustomSelect
455+
<RepositoryBranchSelect
456+
owner={config.owner}
457+
repo={config.repo}
458+
projectId={config.projectId}
482459
value={config.branch}
483460
onChange={(val) => updateConfig({ branch: val })}
484-
onOpen={loadBranches}
485-
options={config.branches.map(branch => ({
486-
value: branch,
487-
label: branch,
488-
icon: <GitBranch className="w-3.5 h-3.5" />
489-
}))}
461+
initialBranches={config.branches}
462+
initialPage={config.branchPage}
463+
initialHasMore={config.branchesHasMore}
490464
footerAction={config.projectId
491465
? {
492466
label: t.deploy.sidebar.newEnvironment,
493467
icon: <Plus className="w-3.5 h-3.5 text-muted-foreground" />,
494468
onClick: handleOpenEnvironmentCreator,
495469
}
496470
: undefined}
497-
placeholder={t.deploy.sidebar.selectBranch}
498-
className="w-full"
499471
/>
500472
</div>
501473
)}
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// @vitest-environment happy-dom
2+
import { act } from "react";
3+
import { createRoot, type Root } from "react-dom/client";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { RepositoryBranchSelect } from "./RepositoryBranchSelect";
6+
import { CustomSelect } from "@/components/ui/CustomSelect";
7+
8+
const api = vi.hoisted(() => ({ listBranches: vi.fn(), getBranchPage: vi.fn() }));
9+
vi.mock("@/lib/api/github", () => ({ githubApi: api }));
10+
vi.mock("@/lib/api/projects", () => ({ projectsApi: api }));
11+
let container: HTMLDivElement;
12+
let root: Root;
13+
const changed = vi.fn();
14+
const page = (names: string[], number = 1, hasMore = false) => ({
15+
data: names.map((name) => ({ name })),
16+
pagination: { page: number, perPage: 100, hasMore },
17+
});
18+
beforeEach(() => {
19+
vi.resetAllMocks();
20+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
21+
container = document.createElement("div");
22+
document.body.append(container);
23+
root = createRoot(container);
24+
});
25+
afterEach(async () => {
26+
await act(async () => root.unmount());
27+
container.remove();
28+
vi.unstubAllGlobals();
29+
});
30+
async function render(repo = "app", projectId?: string) {
31+
await act(async () =>
32+
root.render(
33+
<RepositoryBranchSelect
34+
owner="acme"
35+
repo={repo}
36+
projectId={projectId}
37+
value="main"
38+
onChange={changed}
39+
/>,
40+
),
41+
);
42+
}
43+
async function open() {
44+
await act(async () =>
45+
container.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]')!.click(),
46+
);
47+
}
48+
async function search(query: string) {
49+
const input = document.querySelector<HTMLInputElement>('input[role="combobox"]')!;
50+
await act(async () => {
51+
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, query);
52+
input.dispatchEvent(new Event("input", { bubbles: true }));
53+
});
54+
}
55+
function options() {
56+
return [...document.querySelectorAll<HTMLButtonElement>('[role="option"]')];
57+
}
58+
59+
describe("repository branch selection (#870)", () => {
60+
it("keeps main pinned and searches branches beyond the first hundred in the migration picker", async () => {
61+
api.listBranches
62+
.mockResolvedValueOnce(
63+
page(
64+
Array.from({ length: 100 }, (_, i) => `a-${i}`),
65+
1,
66+
true,
67+
),
68+
)
69+
.mockResolvedValueOnce(page(["main", "master", "z-last"], 2));
70+
await render();
71+
await open();
72+
expect(options()[0]?.textContent).toBe("main");
73+
expect(options()).toHaveLength(101);
74+
await search("z-last");
75+
expect(api.listBranches).toHaveBeenLastCalledWith("acme", "app", 2);
76+
expect(options().map((option) => option.textContent)).toEqual(["z-last"]);
77+
await act(async () =>
78+
document
79+
.querySelector("input")!
80+
.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })),
81+
);
82+
expect(changed).toHaveBeenCalledWith("z-last");
83+
expect(document.querySelector('[role="listbox"]')).toBeNull();
84+
});
85+
86+
it("uses the project-scoped paginated operation for an existing deployment", async () => {
87+
api.getBranchPage.mockResolvedValue(page(["feature", "main"]));
88+
await render("app", "project-id");
89+
await open();
90+
expect(api.getBranchPage).toHaveBeenCalledWith("project-id", 1);
91+
expect(api.listBranches).not.toHaveBeenCalled();
92+
await act(async () =>
93+
options()
94+
.find((option) => option.textContent === "feature")!
95+
.click(),
96+
);
97+
expect(changed).toHaveBeenCalledWith("feature");
98+
});
99+
100+
it("discards a previous repository's late page when the repository changes", async () => {
101+
let finish!: (result: ReturnType<typeof page>) => void;
102+
api.listBranches.mockImplementation((_owner, repo) =>
103+
repo === "old"
104+
? new Promise((resolve) => {
105+
finish = resolve;
106+
})
107+
: Promise.resolve(page(["new-only"])),
108+
);
109+
await render("old");
110+
await open();
111+
await render("new");
112+
await open();
113+
await act(async () => finish(page(["old-only"])));
114+
expect(options().map((option) => option.textContent)).toEqual(["main", "new-only"]);
115+
});
116+
117+
it("shows a retryable page failure without repeatedly requesting the failed page", async () => {
118+
api.listBranches.mockRejectedValueOnce(new Error("offline"));
119+
await render();
120+
await open();
121+
await search("feature");
122+
expect(api.listBranches).toHaveBeenCalledTimes(1);
123+
expect(container.querySelector('[role="alert"]')?.textContent).toContain(
124+
"Could not load branches",
125+
);
126+
api.listBranches.mockResolvedValue(page(["feature"]));
127+
await act(async () =>
128+
container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click(),
129+
);
130+
expect(options().map((option) => option.textContent)).toEqual(["feature"]);
131+
expect(container.querySelector('[role="alert"]')).toBeNull();
132+
});
133+
134+
it("preserves description search and query-specific empty messages for existing selectors", async () => {
135+
await act(async () =>
136+
root.render(
137+
<CustomSelect
138+
value="one"
139+
options={[{ value: "one", label: "Project", description: "example.test" }]}
140+
onChange={changed}
141+
searchPlaceholder="Search projects"
142+
emptySearchMessage={(query) => `No project: ${query}`}
143+
/>,
144+
),
145+
);
146+
await open();
147+
await search("example.test");
148+
expect(options()).toHaveLength(1);
149+
await search("missing");
150+
expect(document.body.textContent).toContain("No project: missing");
151+
});
152+
});

0 commit comments

Comments
 (0)