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.

✨ feat(project): create a project from a GitHub repository (#21552)

Arvin Xu4bd14b731e74
diff --git a/apps/server/src/routers/lambda/__tests__/scm.test.ts b/apps/server/src/routers/lambda/__tests__/scm.test.ts
index cd174ae94fd..80b323576be 100644
--- a/apps/server/src/routers/lambda/__tests__/scm.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/scm.test.ts
@@ -24,12 +24,17 @@ const otherUserId = 'scm-router-user-2';
const scmEnv = vi.hoisted(() => ({ ENABLED_GITHUB_APP: true, GITHUB_APP_SLUG: 'lobehub-dev' }));
vi.mock('@/envs/scm', () => ({ scmEnv }));
-const mocks = vi.hoisted(() => ({ consumeClaim: vi.fn(), fetchInstallation: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ consumeClaim: vi.fn(),
+ fetchInstallation: vi.fn(),
+ listRepositories: vi.fn(),
+}));
vi.mock('@/server/services/scm/oauth/stateStore', () => ({
consumeScmInstallClaim: mocks.consumeClaim,
}));
vi.mock('@/server/services/scm/github/app', () => ({
fetchGitHubInstallation: mocks.fetchInstallation,
+ listGitHubInstallationRepositoryDetails: mocks.listRepositories,
}));
vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
@@ -299,4 +304,94 @@ describe('scmRouter', () => {
caller({ userId, workspaceId: workspace.id }).connectInstallation({ claim: 'c6' }),
).resolves.toMatchObject({ userId, workspaceId: workspace.id });
});
+
+ describe('listRepositories', () => {
+ const repo = (fullName: string, pushedAt: string | null) => ({
+ defaultBranch: 'main',
+ description: null,
+ fullName,
+ htmlUrl: `https://github.com/${fullName}`,
+ ownerAvatarUrl: null,
+ private: false,
+ pushedAt,
+ });
+
+ afterEach(() => {
+ mocks.listRepositories.mockReset();
+ scmEnv.ENABLED_GITHUB_APP = true;
+ });
+
+ it('reports an unconfigured deployment without calling GitHub', async () => {
+ scmEnv.ENABLED_GITHUB_APP = false;
+ expect(await caller({ userId }).listRepositories()).toEqual({
+ configured: false,
+ installations: 0,
+ repositories: [],
+ truncated: false,
+ });
+ expect(mocks.listRepositories).not.toHaveBeenCalled();
+ });
+
+ it('reports no installations so the picker can ask to connect GitHub', async () => {
+ expect(await caller({ userId }).listRepositories()).toEqual({
+ configured: true,
+ installations: 0,
+ repositories: [],
+ truncated: false,
+ });
+ });
+
+ it('merges live installations, newest push first, skipping suspended ones', async () => {
+ await bind('201', { userId });
+ await bind('202', { userId });
+ const suspended = await bind('203', { userId });
+ await ScmInstallationModel.setSuspended(serverDB, suspended.id, true);
+ await bind('204', { userId: otherUserId });
+ mocks.listRepositories.mockImplementation(async (installationId: string) =>
+ installationId === '201'
+ ? {
+ repositories: [
+ repo('a/old', '2026-01-01T00:00:00Z'),
+ repo('a/shared', '2026-03-01T00:00:00Z'),
+ ],
+ truncated: false,
+ }
+ : {
+ repositories: [
+ repo('b/new', '2026-05-01T00:00:00Z'),
+ repo('A/Shared', '2026-03-01T00:00:00Z'),
+ ],
+ truncated: true,
+ },
+ );
+
+ const result = await caller({ userId }).listRepositories();
+
+ expect(mocks.listRepositories.mock.calls.map(([id]) => id).sort()).toEqual(['201', '202']);
+ expect(result.installations).toBe(2);
+ expect(result.truncated).toBe(true);
+ expect(result.repositories.map((item) => item.fullName.toLowerCase())).toEqual([
+ 'b/new',
+ 'a/shared',
+ 'a/old',
+ ]);
+ });
+
+ it('lists what it can when one installation fails, and errors only when all do', async () => {
+ await bind('301', { userId });
+ await bind('302', { userId });
+ mocks.listRepositories.mockImplementation(async (installationId: string) => {
+ if (installationId === '301') throw new Error('rate limited');
+ return { repositories: [repo('c/ok', null)], truncated: false };
+ });
+ expect(
+ (await caller({ userId }).listRepositories()).repositories.map((item) => item.fullName),
+ ).toEqual(['c/ok']);
+
+ mocks.listRepositories.mockRejectedValue(new Error('down'));
+ await expect(caller({ userId }).listRepositories()).rejects.toMatchObject({
+ code: 'BAD_GATEWAY',
+ });
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.test.ts b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.test.ts
new file mode 100644
index 00000000000..a3634a69fe7
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.test.ts
@@ -0,0 +1,31 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { rethrowDuplicateProjectField } from './projectConstraintErrors';
+
+// Drizzle wraps the driver error, so the Postgres fields sit down the cause chain.
+const driverError = (code: string, constraint: string) =>
+ Object.assign(new Error('Failed query: insert into "projects" ...'), {
+ cause: { code, constraint },
+ });
+
+describe('rethrowDuplicateProjectField', () => {
+ it.each([
+ ['projects_slug_user_id_unique', 'DUPLICATE_PROJECT_SLUG'],
+ ['projects_slug_workspace_id_unique', 'DUPLICATE_PROJECT_SLUG'],
+ ['projects_identifier_user_id_unique', 'DUPLICATE_PROJECT_IDENTIFIER'],
+ ['projects_identifier_workspace_id_unique', 'DUPLICATE_PROJECT_IDENTIFIER'],
+ ])('maps %s to %s', (constraint, message) => {
+ expect(() => rethrowDuplicateProjectField(driverError('23505', constraint))).toThrow(
+ expect.objectContaining({ code: 'CONFLICT', message }),
+ );
+ });
+
+ it('rethrows anything else untouched', () => {
+ const other = driverError('23505', 'environments_user_name_unique');
+ expect(() => rethrowDuplicateProjectField(other)).toThrow(other);
+ const notUnique = driverError('23503', 'projects_slug_user_id_unique');
+ expect(() => rethrowDuplicateProjectField(notUnique)).toThrow(notUnique);
+ expect(() => rethrowDuplicateProjectField(new Error('x'))).not.toThrow(TRPCError);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts
new file mode 100644
index 00000000000..b3a0fc1cf3c
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/projectConstraintErrors.ts
@@ -0,0 +1,28 @@
+import { TRPCError } from '@trpc/server';
+
+import { getPostgresErrorField } from '../sandboxStorage/constraintErrors';
+
+/** Unique indexes on `projects`, by the field a person changes to resolve them. */
+const PROJECT_CONSTRAINT_MESSAGES: Record<string, string> = {
+ projects_identifier_user_id_unique: 'DUPLICATE_PROJECT_IDENTIFIER',
+ projects_identifier_workspace_id_unique: 'DUPLICATE_PROJECT_IDENTIFIER',
+ projects_slug_user_id_unique: 'DUPLICATE_PROJECT_SLUG',
+ projects_slug_workspace_id_unique: 'DUPLICATE_PROJECT_SLUG',
+};
+
+/**
+ * A taken slug or identifier is fixed by editing that field, so it arrives as a
+ * CONFLICT with a code the form can translate and show next to the field —
+ * not as the raw driver message, which quotes the whole insert. Trashed
+ * projects still hold their slug and identifier, so this is reachable by
+ * re-creating a project that was just deleted.
+ */
+export const rethrowDuplicateProjectField = (error: unknown): never => {
+ const message =
+ getPostgresErrorField(error, 'code') === '23505'
+ ? PROJECT_CONSTRAINT_MESSAGES[getPostgresErrorField(error, 'constraint') ?? '']
+ : undefined;
+ if (message) throw new TRPCError({ cause: error, code: 'CONFLICT', message });
+
+ throw error;
+};
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index 0ec357677d4..5337d164410 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -16,6 +16,8 @@ import { createDefaultChannel } from '@/server/services/channel/defaultChannel';
import { GoalService } from '@/server/services/goal';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import { rethrowDuplicateProjectField } from './_helpers/projectConstraintErrors';
+
/**
* Reads `workspaceRole` as an optional context field: the cloud workspace-auth
* override injects it, while the OSS stub leaves it absent.
@@ -180,6 +182,13 @@ export const projectRouter = router({
description: z.string().optional(),
identifier: projectIdentifierInput.optional(),
name: z.string().min(1).max(255),
+ repository: z
+ .object({
+ defaultBranch: z.string().max(255).optional(),
+ name: z.string().trim().min(1).max(255),
+ url: z.string().min(1).max(2048),
+ })
+ .optional(),
slug: projectSlugInput.optional(),
visibility: z.enum(PROJECT_VISIBILITIES).optional(),
}),
@@ -189,7 +198,10 @@ export const projectRouter = router({
if (input.coordinatorAgentId) {
await assertResourceUsable(ctx, 'agent', input.coordinatorAgentId);
}
- const project = await withMainAgent(ctx.projectModel, await ctx.projectModel.create(input));
+ const project = await withMainAgent(
+ ctx.projectModel,
+ await ctx.projectModel.create(input).catch(rethrowDuplicateProjectField),
+ );
await createDefaultChannel({
agentId: project.coordinatorAgentId,
db: ctx.serverDB,
diff --git a/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts
index 3aebd6642c2..9967713adcd 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts
@@ -12,7 +12,7 @@ const ENVIRONMENT_NAME_CONSTRAINTS = new Set([
const INSTANCE_DIRECTORY_CONSTRAINT = 'environment_instances_provider_path_unique';
/** Postgres surfaces the driver error somewhere down the `cause` chain. */
-const getPostgresErrorField = (error: unknown, field: string): string | undefined => {
+export const getPostgresErrorField = (error: unknown, field: string): string | undefined => {
let current: unknown = error;
while (current && typeof current === 'object') {
diff --git a/apps/server/src/routers/lambda/scm.ts b/apps/server/src/routers/lambda/scm.ts
index b30edbd4268..67548cc84de 100644
--- a/apps/server/src/routers/lambda/scm.ts
+++ b/apps/server/src/routers/lambda/scm.ts
@@ -1,4 +1,6 @@
+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';
@@ -10,7 +12,10 @@ import {
import { scmEnv } from '@/envs/scm';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { fetchGitHubInstallation } from '@/server/services/scm/github/app';
+import {
+ fetchGitHubInstallation,
+ listGitHubInstallationRepositoryDetails,
+} from '@/server/services/scm/github/app';
import { SCM_MAX_WAKES } from '@/server/services/scm/limits';
import { consumeScmInstallClaim } from '@/server/services/scm/oauth/stateStore';
import { canWriteScmScope } from '@/server/services/scm/scope';
@@ -141,6 +146,67 @@ export const scmRouter = router({
listInstallations: scmProcedure.query(async ({ ctx }) =>
ScmInstallationModel.listByScope(ctx.serverDB, ctx.scope),
),
+
+ /**
+ * Repositories the scope's live GitHub installations can read, most recently
+ * pushed first — the list "new project from GitHub" picks from. Read through
+ * the installations rather than the user's own token, so it shows exactly
+ * what an environment built from the pick can clone. 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.
+ */
+ listRepositories: scmProcedure.query(async ({ ctx }) => {
+ if (!scmEnv.ENABLED_GITHUB_APP) {
+ return { configured: false, installations: 0, repositories: [], truncated: false };
+ }
+
+ 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',
+ });
+ }
+
+ const repositories = [...byName.values()].sort((a, b) =>
+ (b.pushedAt ?? '').localeCompare(a.pushedAt ?? ''),
+ );
+ return { configured: true, installations: installations.length, repositories, truncated };
+ }),
});
export type ScmRouter = typeof scmRouter;
diff --git a/apps/server/src/services/scm/github/app.ts b/apps/server/src/services/scm/github/app.ts
index 299d2fc8543..a35e276e3c9 100644
--- a/apps/server/src/services/scm/github/app.ts
+++ b/apps/server/src/services/scm/github/app.ts
@@ -2,6 +2,7 @@ import type {
ScmActorAssociation,
ScmInstallationRepository,
ScmInstallationSnapshot,
+ ScmRepositoryListItem,
} from '@lobechat/types';
import debug from 'debug';
import { App, Octokit } from 'octokit';
@@ -191,6 +192,42 @@ export const listGitHubInstallationRepositories = async (
return repositories;
};
+/**
+ * The repositories an installation can read, with what a picker shows. Bounded
+ * by `limit` because an all-repositories organization installation can reach
+ * thousands. GitHub returns them in its own order, not by push time, so a
+ * bounded list can miss recent work — `truncated` says so, and the picker
+ * points to pasting the URL instead.
+ */
+export const listGitHubInstallationRepositoryDetails = async (
+ installationId: string,
+ { limit = 500 }: { limit?: number } = {},
+): Promise<{ repositories: ScmRepositoryListItem[]; truncated: boolean }> => {
+ const app = getGitHubApp();
+ if (!app) throw new Error('GitHub App is not configured');
+
+ const octokit = await app.getInstallationOctokit(Number(installationId));
+ const repositories: ScmRepositoryListItem[] = [];
+ for await (const { data } of octokit.paginate.iterator('GET /installation/repositories', {
+ per_page: 100,
+ })) {
+ for (const repo of data) {
+ repositories.push({
+ defaultBranch: repo.default_branch,
+ description: repo.description ?? null,
+ fullName: repo.full_name,
+ htmlUrl: repo.html_url,
+ ownerAvatarUrl: repo.owner?.avatar_url ?? null,
+ private: repo.private,
+ pushedAt: repo.pushed_at ?? null,
+ });
+ }
+ if (repositories.length > limit) break;
+ }
+
+ return { repositories: repositories.slice(0, limit), truncated: repositories.length > 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/locales/en-US/project.json b/locales/en-US/project.json
index 73a31202e61..df69b7bb5d3 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -35,6 +35,8 @@
"create.avatarHint": "Pick an emoji or upload an image. You can also drop an image here.",
"create.avatarInvalidType": "Use a JPG, PNG, GIF, or WEBP image.",
"create.avatarUploadFailed": "Couldn't upload the image. Try again.",
+ "create.blank": "Blank project",
+ "create.fromGithub": "From GitHub repository",
"create.identifierDescription": "Replaces the task number prefix for this project, for example ACE. Leave it empty to use the default prefix.",
"create.identifierInvalid": "Use 3–6 uppercase letters or numbers, starting with a letter.",
"create.identifierLabel": "Identifier (optional)",
@@ -55,6 +57,24 @@
"create.slugLabel": "Slug (optional)",
"create.slugPlaceholder": "my-project",
"create.title": "New project",
+ "createFromGithub.connect": "Connect GitHub",
+ "createFromGithub.disconnected": "Connect GitHub to choose from your repositories, or paste a public repository URL below.",
+ "createFromGithub.duplicateIdentifier": "Another project already uses this identifier. Choose a different one.",
+ "createFromGithub.duplicateName": "A project with this name already exists, including in the trash. Choose a different name.",
+ "createFromGithub.empty": "The connected GitHub accounts haven't given LobeHub access to any repositories yet.",
+ "createFromGithub.environmentHint": "The repository becomes this project's environment, so agents can check it out when they work on the project.",
+ "createFromGithub.loadFailed": "Couldn't load repositories from GitHub.",
+ "createFromGithub.manageAccess": "Manage access",
+ "createFromGithub.private": "Private",
+ "createFromGithub.repositoriesLabel": "Your repositories",
+ "createFromGithub.searchEmpty": "No matching repositories",
+ "createFromGithub.searchPlaceholder": "Search repositories…",
+ "createFromGithub.title": "New project from GitHub",
+ "createFromGithub.truncated": "Only {{count}} repositories are listed. If yours isn't here, paste its URL below.",
+ "createFromGithub.unconfigured": "GitHub isn't set up on this server. Paste a public repository URL below.",
+ "createFromGithub.urlInvalid": "Enter a GitHub repository URL, such as https://github.com/owner/repo.",
+ "createFromGithub.urlLabel": "Or paste a repository URL",
+ "createFromGithub.urlPlaceholder": "https://github.com/owner/repo",
"delete.confirm.continue": "Delete project",
"delete.confirm.kept.files": "Files in the working directories on your devices",
"delete.confirm.kept.work": "Tasks, goals, topics and channels",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index c162cfc9466..1d20bc63a15 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -35,6 +35,8 @@
"create.avatarHint": "选择表情或上传图片,也可以把图片拖到这里",
"create.avatarInvalidType": "请使用 JPG、PNG、GIF 或 WEBP 图片",
"create.avatarUploadFailed": "图片上传失败,请重试",
+ "create.blank": "空白项目",
+ "create.fromGithub": "从 GitHub 仓库创建",
"create.identifierDescription": "填写后替换本项目任务编号的前缀,例如 ACE;不填则使用默认前缀。",
"create.identifierInvalid": "请输入 3–6 位大写字母或数字,并以字母开头。",
"create.identifierLabel": "项目标识(可选)",
@@ -55,6 +57,24 @@
"create.slugLabel": "Slug(可选)",
"create.slugPlaceholder": "my-project",
"create.title": "新建项目",
+ "createFromGithub.connect": "连接 GitHub",
+ "createFromGithub.disconnected": "连接 GitHub 后可直接选择你的仓库,也可以在下方粘贴公开仓库的链接。",
+ "createFromGithub.duplicateIdentifier": "其他项目已在使用这个标识,请换一个。",
+ "createFromGithub.duplicateName": "已存在同名项目(包括回收站中的项目),请换一个名称。",
+ "createFromGithub.empty": "已连接的 GitHub 账号还没有授权 LobeHub 访问任何仓库。",
+ "createFromGithub.environmentHint": "该仓库会成为项目的环境,智能体处理这个项目时可以检出它。",
+ "createFromGithub.loadFailed": "无法从 GitHub 加载仓库。",
+ "createFromGithub.manageAccess": "管理授权",
+ "createFromGithub.private": "私有",
+ "createFromGithub.repositoriesLabel": "你的仓库",
+ "createFromGithub.searchEmpty": "没有匹配的仓库",
+ "createFromGithub.searchPlaceholder": "搜索仓库…",
+ "createFromGithub.title": "从 GitHub 创建项目",
+ "createFromGithub.truncated": "这里只列出了 {{count}} 个仓库。如果没找到你的仓库,请在下方粘贴它的链接。",
+ "createFromGithub.unconfigured": "当前服务器未配置 GitHub。请在下方粘贴公开仓库的链接。",
+ "createFromGithub.urlInvalid": "请输入 GitHub 仓库链接,例如 https://github.com/owner/repo。",
+ "createFromGithub.urlLabel": "或粘贴仓库链接",
+ "createFromGithub.urlPlaceholder": "https://github.com/owner/repo",
"delete.confirm.continue": "删除项目",
"delete.confirm.kept.files": "设备上工作目录中的文件",
"delete.confirm.kept.work": "任务、目标、话题和频道",
diff --git a/packages/database/src/models/__tests__/environment.test.ts b/packages/database/src/models/__tests__/environment.test.ts
index 337f548494c..84b7368d401 100644
--- a/packages/database/src/models/__tests__/environment.test.ts
+++ b/packages/database/src/models/__tests__/environment.test.ts
@@ -62,6 +62,43 @@ describe('EnvironmentModel', () => {
expect((await model.list())[0].name).toBe('Updated resource');
await expect(other.save({ id: env.id, name: 'Denied' })).rejects.toThrow('access denied');
});
+
+ describe('ensureForRepository', () => {
+ it('reuses the caller’s environment for the same repository', async () => {
+ const created = await model.ensureForRepository({
+ name: 'lobehub/lobehub',
+ repositoryUrl: 'https://github.com/lobehub/lobehub',
+ });
+ expect(created.configuration).toMatchObject({
+ kind: 'code',
+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],
+ });
+
+ const reused = await model.ensureForRepository({
+ name: 'anything',
+ repositoryUrl: '[email protected]:lobehub/lobehub.git',
+ });
+ expect(reused.id).toBe(created.id);
+
+ // Another member's environment is never borrowed.
+ const theirs = await other.ensureForRepository({
+ name: 'lobehub/lobehub',
+ repositoryUrl: 'https://github.com/lobehub/lobehub',
+ });
+ expect(theirs.id).not.toBe(created.id);
+ });
+
+ it('suffixes the name when another environment already holds it', async () => {
+ await model.save({ name: 'lobehub/lobehub' });
+ await model.save({ name: 'lobehub/lobehub (2)' });
+
+ const env = await model.ensureForRepository({
+ name: 'lobehub/lobehub',
+ repositoryUrl: 'https://github.com/lobehub/lobehub',
+ });
+ expect(env.name).toBe('lobehub/lobehub (3)');
+ });
+ });
});
it('rejects credentials, clone options and non-repository URLs', () => {
diff --git a/packages/database/src/models/__tests__/project.repository.test.ts b/packages/database/src/models/__tests__/project.repository.test.ts
new file mode 100644
index 00000000000..80e97c8f39d
--- /dev/null
+++ b/packages/database/src/models/__tests__/project.repository.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { environments, projectEnvironments, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { CreateProjectInput } from '../project';
+import { ProjectModel } from '../project';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'project-repository-user';
+let projectIdentifierSequence = 0;
+
+const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>
+ projectModel.create({
+ ...input,
+ identifier: `R${String(++projectIdentifierSequence).padStart(5, '0')}`,
+ });
+
+describe('a project created from a GitHub repository', () => {
+ const model = new ProjectModel(serverDB, userId);
+
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(projectEnvironments);
+ await serverDB.delete(environments);
+ await serverDB.delete(users);
+ });
+
+ it('creates a project from a GitHub repository with its environment attached', async () => {
+ const project = await createProject(model, {
+ name: 'lobehub',
+ repository: {
+ defaultBranch: 'canary',
+ name: 'lobehub/lobehub',
+ url: 'https://github.com/lobehub/lobehub.git',
+ },
+ });
+
+ expect(await model.listEnvironments(project.id)).toEqual([
+ expect.objectContaining({
+ configuration: expect.objectContaining({
+ kind: 'code',
+ sources: [{ kind: 'git', ref: 'canary', url: 'https://github.com/lobehub/lobehub' }],
+ }),
+ name: 'lobehub/lobehub',
+ }),
+ ]);
+
+ // A second project on the same repository shares the definition.
+ const second = await createProject(model, {
+ name: 'lobehub again',
+ repository: { name: 'lobehub/lobehub', url: '[email protected]:lobehub/lobehub.git' },
+ });
+ const [first] = await model.listEnvironments(project.id);
+ expect(await model.listEnvironments(second.id)).toEqual([
+ expect.objectContaining({ id: first.id }),
+ ]);
+ });
+
+ it('names the unique index a taken slug violates, so the router can map it', async () => {
+ await createProject(model, { name: 'Taken', slug: 'taken' });
+ const error = await createProject(model, { name: 'Taken again', slug: 'taken' }).catch(
+ (e: unknown) => e,
+ );
+ let cause: any = error;
+ while (cause && !cause.constraint) cause = cause.cause;
+ expect(cause).toMatchObject({ code: '23505', constraint: 'projects_slug_user_id_unique' });
+ });
+
+ it('creates nothing when the repository URL is not a GitHub repository', async () => {
+ await expect(
+ createProject(model, {
+ name: 'Broken',
+ repository: { name: 'broken', url: 'https://example.com/a/b' },
+ }),
+ ).rejects.toThrow('GitHub');
+ expect(await model.list()).toEqual([]);
+ expect(await serverDB.select().from(environments)).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.ts
index f117aa9a9af..5cfd5a66ceb 100644
--- a/packages/database/src/models/environment.ts
+++ b/packages/database/src/models/environment.ts
@@ -219,6 +219,48 @@ export class EnvironmentModel {
return row;
}
+ /**
+ * The caller's enabled environment that checks out `repositoryUrl`, or a new
+ * `code` environment for it. Reused rather than duplicated so projects made
+ * from the same repository share one definition and its built instances.
+ * Only the caller's own rows match: a colleague's published environment is
+ * theirs to edit, so a project must not silently depend on it.
+ *
+ * A new one is named after the repository; when that name is already taken by
+ * another of the caller's environments, a numeric suffix keeps the
+ * `(user, scope, name)` unique indexes satisfied.
+ */
+ async ensureForRepository(input: {
+ defaultBranch?: string;
+ name: string;
+ repositoryUrl: string;
+ }): Promise<EnvironmentItem> {
+ const url = normalizeProjectRepository(input.repositoryUrl);
+ const [existing] = await this.db
+ .select()
+ .from(environments)
+ .where(
+ and(
+ this.ownership(),
+ eq(environments.enabled, true),
+ sql`${environments.configuration} -> 'sources' @> ${JSON.stringify([{ kind: 'git', url }])}::jsonb`,
+ ),
+ )
+ .orderBy(asc(environments.createdAt))
+ .limit(1);
+ if (existing) return existing;
+
+ const baseName = input.name.trim();
+ let name = baseName;
+ for (let suffix = 2; await this.findByName(name); suffix++) name = `${baseName} (${suffix})`;
+
+ const ref = input.defaultBranch?.trim();
+ return this.create({
+ configuration: { kind: 'code', sources: [{ kind: 'git', url, ...(ref ? { ref } : {}) }] },
+ name,
+ });
+ }
+
private ownership = () => environmentOwnership(this.userId, this.workspaceId);
private visible = () => environmentVisibility(this.userId, this.workspaceId);
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 32f13611993..e2444e6f007 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -37,6 +37,8 @@ export interface CreateProjectInput {
/** Task prefix for this project; omit to keep the scope's default prefix. */
identifier?: string | null;
name: string;
+ /** GitHub repository the project works on; attached as the project's environment. */
+ repository?: { defaultBranch?: string; name: string; url: string };
slug?: string;
visibility?: ProjectVisibility;
}
@@ -147,7 +149,7 @@ export class ProjectModel {
: this.ownedByCaller();
}
- async create(input: CreateProjectInput) {
+ async create({ repository, ...input }: CreateProjectInput) {
const identifier = input.identifier?.trim().toUpperCase() || null;
if (identifier && (identifier.length < 3 || identifier.length > 6)) {
throw new Error('Project identifier must be between 3 and 6 characters');
@@ -189,6 +191,26 @@ export class ProjectModel {
workspaceId: this.workspaceId ?? null,
});
+ // In the same transaction, so a repository the environment cannot accept
+ // leaves no half-made project behind.
+ if (repository) {
+ const environment = await new EnvironmentModel(
+ tx as LobeChatDatabase,
+ this.userId,
+ this.workspaceId,
+ ).ensureForRepository({
+ defaultBranch: repository.defaultBranch,
+ name: repository.name,
+ repositoryUrl: repository.url,
+ });
+ await tx.insert(projectEnvironments).values({
+ addedByUserId: this.userId,
+ environmentId: environment.id,
+ projectId: project.id,
+ workspaceId: this.workspaceId,
+ });
+ }
+
return project;
});
}
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index d2168069871..194fc992dbc 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -167,6 +167,8 @@ export default {
'create.avatarHint': 'Pick an emoji or upload an image. You can also drop an image here.',
'create.avatarInvalidType': 'Use a JPG, PNG, GIF, or WEBP image.',
'create.avatarUploadFailed': "Couldn't upload the image. Try again.",
+ 'create.blank': 'Blank project',
+ 'create.fromGithub': 'From GitHub repository',
'create.identifierDescription':
'Replaces the task number prefix for this project, for example ACE. Leave it empty to use the default prefix.',
'create.identifierInvalid': 'Use 3–6 uppercase letters or numbers, starting with a letter.',
@@ -188,6 +190,32 @@ export default {
'create.slugLabel': 'Slug (optional)',
'create.slugPlaceholder': 'my-project',
'create.title': 'New project',
+ 'createFromGithub.connect': 'Connect GitHub',
+ 'createFromGithub.disconnected':
+ 'Connect GitHub to choose from your repositories, or paste a public repository URL below.',
+ 'createFromGithub.duplicateIdentifier':
+ 'Another project already uses this identifier. Choose a different one.',
+ 'createFromGithub.duplicateName':
+ 'A project with this name already exists, including in the trash. Choose a different name.',
+ 'createFromGithub.empty':
+ "The connected GitHub accounts haven't given LobeHub access to any repositories yet.",
+ 'createFromGithub.environmentHint':
+ "The repository becomes this project's environment, so agents can check it out when they work on the project.",
+ 'createFromGithub.loadFailed': "Couldn't load repositories from GitHub.",
+ 'createFromGithub.manageAccess': 'Manage access',
+ 'createFromGithub.private': 'Private',
+ 'createFromGithub.repositoriesLabel': 'Your repositories',
+ 'createFromGithub.searchEmpty': 'No matching repositories',
+ 'createFromGithub.searchPlaceholder': 'Search repositories…',
+ 'createFromGithub.title': 'New project from GitHub',
+ 'createFromGithub.truncated':
+ "Only {{count}} repositories are listed. If yours isn't here, paste its URL below.",
+ 'createFromGithub.unconfigured':
+ "GitHub isn't set up on this server. Paste a public repository URL below.",
+ 'createFromGithub.urlInvalid':
+ 'Enter a GitHub repository URL, such as https://github.com/owner/repo.',
+ 'createFromGithub.urlLabel': 'Or paste a repository URL',
+ 'createFromGithub.urlPlaceholder': 'https://github.com/owner/repo',
'disabled.action': 'Enable in Labs',
'disabled.title': 'Project workspaces are an Alpha experiment',
'delete.confirm.continue': 'Delete project',
diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.ts
index 8a873b1037e..24c0b851344 100644
--- a/packages/types/src/scm.ts
+++ b/packages/types/src/scm.ts
@@ -64,6 +64,19 @@ export interface ScmInstallationRepository {
private?: boolean;
}
+/** A repository a connected installation can read, as the "new project from GitHub" picker lists it. */
+export interface ScmRepositoryListItem {
+ defaultBranch: string;
+ description: string | null;
+ /** `owner/name` as the provider prints it. */
+ fullName: string;
+ htmlUrl: string;
+ ownerAvatarUrl: string | null;
+ private: boolean;
+ /** ISO timestamp of the latest push; what "recent" sorts by. */
+ pushedAt: string | null;
+}
+
/**
* Open bag for provider-specific installation facts that are safe to read
* without decryption (display names, avatar, granted permissions).
diff --git a/src/features/Projects/CreateFromGithub/Content.tsx b/src/features/Projects/CreateFromGithub/Content.tsx
new file mode 100644
index 00000000000..669c068e08c
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/Content.tsx
@@ -0,0 +1,242 @@
+import type { ScmRepositoryListItem } from '@lobechat/types';
+import {
+ Button,
+ cssVar,
+ Flexbox,
+ Input,
+ ModalFooter,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useProjectStore } from '@/store/project';
+
+import {
+ getCreateProjectInput,
+ getProjectFieldSuggestions,
+ isProjectIdentifierValid,
+} from '../createProjectForm';
+import MainAgentField from '../MainAgentField';
+import { useDefaultMainAgent } from '../useDefaultMainAgent';
+import { parseGithubRepository } from './githubRepository';
+import RepositoryList from './RepositoryList';
+
+/** Server codes for a taken slug or identifier; see `rethrowDuplicateProjectField`. */
+const DUPLICATE_FIELD = {
+ DUPLICATE_PROJECT_IDENTIFIER: 'identifier',
+ DUPLICATE_PROJECT_SLUG: 'name',
+} as const;
+
+interface FormState {
+ /** Default branch of the picked repository; unknown for a pasted URL. */
+ defaultBranch?: string;
+ /** The field another project already holds, as the last create reported it. */
+ duplicate?: 'identifier' | 'name';
+ identifier: string;
+ loading: boolean;
+ /** Explicit pick in this dialog; otherwise the workspace inbox agent, LobeAI. */
+ mainAgentId?: string;
+ name: string;
+ nameEdited: boolean;
+ url: string;
+}
+
+/**
+ * New project from a GitHub repository: pick one the connected GitHub App can
+ * read, or paste a URL, and the project is named after it, led by the default
+ * main agent, and created with the repository attached as its environment —
+ * no fields to fill unless the defaults are wrong.
+ */
+const CreateFromGithubContent = () => {
+ const { t } = useTranslation(['project', 'common']);
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const createProject = useProjectStore((s) => s.createProject);
+ const [form, setForm] = useState<FormState>({
+ identifier: '',
+ loading: false,
+ name: '',
+ nameEdited: false,
+ url: '',
+ });
+
+ const repository = parseGithubRepository(form.url);
+ const urlInvalid = Boolean(form.url.trim()) && !repository;
+ const defaultMainAgentId = useDefaultMainAgent();
+ const mainAgentId = form.mainAgentId ?? defaultMainAgentId;
+ const identifierInvalid =
+ (Boolean(form.identifier.trim()) && !isProjectIdentifierValid(form.identifier)) ||
+ form.duplicate === 'identifier';
+ const createInput = repository
+ ? getCreateProjectInput({
+ identifier: form.identifier,
+ name: form.name,
+ slug: getProjectFieldSuggestions(form.name).slug,
+ })
+ : null;
+
+ /** A new repository renames the project unless the person already named it. */
+ const applyUrl = (url: string, defaultBranch?: string) => {
+ const parsed = parseGithubRepository(url);
+ setForm((current) => {
+ const name = current.nameEdited ? current.name : (parsed?.name ?? '');
+ return { ...current, defaultBranch, duplicate: undefined, name, url };
+ });
+ };
+
+ const selectRepository = (repo: ScmRepositoryListItem) => {
+ applyUrl(repo.htmlUrl, repo.defaultBranch);
+ };
+
+ const updateName = (name: string) => {
+ setForm((current) => ({ ...current, duplicate: undefined, name, nameEdited: true }));
+ };
+
+ const connectGithub = () => {
+ close();
+ navigate(GITHUB_RETURN_TO);
+ };
+
+ const handleCreate = async () => {
+ if (!createInput || !repository || form.loading) return;
+ setForm((current) => ({ ...current, loading: true }));
+ try {
+ const project = await createProject({
+ ...createInput,
+ coordinatorAgentId: mainAgentId,
+ repository: {
+ defaultBranch: form.defaultBranch,
+ name: repository.fullName,
+ url: repository.url,
+ },
+ });
+ close();
+ navigate(`/project/${project.slug ?? project.id}`);
+ } catch (error) {
+ const duplicate =
+ error instanceof Error
+ ? DUPLICATE_FIELD[error.message as keyof typeof DUPLICATE_FIELD]
+ : undefined;
+ if (duplicate) {
+ setForm((current) => ({ ...current, duplicate }));
+ } else {
+ console.error('Failed to create project from GitHub', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ }
+ } finally {
+ setForm((current) => ({ ...current, loading: false }));
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={16} padding={16}>
+ {/* Picking a connected repository is the primary path; the URL field is the fallback. */}
+ <RepositoryList
+ selected={repository?.fullName}
+ onConnect={connectGithub}
+ onSelect={selectRepository}
+ />
+
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('createFromGithub.urlLabel')}
+ </Text>
+ <Input
+ aria-invalid={urlInvalid}
+ placeholder={t('createFromGithub.urlPlaceholder')}
+ style={urlInvalid ? { borderColor: cssVar.colorError } : undefined}
+ value={form.url}
+ onChange={(event) => applyUrl(event.target.value)}
+ onPressEnter={handleCreate}
+ />
+ {urlInvalid && (
+ <Text fontSize={12} type={'danger'}>
+ {t('createFromGithub.urlInvalid')}
+ </Text>
+ )}
+ </Flexbox>
+
+ {repository && (
+ <Flexbox horizontal gap={12}>
+ <Flexbox flex={1} gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.nameLabel')}
+ </Text>
+ <Input
+ aria-invalid={form.duplicate === 'name'}
+ maxLength={255}
+ placeholder={t('create.namePlaceholder')}
+ style={form.duplicate === 'name' ? { borderColor: cssVar.colorError } : undefined}
+ value={form.name}
+ onChange={(event) => updateName(event.target.value)}
+ onPressEnter={handleCreate}
+ />
+ </Flexbox>
+ <Flexbox gap={6} style={{ width: 160 }}>
+ <Text fontSize={13} weight={500}>
+ {t('create.identifierLabel')}
+ </Text>
+ <Input
+ aria-invalid={identifierInvalid}
+ maxLength={6}
+ placeholder={t('create.identifierPlaceholder')}
+ style={identifierInvalid ? { borderColor: cssVar.colorError } : undefined}
+ value={form.identifier}
+ onPressEnter={handleCreate}
+ onChange={(event) =>
+ setForm((current) => ({
+ ...current,
+ duplicate: undefined,
+ identifier: event.target.value.toUpperCase(),
+ }))
+ }
+ />
+ </Flexbox>
+ </Flexbox>
+ )}
+ {repository && (
+ <Text fontSize={12} type={identifierInvalid || form.duplicate ? 'danger' : 'secondary'}>
+ {form.duplicate === 'name'
+ ? t('createFromGithub.duplicateName')
+ : form.duplicate === 'identifier'
+ ? t('createFromGithub.duplicateIdentifier')
+ : identifierInvalid
+ ? t('create.identifierInvalid')
+ : t('createFromGithub.environmentHint')}
+ </Text>
+ )}
+ {repository && (
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('create.mainAgentLabel')}
+ </Text>
+ <MainAgentField
+ agentId={mainAgentId}
+ disabled={form.loading}
+ onChange={(id) => setForm((current) => ({ ...current, mainAgentId: id }))}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={!createInput}
+ loading={form.loading}
+ type={'primary'}
+ onClick={handleCreate}
+ >
+ {t('create.action')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+};
+
+export default CreateFromGithubContent;
diff --git a/src/features/Projects/CreateFromGithub/RepositoryList.tsx b/src/features/Projects/CreateFromGithub/RepositoryList.tsx
new file mode 100644
index 00000000000..0b9d13f0297
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/RepositoryList.tsx
@@ -0,0 +1,216 @@
+import type { ScmRepositoryListItem } from '@lobechat/types';
+import { Avatar, Button, Flexbox, Icon, SearchBar, Skeleton, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowRightIcon, LockIcon } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useScmRepositories } from './useScmRepositories';
+
+const styles = stylex.create({
+ guide: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ display: 'flex',
+ gap: 10,
+ paddingBlock: 12,
+ paddingInline: 12,
+ },
+ guideText: {
+ color: cssVar.colorTextSecondary,
+ flex: '1',
+ fontSize: 12,
+ minWidth: 0,
+ },
+ list: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ maxHeight: 252,
+ overflowY: 'auto',
+ },
+ row: {
+ alignItems: 'center',
+ backgroundColor: {
+ ':hover': cssVar.colorFillTertiary,
+ 'default': 'transparent',
+ },
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: {
+ ':last-child': 'none',
+ 'default': 'solid',
+ },
+ borderBlockEndWidth: 1,
+ borderInlineWidth: 0,
+ borderBlockStartWidth: 0,
+ color: 'inherit',
+ cursor: 'pointer',
+ display: 'flex',
+ gap: 10,
+ paddingBlock: 8,
+ paddingInline: 12,
+ textAlign: 'start',
+ width: '100%',
+ },
+ selected: {
+ backgroundColor: {
+ ':hover': cssVar.colorFillSecondary,
+ 'default': cssVar.colorFillSecondary,
+ },
+ },
+ private: {
+ color: cssVar.colorTextQuaternary,
+ flex: 'none',
+ },
+});
+
+interface RepositoryListProps {
+ /** Leave the dialog for the GitHub integration settings. */
+ onConnect: () => void;
+ onSelect: (repository: ScmRepositoryListItem) => void;
+ /** `owner/name` of the repository the URL field currently names. */
+ selected?: string;
+}
+
+/**
+ * The repositories the connected GitHub App can read, most recently pushed
+ * first and searchable. Not being connected is one click from being solved,
+ * so that state offers the click instead of only reporting it.
+ */
+const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps) => {
+ const { t } = useTranslation(['project', 'common']);
+ const { isValidating, repositories, retry, state, truncated } = useScmRepositories();
+ const [keyword, setKeyword] = useState('');
+
+ const filtered = useMemo(() => {
+ const query = keyword.trim().toLowerCase();
+ if (!repositories || !query) return repositories ?? [];
+ return repositories.filter(
+ (repo) =>
+ repo.fullName.toLowerCase().includes(query) ||
+ repo.description?.toLowerCase().includes(query),
+ );
+ }, [keyword, repositories]);
+
+ const selectedKey = selected?.toLowerCase();
+
+ const label = (
+ <Text fontSize={13} weight={500}>
+ {t('createFromGithub.repositoriesLabel')}
+ </Text>
+ );
+
+ if (state === 'loading')
+ return (
+ <Flexbox gap={6}>
+ {label}
+ <Skeleton height={44} radius={6} />
+ <Skeleton height={44} radius={6} />
+ <Skeleton height={44} radius={6} />
+ </Flexbox>
+ );
+
+ if (state !== 'ready') {
+ const guide = {
+ disconnected: { action: 'connect', text: t('createFromGithub.disconnected') },
+ empty: { action: 'manage', text: t('createFromGithub.empty') },
+ error: { action: 'retry', text: t('createFromGithub.loadFailed') },
+ unconfigured: { action: undefined, text: t('createFromGithub.unconfigured') },
+ }[state];
+
+ return (
+ <Flexbox gap={6}>
+ {label}
+ <div {...stylex.props(styles.guide)} role={state === 'error' ? 'alert' : undefined}>
+ <span {...stylex.props(styles.guideText)}>{guide.text}</span>
+ {guide.action && (
+ <Button
+ loading={guide.action === 'retry' && isValidating}
+ type={guide.action === 'connect' ? 'primary' : 'default'}
+ onClick={guide.action === 'retry' ? () => void retry() : onConnect}
+ >
+ {guide.action === 'retry'
+ ? t('retry', { ns: 'common' })
+ : t(
+ guide.action === 'connect'
+ ? 'createFromGithub.connect'
+ : 'createFromGithub.manageAccess',
+ )}
+ {guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}
+ </Button>
+ )}
+ </div>
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox gap={6}>
+ {label}
+ <SearchBar
+ allowClear
+ placeholder={t('createFromGithub.searchPlaceholder')}
+ value={keyword}
+ onChange={(event) => setKeyword(event.target.value)}
+ />
+ {filtered.length === 0 ? (
+ <Text fontSize={12} style={{ paddingBlock: 8, textAlign: 'center' }} type={'secondary'}>
+ {t('createFromGithub.searchEmpty')}
+ </Text>
+ ) : (
+ <div {...stylex.props(styles.list)} role={'listbox'}>
+ {filtered.map((repo) => {
+ const isSelected = repo.fullName.toLowerCase() === selectedKey;
+ return (
+ <button
+ aria-selected={isSelected}
+ key={repo.fullName}
+ role={'option'}
+ type={'button'}
+ {...stylex.props(styles.row, isSelected && styles.selected)}
+ onClick={() => onSelect(repo)}
+ >
+ <Avatar
+ avatar={repo.ownerAvatarUrl ?? undefined}
+ shape={'square'}
+ size={28}
+ title={repo.fullName}
+ />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Text ellipsis weight={500}>
+ {repo.fullName}
+ </Text>
+ {repo.private && (
+ <span {...stylex.props(styles.private)} title={t('createFromGithub.private')}>
+ <Icon icon={LockIcon} size={12} />
+ </span>
+ )}
+ </Flexbox>
+ {repo.description && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {repo.description}
+ </Text>
+ )}
+ </Flexbox>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ {truncated && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('createFromGithub.truncated', { count: repositories?.length ?? 0 })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+};
+
+export default RepositoryList;
diff --git a/src/features/Projects/CreateFromGithub/githubRepository.test.ts b/src/features/Projects/CreateFromGithub/githubRepository.test.ts
new file mode 100644
index 00000000000..b1245814f51
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/githubRepository.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseGithubRepository } from './githubRepository';
+
+describe('parseGithubRepository', () => {
+ const expected = {
+ fullName: 'lobehub/lobe-chat',
+ name: 'lobe-chat',
+ url: 'https://github.com/lobehub/lobe-chat',
+ };
+
+ it.each([
+ 'https://github.com/lobehub/lobe-chat',
+ 'https://github.com/lobehub/lobe-chat.git',
+ 'https://github.com/lobehub/lobe-chat/',
+ ' https://github.com/lobehub/lobe-chat ',
+ '[email protected]:lobehub/lobe-chat.git',
+ 'lobehub/lobe-chat',
+ ])('reads %s', (value) => {
+ expect(parseGithubRepository(value)).toEqual(expected);
+ });
+
+ it.each([
+ '',
+ 'lobe-chat',
+ 'http://github.com/lobehub/lobe-chat',
+ 'https://gitlab.com/lobehub/lobe-chat',
+ 'https://[email protected]/lobehub/lobe-chat',
+ 'https://github.com/lobehub/lobe-chat/tree/main',
+ 'https://github.com/lobehub/lobe-chat?tab=readme',
+ 'https://github.com/lobehub',
+ 'not a url',
+ ])('rejects %s', (value) => {
+ expect(parseGithubRepository(value)).toBeNull();
+ });
+});
diff --git a/src/features/Projects/CreateFromGithub/githubRepository.ts b/src/features/Projects/CreateFromGithub/githubRepository.ts
new file mode 100644
index 00000000000..344d01ec818
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/githubRepository.ts
@@ -0,0 +1,55 @@
+export interface ParsedGithubRepository {
+ /** `owner/name`. */
+ fullName: string;
+ /** The repository name alone, which the project is named after. */
+ name: string;
+ /** Canonical `https://github.com/owner/name`, the form an environment stores. */
+ url: string;
+}
+
+const SEGMENT = /^[\w.-]+$/;
+
+/**
+ * Read a pasted GitHub repository reference: an https URL (with or without
+ * `.git` or a trailing slash), an ssh `[email protected]:` remote, or bare
+ * `owner/name`. Anything else — another host, a deep link into the tree,
+ * embedded credentials — is not something an environment can clone, so it
+ * yields `null` rather than a guess.
+ */
+export const parseGithubRepository = (value: string): ParsedGithubRepository | null => {
+ const raw = value.trim();
+ if (!raw) return null;
+
+ let path: string | undefined;
+ const ssh = /^git@github\.com:(.+)$/.exec(raw);
+ if (ssh) path = ssh[1];
+ else if (/^[\w.-]+\/[\w.-]+$/.test(raw)) path = raw;
+ else {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return null;
+ }
+ if (
+ url.protocol !== 'https:' ||
+ url.hostname !== 'github.com' ||
+ url.port ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash
+ )
+ return null;
+ path = url.pathname.replace(/^\//, '');
+ }
+
+ const [owner, repo, ...rest] = path
+ .replace(/\/$/, '')
+ .replace(/\.git$/, '')
+ .split('/');
+ if (rest.length > 0 || !owner || !repo || !SEGMENT.test(owner) || !SEGMENT.test(repo))
+ return null;
+
+ return { fullName: `${owner}/${repo}`, name: repo, url: `https://github.com/${owner}/${repo}` };
+};
diff --git a/src/features/Projects/CreateFromGithub/index.tsx b/src/features/Projects/CreateFromGithub/index.tsx
new file mode 100644
index 00000000000..82e85c0e1d0
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/index.tsx
@@ -0,0 +1,18 @@
+import { createModal } from '@lobehub/ui';
+import { lazy, Suspense } from 'react';
+import { Trans } from 'react-i18next';
+
+const CreateFromGithubContent = lazy(() => import('./Content'));
+
+export const openCreateProjectFromGithubModal = () =>
+ createModal({
+ content: (
+ <Suspense fallback={null}>
+ <CreateFromGithubContent />
+ </Suspense>
+ ),
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: <Trans i18nKey={'createFromGithub.title'} ns={'project'} />,
+ width: 520,
+ });
diff --git a/src/features/Projects/CreateFromGithub/useScmRepositories.ts b/src/features/Projects/CreateFromGithub/useScmRepositories.ts
new file mode 100644
index 00000000000..b155d9d94df
--- /dev/null
+++ b/src/features/Projects/CreateFromGithub/useScmRepositories.ts
@@ -0,0 +1,42 @@
+import useSWR from 'swr';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { scmKeys } from '@/libs/swr/keys';
+import { scmService } from '@/services/scm';
+
+export type ScmRepositoriesState =
+ 'disconnected' | 'empty' | 'error' | 'loading' | 'ready' | 'unconfigured';
+
+/**
+ * Repositories the connected GitHub App installations can read. The state
+ * keeps "nothing connected" apart from "connected, nothing granted": the first
+ * is fixed by connecting, the second by changing access on GitHub. A failed
+ * refresh keeps the list already loaded rather than replacing it with an error.
+ */
+export const useScmRepositories = () => {
+ const workspaceId = useActiveWorkspaceId();
+ const swr = useSWR(scmKeys.repositories(workspaceId), () => scmService.listRepositories(), {
+ revalidateOnFocus: false,
+ });
+
+ const state: ScmRepositoriesState = !swr.data
+ ? swr.error
+ ? 'error'
+ : 'loading'
+ : !swr.data.configured
+ ? 'unconfigured'
+ : swr.data.installations === 0
+ ? 'disconnected'
+ : swr.data.repositories.length === 0
+ ? 'empty'
+ : 'ready';
+
+ return {
+ error: swr.error,
+ isValidating: swr.isValidating,
+ repositories: swr.data?.repositories,
+ retry: () => swr.mutate(),
+ state,
+ truncated: swr.data?.truncated ?? false,
+ };
+};
diff --git a/src/features/Projects/List/index.tsx b/src/features/Projects/List/index.tsx
index 243d61dc852..248b991fefe 100644
--- a/src/features/Projects/List/index.tsx
+++ b/src/features/Projects/List/index.tsx
@@ -1,6 +1,7 @@
'use client';
import { agentDisplayName } from '@lobechat/types';
+import { Github } from '@lobehub/icons';
import {
ActionIcon,
Button,
@@ -41,6 +42,7 @@ import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';
import { useFavoriteMenuItem, useFavoriteToggle } from '@/features/Favorites';
import NavHeader from '@/features/NavHeader';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { openCreateProjectFromGithubModal } from '@/features/Projects/CreateFromGithub';
import { openCreateProjectModal } from '@/features/Projects/CreateProjectModal';
import { createDeleteProjectModal } from '@/features/Projects/DeleteProjectModal';
import ProjectDisabled from '@/features/Projects/ProjectDisabled';
@@ -337,6 +339,26 @@ const ProjectListPage = memo(() => {
type: 'checkbox' as const,
}));
+ const createMenuItems = useMemo<DropdownItem[]>(
+ () => [
+ {
+ icon: PlusIcon,
+ key: 'blank',
+ label: t('create.blank'),
+ onClick: () => openCreateProjectModal(),
+ },
+ {
+ // A filled brand mark: as a component, the menu's Icon wrapper would paint it with
+ // `fill: transparent` (stroke-icon styling) and leave the slot empty.
+ icon: <Github aria-hidden size={16} />,
+ key: 'github',
+ label: t('create.fromGithub'),
+ onClick: () => openCreateProjectFromGithubModal(),
+ },
+ ],
+ [t],
+ );
+
// A drop inside search results would reorder only the matches, so dragging
// waits for the full list.
const draggable = sortBy === 'manual' && canManage && !normalizedKeyword;
@@ -374,9 +396,9 @@ const ProjectListPage = memo(() => {
{t(`sidebar.sort.${sortBy}`)}
</Button>
</DropdownMenu>
- <Button icon={PlusIcon} onClick={() => openCreateProjectModal()}>
- {t('create.action')}
- </Button>
+ <DropdownMenu items={createMenuItems} placement={'bottomRight'}>
+ <Button icon={PlusIcon}>{t('create.action')}</Button>
+ </DropdownMenu>
</Flexbox>
</Flexbox>
{listState === 'error' ? (
diff --git a/src/features/Projects/createProjectForm.test.ts b/src/features/Projects/createProjectForm.test.ts
index 10ce92582dc..15c3256f69b 100644
--- a/src/features/Projects/createProjectForm.test.ts
+++ b/src/features/Projects/createProjectForm.test.ts
@@ -7,6 +7,7 @@ import {
getProjectFieldSuggestions,
isProjectIdentifierValid,
isProjectSlugValid,
+ PROJECT_SLUG_MAX_LENGTH,
} from './createProjectForm';
describe('createProjectForm', () => {
@@ -20,6 +21,19 @@ describe('createProjectForm', () => {
expect(getProjectFieldSuggestions(' ')).toEqual({ slug: '' });
});
+ it('bounds the generated slug so a long name still creates a project', () => {
+ const longName = 'a'.repeat(120);
+ const { slug } = getProjectFieldSuggestions(longName);
+
+ expect(slug).toBe('a'.repeat(PROJECT_SLUG_MAX_LENGTH));
+ expect(isProjectSlugValid(slug)).toBe(true);
+ expect(getCreateProjectInput({ identifier: 'LOBE', name: longName, slug })).toEqual({
+ identifier: 'LOBE',
+ name: longName,
+ slug: 'a'.repeat(PROJECT_SLUG_MAX_LENGTH),
+ });
+ });
+
it('omits an empty identifier so tasks keep the default prefix', () => {
expect(getCreateProjectInput({ identifier: ' ', name: 'LobeHub', slug: '' })).toEqual({
name: 'LobeHub',
@@ -64,6 +78,15 @@ describe('createProjectForm', () => {
).toBeNull();
});
+ it('rejects a user-provided slug longer than the backend limit', () => {
+ const overLongSlug = 'a'.repeat(PROJECT_SLUG_MAX_LENGTH + 1);
+
+ expect(isProjectSlugValid(overLongSlug)).toBe(false);
+ expect(
+ getCreateProjectInput({ identifier: 'LOBE', name: 'LobeHub Project', slug: overLongSlug }),
+ ).toBeNull();
+ });
+
it('leaves the main agent out so the server creates a dedicated one', () => {
expect(
buildCreateProjectRequest(
diff --git a/src/features/Projects/createProjectForm.ts b/src/features/Projects/createProjectForm.ts
index 3fae4dc2a18..474b49bf9f9 100644
--- a/src/features/Projects/createProjectForm.ts
+++ b/src/features/Projects/createProjectForm.ts
@@ -4,6 +4,11 @@ import { pinyin } from 'pinyin-pro';
const PROJECT_SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+/** Mirrors the `max(100)` on `projectSlugInput` in the project router. */
+export const PROJECT_SLUG_MAX_LENGTH = 100;
+
+const boundSlug = (slug: string) => slug.slice(0, PROJECT_SLUG_MAX_LENGTH).replace(/-+$/, '');
+
export interface CreateProjectDraft {
identifier: string;
name: string;
@@ -23,7 +28,7 @@ export const getProjectFieldSuggestions = (name: string): ProjectFieldSuggestion
toneType: 'none',
type: 'array',
}).join(' ');
- const slug = kebabCase(transliteratedName).replaceAll(/[^a-z0-9-]/g, '');
+ const slug = boundSlug(kebabCase(transliteratedName).replaceAll(/[^a-z0-9-]/g, ''));
return { slug };
};
@@ -33,7 +38,10 @@ export const isProjectIdentifierValid = (identifier: string) =>
export const isProjectSlugValid = (slug: string) => {
const normalizedSlug = slug.trim().toLowerCase();
- return !normalizedSlug || PROJECT_SLUG_REGEX.test(normalizedSlug);
+ return (
+ !normalizedSlug ||
+ (normalizedSlug.length <= PROJECT_SLUG_MAX_LENGTH && PROJECT_SLUG_REGEX.test(normalizedSlug))
+ );
};
export const getCreateProjectInput = (draft: CreateProjectDraft) => {
diff --git a/src/features/Projects/useDefaultMainAgent.ts b/src/features/Projects/useDefaultMainAgent.ts
new file mode 100644
index 00000000000..ea73b735a89
--- /dev/null
+++ b/src/features/Projects/useDefaultMainAgent.ts
@@ -0,0 +1,6 @@
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+
+/** The main agent a new project starts with: the workspace inbox agent, LobeAI. */
+export const useDefaultMainAgent = () =>
+ useAgentStore(builtinAgentSelectors.inboxAgentId);
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index e0fe1d69762..431766e9db7 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -635,6 +635,10 @@ export const scmKeys = {
'scm:installations',
workspaceId ?? null,
]),
+ repositories: def('scm:repositories', (workspaceId: string | null | undefined) => [
+ 'scm:repositories',
+ workspaceId ?? null,
+ ]),
wakeTarget: def('scm:wakeTarget', (topicId: string) => ['scm:wakeTarget', topicId]),
};
diff --git a/src/services/project.ts b/src/services/project.ts
index aea997f7655..4a358eb2900 100644
--- a/src/services/project.ts
+++ b/src/services/project.ts
@@ -61,6 +61,7 @@ class ProjectService {
description?: string;
identifier?: string;
name: string;
+ repository?: { defaultBranch?: string; name: string; url: string };
slug?: string;
visibility?: ProjectVisibility;
},
diff --git a/src/services/scm.ts b/src/services/scm.ts
index 2aeb5dd12aa..02443343783 100644
--- a/src/services/scm.ts
+++ b/src/services/scm.ts
@@ -15,6 +15,8 @@ class ScmService {
lambdaClient.scm.listChangeRequests.query(params);
listInstallations = async () => lambdaClient.scm.listInstallations.query();
+
+ listRepositories = async () => lambdaClient.scm.listRepositories.query();
}
export const scmService = new ScmService();
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 695f2b7783d..1ffd9f80b72 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -52,6 +52,8 @@ interface ProjectStore extends ProjectStoreState {
coordinatorAgentId?: string;
identifier?: string;
name: string;
+ /** GitHub repository to attach as the project's environment, in the same write. */
+ repository?: { defaultBranch?: string; name: string; url: string };
slug?: string;
}) => Promise<ProjectListItem>;
deleteProject: (id: string) => Promise<void>;