Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(environment): list GitHub repos through the GitHub App installations (#22633)

Rdmclin24769e7597372
diff --git a/apps/server/src/routers/lambda/__tests__/environment.test.ts b/apps/server/src/routers/lambda/__tests__/environment.test.ts
index daa2b69457f..d02b2c8f066 100644
--- a/apps/server/src/routers/lambda/__tests__/environment.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/environment.test.ts
@@ -25,14 +25,13 @@ vi.mock('@/database/models/environment', () => ({
}),
}));
-const mockListRepositoryBranches = vi.fn();
+const mockListBranches = vi.fn();
+const mockListRepositories = vi.fn();
-vi.mock('@/server/services/connectorData', () => ({
- ConnectorDataService: vi.fn(function () {
- return {
- getGitHubClient: async () => ({ listRepositoryBranches: mockListRepositoryBranches }),
- };
- }),
+vi.mock('@/server/services/scm/repositories', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ listScopeGitHubRepositories: mockListRepositories,
+ listScopeGitHubRepositoryBranches: mockListBranches,
}));
// The definitions need no drive: if this router ever asked for the claim, the
@@ -44,7 +43,7 @@ vi.mock('@/server/services/sandbox', () => ({
}));
const { environmentRouter } = await import('../environment');
-const { ConnectorDataError } = await import('@lobechat/connector-data');
+const { ScmRepositoriesUnavailableError } = await import('@/server/services/scm/repositories');
/** Shaped like the driver error drizzle surfaces, nested behind `cause`. */
const driverError = (code: string, constraint?: string) => {
@@ -192,19 +191,23 @@ describe('environmentRouter', () => {
});
describe('listGithubBranches', () => {
- it('lists the branches of one repository through the connected GitHub account', async () => {
- mockListRepositoryBranches.mockResolvedValue(['canary', 'main']);
+ it('lists branches through the installation that grants the repository', async () => {
+ mockListBranches.mockResolvedValue(['canary', 'main']);
const result = await caller().listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });
expect(result).toEqual({ branches: ['canary', 'main'], connected: true, truncated: false });
- expect(mockListRepositoryBranches).toHaveBeenCalledWith('lobehub', 'lobehub');
+ expect(mockListBranches).toHaveBeenCalledWith(
+ ctx.serverDB,
+ { userId: 'user-1', workspaceId: 'ws-1' },
+ { limit: 1000, repoFullName: 'lobehub/lobehub' },
+ );
});
// At the ceiling the list may be partial; the picker falls back to typing
// so a branch past it can still be entered.
it('says when the list reached the ceiling and may be partial', async () => {
- mockListRepositoryBranches.mockResolvedValue(
+ mockListBranches.mockResolvedValue(
Array.from({ length: 1000 }, (_, index) => `branch-${index}`),
);
@@ -213,20 +216,113 @@ describe('environmentRouter', () => {
expect(result.truncated).toBe(true);
});
- it('answers not connected rather than failing when GitHub is unavailable', async () => {
- mockListRepositoryBranches.mockRejectedValue(
- new ConnectorDataError({
- code: 'not_connected',
- message: 'no token',
- operation: 'listRepositoryBranches',
- provider: 'github',
- retryable: false,
- }),
- );
+ it('answers not connected when no installation grants the repository', async () => {
+ mockListBranches.mockResolvedValue(null);
const result = await caller().listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });
expect(result).toEqual({ branches: [], connected: false, truncated: false });
});
});
+
+ describe('listGithubRepositories', () => {
+ const listed = (overrides: object = {}) => ({
+ configured: true,
+ installations: 1,
+ repositories: [],
+ truncated: false,
+ ...overrides,
+ });
+
+ // The regression behind T-13707: the picker read the person's Market OAuth
+ // connection, so a broken proxy hid repositories the workspace's GitHub App
+ // could clone. The list now comes from those installations.
+ it('lists what the scope GitHub App installations can read, grouped by owner', async () => {
+ mockListRepositories.mockResolvedValue(
+ listed({
+ repositories: [
+ {
+ defaultBranch: 'canary',
+ description: null,
+ fullName: 'lobehub/lobehub',
+ htmlUrl: 'https://github.com/lobehub/lobehub',
+ ownerAvatarUrl: null,
+ private: false,
+ pushedAt: '2026-11-01T00:00:00Z',
+ },
+ {
+ defaultBranch: 'main',
+ description: null,
+ fullName: 'lobehub-biz/torii',
+ htmlUrl: 'https://github.com/lobehub-biz/torii',
+ ownerAvatarUrl: null,
+ private: true,
+ pushedAt: null,
+ },
+ ],
+ }),
+ );
+
+ expect(await caller().listGithubRepositories()).toEqual({
+ configured: true,
+ connected: true,
+ truncated: false,
+ repositories: [
+ { defaultBranch: 'canary', isPrivate: false, name: 'lobehub', owner: 'lobehub' },
+ { defaultBranch: 'main', isPrivate: true, name: 'torii', owner: 'lobehub-biz' },
+ ],
+ });
+ expect(mockListRepositories).toHaveBeenCalledWith(ctx.serverDB, {
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('answers not connected when the scope has no installation', async () => {
+ mockListRepositories.mockResolvedValue(listed({ installations: 0 }));
+ expect(await caller().listGithubRepositories()).toEqual({
+ configured: true,
+ connected: false,
+ repositories: [],
+ truncated: false,
+ });
+ });
+
+ // Without a GitHub App there is nothing to install, so the picker must not
+ // offer a connect button that leads nowhere.
+ it('says when this server has no GitHub App at all', async () => {
+ mockListRepositories.mockResolvedValue(listed({ configured: false, installations: 0 }));
+ expect(await caller().listGithubRepositories()).toMatchObject({
+ configured: false,
+ connected: false,
+ });
+ });
+
+ it('passes on that an installation held more repositories than were listed', async () => {
+ mockListRepositories.mockResolvedValue(listed({ truncated: true }));
+
+ expect((await caller().listGithubRepositories()).truncated).toBe(true);
+ });
+
+ it('keeps an installed scope with nothing granted apart from not connected', async () => {
+ mockListRepositories.mockResolvedValue(listed());
+
+ expect(await caller().listGithubRepositories()).toEqual({
+ configured: true,
+ connected: true,
+ truncated: false,
+ repositories: [],
+ });
+ });
+
+ it('reports a failure when every installation failed to answer', async () => {
+ mockListRepositories.mockRejectedValue(
+ new ScmRepositoriesUnavailableError(new Error('rate limited')),
+ );
+
+ await expect(caller().listGithubRepositories()).rejects.toMatchObject({
+ code: 'BAD_GATEWAY',
+ });
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/environment.ts b/apps/server/src/routers/lambda/environment.ts
index 92788393711..d55e9b6c263 100644
--- a/apps/server/src/routers/lambda/environment.ts
+++ b/apps/server/src/routers/lambda/environment.ts
@@ -1,4 +1,3 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -7,7 +6,11 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { EnvironmentModel } from '@/database/models/environment';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { ConnectorDataService } from '@/server/services/connectorData';
+import {
+ listScopeGitHubRepositories,
+ listScopeGitHubRepositoryBranches,
+ ScmRepositoriesUnavailableError,
+} from '@/server/services/scm/repositories';
import { configurationSchema, newConfigurationSchema } from './_schema/environment';
import {
@@ -27,14 +30,6 @@ import { idSchema, nameSchema, visibilitySchema } from './sandboxStorage/schemas
* drive and is managed through `sandboxStorage`, which does ask.
*/
-/**
- * "You have not connected GitHub" travels as an error from the connector layer,
- * but for the picker it is an answer, not a failure — the one it is there to
- * help the user fix.
- */
-const isGithubUnavailable = (error: unknown): boolean =>
- error instanceof ConnectorDataError && error.provider === 'github' && !error.retryable;
-
const environmentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -49,17 +44,18 @@ const environmentProcedure = wsCompatProcedure.use(serverDatabase).use(async (op
});
});
+/**
+ * GitHub reads go through the scope's GitHub App installations — the same
+ * grant `resolveScmCloneCredential` clones with — so the picker offers exactly
+ * what a build from the pick can check out. Not the person's own OAuth
+ * connection: that sees more than any build can clone, and depends on a proxy
+ * the clone never uses.
+ */
const githubProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
return opts.next({
- ctx: {
- connectorDataService: new ConnectorDataService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ),
- },
+ ctx: { scope: { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null } },
});
});
@@ -88,49 +84,71 @@ export const environmentProcedures = {
/**
* The branches of one repository, so the environment's checkout target is
- * picked from what exists rather than typed. No connection is not an error,
- * it is `connected: false`.
+ * picked from what exists rather than typed. No installation granting the
+ * repository is not an error, it is `connected: false`.
*/
listGithubBranches: githubProcedure
.input(z.object({ owner: z.string().min(1).max(255), repository: z.string().min(1).max(255) }))
.query(async ({ ctx, input }) => {
- try {
- const client = await ctx.connectorDataService.getGitHubClient();
- const branches = await client.listRepositoryBranches(input.owner, input.repository);
-
- return {
- branches,
- connected: true,
- // At the ceiling the list may be missing branches, and a picker
- // that only offers what it was given would make those unselectable.
- truncated: branches.length >= MAX_REPOSITORY_BRANCHES,
- };
- } catch (error) {
- if (isGithubUnavailable(error)) return { branches: [], connected: false, truncated: false };
-
- throw error;
- }
+ const branches = await listScopeGitHubRepositoryBranches(ctx.serverDB, ctx.scope, {
+ limit: MAX_REPOSITORY_BRANCHES,
+ repoFullName: `${input.owner}/${input.repository}`,
+ });
+ if (!branches) return { branches: [], connected: false, truncated: false };
+
+ return {
+ branches,
+ connected: true,
+ // At the ceiling the list may be missing branches, and a picker
+ // that only offers what it was given would make those unselectable.
+ truncated: branches.length >= MAX_REPOSITORY_BRANCHES,
+ };
}),
/**
- * Every repository this account can build an environment from, newest
- * activity first, each carrying the owner it belongs to so the caller can
- * group them without a second request per organization.
+ * Every repository this scope's GitHub App installations can read, newest
+ * push first, each carrying the owner it belongs to so the caller can group
+ * them without a second request per organization.
*
- * A missing GitHub connection is NOT an error here: it is the state the
- * picker exists to resolve, so it answers `connected: false` and lets the
- * UI offer the connection instead of a failure.
+ * No installation is NOT an error here: it is the state the picker exists
+ * to resolve, so it answers `connected: false` and lets the UI offer the
+ * GitHub integration instead of a failure. `configured: false` says that
+ * offer would lead nowhere: this server has no GitHub App to install.
+ * `truncated` says an installation held more than the listing reads, so a
+ * repository may be missing from the choices.
*/
listGithubRepositories: githubProcedure.query(async ({ ctx }) => {
+ let listed: Awaited<ReturnType<typeof listScopeGitHubRepositories>>;
try {
- const client = await ctx.connectorDataService.getGitHubClient();
-
- return { connected: true, repositories: await client.listAccessibleRepositories() };
+ listed = await listScopeGitHubRepositories(ctx.serverDB, ctx.scope);
} catch (error) {
- if (isGithubUnavailable(error)) return { connected: false, repositories: [] };
+ if (!(error instanceof ScmRepositoriesUnavailableError)) throw error;
- throw error;
+ throw new TRPCError({ cause: error.cause, code: 'BAD_GATEWAY', message: error.message });
}
+ if (!listed.configured || listed.installations === 0) {
+ return {
+ configured: listed.configured,
+ connected: false,
+ repositories: [],
+ truncated: false,
+ };
+ }
+
+ return {
+ configured: true,
+ connected: true,
+ truncated: listed.truncated,
+ repositories: listed.repositories.map((item) => {
+ const [owner, name] = item.fullName.split('/');
+ return {
+ defaultBranch: item.defaultBranch,
+ isPrivate: item.private,
+ name,
+ owner,
+ };
+ }),
+ };
}),
/**
diff --git a/apps/server/src/routers/lambda/scm.ts b/apps/server/src/routers/lambda/scm.ts
index 67548cc84de..0556cd946ff 100644
--- a/apps/server/src/routers/lambda/scm.ts
+++ b/apps/server/src/routers/lambda/scm.ts
@@ -1,6 +1,4 @@
-import type { ScmRepositoryListItem } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import pMap from 'p-map';
import { z } from 'zod';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
@@ -12,12 +10,13 @@ import {
import { scmEnv } from '@/envs/scm';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import {
- fetchGitHubInstallation,
- listGitHubInstallationRepositoryDetails,
-} from '@/server/services/scm/github/app';
+import { fetchGitHubInstallation } from '@/server/services/scm/github/app';
import { SCM_MAX_WAKES } from '@/server/services/scm/limits';
import { consumeScmInstallClaim } from '@/server/services/scm/oauth/stateStore';
+import {
+ listScopeGitHubRepositories,
+ ScmRepositoriesUnavailableError,
+} from '@/server/services/scm/repositories';
import { canWriteScmScope } from '@/server/services/scm/scope';
/** Path the "Connect GitHub" button navigates to; the server route owns the redirect. */
@@ -156,56 +155,13 @@ export const scmRouter = router({
* others listed; only when every one fails is that an error.
*/
listRepositories: scmProcedure.query(async ({ ctx }) => {
- if (!scmEnv.ENABLED_GITHUB_APP) {
- return { configured: false, installations: 0, repositories: [], truncated: false };
- }
+ try {
+ return await listScopeGitHubRepositories(ctx.serverDB, ctx.scope);
+ } catch (error) {
+ if (!(error instanceof ScmRepositoriesUnavailableError)) throw error;
- const installations = (await ScmInstallationModel.listByScope(ctx.serverDB, ctx.scope)).filter(
- (item) => item.provider === 'github' && !item.suspendedAt,
- );
- // Bounded fan-out: one GitHub request per installation, capped so a scope with
- // many installations cannot open an unbounded number of connections at once.
- const outcomes = await pMap(
- installations,
- async (item) => {
- try {
- const value = await listGitHubInstallationRepositoryDetails(item.installationId);
- return { installationId: item.installationId, ok: true as const, value };
- } catch (error) {
- return { error, installationId: item.installationId, ok: false as const };
- }
- },
- { concurrency: 5 },
- );
-
- const byName = new Map<string, ScmRepositoryListItem>();
- const failures: unknown[] = [];
- let truncated = false;
- for (const outcome of outcomes) {
- if (!outcome.ok) {
- failures.push(outcome.error);
- console.error(
- '[scm:listRepositories] installation %s: %s',
- outcome.installationId,
- (outcome.error as Error)?.message,
- );
- continue;
- }
- truncated ||= outcome.value.truncated;
- for (const repo of outcome.value.repositories) byName.set(repo.fullName.toLowerCase(), repo);
- }
- if (installations.length > 0 && failures.length === installations.length) {
- throw new TRPCError({
- cause: failures[0],
- code: 'BAD_GATEWAY',
- message: 'Could not list repositories from GitHub',
- });
+ throw new TRPCError({ cause: error.cause, code: 'BAD_GATEWAY', message: error.message });
}
-
- const repositories = [...byName.values()].sort((a, b) =>
- (b.pushedAt ?? '').localeCompare(a.pushedAt ?? ''),
- );
- return { configured: true, installations: installations.length, repositories, truncated };
}),
});
diff --git a/apps/server/src/services/scm/__tests__/repositories.test.ts b/apps/server/src/services/scm/__tests__/repositories.test.ts
new file mode 100644
index 00000000000..3295dc7f875
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/repositories.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmInstallationModel } from '@/database/models/scm';
+import { scmInstallations, users } from '@/database/schemas';
+
+import { listScopeGitHubRepositoryBranches } from '../repositories';
+
+const scmEnv = vi.hoisted(() => ({ ENABLED_GITHUB_APP: true }));
+const listBranches = vi.hoisted(() => vi.fn());
+
+vi.mock('@/envs/scm', () => ({ scmEnv }));
+vi.mock('../github/app', () => ({
+ listGitHubInstallationRepositoryBranches: listBranches,
+ listGitHubInstallationRepositoryDetails: vi.fn(),
+}));
+
+const serverDB = await getTestDB();
+const userId = 'scm-repositories-user';
+const scope = { userId, workspaceId: null };
+
+const install = (params: {
+ accountLogin: string;
+ installationId: string;
+ repositories?: string[];
+ repositorySelection?: 'all' | 'selected';
+ suspended?: boolean;
+}) =>
+ ScmInstallationModel.bind(serverDB, {
+ accountExternalId: `ext-${params.installationId}`,
+ accountLogin: params.accountLogin,
+ accountType: 'organization',
+ installationId: params.installationId,
+ provider: 'github',
+ repositories: (params.repositories ?? []).map((fullName, index) => ({
+ externalId: `${params.installationId}-${index}`,
+ fullName,
+ })),
+ repositorySelection: params.repositorySelection ?? 'selected',
+ suspendedAt: params.suspended ? new Date() : null,
+ userId,
+ });
+
+const branchesOf = (repoFullName: string) =>
+ listScopeGitHubRepositoryBranches(serverDB, scope, { limit: 1000, repoFullName });
+
+beforeEach(async () => {
+ listBranches.mockReset();
+ listBranches.mockResolvedValue(['main']);
+ scmEnv.ENABLED_GITHUB_APP = true;
+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmInstallations).where(eq(scmInstallations.userId, userId));
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+describe('listScopeGitHubRepositoryBranches', () => {
+ it('reads through the installation that was granted the repository', async () => {
+ await install({ accountLogin: 'acme', installationId: '11', repositories: ['acme/other'] });
+ await install({ accountLogin: 'acme', installationId: '12', repositories: ['acme/app'] });
+
+ expect(await branchesOf('acme/app')).toEqual(['main']);
+ expect(listBranches).toHaveBeenCalledWith({
+ installationId: '12',
+ limit: 1000,
+ repoFullName: 'acme/app',
+ });
+ });
+
+ it('matches an all-repositories installation by account', async () => {
+ await install({ accountLogin: 'Acme', installationId: '21', repositorySelection: 'all' });
+
+ expect(await branchesOf('acme/anything')).toEqual(['main']);
+ expect(listBranches).toHaveBeenCalledWith(expect.objectContaining({ installationId: '21' }));
+ });
+
+ it('answers null when no live installation grants the repository', async () => {
+ await install({ accountLogin: 'acme', installationId: '31', repositories: ['acme/other'] });
+ await install({
+ accountLogin: 'acme',
+ installationId: '32',
+ repositories: ['acme/app'],
+ suspended: true,
+ });
+
+ expect(await branchesOf('acme/app')).toBeNull();
+ expect(listBranches).not.toHaveBeenCalled();
+ });
+
+ it('answers null without reading anything when the GitHub App is not configured', async () => {
+ scmEnv.ENABLED_GITHUB_APP = false;
+ await install({ accountLogin: 'acme', installationId: '41', repositorySelection: 'all' });
+
+ expect(await branchesOf('acme/app')).toBeNull();
+ expect(listBranches).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/scm/cloneCredential.ts b/apps/server/src/services/scm/cloneCredential.ts
index 94086c834ef..3f675f6d953 100644
--- a/apps/server/src/services/scm/cloneCredential.ts
+++ b/apps/server/src/services/scm/cloneCredential.ts
@@ -60,7 +60,7 @@ export const githubRepositoryOf = (
* and falling through to the other credential path beats minting one that
* cannot clone.
*/
-const installationFor = (
+export const findGitHubInstallationFor = (
installations: ScmInstallationItem[],
repository: string,
): ScmInstallationItem | undefined => {
@@ -107,7 +107,7 @@ export const resolveScmCloneCredential = async (params: {
userId: params.userId,
workspaceId: params.workspaceId,
});
- const installation = installationFor(installations, repository);
+ const installation = findGitHubInstallationFor(installations, repository);
if (!installation) {
log('no installation in scope grants %s', repository);
return null;
diff --git a/apps/server/src/services/scm/github/app.ts b/apps/server/src/services/scm/github/app.ts
index a35e276e3c9..5ea5626679a 100644
--- a/apps/server/src/services/scm/github/app.ts
+++ b/apps/server/src/services/scm/github/app.ts
@@ -228,6 +228,36 @@ export const listGitHubInstallationRepositoryDetails = async (
return { repositories: repositories.slice(0, limit), truncated: repositories.length > limit };
};
+/**
+ * Branch names of one repository, read with the installation's own token —
+ * the same grant a build from that repository clones with. Walked to `limit`
+ * rather than to the end: a repository with thousands of branches would
+ * otherwise be dozens of requests behind one picker, so a caller that gets
+ * exactly `limit` back should treat the list as partial.
+ */
+export const listGitHubInstallationRepositoryBranches = async (params: {
+ installationId: string;
+ limit: number;
+ repoFullName: string;
+}): Promise<string[]> => {
+ const app = getGitHubApp();
+ if (!app) throw new Error('GitHub App is not configured');
+
+ const { owner, repo } = parseRepo(params.repoFullName);
+ const octokit = await app.getInstallationOctokit(Number(params.installationId));
+ const names: string[] = [];
+ for await (const { data } of octokit.paginate.iterator('GET /repos/{owner}/{repo}/branches', {
+ owner,
+ per_page: 100,
+ repo,
+ })) {
+ for (const branch of data) if (branch.name) names.push(branch.name);
+ if (names.length >= params.limit) break;
+ }
+
+ return names.slice(0, params.limit);
+};
+
/**
* Cut an Actions job log down to the part that explains the failure. Logs
* open with hundreds of lines of checkout noise; the first `##[error]`
diff --git a/apps/server/src/services/scm/repositories.ts b/apps/server/src/services/scm/repositories.ts
new file mode 100644
index 00000000000..aafa0d1e299
--- /dev/null
+++ b/apps/server/src/services/scm/repositories.ts
@@ -0,0 +1,125 @@
+import type { ScmRepositoryListItem } from '@lobechat/types';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { ScmInstallationModel } from '@/database/models/scm';
+import type { LobeChatDatabase } from '@/database/type';
+import { scmEnv } from '@/envs/scm';
+
+import { findGitHubInstallationFor } from './cloneCredential';
+import {
+ listGitHubInstallationRepositoryBranches,
+ listGitHubInstallationRepositoryDetails,
+} from './github/app';
+
+const log = debug('lobe-server:scm:repositories');
+
+interface ScmScope {
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/** Every installation of the scope failed to answer; nothing was listed. */
+export class ScmRepositoriesUnavailableError extends Error {
+ constructor(cause: unknown) {
+ super('Could not list repositories from GitHub', { cause });
+ this.name = 'ScmRepositoriesUnavailableError';
+ }
+}
+
+const liveGitHubInstallations = async (db: LobeChatDatabase, scope: ScmScope) =>
+ (await ScmInstallationModel.listByScope(db, scope)).filter(
+ (item) => item.provider === 'github' && !item.suspendedAt,
+ );
+
+/**
+ * Repositories the scope's live GitHub App installations can read, most
+ * recently pushed first. Read through the installations rather than anyone's
+ * own token, so the list is exactly what a build from the pick can clone (see
+ * `resolveScmCloneCredential`). One installation failing (rate limit, revoked
+ * on GitHub before the webhook lands) leaves the others listed; only when
+ * every one fails is that an error.
+ */
+export const listScopeGitHubRepositories = async (
+ db: LobeChatDatabase,
+ scope: ScmScope,
+): Promise<{
+ configured: boolean;
+ installations: number;
+ repositories: ScmRepositoryListItem[];
+ truncated: boolean;
+}> => {
+ if (!scmEnv.ENABLED_GITHUB_APP) {
+ return { configured: false, installations: 0, repositories: [], truncated: false };
+ }
+
+ const installations = await liveGitHubInstallations(db, scope);
+ // Bounded fan-out: one GitHub request per installation, capped so a scope with
+ // many installations cannot open an unbounded number of connections at once.
+ const outcomes = await pMap(
+ installations,
+ async (item) => {
+ try {
+ const value = await listGitHubInstallationRepositoryDetails(item.installationId);
+ return { installationId: item.installationId, ok: true as const, value };
+ } catch (error) {
+ return { error, installationId: item.installationId, ok: false as const };
+ }
+ },
+ { concurrency: 5 },
+ );
+
+ const byName = new Map<string, ScmRepositoryListItem>();
+ const failures: unknown[] = [];
+ let truncated = false;
+ for (const outcome of outcomes) {
+ if (!outcome.ok) {
+ failures.push(outcome.error);
+ console.error(
+ '[scm:repositories] installation %s: %s',
+ outcome.installationId,
+ (outcome.error as Error)?.message,
+ );
+ continue;
+ }
+ truncated ||= outcome.value.truncated;
+ for (const repo of outcome.value.repositories) byName.set(repo.fullName.toLowerCase(), repo);
+ }
+ if (installations.length > 0 && failures.length === installations.length) {
+ throw new ScmRepositoriesUnavailableError(failures[0]);
+ }
+
+ const repositories = [...byName.values()].sort((a, b) =>
+ (b.pushedAt ?? '').localeCompare(a.pushedAt ?? ''),
+ );
+ return { configured: true, installations: installations.length, repositories, truncated };
+};
+
+/**
+ * Branch names of one repository, through the scope's installation that was
+ * granted it. `null` when no live installation grants the repository (or the
+ * App is not configured): the caller cannot list it, which is not a failure.
+ * At `limit` the list may be partial.
+ */
+export const listScopeGitHubRepositoryBranches = async (
+ db: LobeChatDatabase,
+ scope: ScmScope,
+ params: { limit: number; repoFullName: string },
+): Promise<string[] | null> => {
+ if (!scmEnv.ENABLED_GITHUB_APP) return null;
+
+ const installation = findGitHubInstallationFor(
+ await liveGitHubInstallations(db, scope),
+ params.repoFullName,
+ );
+ if (!installation) {
+ log('no installation in scope grants %s', params.repoFullName);
+ return null;
+ }
+
+ return listGitHubInstallationRepositoryBranches({
+ installationId: installation.installationId,
+ limit: params.limit,
+ repoFullName: params.repoFullName,
+ });
+};
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 5b2a6f7642c..443dad63cf1 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -772,6 +772,8 @@
"environments.github.repositoryPending": "Choose an organization first",
"environments.github.repositoryPlaceholder": "Search repositories",
"environments.github.reviewAccess": "Review access",
+ "environments.github.truncated": "Only {{count}} repositories are listed, so some may be missing. Limit the GitHub App to fewer repositories to see the rest.",
+ "environments.github.unconfigured": "GitHub isn't set up on this server, so repositories can't be listed.",
"environments.hasInstances": "Remove its other copies first",
"environments.inProject": "A project still uses this environment — remove it from the project first",
"environments.instances.add": "New copy",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index bba740bd864..8140658c56b 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -772,6 +772,8 @@
"environments.github.repositoryPending": "请先选择组织",
"environments.github.repositoryPlaceholder": "搜索仓库",
"environments.github.reviewAccess": "检查授权范围",
+ "environments.github.truncated": "这里只列出了 {{count}} 个仓库,可能有遗漏。把 GitHub App 的授权范围缩小到更少的仓库即可看到其余仓库。",
+ "environments.github.unconfigured": "当前服务器未配置 GitHub,无法列出仓库。",
"environments.hasInstances": "请先删掉它的其他副本",
"environments.inProject": "仍有项目在使用这个环境——请先把它从项目中移除",
"environments.instances.add": "新建副本",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index d8b5d82609c..05b5a5e6577 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4583,6 +4583,10 @@ When I am ___, I need ___
'environments.github.noRepositories': 'This connection cannot see any repositories yet',
'environments.github.connect': 'Connect GitHub',
'environments.github.reviewAccess': 'Review access',
+ 'environments.github.truncated':
+ 'Only {{count}} repositories are listed, so some may be missing. Limit the GitHub App to fewer repositories to see the rest.',
+ 'environments.github.unconfigured':
+ "GitHub isn't set up on this server, so repositories can't be listed.",
'environments.instances.create': 'New copy',
'environments.form.description': 'Description',
'environments.form.descriptionPlaceholder': 'What this environment is for',
diff --git a/src/features/EnvironmentManager/EnvironmentForm.tsx b/src/features/EnvironmentManager/EnvironmentForm.tsx
index f369c1e5fc3..4adb8b74277 100644
--- a/src/features/EnvironmentManager/EnvironmentForm.tsx
+++ b/src/features/EnvironmentManager/EnvironmentForm.tsx
@@ -7,6 +7,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { environmentService, type SandboxEnvironmentSpecification } from '@/services/environment';
import EnvironmentVariables from './EnvironmentVariables';
@@ -85,8 +86,11 @@ const BranchField = memo<{
}>(({ onSave, owner, repository, value }) => {
const { t } = useTranslation('setting');
const [editing, setEditing] = useState(false);
+ // Keyed by workspace: which branches can be listed depends on that
+ // workspace's GitHub App installations.
+ const workspaceId = useActiveWorkspaceId();
const { data, error, isLoading } = useSWR(
- editing ? ['sandbox-github-branches', owner, repository] : null,
+ editing ? ['sandbox-github-branches', workspaceId, owner, repository] : null,
() => environmentService.listGithubBranches({ owner, repository }),
);
diff --git a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
index 7b1e9bdc28d..7f54236b79b 100644
--- a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
+++ b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
@@ -6,6 +6,7 @@ import { ArrowRightIcon, LockIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useGithubRepositories } from './useGithubRepositories';
@@ -70,7 +71,7 @@ interface GithubRepositoryPickerProps {
onChange: (selection: GithubRepositorySelection | undefined) => void;
/**
* Run before navigating away from this picker. The picker lives in a dialog,
- * and leaving it open behind the credentials page would strand whatever the
+ * and leaving it open behind the GitHub integration page would strand whatever the
* person had already typed.
*/
onLeave?: () => void;
@@ -81,11 +82,11 @@ interface GithubRepositoryPickerProps {
* The one repository an environment builds from, chosen in two steps:
* organization, then repository within it.
*
- * Both lists come from a single `/user/repos` call, which already spans every
- * organization the account belongs to. The organizations are derived from what
- * came back rather than fetched separately: an organization holding nothing
- * this account can reach is not a choice, and listing per organization would
- * be one request per organization for a set already in hand — switching
+ * Both lists come from one listing of what the workspace's GitHub App
+ * installations can read — the same grant a build clones with, so every
+ * choice offered is one the build can check out. The organizations are
+ * derived from what came back rather than fetched separately: an organization
+ * holding nothing the installations can reach is not a choice, and switching
* organizations costs nothing here.
*
* Both are searchable, because either half can be the one the person
@@ -94,7 +95,7 @@ interface GithubRepositoryPickerProps {
* Choosing nothing is a choice: an environment with no repository is a blank
* working directory, which is a reasonable thing to want.
*
- * No GitHub connection is not an error and not a dead end — it is one click
+ * No GitHub App installation is not an error and not a dead end — it is one click
* from being resolved, so the picker offers that click rather than reporting
* a state and leaving the person to find the page themselves.
*/
@@ -105,7 +106,7 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
const connectGithub = () => {
onLeave?.();
- navigate('/settings/credential');
+ navigate(GITHUB_RETURN_TO);
};
const { data, isLoading, isValidating, retry, state } = useGithubRepositories();
@@ -137,29 +138,33 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
: 'environments.github.loadFailed',
),
}
- : state === 'disconnected'
- ? { action: 'connect', text: t('environments.github.notConnected') }
- : state === 'empty'
- ? { action: 'review', text: t('environments.github.noRepositories') }
- : undefined;
+ : state === 'unconfigured'
+ ? { action: undefined, text: t('environments.github.unconfigured') }
+ : state === 'disconnected'
+ ? { action: 'connect', text: t('environments.github.notConnected') }
+ : state === 'empty'
+ ? { action: 'review', text: t('environments.github.noRepositories') }
+ : undefined;
const guideContent = guide && (
<div className={styles.guide} role={state === 'error' ? 'alert' : undefined}>
<span className={styles.guideText}>{guide.text}</span>
- <Button
- loading={guide.action === 'retry' && isValidating}
- size={'small'}
- onClick={guide.action === 'retry' ? () => void retry() : connectGithub}
- >
- {guide.action === 'retry'
- ? t('retry', { ns: 'common' })
- : t(
- guide.action === 'connect'
- ? 'environments.github.connect'
- : 'environments.github.reviewAccess',
- )}
- {guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}
- </Button>
+ {guide.action && (
+ <Button
+ loading={guide.action === 'retry' && isValidating}
+ size={'small'}
+ onClick={guide.action === 'retry' ? () => void retry() : connectGithub}
+ >
+ {guide.action === 'retry'
+ ? t('retry', { ns: 'common' })
+ : t(
+ guide.action === 'connect'
+ ? 'environments.github.connect'
+ : 'environments.github.reviewAccess',
+ )}
+ {guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}
+ </Button>
+ )}
</div>
);
@@ -245,6 +250,11 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
/>
</div>
</Flexbox>
+ {data?.truncated && (
+ <Text fontSize={11} type={'secondary'}>
+ {t('environments.github.truncated', { count: repositories.length })}
+ </Text>
+ )}
</Flexbox>
);
});
diff --git a/src/features/EnvironmentManager/useGithubRepositories.test.ts b/src/features/EnvironmentManager/useGithubRepositories.test.ts
index 38c447b2ba1..8cd94d3d1de 100644
--- a/src/features/EnvironmentManager/useGithubRepositories.test.ts
+++ b/src/features/EnvironmentManager/useGithubRepositories.test.ts
@@ -60,9 +60,7 @@ describe('GitHub repository loading', () => {
});
it('does not call a pending request empty', () => {
- vi.spyOn(environmentService, 'listGithubRepositories').mockReturnValue(
- new Promise(() => {}),
- );
+ vi.spyOn(environmentService, 'listGithubRepositories').mockReturnValue(new Promise(() => {}));
const { result } = setup();
expect(result.current.state).toBe('loading');
});
@@ -75,4 +73,15 @@ describe('GitHub repository loading', () => {
const { result } = setup();
await waitFor(() => expect(result.current.state).toBe('disconnected'));
});
+
+ it('tells a server with no GitHub App apart from a scope that has not connected one', async () => {
+ vi.spyOn(environmentService, 'listGithubRepositories').mockResolvedValue({
+ configured: false,
+ connected: false,
+ repositories: [],
+ truncated: false,
+ });
+ const { result } = setup();
+ await waitFor(() => expect(result.current.state).toBe('unconfigured'));
+ });
});
diff --git a/src/features/EnvironmentManager/useGithubRepositories.ts b/src/features/EnvironmentManager/useGithubRepositories.ts
index aa28fb95e3b..7766054f7cc 100644
--- a/src/features/EnvironmentManager/useGithubRepositories.ts
+++ b/src/features/EnvironmentManager/useGithubRepositories.ts
@@ -1,21 +1,30 @@
import useSWR from 'swr';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { environmentService } from '@/services/environment';
-/** Keeps request failure distinct from a successful empty repository listing. */
+/**
+ * Keeps request failure distinct from a successful empty repository listing.
+ * Keyed by workspace: the list comes from that workspace's GitHub App
+ * installations, so another workspace's cached list would offer repositories
+ * its builds cannot clone.
+ */
export const useGithubRepositories = () => {
- const swr = useSWR('sandbox-github-repositories', () =>
+ const workspaceId = useActiveWorkspaceId();
+ const swr = useSWR(['sandbox-github-repositories', workspaceId], () =>
environmentService.listGithubRepositories(),
);
const state = swr.error
? 'error'
: !swr.data
? 'loading'
- : !swr.data.connected
- ? 'disconnected'
- : swr.data.repositories.length === 0
- ? 'empty'
- : 'ready';
+ : swr.data.configured === false
+ ? 'unconfigured'
+ : !swr.data.connected
+ ? 'disconnected'
+ : swr.data.repositories.length === 0
+ ? 'empty'
+ : 'ready';
return {
...swr,